开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
main
分支 (60)
标签 (129)
main
drone
fix-drone-stages-stuck-in-pending-state
main-gh0-40
release/3.3.0
hitesh-test2
turbo-changes
devcontainer-1
release/3.2.0
release/3.2.0-old
try-new-ui
jobatzil/login/xforwardedfor
release/3.1.0
BT-10437
release/3.0.0
fix-test-failure-14
test-fix-branch
dummy-branch
fix-go-revert
devcontainer-setup
v2.28.1
v2.28.0
v2.27.2
v2.27.1
v2.27.0
v3.3.0
v3.2.0
v2.26.0
v3.1.1
v3.1.0
v2.25.1-debug
v3.0.1
v2.25.0
v3.0.1-debug
v3.0.0
v3.0.0-beta.12
v3.0.0-beta.11
v3.0.0-beta.10
v3.0.0-beta.9
v3.0.0-beta.8
main
分支 (60)
标签 (129)
main
drone
fix-drone-stages-stuck-in-pending-state
main-gh0-40
release/3.3.0
hitesh-test2
turbo-changes
devcontainer-1
release/3.2.0
release/3.2.0-old
try-new-ui
jobatzil/login/xforwardedfor
release/3.1.0
BT-10437
release/3.0.0
fix-test-failure-14
test-fix-branch
dummy-branch
fix-go-revert
devcontainer-setup
v2.28.1
v2.28.0
v2.27.2
v2.27.1
v2.27.0
v3.3.0
v3.2.0
v2.26.0
v3.1.1
v3.1.0
v2.25.1-debug
v3.0.1
v2.25.0
v3.0.1-debug
v3.0.0
v3.0.0-beta.12
v3.0.0-beta.11
v3.0.0-beta.10
v3.0.0-beta.9
v3.0.0-beta.8
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
main
分支 (60)
标签 (129)
main
drone
fix-drone-stages-stuck-in-pending-state
main-gh0-40
release/3.3.0
hitesh-test2
turbo-changes
devcontainer-1
release/3.2.0
release/3.2.0-old
try-new-ui
jobatzil/login/xforwardedfor
release/3.1.0
BT-10437
release/3.0.0
fix-test-failure-14
test-fix-branch
dummy-branch
fix-go-revert
devcontainer-setup
v2.28.1
v2.28.0
v2.27.2
v2.27.1
v2.27.0
v3.3.0
v3.2.0
v2.26.0
v3.1.1
v3.1.0
v2.25.1-debug
v3.0.1
v2.25.0
v3.0.1-debug
v3.0.0
v3.0.0-beta.12
v3.0.0-beta.11
v3.0.0-beta.10
v3.0.0-beta.9
v3.0.0-beta.8
harness
/
git
/
api
/
commit.go
harness
/
git
/
api
/
commit.go
commit.go 18.70 KB
一键复制 编辑 原始数据 按行查看 历史
Enver Biševac 提交于 2025年10月29日 22:06 +08:00 . feat: [CODE-4627]: add modernize tool (#4668)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
// Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"bufio"
"bytes"
"context"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/command"
"github.com/harness/gitness/git/enum"
"github.com/harness/gitness/git/sha"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
)
type CommitChangesOptions struct {
Committer Signature
Author Signature
Message string
}
type CommitFileStats struct {
ChangeType enum.FileDiffStatus
Path string
OldPath string // populated only in case of renames
Insertions int64
Deletions int64
}
type Commit struct {
SHA sha.SHA
TreeSHA sha.SHA
ParentSHAs []sha.SHA
Title string
Message string
Author Signature
Committer Signature
SignedData *SignedData
FileStats []CommitFileStats
}
type CommitFilter struct {
Path string
AfterRef string
Since int64
Until int64
Committer string
Author string
Regex bool
}
// CommitDivergenceRequest contains the refs for which the converging commits should be counted.
type CommitDivergenceRequest struct {
// From is the ref from which the counting of the diverging commits starts.
From string
// To is the ref at which the counting of the diverging commits ends.
To string
}
// CommitDivergence contains the information of the count of converging commits between two refs.
type CommitDivergence struct {
// Ahead is the count of commits the 'From' ref is ahead of the 'To' ref.
Ahead int32
// Behind is the count of commits the 'From' ref is behind the 'To' ref.
Behind int32
}
type PathRenameDetails struct {
OldPath string
Path string
CommitSHABefore sha.SHA
CommitSHAAfter sha.SHA
}
func (g *Git) listCommitSHAs(
ctx context.Context,
repoPath string,
alternateObjectDirs []string,
ref string,
page int,
limit int,
filter CommitFilter,
) ([]sha.SHA, error) {
cmd := command.New("rev-list")
// return commits only up to a certain reference if requested
if filter.AfterRef != "" {
// ^REF tells the rev-list command to return only commits that aren't reachable by SHA
cmd.Add(command.WithArg(fmt.Sprintf("^%s", filter.AfterRef)))
}
// add refCommitSHA as starting point
cmd.Add(command.WithArg(ref))
cmd.Add(command.WithAlternateObjectDirs(alternateObjectDirs...))
if len(filter.Path) != 0 {
cmd.Add(command.WithPostSepArg(filter.Path))
}
// add pagination if requested
// TODO: we should add absolut limits to protect git (return error)
if limit > 0 {
cmd.Add(command.WithFlag("--max-count", strconv.Itoa(limit)))
if page > 1 {
cmd.Add(command.WithFlag("--skip", strconv.Itoa((page-1)*limit)))
}
}
if filter.Since > 0 || filter.Until > 0 {
cmd.Add(command.WithFlag("--date", "unix"))
}
if filter.Since > 0 {
cmd.Add(command.WithFlag("--since", strconv.FormatInt(filter.Since, 10)))
}
if filter.Until > 0 {
cmd.Add(command.WithFlag("--until", strconv.FormatInt(filter.Until, 10)))
}
if filter.Regex {
cmd.Add(command.WithFlag("-E"))
}
if filter.Committer != "" {
cmd.Add(command.WithFlag("--committer", filter.Committer))
}
if filter.Author != "" {
cmd.Add(command.WithFlag("--author", filter.Author))
}
output := &bytes.Buffer{}
err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output))
if cErr := command.AsError(err); cErr != nil && cErr.IsExitCode(128) {
if cErr.IsAmbiguousArgErr() || cErr.IsBadObject() {
return []sha.SHA{}, nil // return an empty list if reference doesn't exist
}
}
if err != nil {
return nil, processGitErrorf(err, "failed to trigger rev-list command")
}
var objectSHAs []sha.SHA
scanner := bufio.NewScanner(output)
for scanner.Scan() {
objectSHA, err := sha.New(scanner.Text())
if err != nil {
return nil, fmt.Errorf("failed to parse commit sha: %w", err)
}
objectSHAs = append(objectSHAs, objectSHA)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to scan commit sha list: %w", err)
}
return objectSHAs, nil
}
// ListCommitSHAs lists the commits reachable from ref.
// Note: ref & afterRef can be Branch / Tag / CommitSHA.
// Note: commits returned are [ref->...->afterRef).
func (g *Git) ListCommitSHAs(
ctx context.Context,
repoPath string,
alternateObjectDirs []string,
ref string,
page int,
limit int,
filter CommitFilter,
) ([]sha.SHA, error) {
return g.listCommitSHAs(ctx, repoPath, alternateObjectDirs, ref, page, limit, filter)
}
// ListCommits lists the commits reachable from ref.
// Note: ref & afterRef can be Branch / Tag / CommitSHA.
// Note: commits returned are [ref->...->afterRef).
func (g *Git) ListCommits(
ctx context.Context,
repoPath string,
ref string,
page int,
limit int,
includeStats bool,
filter CommitFilter,
) ([]Commit, []PathRenameDetails, error) {
if repoPath == "" {
return nil, nil, ErrRepositoryPathEmpty
}
commitSHAs, err := g.listCommitSHAs(ctx, repoPath, nil, ref, page, limit, filter)
if err != nil {
return nil, nil, fmt.Errorf("failed to list commit SHAs: %w", err)
}
commits, err := CatFileCommits(ctx, repoPath, nil, commitSHAs)
if err != nil {
return nil, nil, fmt.Errorf("failed to list commits by SHAs: %w", err)
}
if includeStats {
for i := range commits {
fileStats, err := getCommitFileStats(ctx, repoPath, commits[i].SHA)
if err != nil {
return nil, nil, fmt.Errorf("encountered error getting commit file stats: %w", err)
}
commits[i].FileStats = fileStats
}
}
if len(filter.Path) != 0 {
renameDetailsList, err := getRenameDetails(ctx, repoPath, commits, filter.Path)
if err != nil {
return nil, nil, err
}
cleanedUpCommits := cleanupCommitsForRename(commits, renameDetailsList, filter.Path)
return cleanedUpCommits, renameDetailsList, nil
}
return commits, nil, nil
}
func getCommitFileStats(
ctx context.Context,
repoPath string,
sha sha.SHA,
) ([]CommitFileStats, error) {
g, ctx := errgroup.WithContext(ctx)
var changeInfoChanges map[string]changeInfoChange
var changeInfoTypes map[string]changeInfoType
g.Go(func() error {
var err error
changeInfoChanges, err = getChangeInfoChanges(ctx, repoPath, sha)
return err
})
g.Go(func() error {
var err error
changeInfoTypes, err = getChangeInfoTypes(ctx, repoPath, sha)
return err
})
if err := g.Wait(); err != nil {
return nil, fmt.Errorf("failed to get change infos: %w", err)
}
if len(changeInfoTypes) == 0 {
return []CommitFileStats{}, nil
}
fileStats := make([]CommitFileStats, len(changeInfoChanges))
i := 0
for path, info := range changeInfoChanges {
fileStats[i] = CommitFileStats{
Path: changeInfoTypes[path].Path,
OldPath: changeInfoTypes[path].OldPath,
ChangeType: changeInfoTypes[path].Status,
Insertions: info.Insertions,
Deletions: info.Deletions,
}
i++
}
return fileStats, nil
}
// In case of rename of a file, same commit will be listed twice - Once in old file and second time in new file.
// Hence, we are making it a pattern to only list it as part of new file and not as part of old file.
func cleanupCommitsForRename(
commits []Commit,
renameDetails []PathRenameDetails,
path string,
) []Commit {
if len(commits) == 0 {
return commits
}
for _, renameDetail := range renameDetails {
// Since rename details is present it implies that we have commits and hence don't need null check.
if commits[0].SHA.Equal(renameDetail.CommitSHABefore) && path == renameDetail.OldPath {
return commits[1:]
}
}
return commits
}
func getRenameDetails(
ctx context.Context,
repoPath string,
commits []Commit,
path string,
) ([]PathRenameDetails, error) {
if len(commits) == 0 {
return []PathRenameDetails{}, nil
}
renameDetailsList := make([]PathRenameDetails, 0, 2)
renameDetails, err := gitGetRenameDetails(ctx, repoPath, commits[0].SHA, path)
if err != nil {
return nil, err
}
if renameDetails.Path != "" || renameDetails.OldPath != "" {
renameDetails.CommitSHABefore = commits[0].SHA
renameDetailsList = append(renameDetailsList, *renameDetails)
}
if len(commits) == 1 {
return renameDetailsList, nil
}
renameDetailsLast, err := gitGetRenameDetails(ctx, repoPath, commits[len(commits)-1].SHA, path)
if err != nil {
return nil, err
}
if renameDetailsLast.Path != "" || renameDetailsLast.OldPath != "" {
renameDetailsLast.CommitSHAAfter = commits[len(commits)-1].SHA
renameDetailsList = append(renameDetailsList, *renameDetailsLast)
}
return renameDetailsList, nil
}
func gitGetRenameDetails(
ctx context.Context,
repoPath string,
sha sha.SHA,
path string,
) (*PathRenameDetails, error) {
changeInfos, err := getChangeInfoTypes(ctx, repoPath, sha)
if err != nil {
return &PathRenameDetails{}, fmt.Errorf("failed to get change infos %w", err)
}
for _, c := range changeInfos {
if c.Status == enum.FileDiffStatusRenamed && (c.OldPath == path || c.Path == path) {
return &PathRenameDetails{
OldPath: c.OldPath,
Path: c.Path,
}, nil
}
}
return &PathRenameDetails{}, nil
}
func gitLogNameStatus(ctx context.Context, repoPath string, sha sha.SHA) ([]string, error) {
cmd := command.New("log",
command.WithFlag("--name-status"),
command.WithFlag("--format="), //nolint:goconst
command.WithFlag("--max-count=1"),
command.WithArg(sha.String()),
)
output := &bytes.Buffer{}
err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output))
if err != nil {
return nil, fmt.Errorf("failed to trigger log command: %w", err)
}
return parseLinesToSlice(output.Bytes()), nil
}
func gitShowNumstat(
ctx context.Context,
repoPath string,
sha sha.SHA,
) ([]string, error) {
cmd := command.New("show",
command.WithFlag("--numstat"),
command.WithFlag("--format="), //nolint:goconst
command.WithArg(sha.String()),
)
output := &bytes.Buffer{}
err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output))
if err != nil {
return nil, fmt.Errorf("failed to trigger show command: %w", err)
}
return parseLinesToSlice(output.Bytes()), nil
}
// Will match "R100\tREADME.md\tREADME_new.md".
// Will extract README.md and README_new.md.
var renameRegex = regexp.MustCompile(`\t(.+)\t(.+)`)
func getChangeInfoTypes(
ctx context.Context,
repoPath string,
sha sha.SHA,
) (map[string]changeInfoType, error) {
lines, err := gitLogNameStatus(ctx, repoPath, sha)
if err != nil {
return nil, err
}
changeInfoTypes := make(map[string]changeInfoType, len(lines))
for _, line := range lines {
c := changeInfoType{}
matches := renameRegex.FindStringSubmatch(line) // renamed file
if len(matches) > 0 {
c.OldPath = matches[1]
c.Path = matches[2]
} else {
lineParts := strings.Split(line, "\t")
if len(lineParts) != 2 {
return changeInfoTypes, fmt.Errorf("could not parse file change status string %q", line)
}
c.Path = lineParts[1]
}
c.Status = convertFileDiffStatus(ctx, line)
changeInfoTypes[c.Path] = c
}
return changeInfoTypes, nil
}
// Will match "31\t0\t.harness/apidiff.yaml" and extract 31, 0 and .harness/apidiff.yaml.
// Will match "-\t-\ttools/code-api/chart/charts/harness-common-1.0.27.tgz" and extract -, -, and a filename.
var insertionsDeletionsRegex = regexp.MustCompile(`(\d+|-)\t(\d+|-)\t(.+)`)
// Will match "0\t0\tREADME.md => README_new.md" and extract README_new.md.
// Will match "-\t-\tfile_name.bin => file_name_new.bin" and extract file_name_new.bin.
var renameRegexWithArrow = regexp.MustCompile(`(?:\d+|-)\t(?:\d+|-)\t.+\s=>\s(.+)`)
func getChangeInfoChanges(
ctx context.Context,
repoPath string,
sha sha.SHA,
) (map[string]changeInfoChange, error) {
lines, err := gitShowNumstat(ctx, repoPath, sha)
if err != nil {
return nil, err
}
changeInfos := make(map[string]changeInfoChange, len(lines))
for _, line := range lines {
matches := insertionsDeletionsRegex.FindStringSubmatch(line)
if len(matches) != 4 {
return map[string]changeInfoChange{},
fmt.Errorf("failed to regex match insertions and deletions for %q", line)
}
path := matches[3]
if renMatches := renameRegexWithArrow.FindStringSubmatch(line); len(renMatches) == 2 {
path = renMatches[1]
}
if matches[1] == "-" || matches[2] == "-" {
changeInfos[path] = changeInfoChange{}
continue
}
insertions, err := strconv.ParseInt(matches[1], 10, 64)
if err != nil {
return map[string]changeInfoChange{},
fmt.Errorf("failed to parse insertions for %q", line)
}
deletions, err := strconv.ParseInt(matches[2], 10, 64)
if err != nil {
return map[string]changeInfoChange{},
fmt.Errorf("failed to parse deletions for %q", line)
}
changeInfos[path] = changeInfoChange{
Insertions: insertions,
Deletions: deletions,
}
}
return changeInfos, nil
}
type changeInfoType struct {
Status enum.FileDiffStatus
OldPath string // populated only in case of renames
Path string
}
type changeInfoChange struct {
Insertions int64
Deletions int64
}
func convertFileDiffStatus(ctx context.Context, c string) enum.FileDiffStatus {
switch {
case strings.HasPrefix(c, "A"):
return enum.FileDiffStatusAdded
case strings.HasPrefix(c, "C"):
return enum.FileDiffStatusCopied
case strings.HasPrefix(c, "D"):
return enum.FileDiffStatusDeleted
case strings.HasPrefix(c, "M"):
return enum.FileDiffStatusModified
case strings.HasPrefix(c, "R"):
return enum.FileDiffStatusRenamed
default:
log.Ctx(ctx).Warn().Msgf("encountered unknown change type %s", c)
return enum.FileDiffStatusUndefined
}
}
// GetCommitFromRev returns the (latest) commit for a specific revision.
func (g *Git) GetCommitFromRev(
ctx context.Context,
repoPath string,
rev string,
) (*Commit, error) {
if repoPath == "" {
return nil, ErrRepositoryPathEmpty
}
commitSHA, err := g.ResolveRev(ctx, repoPath, rev+"^{commit}")
if errors.IsInvalidArgument(err) {
return nil, errors.NotFoundf("revision %q not found", rev)
}
if err != nil {
return nil, fmt.Errorf("failed to resolve revision %q: %w", rev, err)
}
return GetCommit(ctx, repoPath, commitSHA)
}
// GetCommits returns the commits for a specific list of SHAs.
func (g *Git) GetCommits(
ctx context.Context,
repoPath string,
commitSHAs []sha.SHA,
) ([]Commit, error) {
if repoPath == "" {
return nil, ErrRepositoryPathEmpty
}
commits, err := CatFileCommits(ctx, repoPath, nil, commitSHAs)
if err != nil {
return nil, fmt.Errorf("failed to list commits by SHAs: %w", err)
}
return commits, nil
}
func GetCommit(ctx context.Context, repoPath string, commitSHA sha.SHA) (*Commit, error) {
commits, err := CatFileCommits(ctx, repoPath, nil, []sha.SHA{commitSHA})
if err != nil {
return nil, fmt.Errorf("failed to list commit by SHA: %w", err)
}
if len(commits) != 1 {
return nil, fmt.Errorf("expected one commit, but got %d", len(commits))
}
return &commits[0], nil
}
func GetLatestCommit(
ctx context.Context,
repoPath string,
rev string,
path string,
) (*Commit, error) {
cmd := command.New("log",
command.WithFlag("--max-count", "1"),
command.WithFlag("--format="+fmtCommitHash),
command.WithArg(rev),
command.WithPostSepArg(path))
output := &bytes.Buffer{}
err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output))
if err != nil {
if strings.Contains(err.Error(), "ambiguous argument") {
return nil, errors.NotFoundf("revision %q not found", rev)
}
return nil, fmt.Errorf("failed to run git to get commit data: %w", err)
}
commitLine := strings.TrimSpace(output.String())
if commitLine == "" {
return nil, errors.InvalidArgumentf("path %q not found in %s", path, rev)
}
commitSHA := sha.Must(commitLine)
return GetCommit(ctx, repoPath, commitSHA)
}
// GetCommitDivergences returns the count of the diverging commits for all branch pairs.
// IMPORTANT: If a maxCount is provided it limits the overal count of diverging commits
// (maxCount 10 could lead to (0, 10) while it's actually (2, 12)).
func (g *Git) GetCommitDivergences(
ctx context.Context,
repoPath string,
requests []CommitDivergenceRequest,
maxCount int32,
) ([]CommitDivergence, error) {
if repoPath == "" {
return nil, ErrRepositoryPathEmpty
}
var err error
res := make([]CommitDivergence, len(requests))
for i, req := range requests {
res[i], err = g.getCommitDivergence(ctx, repoPath, req, maxCount)
if errors.IsNotFound(err) {
res[i] = CommitDivergence{Ahead: -1, Behind: -1}
continue
}
if err != nil {
return nil, err
}
}
return res, nil
}
// getCommitDivergence returns the count of diverging commits for a pair of branches.
// IMPORTANT: If a maxCount is provided it limits the overall count of diverging commits
// (maxCount 10 could lead to (0, 10) while it's actually (2, 12)).
func (g *Git) getCommitDivergence(
ctx context.Context,
repoPath string,
req CommitDivergenceRequest,
maxCount int32,
) (CommitDivergence, error) {
cmd := command.New("rev-list",
command.WithFlag("--count"),
command.WithFlag("--left-right"),
)
// limit count if requested.
if maxCount > 0 {
cmd.Add(command.WithFlag("--max-count", strconv.Itoa(int(maxCount))))
}
// add query to get commits without shared base commits
cmd.Add(command.WithArg(req.From + "..." + req.To))
stdout := &bytes.Buffer{}
err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout))
if err != nil {
return CommitDivergence{},
processGitErrorf(err, "git rev-list failed for '%s...%s'", req.From, req.To)
}
// parse output, e.g.: `1 2\n`
output := stdout.String()
rawLeft, rawRight, ok := strings.Cut(output, "\t")
if !ok {
return CommitDivergence{}, fmt.Errorf("git rev-list returned unexpected output '%s'", output)
}
// trim any unnecessary characters
rawLeft = strings.TrimRight(rawLeft, " \t")
rawRight = strings.TrimRight(rawRight, " \t\n")
// parse numbers
left, err := strconv.ParseInt(rawLeft, 10, 32)
if err != nil {
return CommitDivergence{},
fmt.Errorf("failed to parse git rev-list output for ahead '%s' (full: '%s')): %w",
rawLeft, output, err)
}
right, err := strconv.ParseInt(rawRight, 10, 32)
if err != nil {
return CommitDivergence{},
fmt.Errorf("failed to parse git rev-list output for behind '%s' (full: '%s')): %w",
rawRight, output, err)
}
return CommitDivergence{
Ahead: int32(left),
Behind: int32(right),
}, nil
}
func parseLinesToSlice(output []byte) []string {
if len(output) == 0 {
return nil
}
lines := bytes.Split(bytes.TrimSpace(output), []byte{'\n'})
slice := make([]string, len(lines))
for i, line := range lines {
slice[i] = string(line)
}
return slice
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

暂无描述
暂无标签
Apache-2.0
使用 Apache-2.0 开源许可协议
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/open_source_reference/harness.git
git@gitee.com:open_source_reference/harness.git
open_source_reference
harness
harness
main
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /