开源 企业版 高校版 私有云 模力方舟 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
/
diff.go
harness
/
git
/
api
/
diff.go
diff.go 19.54 KB
一键复制 编辑 原始数据 按行查看 历史
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 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
// 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"
"io"
"math"
"regexp"
"strconv"
"strings"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/command"
"github.com/harness/gitness/git/parser"
"github.com/harness/gitness/git/sha"
"github.com/harness/gitness/types"
)
type FileDiffRequest struct {
Path string `json:"path"`
StartLine int `json:"start_line"`
EndLine int `json:"-"` // warning: changes are possible and this field may not exist in the future
}
type FileDiffRequests []FileDiffRequest
type DiffShortStat struct {
Files int
Additions int
Deletions int
}
// modifyHeader needs to modify diff hunk header with the new start line
// and end line with calculated span.
// if diff hunk header is -100, 50 +100, 50 and startLine = 120, endLine=140
// then we need to modify header to -120,20 +120,20.
// warning: changes are possible and param endLine may not exist in the future.
func modifyHeader(hunk parser.HunkHeader, startLine, endLine int) []byte {
oldStartLine := hunk.OldLine
newStartLine := hunk.NewLine
oldSpan := hunk.OldSpan
newSpan := hunk.NewSpan
oldEndLine := oldStartLine + oldSpan
newEndLine := newStartLine + newSpan
if startLine > 0 {
if startLine < oldEndLine {
oldStartLine = startLine
}
if startLine < newEndLine {
newStartLine = startLine
}
}
if endLine > 0 {
if endLine < oldEndLine {
oldSpan = endLine - startLine
} else if oldEndLine > startLine {
oldSpan = oldEndLine - startLine
}
if endLine < newEndLine {
newSpan = endLine - startLine
} else if newEndLine > startLine {
newSpan = newEndLine - startLine
}
}
return fmt.Appendf(nil, "@@ -%d,%d +%d,%d @@",
oldStartLine, oldSpan, newStartLine, newSpan)
}
// cutLinesFromFullFileDiff reads from r and writes to w headers and between
// startLine and endLine. if startLine and endLine is equal to 0 then it uses io.Copy
// warning: changes are possible and param endLine may not exist in the future
//
//nolint:gocognit
func cutLinesFromFullFileDiff(w io.Writer, r io.Reader, startLine, endLine int) error {
if startLine < 0 {
startLine = 0
}
if endLine < 0 {
endLine = 0
}
if startLine == 0 && endLine > 0 {
startLine = 1
}
if endLine < startLine {
endLine = 0
}
// no need for processing lines just copy the data
if startLine == 0 && endLine == 0 {
_, err := io.Copy(w, r)
return err
}
linePos := 0
start := false
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Bytes()
if start {
linePos++
}
if endLine > 0 && linePos > endLine {
break
}
if linePos > 0 &&
(startLine > 0 && linePos < startLine) {
continue
}
if len(line) >= 2 && bytes.HasPrefix(line, []byte{'@', '@'}) {
hunk, ok := parser.ParseDiffHunkHeader(string(line)) // TBD: maybe reader?
if !ok {
return fmt.Errorf("failed to extract lines from diff, range [%d,%d] : %w",
startLine, endLine, ErrParseDiffHunkHeader)
}
line = modifyHeader(hunk, startLine, endLine)
start = true
}
if _, err := w.Write(line); err != nil {
return err
}
if _, err := w.Write([]byte{'\n'}); err != nil {
return err
}
}
return scanner.Err()
}
//nolint:gocognit
func (g *Git) RawDiff(
ctx context.Context,
w io.Writer,
repoPath string,
baseRef string,
headRef string,
mergeBase bool,
ignoreWhitespace bool,
alternates []string,
files ...FileDiffRequest,
) error {
if repoPath == "" {
return ErrRepositoryPathEmpty
}
baseTag, err := g.GetAnnotatedTag(ctx, repoPath, baseRef)
if err == nil {
baseRef = baseTag.TargetSHA.String()
}
headTag, err := g.GetAnnotatedTag(ctx, repoPath, headRef)
if err == nil {
headRef = headTag.TargetSHA.String()
}
if mergeBase {
mergeBaseSHA, _, err := g.GetMergeBase(ctx, repoPath, "", baseRef, headRef, true)
if err != nil {
return fmt.Errorf("failed to get merge base for %s and %s: %w", baseRef, headRef, err)
}
baseRef = mergeBaseSHA.String()
}
cmd := command.New("diff",
command.WithFlag("-M"),
command.WithFlag("--full-index"),
command.WithAlternateObjectDirs(alternates...),
)
if ignoreWhitespace {
// Ignore whitespace when comparing lines.
cmd.Add(command.WithFlag("-w"))
}
perFileDiffRequired := false
paths := make([]string, 0, len(files))
if len(files) > 0 {
for _, file := range files {
paths = append(paths, file.Path)
if file.StartLine > 0 || file.EndLine > 0 {
perFileDiffRequired = true
}
}
}
processed := 0
again:
startLine := 0
endLine := 0
newCmd := cmd.Clone()
if len(files) > 0 {
startLine = files[processed].StartLine
endLine = files[processed].EndLine
}
if perFileDiffRequired {
if startLine > 0 || endLine > 0 {
newCmd.Add(command.WithFlag("-U" + strconv.Itoa(math.MaxInt32)))
}
paths = []string{files[processed].Path}
}
newCmd.Add(command.WithArg(baseRef, headRef))
if len(paths) > 0 {
newCmd.Add(command.WithPostSepArg(paths...))
}
pipeRead, pipeWrite := io.Pipe()
go func() {
var err error
defer func() {
// If running of the command below fails, make the pipe reader also fail with the same error.
_ = pipeWrite.CloseWithError(err)
}()
err = newCmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite))
if err != nil {
err = processGitErrorf(err, "git diff failed between %q and %q", baseRef, headRef)
if cErr := command.AsError(err); cErr != nil {
if cErr.IsExitCode(128) && cErr.IsBadObject() {
err = errors.NotFound("commit not found")
}
}
}
}()
if err = cutLinesFromFullFileDiff(w, pipeRead, startLine, endLine); err != nil {
return err
}
if perFileDiffRequired {
processed++
if processed < len(files) {
goto again
}
}
return nil
}
// CommitDiff will stream diff for provided ref.
func (g *Git) CommitDiff(
ctx context.Context,
repoPath string,
rev string,
ignoreWhitespace bool,
w io.Writer,
) error {
if repoPath == "" {
return ErrRepositoryPathEmpty
}
if rev == "" {
return errors.InvalidArgument("git revision cannot be empty")
}
cmd := command.New("show",
command.WithFlag("--full-index"),
command.WithFlag("--pretty=format:%b"),
command.WithArg(rev),
)
if ignoreWhitespace {
// Ignore whitespace when comparing lines.
cmd.Add(command.WithFlag("-w"))
}
if err := cmd.Run(ctx,
command.WithDir(repoPath),
command.WithStdout(w),
); err != nil {
return processGitErrorf(err, "commit diff error")
}
return nil
}
func (g *Git) DiffShortStat(
ctx context.Context,
repoPath string,
baseRef string,
headRef string,
useMergeBase bool,
ignoreWhitespace bool,
) (DiffShortStat, error) {
if repoPath == "" {
return DiffShortStat{}, ErrRepositoryPathEmpty
}
separator := ".."
if useMergeBase {
separator = "..."
}
shortstatArgs := []string{baseRef + separator + headRef}
if len(baseRef) == 0 || baseRef == types.NilSHA {
shortstatArgs = []string{sha.EmptyTree.String(), headRef}
}
stat, err := GetDiffShortStat(ctx, repoPath, ignoreWhitespace, shortstatArgs...)
if err != nil {
return DiffShortStat{}, processGitErrorf(err, "failed to get diff short stat between %s and %s",
baseRef, headRef)
}
return stat, nil
}
// GetDiffHunkHeaders for each file in diff output returns file name (old and new to detect renames),
// and all hunk headers. The diffs are generated with unified=0 parameter to create minimum sized hunks.
// Hunks' body is ignored.
// The purpose of this function is to get data based on which code comments could be repositioned.
func (g *Git) GetDiffHunkHeaders(
ctx context.Context,
repoPath string,
targetRef string,
sourceRef string,
) ([]*parser.DiffFileHunkHeaders, error) {
if repoPath == "" {
return nil, ErrRepositoryPathEmpty
}
pipeRead, pipeWrite := io.Pipe()
stderr := &bytes.Buffer{}
go func() {
var err error
defer func() {
// If running of the command below fails, make the pipe reader also fail with the same error.
_ = pipeWrite.CloseWithError(err)
}()
cmd := command.New("diff",
command.WithFlag("--patch"),
command.WithFlag("--full-index"),
command.WithFlag("--no-color"),
command.WithFlag("--unified=0"),
command.WithArg(sourceRef),
command.WithArg(targetRef),
)
err = cmd.Run(ctx,
command.WithDir(repoPath),
command.WithStdout(pipeWrite),
command.WithStderr(stderr), // We capture stderr output in a buffer.
)
}()
fileHunkHeaders, err := parser.GetHunkHeaders(pipeRead)
// First check if there's something in the stderr buffer, if yes that's the error
if errStderr := parseDiffStderr(stderr); errStderr != nil {
return nil, errStderr
}
// Next check if reading the git diff output caused an error
if err != nil {
return nil, err
}
return fileHunkHeaders, nil
}
// DiffCut parses full file git diff output and returns lines specified with the parameters.
// The purpose of this function is to get diff data with which code comments could be generated.
//
//nolint:gocognit
func (g *Git) DiffCut(
ctx context.Context,
repoPath string,
targetRef string,
sourceRef string,
path string,
ignoreWhitespace bool,
params parser.DiffCutParams,
) (parser.HunkHeader, parser.Hunk, error) {
if repoPath == "" {
return parser.HunkHeader{}, parser.Hunk{}, ErrRepositoryPathEmpty
}
// first fetch the list of the changed files
pipeRead, pipeWrite := io.Pipe()
go func() {
var err error
defer func() {
// If running of the command below fails, make the pipe reader also fail with the same error.
_ = pipeWrite.CloseWithError(err)
}()
cmd := command.New("diff",
command.WithFlag("--raw"),
command.WithFlag("--merge-base"),
command.WithFlag("-z"),
command.WithFlag("--find-renames"),
command.WithArg(targetRef),
command.WithArg(sourceRef))
if ignoreWhitespace {
// Ignore whitespace when comparing lines.
cmd.Add(command.WithFlag("-w"))
}
err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite))
}()
diffEntries, err := parser.DiffRaw(pipeRead)
if err != nil {
return parser.HunkHeader{}, parser.Hunk{}, fmt.Errorf("failed to find the list of changed files: %w", err)
}
var oldSHA, newSHA string
for _, entry := range diffEntries {
if entry.Status == parser.DiffStatusRenamed || entry.Status == parser.DiffStatusCopied {
// Entries with the status 'R' and 'C' output two paths: the old path and the new path.
// Using the params.LineStartNew flag to match the path with the entry's old or new path.
if entry.Path != path && entry.OldPath != path {
continue
}
if params.LineStartNew && path == entry.OldPath {
msg := "for renamed files provide the new file name if commenting the changed lines"
return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg)
}
if !params.LineStartNew && path == entry.Path {
msg := "for renamed files provide the old file name if commenting the old lines"
return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg)
}
} else if entry.Path != path {
// All other statuses output just one path: If the path doesn't match it, proceed with the next entry.
continue
}
rawFileMode := entry.OldFileMode
if params.LineStartNew {
rawFileMode = entry.NewFileMode
}
fileType, _, err := parseTreeNodeMode(rawFileMode)
if err != nil {
return parser.HunkHeader{}, parser.Hunk{},
fmt.Errorf("failed to parse file mode %s for path %s: %w", rawFileMode, path, err)
}
switch fileType {
default:
return parser.HunkHeader{}, parser.Hunk{}, errors.Internal(nil, "unrecognized object type")
case TreeNodeTypeCommit:
msg := "code comment is not allowed on a submodule"
return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg)
case TreeNodeTypeTree:
msg := "code comment is not allowed on a directory"
return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg)
case TreeNodeTypeBlob:
// a blob is what we want
}
var hunkHeader parser.HunkHeader
var hunk parser.Hunk
switch entry.Status {
case parser.DiffStatusRenamed, parser.DiffStatusCopied, parser.DiffStatusModified:
// For modified and renamed compare file blob SHAs directly.
oldSHA = entry.OldBlobSHA
newSHA = entry.NewBlobSHA
hunkHeader, hunk, err = g.diffCutFromHunk(ctx, repoPath, oldSHA, newSHA, ignoreWhitespace, params)
case parser.DiffStatusAdded, parser.DiffStatusDeleted, parser.DiffStatusType:
// for added and deleted files read the file content directly
if params.LineStartNew {
hunkHeader, hunk, err = g.diffCutFromBlob(ctx, repoPath, true, entry.NewBlobSHA, params)
} else {
hunkHeader, hunk, err = g.diffCutFromBlob(ctx, repoPath, false, entry.OldBlobSHA, params)
}
default:
return parser.HunkHeader{}, parser.Hunk{},
fmt.Errorf("unrecognized git diff file status=%c for path=%s", entry.Status, path)
}
if err != nil {
return parser.HunkHeader{}, parser.Hunk{},
fmt.Errorf("failed to extract hunk for git diff file status=%c path=%s: %w", entry.Status, path, err)
}
// The returned diff hunk will be stored in the DB and will only be used for display, as a reference.
// Therefore, we trim too long lines to protect the system and the DB.
const maxLineLen = 200
parser.LimitLineLen(&hunk.Lines, maxLineLen)
return hunkHeader, hunk, nil
}
return parser.HunkHeader{}, parser.Hunk{}, errors.NotFound("path not found")
}
func (g *Git) diffCutFromHunk(
ctx context.Context,
repoPath string,
oldSHA string,
newSHA string,
ignoreWhitespace bool,
params parser.DiffCutParams,
) (parser.HunkHeader, parser.Hunk, error) {
pipeRead, pipeWrite := io.Pipe()
stderr := bytes.NewBuffer(nil)
go func() {
var err error
defer func() {
// If running of the command below fails, make the pipe reader also fail with the same error.
_ = pipeWrite.CloseWithError(err)
}()
cmd := command.New("diff",
command.WithFlag("--patch"),
command.WithFlag("--full-index"),
command.WithFlag("--no-color"),
command.WithFlag("--unified=100000000"),
command.WithArg(oldSHA),
command.WithArg(newSHA))
if ignoreWhitespace {
// Ignore whitespace when comparing lines.
cmd.Add(command.WithFlag("-w"))
}
err = cmd.Run(ctx,
command.WithDir(repoPath),
command.WithStdout(pipeWrite),
command.WithStderr(stderr))
}()
diffCutHeader, linesHunk, err := parser.DiffCut(pipeRead, params)
if errStderr := parseDiffStderr(stderr); errStderr != nil {
// First check if there's something in the stderr buffer, if yes that's the error
return parser.HunkHeader{}, parser.Hunk{}, errStderr
}
if err != nil {
// Next check if reading the git diff output caused an error
return parser.HunkHeader{}, parser.Hunk{}, err
}
return diffCutHeader, linesHunk, nil
}
func (g *Git) diffCutFromBlob(
ctx context.Context,
repoPath string,
asAdded bool,
sha string,
params parser.DiffCutParams,
) (parser.HunkHeader, parser.Hunk, error) {
pipeRead, pipeWrite := io.Pipe()
go func() {
var err error
defer func() {
// If running of the command below fails, make the pipe reader also fail with the same error.
_ = pipeWrite.CloseWithError(err)
}()
cmd := command.New("cat-file",
command.WithFlag("-p"),
command.WithArg(sha))
err = cmd.Run(ctx,
command.WithDir(repoPath),
command.WithStdout(pipeWrite))
}()
cutHeader, cut, err := parser.BlobCut(pipeRead, params)
if err != nil {
// Next check if reading the git diff output caused an error
return parser.HunkHeader{}, parser.Hunk{}, err
}
// Convert parser.CutHeader to parser.HunkHeader and parser.Cut to parser.Hunk.
var hunkHeader parser.HunkHeader
var hunk parser.Hunk
if asAdded {
for i := range cut.Lines {
cut.Lines[i] = "+" + cut.Lines[i]
}
hunkHeader = parser.HunkHeader{
NewLine: cutHeader.Line,
NewSpan: cutHeader.Span,
}
hunk = parser.Hunk{
HunkHeader: parser.HunkHeader{NewLine: cut.Line, NewSpan: cut.Span},
Lines: cut.Lines,
}
} else {
for i := range cut.Lines {
cut.Lines[i] = "-" + cut.Lines[i]
}
hunkHeader = parser.HunkHeader{
OldLine: cutHeader.Line,
OldSpan: cutHeader.Span,
}
hunk = parser.Hunk{
HunkHeader: parser.HunkHeader{OldLine: cut.Line, OldSpan: cut.Span},
Lines: cut.Lines,
}
}
return hunkHeader, hunk, nil
}
func (g *Git) DiffFileName(ctx context.Context,
repoPath string,
baseRef string,
headRef string,
mergeBase bool,
ignoreWhitespace bool,
) ([]string, error) {
cmd := command.New("diff", command.WithFlag("--name-only"))
if mergeBase {
cmd.Add(command.WithFlag("--merge-base"))
}
cmd.Add(command.WithArg(baseRef, headRef))
if ignoreWhitespace {
// Ignore whitespace when comparing lines.
cmd.Add(command.WithFlag("-w"))
}
stdout := &bytes.Buffer{}
err := cmd.Run(ctx,
command.WithDir(repoPath),
command.WithStdout(stdout),
)
if err != nil {
return nil, processGitErrorf(err, "failed to trigger diff command")
}
return parseLinesToSlice(stdout.Bytes()), nil
}
// GetDiffShortStat counts number of changed files, number of additions and deletions.
func GetDiffShortStat(
ctx context.Context,
repoPath string,
ignoreWhitespace bool,
args ...string,
) (DiffShortStat, error) {
// Now if we call:
// $ git diff --shortstat 1ebb35b98889ff77299f24d82da426b434b0cca0...788b8b1440462d477f45b0088875
// we get:
// " 9902 files changed, 2034198 insertions(+), 298800 deletions(-)\n"
cmd := command.New("diff",
command.WithFlag("--shortstat"),
command.WithArg(args...),
)
if ignoreWhitespace {
// Ignore whitespace when comparing lines.
cmd.Add(command.WithFlag("-w"))
}
stdout := &bytes.Buffer{}
if err := cmd.Run(ctx,
command.WithDir(repoPath),
command.WithStdout(stdout),
); err != nil {
return DiffShortStat{}, err
}
return parseDiffStat(stdout.String())
}
var shortStatFormat = regexp.MustCompile(
`\s*(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?`)
func parseDiffStat(stdout string) (stat DiffShortStat, err error) {
if len(stdout) == 0 || stdout == "\n" {
return DiffShortStat{}, nil
}
groups := shortStatFormat.FindStringSubmatch(stdout)
if len(groups) != 4 {
return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s groups: %s", stdout, groups)
}
stat.Files, err = strconv.Atoi(groups[1])
if err != nil {
return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s. Error parsing NumFiles %w",
stdout, err)
}
if len(groups[2]) != 0 {
stat.Additions, err = strconv.Atoi(groups[2])
if err != nil {
return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s. Error parsing NumAdditions %w",
stdout, err)
}
}
if len(groups[3]) != 0 {
stat.Deletions, err = strconv.Atoi(groups[3])
if err != nil {
return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s. Error parsing NumDeletions %w",
stdout, err)
}
}
return stat, nil
}
func parseDiffStderr(stderr *bytes.Buffer) error {
errRaw := stderr.String() // assume there will never be a lot of output to stdout
if len(errRaw) == 0 {
return nil
}
if idx := strings.IndexByte(errRaw, '\n'); idx > 0 {
errRaw = errRaw[:idx] // get only the first line of the output
}
errRaw = strings.TrimPrefix(errRaw, "fatal: ") // git errors start with the "fatal: " prefix
if strings.Contains(errRaw, "bad revision") {
return parser.ErrSHADoesNotMatch
}
return errors.New(errRaw)
}
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 によって変換されたページ (->オリジナル) /