2014-04-13 07:05:36 +05:30
// Copyright 2014 The Gogs Authors. All rights reserved.
2019-09-06 07:50:09 +05:30
// Copyright 2019 The Gitea Authors. All rights reserved.
2022-11-27 23:50:29 +05:30
// SPDX-License-Identifier: MIT
2014-04-13 07:05:36 +05:30
2019-09-06 07:50:09 +05:30
package gitdiff
2014-04-13 07:05:36 +05:30
import (
"bufio"
2014-12-09 12:48:25 +05:30
"bytes"
2024-03-24 17:14:30 +05:30
"cmp"
2019-11-30 20:10:22 +05:30
"context"
2014-06-19 10:38:03 +05:30
"fmt"
2020-12-27 03:28:21 +05:30
"html"
2016-01-09 12:21:17 +05:30
"html/template"
2014-04-13 07:05:36 +05:30
"io"
2019-11-15 08:22:59 +05:30
"net/url"
2014-04-13 07:05:36 +05:30
"strings"
2021-08-31 09:46:23 +05:30
"time"
2014-04-13 07:05:36 +05:30
2021-09-19 17:19:59 +05:30
"code.gitea.io/gitea/models/db"
2022-06-12 21:21:54 +05:30
git_model "code.gitea.io/gitea/models/git"
2022-06-13 15:07:59 +05:30
issues_model "code.gitea.io/gitea/models/issues"
2022-05-07 23:58:10 +05:30
pull_model "code.gitea.io/gitea/models/pull"
2021-11-24 15:19:20 +05:30
user_model "code.gitea.io/gitea/models/user"
2021-09-10 01:43:36 +05:30
"code.gitea.io/gitea/modules/analyze"
2019-08-15 17:37:28 +05:30
"code.gitea.io/gitea/modules/charset"
2019-03-27 15:03:00 +05:30
"code.gitea.io/gitea/modules/git"
2016-12-06 23:28:31 +05:30
"code.gitea.io/gitea/modules/highlight"
2021-04-09 03:55:57 +05:30
"code.gitea.io/gitea/modules/lfs"
2016-11-10 21:54:48 +05:30
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
2022-08-14 00:02:34 +05:30
"code.gitea.io/gitea/modules/translation"
2019-08-23 22:10:30 +05:30
2016-11-05 22:26:35 +05:30
"github.com/sergi/go-diff/diffmatchpatch"
2019-08-15 17:37:28 +05:30
stdcharset "golang.org/x/net/html/charset"
2021-07-13 06:43:52 +05:30
"golang.org/x/text/encoding"
2016-11-05 22:26:35 +05:30
"golang.org/x/text/transform"
2014-04-13 07:05:36 +05:30
)
2022-07-23 16:58:02 +05:30
// DiffLineType represents the type of DiffLine.
2016-01-07 01:30:40 +05:30
type DiffLineType uint8
2016-11-22 16:38:23 +05:30
// DiffLineType possible values.
2014-04-13 07:05:36 +05:30
const (
2016-11-07 21:54:59 +05:30
DiffLinePlain DiffLineType = iota + 1
DiffLineAdd
DiffLineDel
2016-11-07 22:03:03 +05:30
DiffLineSection
2014-04-13 07:05:36 +05:30
)
2022-07-23 16:58:02 +05:30
// DiffFileType represents the type of DiffFile.
2016-01-07 01:30:40 +05:30
type DiffFileType uint8
2016-11-22 16:38:23 +05:30
// DiffFileType possible values.
2014-04-13 07:05:36 +05:30
const (
2016-11-07 21:54:59 +05:30
DiffFileAdd DiffFileType = iota + 1
DiffFileChange
DiffFileDel
2016-11-07 22:03:03 +05:30
DiffFileRename
2020-09-09 18:38:40 +05:30
DiffFileCopy
2014-04-13 07:05:36 +05:30
)
2019-11-15 08:22:59 +05:30
// DiffLineExpandDirection represents the DiffLineSection expand direction
type DiffLineExpandDirection uint8
// DiffLineExpandDirection possible values.
const (
DiffLineExpandNone DiffLineExpandDirection = iota + 1
DiffLineExpandSingle
DiffLineExpandUpDown
DiffLineExpandUp
DiffLineExpandDown
)
2016-11-24 14:00:08 +05:30
// DiffLine represents a line difference in a DiffSection.
2014-04-13 07:05:36 +05:30
type DiffLine struct {
2024-02-16 17:46:11 +05:30
LeftIdx int
RightIdx int
Match int
Type DiffLineType
Content string
Conversations [ ] issues_model . CodeConversation
SectionInfo * DiffLineSectionInfo
2019-11-15 08:22:59 +05:30
}
// DiffLineSectionInfo represents diff line section meta data
type DiffLineSectionInfo struct {
Path string
LastLeftIdx int
LastRightIdx int
LeftIdx int
RightIdx int
LeftHunkSize int
RightHunkSize int
2014-04-13 07:05:36 +05:30
}
2020-08-20 20:23:06 +05:30
// BlobExcerptChunkSize represent max lines of excerpt
const BlobExcerptChunkSize = 20
2019-11-15 08:22:59 +05:30
2022-07-23 16:58:02 +05:30
// GetType returns the type of DiffLine.
2016-01-07 01:30:40 +05:30
func ( d * DiffLine ) GetType ( ) int {
return int ( d . Type )
2014-04-13 07:05:36 +05:30
}
2023-05-07 15:19:46 +05:30
// GetHTMLDiffLineType returns the diff line type name for HTML
func ( d * DiffLine ) GetHTMLDiffLineType ( ) string {
switch d . Type {
case DiffLineAdd :
return "add"
case DiffLineDel :
return "del"
case DiffLineSection :
return "tag"
}
return "same"
}
2022-07-23 16:58:02 +05:30
// CanComment returns whether a line can get commented
2018-08-06 10:13:22 +05:30
func ( d * DiffLine ) CanComment ( ) bool {
2024-02-16 17:46:11 +05:30
return len ( d . Conversations ) == 0 && d . Type != DiffLineSection
2018-08-06 10:13:22 +05:30
}
// GetCommentSide returns the comment side of the first comment, if not set returns empty string
func ( d * DiffLine ) GetCommentSide ( ) string {
2024-02-16 17:46:11 +05:30
if len ( d . Conversations ) == 0 || len ( d . Conversations [ 0 ] ) == 0 {
2018-08-06 10:13:22 +05:30
return ""
}
2024-02-16 17:46:11 +05:30
return d . Conversations [ 0 ] [ 0 ] . DiffSide ( )
2018-08-06 10:13:22 +05:30
}
2019-06-25 01:53:52 +05:30
// GetLineTypeMarker returns the line type marker
func ( d * DiffLine ) GetLineTypeMarker ( ) string {
if strings . IndexByte ( " +-" , d . Content [ 0 ] ) > - 1 {
return d . Content [ 0 : 1 ]
}
return ""
}
2019-11-15 08:22:59 +05:30
// GetBlobExcerptQuery builds query string to get blob excerpt
func ( d * DiffLine ) GetBlobExcerptQuery ( ) string {
query := fmt . Sprintf (
"last_left=%d&last_right=%d&" +
"left=%d&right=%d&" +
"left_hunk_size=%d&right_hunk_size=%d&" +
"path=%s" ,
d . SectionInfo . LastLeftIdx , d . SectionInfo . LastRightIdx ,
d . SectionInfo . LeftIdx , d . SectionInfo . RightIdx ,
d . SectionInfo . LeftHunkSize , d . SectionInfo . RightHunkSize ,
url . QueryEscape ( d . SectionInfo . Path ) )
return query
}
// GetExpandDirection gets DiffLineExpandDirection
func ( d * DiffLine ) GetExpandDirection ( ) DiffLineExpandDirection {
Fix incorrect diff expander for deletion of last lines in a file (#29501)
Fixes: https://github.com/go-gitea/gitea/issues/29498
I don't quite understand this code, but this change does seem to fix the
issue and I tested a number of diffs with it and saw no issue. The
function gets such value if last line is an addition:
```
LastLeftIdx: (int) 0,
LastRightIdx: (int) 47,
LeftIdx: (int) 47,
RightIdx: (int) 48,
```
If it's a deletion, it gets:
```
LastLeftIdx: (int) 47,
LastRightIdx: (int) 0,
LeftIdx: (int) 48,
RightIdx: (int) 47,
```
So I think it's correct to make this check respect both left and right
side.
(cherry picked from commit 3b99066aa866e51e6a610716eaddfd1ea3645a67)
2024-03-01 21:42:21 +05:30
if d . Type != DiffLineSection || d . SectionInfo == nil || d . SectionInfo . LeftIdx - d . SectionInfo . LastLeftIdx <= 1 || d . SectionInfo . RightIdx - d . SectionInfo . LastRightIdx <= 1 {
2019-11-15 08:22:59 +05:30
return DiffLineExpandNone
}
if d . SectionInfo . LastLeftIdx <= 0 && d . SectionInfo . LastRightIdx <= 0 {
return DiffLineExpandUp
2020-08-20 20:23:06 +05:30
} else if d . SectionInfo . RightIdx - d . SectionInfo . LastRightIdx > BlobExcerptChunkSize && d . SectionInfo . RightHunkSize > 0 {
2019-11-15 08:22:59 +05:30
return DiffLineExpandUpDown
} else if d . SectionInfo . LeftHunkSize <= 0 && d . SectionInfo . RightHunkSize <= 0 {
return DiffLineExpandDown
}
return DiffLineExpandSingle
}
2020-01-23 22:58:15 +05:30
func getDiffLineSectionInfo ( treePath , line string , lastLeftIdx , lastRightIdx int ) * DiffLineSectionInfo {
2020-01-28 13:32:03 +05:30
leftLine , leftHunk , rightLine , righHunk := git . ParseDiffHunkString ( line )
2020-01-23 22:58:15 +05:30
2019-11-15 08:22:59 +05:30
return & DiffLineSectionInfo {
2020-01-23 22:58:15 +05:30
Path : treePath ,
2019-11-15 08:22:59 +05:30
LastLeftIdx : lastLeftIdx ,
LastRightIdx : lastRightIdx ,
LeftIdx : leftLine ,
RightIdx : rightLine ,
LeftHunkSize : leftHunk ,
RightHunkSize : righHunk ,
}
}
2019-06-27 03:05:07 +05:30
// escape a line's content or return <br> needed for copy/paste purposes
2022-08-14 00:02:34 +05:30
func getLineContent ( content string , locale translation . Locale ) DiffInline {
2019-06-27 03:05:07 +05:30
if len ( content ) > 0 {
2022-08-14 00:02:34 +05:30
return DiffInlineWithUnicodeEscape ( template . HTML ( html . EscapeString ( content ) ) , locale )
2019-06-27 03:05:07 +05:30
}
2022-08-14 00:02:34 +05:30
return DiffInline { EscapeStatus : & charset . EscapeStatus { } , Content : "<br>" }
2019-06-27 03:05:07 +05:30
}
2016-11-24 14:00:08 +05:30
// DiffSection represents a section of a DiffFile.
2014-04-13 07:05:36 +05:30
type DiffSection struct {
2021-11-18 02:07:00 +05:30
file * DiffFile
2020-07-01 03:04:03 +05:30
FileName string
Name string
Lines [ ] * DiffLine
2014-04-13 07:05:36 +05:30
}
2016-01-09 12:21:17 +05:30
var (
2019-06-25 01:53:52 +05:30
addedCodePrefix = [ ] byte ( ` <span class="added-code"> ` )
removedCodePrefix = [ ] byte ( ` <span class="removed-code"> ` )
codeTagSuffix = [ ] byte ( ` </span> ` )
2016-01-09 12:21:17 +05:30
)
2021-02-14 20:21:00 +05:30
2022-07-23 16:58:02 +05:30
func diffToHTML ( lineWrapperTags [ ] string , diffs [ ] diffmatchpatch . Diff , lineType DiffLineType ) string {
2016-08-07 22:19:47 +05:30
buf := bytes . NewBuffer ( nil )
2022-07-23 16:58:02 +05:30
// restore the line wrapper tags <span class="line"> and <span class="cl">, if necessary
for _ , tag := range lineWrapperTags {
buf . WriteString ( tag )
}
2020-10-22 03:44:44 +05:30
for _ , diff := range diffs {
switch {
case diff . Type == diffmatchpatch . DiffEqual :
buf . WriteString ( diff . Text )
case diff . Type == diffmatchpatch . DiffInsert && lineType == DiffLineAdd :
2016-01-09 12:21:17 +05:30
buf . Write ( addedCodePrefix )
2020-10-22 03:44:44 +05:30
buf . WriteString ( diff . Text )
2016-01-09 12:21:17 +05:30
buf . Write ( codeTagSuffix )
2020-10-22 03:44:44 +05:30
case diff . Type == diffmatchpatch . DiffDelete && lineType == DiffLineDel :
2016-01-09 12:21:17 +05:30
buf . Write ( removedCodePrefix )
2020-10-22 03:44:44 +05:30
buf . WriteString ( diff . Text )
2016-01-09 12:21:17 +05:30
buf . Write ( codeTagSuffix )
2016-01-04 02:56:46 +05:30
}
}
2022-07-23 16:58:02 +05:30
for range lineWrapperTags {
buf . WriteString ( "</span>" )
}
return buf . String ( )
2016-01-04 02:56:46 +05:30
}
2016-11-22 16:38:23 +05:30
// GetLine gets a specific line by type (add or del) and file line number
2016-01-08 18:20:25 +05:30
func ( diffSection * DiffSection ) GetLine ( lineType DiffLineType , idx int ) * DiffLine {
2016-08-07 22:19:47 +05:30
var (
difference = 0
addCount = 0
delCount = 0
matchDiffLine * DiffLine
)
LOOP :
2016-01-08 18:20:25 +05:30
for _ , diffLine := range diffSection . Lines {
2016-08-07 22:19:47 +05:30
switch diffLine . Type {
2016-11-07 21:54:59 +05:30
case DiffLineAdd :
2016-08-07 22:19:47 +05:30
addCount ++
2016-11-07 21:54:59 +05:30
case DiffLineDel :
2016-08-07 22:19:47 +05:30
delCount ++
default :
if matchDiffLine != nil {
break LOOP
}
2016-01-08 18:20:25 +05:30
difference = diffLine . RightIdx - diffLine . LeftIdx
2016-08-07 22:19:47 +05:30
addCount = 0
delCount = 0
2016-01-04 02:56:46 +05:30
}
2016-08-07 22:19:47 +05:30
switch lineType {
2016-11-07 21:54:59 +05:30
case DiffLineDel :
2016-01-09 12:21:17 +05:30
if diffLine . RightIdx == 0 && diffLine . LeftIdx == idx - difference {
2016-08-07 22:19:47 +05:30
matchDiffLine = diffLine
2016-01-08 18:20:25 +05:30
}
2016-11-07 21:54:59 +05:30
case DiffLineAdd :
2016-01-09 12:21:17 +05:30
if diffLine . LeftIdx == 0 && diffLine . RightIdx == idx + difference {
2016-08-07 22:19:47 +05:30
matchDiffLine = diffLine
2016-01-04 02:56:46 +05:30
}
}
}
2016-08-07 22:19:47 +05:30
if addCount == delCount {
return matchDiffLine
}
2016-01-04 02:56:46 +05:30
return nil
}
2016-08-07 22:19:47 +05:30
var diffMatchPatch = diffmatchpatch . New ( )
func init ( ) {
diffMatchPatch . DiffEditCost = 100
}
2022-01-07 06:48:52 +05:30
// DiffInline is a struct that has a content and escape status
type DiffInline struct {
2022-08-14 00:02:34 +05:30
EscapeStatus * charset . EscapeStatus
2022-01-07 06:48:52 +05:30
Content template . HTML
}
// DiffInlineWithUnicodeEscape makes a DiffInline with hidden unicode characters escaped
2022-08-14 00:02:34 +05:30
func DiffInlineWithUnicodeEscape ( s template . HTML , locale translation . Locale ) DiffInline {
2024-02-22 02:48:44 +05:30
status , content := charset . EscapeControlHTML ( s , locale , charset . DiffContext )
2023-12-17 20:08:54 +05:30
return DiffInline { EscapeStatus : status , Content : content }
2022-01-07 06:48:52 +05:30
}
// DiffInlineWithHighlightCode makes a DiffInline with code highlight and hidden unicode characters escaped
2022-08-14 00:02:34 +05:30
func DiffInlineWithHighlightCode ( fileName , language , code string , locale translation . Locale ) DiffInline {
2022-11-19 16:38:06 +05:30
highlighted , _ := highlight . Code ( fileName , language , code )
2024-02-22 02:48:44 +05:30
status , content := charset . EscapeControlHTML ( highlighted , locale , charset . DiffContext )
2023-12-17 20:08:54 +05:30
return DiffInline { EscapeStatus : status , Content : content }
2022-01-07 06:48:52 +05:30
}
2016-11-22 16:38:23 +05:30
// GetComputedInlineDiffFor computes inline diff for the given line.
2022-08-14 00:02:34 +05:30
func ( diffSection * DiffSection ) GetComputedInlineDiffFor ( diffLine * DiffLine , locale translation . Locale ) DiffInline {
2016-08-07 22:19:47 +05:30
if setting . Git . DisableDiffHighlight {
2022-08-14 00:02:34 +05:30
return getLineContent ( diffLine . Content [ 1 : ] , locale )
2016-01-28 02:24:08 +05:30
}
2020-07-01 03:04:03 +05:30
2016-08-07 22:19:47 +05:30
var (
compareDiffLine * DiffLine
diff1 string
diff2 string
)
2016-01-04 02:56:46 +05:30
2021-11-18 02:07:00 +05:30
language := ""
if diffSection . file != nil {
language = diffSection . file . Language
}
2016-01-28 02:24:08 +05:30
// try to find equivalent diff line. ignore, otherwise
2016-08-07 22:19:47 +05:30
switch diffLine . Type {
2020-07-01 03:04:03 +05:30
case DiffLineSection :
2022-08-14 00:02:34 +05:30
return getLineContent ( diffLine . Content [ 1 : ] , locale )
2016-11-07 21:54:59 +05:30
case DiffLineAdd :
compareDiffLine = diffSection . GetLine ( DiffLineDel , diffLine . RightIdx )
2016-01-28 02:24:08 +05:30
if compareDiffLine == nil {
2022-08-14 00:02:34 +05:30
return DiffInlineWithHighlightCode ( diffSection . FileName , language , diffLine . Content [ 1 : ] , locale )
2016-01-28 02:24:08 +05:30
}
diff1 = compareDiffLine . Content
diff2 = diffLine . Content
2016-11-07 21:54:59 +05:30
case DiffLineDel :
compareDiffLine = diffSection . GetLine ( DiffLineAdd , diffLine . LeftIdx )
2016-01-28 02:24:08 +05:30
if compareDiffLine == nil {
2022-08-14 00:02:34 +05:30
return DiffInlineWithHighlightCode ( diffSection . FileName , language , diffLine . Content [ 1 : ] , locale )
2016-01-04 02:56:46 +05:30
}
2016-01-28 02:24:08 +05:30
diff1 = diffLine . Content
diff2 = compareDiffLine . Content
2016-08-07 22:19:47 +05:30
default :
2019-06-25 01:53:52 +05:30
if strings . IndexByte ( " +-" , diffLine . Content [ 0 ] ) > - 1 {
2022-08-14 00:02:34 +05:30
return DiffInlineWithHighlightCode ( diffSection . FileName , language , diffLine . Content [ 1 : ] , locale )
2019-06-25 01:53:52 +05:30
}
2022-08-14 00:02:34 +05:30
return DiffInlineWithHighlightCode ( diffSection . FileName , language , diffLine . Content , locale )
2016-01-28 02:24:08 +05:30
}
2016-01-04 02:56:46 +05:30
2022-07-23 16:58:02 +05:30
hcd := newHighlightCodeDiff ( )
diffRecord := hcd . diffWithHighlight ( diffSection . FileName , language , diff1 [ 1 : ] , diff2 [ 1 : ] )
// it seems that Gitea doesn't need the line wrapper of Chroma, so do not add them back
// if the line wrappers are still needed in the future, it can be added back by "diffToHTML(hcd.lineWrapperTags. ...)"
diffHTML := diffToHTML ( nil , diffRecord , diffLine . Type )
2022-08-14 00:02:34 +05:30
return DiffInlineWithUnicodeEscape ( template . HTML ( diffHTML ) , locale )
2016-01-04 02:56:46 +05:30
}
2016-11-24 14:00:08 +05:30
// DiffFile represents a file diff.
2014-04-13 07:05:36 +05:30
type DiffFile struct {
2022-05-07 23:58:10 +05:30
Name string
2022-05-09 03:59:50 +05:30
NameHash string
2022-05-07 23:58:10 +05:30
OldName string
Index int
Addition , Deletion int
Type DiffFileType
IsCreated bool
IsDeleted bool
IsBin bool
IsLFSFile bool
IsRenamed bool
IsAmbiguous bool
IsSubmodule bool
Sections [ ] * DiffSection
IsIncomplete bool
IsIncompleteLineTooLong bool
IsProtected bool
IsGenerated bool
IsVendored bool
IsViewed bool // User specific
HasChangedSinceLastReview bool // User specific
Language string
2023-05-29 23:26:08 +05:30
Mode string
OldMode string
2014-04-13 07:05:36 +05:30
}
2016-11-22 16:38:23 +05:30
// GetType returns type of diff file.
2016-01-07 01:30:40 +05:30
func ( diffFile * DiffFile ) GetType ( ) int {
return int ( diffFile . Type )
}
2019-11-15 08:22:59 +05:30
// GetTailSection creates a fake DiffLineSection if the last section is not the end of the file
func ( diffFile * DiffFile ) GetTailSection ( gitRepo * git . Repository , leftCommitID , rightCommitID string ) * DiffSection {
2020-01-22 12:50:58 +05:30
if len ( diffFile . Sections ) == 0 || diffFile . Type != DiffFileChange || diffFile . IsBin || diffFile . IsLFSFile {
2019-11-15 08:22:59 +05:30
return nil
}
leftCommit , err := gitRepo . GetCommit ( leftCommitID )
if err != nil {
return nil
}
rightCommit , err := gitRepo . GetCommit ( rightCommitID )
if err != nil {
return nil
}
lastSection := diffFile . Sections [ len ( diffFile . Sections ) - 1 ]
lastLine := lastSection . Lines [ len ( lastSection . Lines ) - 1 ]
leftLineCount := getCommitFileLineCount ( leftCommit , diffFile . Name )
rightLineCount := getCommitFileLineCount ( rightCommit , diffFile . Name )
if leftLineCount <= lastLine . LeftIdx || rightLineCount <= lastLine . RightIdx {
return nil
}
tailDiffLine := & DiffLine {
Type : DiffLineSection ,
Content : " " ,
SectionInfo : & DiffLineSectionInfo {
Path : diffFile . Name ,
LastLeftIdx : lastLine . LeftIdx ,
LastRightIdx : lastLine . RightIdx ,
LeftIdx : leftLineCount ,
RightIdx : rightLineCount ,
2022-01-20 23:16:10 +05:30
} ,
}
2020-07-01 03:04:03 +05:30
tailSection := & DiffSection { FileName : diffFile . Name , Lines : [ ] * DiffLine { tailDiffLine } }
2019-11-15 08:22:59 +05:30
return tailSection
}
2022-05-07 23:58:10 +05:30
// GetDiffFileName returns the name of the diff file, or its old name in case it was deleted
func ( diffFile * DiffFile ) GetDiffFileName ( ) string {
if diffFile . Name == "" {
return diffFile . OldName
}
return diffFile . Name
}
func ( diffFile * DiffFile ) ShouldBeHidden ( ) bool {
return diffFile . IsGenerated || diffFile . IsViewed
}
2023-08-07 01:22:34 +05:30
func ( diffFile * DiffFile ) ModeTranslationKey ( mode string ) string {
switch mode {
case "040000" :
return "git.filemode.directory"
case "100644" :
return "git.filemode.normal_file"
case "100755" :
return "git.filemode.executable_file"
case "120000" :
return "git.filemode.symbolic_link"
case "160000" :
return "git.filemode.submodule"
default :
return mode
}
}
2019-11-15 08:22:59 +05:30
func getCommitFileLineCount ( commit * git . Commit , filePath string ) int {
blob , err := commit . GetBlobByPath ( filePath )
if err != nil {
return 0
}
lineCount , err := blob . GetBlobLineCount ( )
if err != nil {
return 0
}
return lineCount
}
2016-11-24 14:00:08 +05:30
// Diff represents a difference between two git trees.
2014-04-13 07:05:36 +05:30
type Diff struct {
2022-05-07 23:58:10 +05:30
Start , End string
NumFiles int
TotalAddition , TotalDeletion int
Files [ ] * DiffFile
IsIncomplete bool
NumViewedFiles int // user-specific
2014-04-13 07:05:36 +05:30
}
2018-08-06 10:13:22 +05:30
// LoadComments loads comments into each line
2023-06-21 21:38:12 +05:30
func ( diff * Diff ) LoadComments ( ctx context . Context , issue * issues_model . Issue , currentUser * user_model . User , showOutdatedComments bool ) error {
2024-02-16 17:46:11 +05:30
allConversations , err := issues_model . FetchCodeConversations ( ctx , issue , currentUser , showOutdatedComments )
2018-08-06 10:13:22 +05:30
if err != nil {
return err
}
for _ , file := range diff . Files {
2024-02-16 17:46:11 +05:30
if lineCommits , ok := allConversations [ file . Name ] ; ok {
2018-08-06 10:13:22 +05:30
for _ , section := range file . Sections {
for _ , line := range section . Lines {
2024-02-16 17:46:11 +05:30
if conversations , ok := lineCommits [ int64 ( line . LeftIdx * - 1 ) ] ; ok {
line . Conversations = append ( line . Conversations , conversations ... )
2018-08-06 10:13:22 +05:30
}
if comments , ok := lineCommits [ int64 ( line . RightIdx ) ] ; ok {
2024-02-16 17:46:11 +05:30
line . Conversations = append ( line . Conversations , comments ... )
2018-08-06 10:13:22 +05:30
}
}
}
}
}
return nil
}
2016-11-22 16:38:23 +05:30
const cmdDiffHead = "diff --git "
2014-04-13 07:05:36 +05:30
2020-10-16 22:43:18 +05:30
// ParsePatch builds a Diff object from a io.Reader and some parameters.
2023-10-03 16:00:41 +05:30
func ParsePatch ( ctx context . Context , maxLines , maxLineCharacters , maxFiles int , reader io . Reader , skipToFile string ) ( * Diff , error ) {
2021-11-21 22:21:08 +05:30
log . Debug ( "ParsePatch(%d, %d, %d, ..., %s)" , maxLines , maxLineCharacters , maxFiles , skipToFile )
2020-10-16 22:43:18 +05:30
var curFile * DiffFile
2021-11-20 19:20:00 +05:30
skipping := skipToFile != ""
2020-10-16 22:43:18 +05:30
diff := & Diff { Files : make ( [ ] * DiffFile , 0 ) }
sb := strings . Builder { }
// OK let's set a reasonable buffer size.
2023-03-06 07:07:58 +05:30
// This should be at least the size of maxLineCharacters or 4096 whichever is larger.
2020-10-16 22:43:18 +05:30
readerSize := maxLineCharacters
if readerSize < 4096 {
readerSize = 4096
}
input := bufio . NewReaderSize ( reader , readerSize )
line , err := input . ReadString ( '\n' )
if err != nil {
if err == io . EOF {
return diff , nil
}
return diff , err
}
2023-05-29 23:26:08 +05:30
prepareValue := func ( s , p string ) string {
return strings . TrimSpace ( strings . TrimPrefix ( s , p ) )
}
2020-10-16 22:43:18 +05:30
parsingLoop :
for {
// 1. A patch file always begins with `diff --git ` + `a/path b/path` (possibly quoted)
// if it does not we have bad input!
if ! strings . HasPrefix ( line , cmdDiffHead ) {
2021-11-20 19:20:00 +05:30
return diff , fmt . Errorf ( "invalid first file line: %s" , line )
2014-04-13 07:05:36 +05:30
}
2021-11-21 22:21:08 +05:30
if maxFiles > - 1 && len ( diff . Files ) >= maxFiles {
2021-10-15 21:35:33 +05:30
lastFile := createDiffFile ( diff , line )
diff . End = lastFile . Name
2020-10-16 22:43:18 +05:30
diff . IsIncomplete = true
2021-09-22 11:08:34 +05:30
_ , err := io . Copy ( io . Discard , reader )
2020-10-16 22:43:18 +05:30
if err != nil {
// By the definition of io.Copy this never returns io.EOF
2021-11-20 19:20:00 +05:30
return diff , fmt . Errorf ( "error during io.Copy: %w" , err )
2020-10-16 22:43:18 +05:30
}
break parsingLoop
}
2014-04-13 07:05:36 +05:30
2020-10-16 22:43:18 +05:30
curFile = createDiffFile ( diff , line )
2021-11-20 19:20:00 +05:30
if skipping {
if curFile . Name != skipToFile {
line , err = skipToNextDiffHead ( input )
if err != nil {
if err == io . EOF {
return diff , nil
}
return diff , err
}
continue
}
skipping = false
}
2020-10-16 22:43:18 +05:30
diff . Files = append ( diff . Files , curFile )
// 2. It is followed by one or more extended header lines:
//
// old mode <mode>
// new mode <mode>
// deleted file mode <mode>
// new file mode <mode>
// copy from <path>
// copy to <path>
// rename from <path>
// rename to <path>
// similarity index <number>
// dissimilarity index <number>
// index <hash>..<hash> <mode>
//
// * <mode> 6-digit octal numbers including the file type and file permission bits.
// * <path> does not include the a/ and b/ prefixes
// * <number> percentage of unchanged lines for similarity, percentage of changed
// lines dissimilarity as integer rounded down with terminal %. 100% => equal files.
// * The index line includes the blob object names before and after the change.
// The <mode> is included if the file mode does not change; otherwise, separate
// lines indicate the old and the new mode.
// 3. Following this header the "standard unified" diff format header may be encountered: (but not for every case...)
//
// --- a/<path>
// +++ b/<path>
//
// With multiple hunks
//
// @@ <hunk descriptor> @@
// +added line
// -removed line
// unchanged line
//
// 4. Binary files get:
//
// Binary files a/<path> and b/<path> differ
//
// but one of a/<path> and b/<path> could be /dev/null.
curFileLoop :
2017-11-29 04:52:24 +05:30
for {
2020-10-16 22:43:18 +05:30
line , err = input . ReadString ( '\n' )
2017-11-29 04:52:24 +05:30
if err != nil {
2020-10-16 22:43:18 +05:30
if err != io . EOF {
return diff , err
2017-11-29 04:52:24 +05:30
}
2020-10-16 22:43:18 +05:30
break parsingLoop
2017-11-29 04:52:24 +05:30
}
2023-05-29 23:26:08 +05:30
2020-10-16 22:43:18 +05:30
switch {
2020-10-22 04:38:44 +05:30
case strings . HasPrefix ( line , cmdDiffHead ) :
break curFileLoop
2020-10-16 22:43:18 +05:30
case strings . HasPrefix ( line , "old mode " ) ||
strings . HasPrefix ( line , "new mode " ) :
2023-05-29 23:26:08 +05:30
if strings . HasPrefix ( line , "old mode " ) {
curFile . OldMode = prepareValue ( line , "old mode " )
}
if strings . HasPrefix ( line , "new mode " ) {
curFile . Mode = prepareValue ( line , "new mode " )
}
2020-10-16 22:43:18 +05:30
if strings . HasSuffix ( line , " 160000\n" ) {
curFile . IsSubmodule = true
}
2021-02-28 00:16:14 +05:30
case strings . HasPrefix ( line , "rename from " ) :
curFile . IsRenamed = true
curFile . Type = DiffFileRename
if curFile . IsAmbiguous {
2023-05-29 23:26:08 +05:30
curFile . OldName = prepareValue ( line , "rename from " )
2021-02-28 00:16:14 +05:30
}
case strings . HasPrefix ( line , "rename to " ) :
curFile . IsRenamed = true
curFile . Type = DiffFileRename
if curFile . IsAmbiguous {
2023-05-29 23:26:08 +05:30
curFile . Name = prepareValue ( line , "rename to " )
2021-02-28 00:16:14 +05:30
curFile . IsAmbiguous = false
}
2020-10-16 22:43:18 +05:30
case strings . HasPrefix ( line , "copy from " ) :
curFile . IsRenamed = true
curFile . Type = DiffFileCopy
2021-02-28 00:16:14 +05:30
if curFile . IsAmbiguous {
2023-05-29 23:26:08 +05:30
curFile . OldName = prepareValue ( line , "copy from " )
2021-02-28 00:16:14 +05:30
}
2020-10-16 22:43:18 +05:30
case strings . HasPrefix ( line , "copy to " ) :
curFile . IsRenamed = true
curFile . Type = DiffFileCopy
2021-02-28 00:16:14 +05:30
if curFile . IsAmbiguous {
2023-05-29 23:26:08 +05:30
curFile . Name = prepareValue ( line , "copy to " )
2021-02-28 00:16:14 +05:30
curFile . IsAmbiguous = false
}
2020-10-16 22:43:18 +05:30
case strings . HasPrefix ( line , "new file" ) :
curFile . Type = DiffFileAdd
curFile . IsCreated = true
2023-05-29 23:26:08 +05:30
if strings . HasPrefix ( line , "new file mode " ) {
curFile . Mode = prepareValue ( line , "new file mode " )
}
2020-10-16 22:43:18 +05:30
if strings . HasSuffix ( line , " 160000\n" ) {
curFile . IsSubmodule = true
}
case strings . HasPrefix ( line , "deleted" ) :
curFile . Type = DiffFileDel
curFile . IsDeleted = true
if strings . HasSuffix ( line , " 160000\n" ) {
curFile . IsSubmodule = true
}
case strings . HasPrefix ( line , "index" ) :
if strings . HasSuffix ( line , " 160000\n" ) {
curFile . IsSubmodule = true
}
case strings . HasPrefix ( line , "similarity index 100%" ) :
curFile . Type = DiffFileRename
case strings . HasPrefix ( line , "Binary" ) :
curFile . IsBin = true
case strings . HasPrefix ( line , "--- " ) :
2021-02-28 00:16:14 +05:30
// Handle ambiguous filenames
if curFile . IsAmbiguous {
2021-11-07 23:22:50 +05:30
// The shortest string that can end up here is:
2022-01-10 15:02:37 +05:30
// "--- a\t\n" without the quotes.
2021-11-07 23:22:50 +05:30
// This line has a len() of 7 but doesn't contain a oldName.
// So the amount that the line need is at least 8 or more.
// The code will otherwise panic for a out-of-bounds.
if len ( line ) > 7 && line [ 4 ] == 'a' {
2021-02-28 00:16:14 +05:30
curFile . OldName = line [ 6 : len ( line ) - 1 ]
if line [ len ( line ) - 2 ] == '\t' {
curFile . OldName = curFile . OldName [ : len ( curFile . OldName ) - 1 ]
}
} else {
curFile . OldName = ""
}
}
// Otherwise do nothing with this line
2020-10-16 22:43:18 +05:30
case strings . HasPrefix ( line , "+++ " ) :
2021-02-28 00:16:14 +05:30
// Handle ambiguous filenames
if curFile . IsAmbiguous {
if len ( line ) > 6 && line [ 4 ] == 'b' {
curFile . Name = line [ 6 : len ( line ) - 1 ]
if line [ len ( line ) - 2 ] == '\t' {
curFile . Name = curFile . Name [ : len ( curFile . Name ) - 1 ]
}
if curFile . OldName == "" {
curFile . OldName = curFile . Name
}
} else {
curFile . Name = curFile . OldName
}
curFile . IsAmbiguous = false
}
// Otherwise do nothing with this line, but now switch to parsing hunks
2023-10-03 16:00:41 +05:30
lineBytes , isFragment , err := parseHunks ( ctx , curFile , maxLines , maxLineCharacters , input )
2020-10-16 22:43:18 +05:30
diff . TotalAddition += curFile . Addition
diff . TotalDeletion += curFile . Deletion
if err != nil {
if err != io . EOF {
return diff , err
}
break parsingLoop
}
sb . Reset ( )
_ , _ = sb . Write ( lineBytes )
for isFragment {
lineBytes , isFragment , err = input . ReadLine ( )
if err != nil {
// Now by the definition of ReadLine this cannot be io.EOF
2021-11-20 19:20:00 +05:30
return diff , fmt . Errorf ( "unable to ReadLine: %w" , err )
2020-10-16 22:43:18 +05:30
}
_ , _ = sb . Write ( lineBytes )
}
line = sb . String ( )
sb . Reset ( )
break curFileLoop
2015-12-02 11:40:13 +05:30
}
}
2020-10-16 22:43:18 +05:30
}
2021-07-13 06:43:52 +05:30
// TODO: There are numerous issues with this:
2020-10-16 22:43:18 +05:30
// - we might want to consider detecting encoding while parsing but...
// - we're likely to fail to get the correct encoding here anyway as we won't have enough information
2022-01-20 23:16:10 +05:30
diffLineTypeBuffers := make ( map [ DiffLineType ] * bytes . Buffer , 3 )
diffLineTypeDecoders := make ( map [ DiffLineType ] * encoding . Decoder , 3 )
2021-07-13 06:43:52 +05:30
diffLineTypeBuffers [ DiffLinePlain ] = new ( bytes . Buffer )
diffLineTypeBuffers [ DiffLineAdd ] = new ( bytes . Buffer )
diffLineTypeBuffers [ DiffLineDel ] = new ( bytes . Buffer )
2020-10-16 22:43:18 +05:30
for _ , f := range diff . Files {
2024-05-20 20:42:50 +05:30
f . NameHash = git . HashFilePathForWebUI ( f . Name )
2022-05-09 03:59:50 +05:30
2021-07-13 06:43:52 +05:30
for _ , buffer := range diffLineTypeBuffers {
buffer . Reset ( )
}
2020-10-16 22:43:18 +05:30
for _ , sec := range f . Sections {
for _ , l := range sec . Lines {
if l . Type == DiffLineSection {
continue
}
2021-07-13 06:43:52 +05:30
diffLineTypeBuffers [ l . Type ] . WriteString ( l . Content [ 1 : ] )
diffLineTypeBuffers [ l . Type ] . WriteString ( "\n" )
2020-10-16 22:43:18 +05:30
}
}
2021-07-13 06:43:52 +05:30
for lineType , buffer := range diffLineTypeBuffers {
diffLineTypeDecoders [ lineType ] = nil
if buffer . Len ( ) == 0 {
continue
}
charsetLabel , err := charset . DetectEncoding ( buffer . Bytes ( ) )
if charsetLabel != "UTF-8" && err == nil {
encoding , _ := stdcharset . Lookup ( charsetLabel )
if encoding != nil {
diffLineTypeDecoders [ lineType ] = encoding . NewDecoder ( )
}
}
}
for _ , sec := range f . Sections {
for _ , l := range sec . Lines {
decoder := diffLineTypeDecoders [ l . Type ]
if decoder != nil {
if c , _ , err := transform . String ( decoder , l . Content [ 1 : ] ) ; err == nil {
l . Content = l . Content [ 0 : 1 ] + c
2020-10-16 22:43:18 +05:30
}
}
}
2014-09-17 09:33:03 +05:30
}
2020-10-16 22:43:18 +05:30
}
2014-09-17 09:33:03 +05:30
2020-10-16 22:43:18 +05:30
diff . NumFiles = len ( diff . Files )
return diff , nil
}
2016-12-26 06:46:37 +05:30
2021-11-20 19:20:00 +05:30
func skipToNextDiffHead ( input * bufio . Reader ) ( line string , err error ) {
// need to skip until the next cmdDiffHead
2022-06-20 15:32:49 +05:30
var isFragment , wasFragment bool
2021-11-20 19:20:00 +05:30
var lineBytes [ ] byte
for {
lineBytes , isFragment , err = input . ReadLine ( )
if err != nil {
2023-07-07 11:01:56 +05:30
return "" , err
2021-11-20 19:20:00 +05:30
}
if wasFragment {
wasFragment = isFragment
continue
}
if bytes . HasPrefix ( lineBytes , [ ] byte ( cmdDiffHead ) ) {
break
}
wasFragment = isFragment
}
line = string ( lineBytes )
if isFragment {
var tail string
tail , err = input . ReadString ( '\n' )
if err != nil {
2023-07-07 11:01:56 +05:30
return "" , err
2021-11-20 19:20:00 +05:30
}
line += tail
}
2022-06-20 15:32:49 +05:30
return line , err
2021-11-20 19:20:00 +05:30
}
2023-10-03 16:00:41 +05:30
func parseHunks ( ctx context . Context , curFile * DiffFile , maxLines , maxLineCharacters int , input * bufio . Reader ) ( lineBytes [ ] byte , isFragment bool , err error ) {
2020-10-16 22:43:18 +05:30
sb := strings . Builder { }
2016-12-26 06:46:37 +05:30
2020-10-16 22:43:18 +05:30
var (
curSection * DiffSection
curFileLinesCount int
curFileLFSPrefix bool
)
2016-12-26 06:46:37 +05:30
2021-08-29 19:58:04 +05:30
lastLeftIdx := - 1
2020-10-16 22:43:18 +05:30
leftLine , rightLine := 1 , 1
2016-12-26 06:46:37 +05:30
2020-10-16 22:43:18 +05:30
for {
2020-11-22 04:11:24 +05:30
for isFragment {
curFile . IsIncomplete = true
2021-05-04 18:28:49 +05:30
curFile . IsIncompleteLineTooLong = true
2020-11-22 04:11:24 +05:30
_ , isFragment , err = input . ReadLine ( )
if err != nil {
// Now by the definition of ReadLine this cannot be io.EOF
2023-07-07 11:01:56 +05:30
return nil , false , fmt . Errorf ( "unable to ReadLine: %w" , err )
2020-11-22 04:11:24 +05:30
}
}
2020-10-16 22:43:18 +05:30
sb . Reset ( )
lineBytes , isFragment , err = input . ReadLine ( )
if err != nil {
if err == io . EOF {
2023-07-07 11:01:56 +05:30
return lineBytes , isFragment , err
2016-12-26 06:46:37 +05:30
}
2021-11-20 19:20:00 +05:30
err = fmt . Errorf ( "unable to ReadLine: %w" , err )
2023-07-07 11:01:56 +05:30
return nil , false , err
2020-10-16 22:43:18 +05:30
}
if lineBytes [ 0 ] == 'd' {
// End of hunks
2023-07-07 11:01:56 +05:30
return lineBytes , isFragment , err
2016-12-26 06:46:37 +05:30
}
2020-10-16 22:43:18 +05:30
switch lineBytes [ 0 ] {
case '@' :
2021-11-21 22:21:08 +05:30
if maxLines > - 1 && curFileLinesCount >= maxLines {
2020-10-16 22:43:18 +05:30
curFile . IsIncomplete = true
continue
}
2014-04-13 07:05:36 +05:30
2020-10-16 22:43:18 +05:30
_ , _ = sb . Write ( lineBytes )
for isFragment {
// This is very odd indeed - we're in a section header and the line is too long
// This really shouldn't happen...
lineBytes , isFragment , err = input . ReadLine ( )
if err != nil {
// Now by the definition of ReadLine this cannot be io.EOF
2023-07-07 11:01:56 +05:30
return nil , false , fmt . Errorf ( "unable to ReadLine: %w" , err )
2020-10-16 22:43:18 +05:30
}
_ , _ = sb . Write ( lineBytes )
}
line := sb . String ( )
// Create a new section to represent this hunk
2021-11-18 02:07:00 +05:30
curSection = & DiffSection { file : curFile }
2021-09-05 15:46:49 +05:30
lastLeftIdx = - 1
2014-04-13 07:05:36 +05:30
curFile . Sections = append ( curFile . Sections , curSection )
2020-10-16 22:43:18 +05:30
2020-01-23 22:58:15 +05:30
lineSectionInfo := getDiffLineSectionInfo ( curFile . Name , line , leftLine - 1 , rightLine - 1 )
2019-11-15 08:22:59 +05:30
diffLine := & DiffLine {
Type : DiffLineSection ,
Content : line ,
SectionInfo : lineSectionInfo ,
2015-07-29 20:25:01 +05:30
}
2019-11-15 08:22:59 +05:30
curSection . Lines = append ( curSection . Lines , diffLine )
2020-07-01 03:04:03 +05:30
curSection . FileName = curFile . Name
2019-11-15 08:22:59 +05:30
// update line number.
leftLine = lineSectionInfo . LeftIdx
rightLine = lineSectionInfo . RightIdx
2014-04-13 07:05:36 +05:30
continue
2020-10-16 22:43:18 +05:30
case '\\' :
2021-11-21 22:21:08 +05:30
if maxLines > - 1 && curFileLinesCount >= maxLines {
2020-10-16 22:43:18 +05:30
curFile . IsIncomplete = true
continue
}
// This is used only to indicate that the current file does not have a terminal newline
if ! bytes . Equal ( lineBytes , [ ] byte ( "\\ No newline at end of file" ) ) {
2023-07-07 11:01:56 +05:30
return nil , false , fmt . Errorf ( "unexpected line in hunk: %s" , string ( lineBytes ) )
2020-10-16 22:43:18 +05:30
}
// Technically this should be the end the file!
// FIXME: we should be putting a marker at the end of the file if there is no terminal new line
continue
case '+' :
curFileLinesCount ++
2014-04-13 07:05:36 +05:30
curFile . Addition ++
2021-11-21 22:21:08 +05:30
if maxLines > - 1 && curFileLinesCount >= maxLines {
2020-10-16 22:43:18 +05:30
curFile . IsIncomplete = true
continue
}
2021-08-29 19:58:04 +05:30
diffLine := & DiffLine { Type : DiffLineAdd , RightIdx : rightLine , Match : - 1 }
2014-04-13 07:05:36 +05:30
rightLine ++
2021-04-01 23:59:14 +05:30
if curSection == nil {
// Create a new section to represent this hunk
2021-11-18 02:07:00 +05:30
curSection = & DiffSection { file : curFile }
2021-04-01 23:59:14 +05:30
curFile . Sections = append ( curFile . Sections , curSection )
2021-09-05 15:46:49 +05:30
lastLeftIdx = - 1
2021-04-01 23:59:14 +05:30
}
2021-08-29 19:58:04 +05:30
if lastLeftIdx > - 1 {
diffLine . Match = lastLeftIdx
curSection . Lines [ lastLeftIdx ] . Match = len ( curSection . Lines )
lastLeftIdx ++
if lastLeftIdx >= len ( curSection . Lines ) || curSection . Lines [ lastLeftIdx ] . Type != DiffLineDel {
lastLeftIdx = - 1
}
}
2014-04-13 07:05:36 +05:30
curSection . Lines = append ( curSection . Lines , diffLine )
2020-10-16 22:43:18 +05:30
case '-' :
curFileLinesCount ++
2014-04-13 07:05:36 +05:30
curFile . Deletion ++
2021-11-21 22:21:08 +05:30
if maxLines > - 1 && curFileLinesCount >= maxLines {
2020-10-16 22:43:18 +05:30
curFile . IsIncomplete = true
continue
}
2021-08-29 19:58:04 +05:30
diffLine := & DiffLine { Type : DiffLineDel , LeftIdx : leftLine , Match : - 1 }
2014-04-13 07:05:36 +05:30
if leftLine > 0 {
leftLine ++
}
2021-04-01 23:59:14 +05:30
if curSection == nil {
// Create a new section to represent this hunk
2021-11-18 02:07:00 +05:30
curSection = & DiffSection { file : curFile }
2021-04-01 23:59:14 +05:30
curFile . Sections = append ( curFile . Sections , curSection )
2021-09-05 15:46:49 +05:30
lastLeftIdx = - 1
2021-04-01 23:59:14 +05:30
}
2021-08-29 19:58:04 +05:30
if len ( curSection . Lines ) == 0 || curSection . Lines [ len ( curSection . Lines ) - 1 ] . Type != DiffLineDel {
lastLeftIdx = len ( curSection . Lines )
}
2014-04-13 07:05:36 +05:30
curSection . Lines = append ( curSection . Lines , diffLine )
2020-10-16 22:43:18 +05:30
case ' ' :
curFileLinesCount ++
2021-11-21 22:21:08 +05:30
if maxLines > - 1 && curFileLinesCount >= maxLines {
2020-10-16 22:43:18 +05:30
curFile . IsIncomplete = true
continue
}
diffLine := & DiffLine { Type : DiffLinePlain , LeftIdx : leftLine , RightIdx : rightLine }
leftLine ++
rightLine ++
2021-08-29 19:58:04 +05:30
lastLeftIdx = - 1
2021-04-01 23:59:14 +05:30
if curSection == nil {
// Create a new section to represent this hunk
2021-11-18 02:07:00 +05:30
curSection = & DiffSection { file : curFile }
2021-04-01 23:59:14 +05:30
curFile . Sections = append ( curFile . Sections , curSection )
}
2020-10-16 22:43:18 +05:30
curSection . Lines = append ( curSection . Lines , diffLine )
default :
// This is unexpected
2023-07-07 11:01:56 +05:30
return nil , false , fmt . Errorf ( "unexpected line in hunk: %s" , string ( lineBytes ) )
2014-04-13 07:05:36 +05:30
}
2020-10-16 22:43:18 +05:30
line := string ( lineBytes )
if isFragment {
curFile . IsIncomplete = true
2021-05-04 18:28:49 +05:30
curFile . IsIncompleteLineTooLong = true
2020-10-16 22:43:18 +05:30
for isFragment {
lineBytes , isFragment , err = input . ReadLine ( )
2019-11-28 14:35:57 +05:30
if err != nil {
2020-10-16 22:43:18 +05:30
// Now by the definition of ReadLine this cannot be io.EOF
2023-07-07 11:01:56 +05:30
return lineBytes , isFragment , fmt . Errorf ( "unable to ReadLine: %w" , err )
2019-11-28 14:35:57 +05:30
}
}
2020-10-16 22:43:18 +05:30
}
2020-11-22 04:11:24 +05:30
if len ( line ) > maxLineCharacters {
curFile . IsIncomplete = true
2021-05-04 18:28:49 +05:30
curFile . IsIncompleteLineTooLong = true
2020-11-22 04:11:24 +05:30
line = line [ : maxLineCharacters ]
}
2020-10-16 22:43:18 +05:30
curSection . Lines [ len ( curSection . Lines ) - 1 ] . Content = line
2019-11-28 14:35:57 +05:30
2020-10-16 22:43:18 +05:30
// handle LFS
2021-04-09 03:55:57 +05:30
if line [ 1 : ] == lfs . MetaFileIdentifier {
2020-10-16 22:43:18 +05:30
curFileLFSPrefix = true
2021-04-09 03:55:57 +05:30
} else if curFileLFSPrefix && strings . HasPrefix ( line [ 1 : ] , lfs . MetaFileOidPrefix ) {
oid := strings . TrimPrefix ( line [ 1 : ] , lfs . MetaFileOidPrefix )
2020-10-16 22:43:18 +05:30
if len ( oid ) == 64 {
2022-06-12 21:21:54 +05:30
m := & git_model . LFSMetaObject { Pointer : lfs . Pointer { Oid : oid } }
2023-10-03 16:00:41 +05:30
count , err := db . CountByBean ( ctx , m )
2015-12-02 11:40:13 +05:30
2020-10-16 22:43:18 +05:30
if err == nil && count > 0 {
curFile . IsBin = true
curFile . IsLFSFile = true
curSection . Lines = nil
2021-09-05 15:46:49 +05:30
lastLeftIdx = - 1
2014-04-13 07:05:36 +05:30
}
}
}
}
2020-10-16 22:43:18 +05:30
}
2014-04-13 07:05:36 +05:30
2020-10-16 22:43:18 +05:30
func createDiffFile ( diff * Diff , line string ) * DiffFile {
// The a/ and b/ filenames are the same unless rename/copy is involved.
// Especially, even for a creation or a deletion, /dev/null is not used
// in place of the a/ or b/ filenames.
//
// When rename/copy is involved, file1 and file2 show the name of the
// source file of the rename/copy and the name of the file that rename/copy
// produces, respectively.
//
// Path names are quoted if necessary.
//
// This means that you should always be able to determine the file name even when there
// there is potential ambiguity...
//
// but we can be simpler with our heuristics by just forcing git to prefix things nicely
curFile := & DiffFile {
Index : len ( diff . Files ) + 1 ,
Type : DiffFileChange ,
Sections : make ( [ ] * DiffSection , 0 , 10 ) ,
}
rd := strings . NewReader ( line [ len ( cmdDiffHead ) : ] + " " )
curFile . Type = DiffFileChange
2022-06-20 15:32:49 +05:30
var oldNameAmbiguity , newNameAmbiguity bool
2021-02-28 00:16:14 +05:30
curFile . OldName , oldNameAmbiguity = readFileName ( rd )
curFile . Name , newNameAmbiguity = readFileName ( rd )
if oldNameAmbiguity && newNameAmbiguity {
curFile . IsAmbiguous = true
// OK we should bet that the oldName and the newName are the same if they can be made to be same
// So we need to start again ...
if ( len ( line ) - len ( cmdDiffHead ) - 1 ) % 2 == 0 {
// diff --git a/b b/b b/b b/b b/b b/b
//
midpoint := ( len ( line ) + len ( cmdDiffHead ) - 1 ) / 2
2024-04-22 17:18:42 +05:30
newl , old := line [ len ( cmdDiffHead ) : midpoint ] , line [ midpoint + 1 : ]
if len ( newl ) > 2 && len ( old ) > 2 && newl [ 2 : ] == old [ 2 : ] {
2021-02-28 00:16:14 +05:30
curFile . OldName = old [ 2 : ]
curFile . Name = old [ 2 : ]
}
}
}
2020-10-16 22:43:18 +05:30
curFile . IsRenamed = curFile . Name != curFile . OldName
return curFile
}
2021-02-28 00:16:14 +05:30
func readFileName ( rd * strings . Reader ) ( string , bool ) {
ambiguity := false
2020-10-16 22:43:18 +05:30
var name string
char , _ := rd . ReadByte ( )
_ = rd . UnreadByte ( )
if char == '"' {
fmt . Fscanf ( rd , "%q " , & name )
2021-11-07 23:22:50 +05:30
if len ( name ) == 0 {
2022-07-23 16:58:02 +05:30
log . Error ( "Reader has no file name: reader=%+v" , rd )
2021-11-07 23:22:50 +05:30
return "" , true
}
2020-10-16 22:43:18 +05:30
if name [ 0 ] == '\\' {
name = name [ 1 : ]
2014-12-09 12:48:25 +05:30
}
2020-10-16 22:43:18 +05:30
} else {
2021-02-28 00:16:14 +05:30
// This technique is potentially ambiguous it may not be possible to uniquely identify the filenames from the diff line alone
ambiguity = true
2020-10-16 22:43:18 +05:30
fmt . Fscanf ( rd , "%s " , & name )
2021-02-28 00:16:14 +05:30
char , _ := rd . ReadByte ( )
_ = rd . UnreadByte ( )
for ! ( char == 0 || char == '"' || char == 'b' ) {
var suffix string
fmt . Fscanf ( rd , "%s " , & suffix )
name += " " + suffix
char , _ = rd . ReadByte ( )
_ = rd . UnreadByte ( )
}
}
if len ( name ) < 2 {
2022-07-23 16:58:02 +05:30
log . Error ( "Unable to determine name from reader: reader=%+v" , rd )
2021-02-28 00:16:14 +05:30
return "" , true
2014-12-09 12:48:25 +05:30
}
2021-02-28 00:16:14 +05:30
return name [ 2 : ] , ambiguity
2014-04-13 07:05:36 +05:30
}
2021-11-21 22:21:08 +05:30
// DiffOptions represents the options for a DiffRange
type DiffOptions struct {
BeforeCommitID string
AfterCommitID string
SkipTo string
MaxLines int
MaxLineCharacters int
MaxFiles int
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
WhitespaceBehavior git . TrustedCmdArgs
2021-11-21 22:21:08 +05:30
DirectComparison bool
}
// GetDiff builds a Diff between two commits of a repository.
2018-08-14 23:19:33 +05:30
// Passing the empty string as beforeCommitID returns a diff from the parent commit.
// The whitespaceBehavior is either an empty string or a git flag
2023-10-03 16:00:41 +05:30
func GetDiff ( ctx context . Context , gitRepo * git . Repository , opts * DiffOptions , files ... string ) ( * Diff , error ) {
2021-08-31 09:46:23 +05:30
repoPath := gitRepo . Path
2014-04-13 07:05:36 +05:30
2021-11-21 22:21:08 +05:30
commit , err := gitRepo . GetCommit ( opts . AfterCommitID )
2014-04-13 07:05:36 +05:30
if err != nil {
return nil , err
}
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
cmdDiff := git . NewCommand ( gitRepo . Ctx )
2023-12-14 02:32:00 +05:30
objectFormat , err := gitRepo . GetObjectFormat ( )
if err != nil {
return nil , err
}
2023-12-17 17:26:08 +05:30
if ( len ( opts . BeforeCommitID ) == 0 || opts . BeforeCommitID == objectFormat . EmptyObjectID ( ) . String ( ) ) && commit . ParentCount ( ) == 0 {
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
cmdDiff . AddArguments ( "diff" , "--src-prefix=\\a/" , "--dst-prefix=\\b/" , "-M" ) .
AddArguments ( opts . WhitespaceBehavior ... ) .
2023-12-14 02:32:00 +05:30
AddDynamicArguments ( objectFormat . EmptyTree ( ) . String ( ) ) .
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
AddDynamicArguments ( opts . AfterCommitID )
2014-05-29 07:45:15 +05:30
} else {
2021-11-21 22:21:08 +05:30
actualBeforeCommitID := opts . BeforeCommitID
2018-08-14 23:19:33 +05:30
if len ( actualBeforeCommitID ) == 0 {
parentCommit , _ := commit . Parent ( 0 )
actualBeforeCommitID = parentCommit . ID . String ( )
}
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
cmdDiff . AddArguments ( "diff" , "--src-prefix=\\a/" , "--dst-prefix=\\b/" , "-M" ) .
AddArguments ( opts . WhitespaceBehavior ... ) .
AddDynamicArguments ( actualBeforeCommitID , opts . AfterCommitID )
2021-11-21 22:21:08 +05:30
opts . BeforeCommitID = actualBeforeCommitID
2014-04-13 07:05:36 +05:30
}
2021-11-20 19:20:00 +05:30
// In git 2.31, git diff learned --skip-to which we can use to shortcut skip to file
// so if we are using at least this version of git we don't have to tell ParsePatch to do
// the skipping for us
2021-11-21 22:21:08 +05:30
parsePatchSkipToFile := opts . SkipTo
if opts . SkipTo != "" && git . CheckGitVersionAtLeast ( "2.31" ) == nil {
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
cmdDiff . AddOptionFormat ( "--skip-to=%s" , opts . SkipTo )
2021-11-20 19:20:00 +05:30
parsePatchSkipToFile = ""
2021-10-15 21:35:33 +05:30
}
2021-11-21 22:21:08 +05:30
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
cmdDiff . AddDashesAndList ( files ... )
2021-11-21 22:21:08 +05:30
2022-01-23 11:27:52 +05:30
reader , writer := io . Pipe ( )
defer func ( ) {
_ = reader . Close ( )
_ = writer . Close ( )
} ( )
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
go func ( ) {
2023-08-13 18:19:30 +05:30
stderr := & bytes . Buffer { }
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
cmdDiff . SetDescription ( fmt . Sprintf ( "GetDiffRange [repo_path: %s]" , repoPath ) )
if err := cmdDiff . Run ( & git . RunOpts {
2022-01-23 11:27:52 +05:30
Timeout : time . Duration ( setting . Git . Timeout . Default ) * time . Second ,
Dir : repoPath ,
Stdout : writer ,
2023-08-13 18:19:30 +05:30
Stderr : stderr ,
2022-01-23 11:27:52 +05:30
} ) ; err != nil {
2023-08-13 18:19:30 +05:30
log . Error ( "error during GetDiff(git diff dir: %s): %v, stderr: %s" , repoPath , err , stderr . String ( ) )
2022-01-23 11:27:52 +05:30
}
2015-12-02 11:40:13 +05:30
2022-01-23 11:27:52 +05:30
_ = writer . Close ( )
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
} ( )
2014-07-07 03:02:36 +05:30
2023-10-03 16:00:41 +05:30
diff , err := ParsePatch ( ctx , opts . MaxLines , opts . MaxLineCharacters , opts . MaxFiles , reader , parsePatchSkipToFile )
2015-12-02 11:40:13 +05:30
if err != nil {
2021-11-20 19:20:00 +05:30
return nil , fmt . Errorf ( "unable to ParsePatch: %w" , err )
2015-12-02 11:40:13 +05:30
}
2021-11-21 22:21:08 +05:30
diff . Start = opts . SkipTo
2021-09-10 01:43:36 +05:30
2024-03-24 17:14:30 +05:30
checker , err := gitRepo . GitAttributeChecker ( opts . AfterCommitID , git . LinguistAttributes ... )
if err != nil {
return nil , fmt . Errorf ( "unable to GitAttributeChecker: %w" , err )
}
defer checker . Close ( )
2021-09-10 01:43:36 +05:30
2019-11-15 08:22:59 +05:30
for _ , diffFile := range diff . Files {
2021-09-10 01:43:36 +05:30
gotVendor := false
gotGenerated := false
2024-03-24 17:14:30 +05:30
attrs , err := checker . CheckPath ( diffFile . Name )
if err != nil {
log . Error ( "checker.CheckPath(%s) failed: %v" , diffFile . Name , err )
} else {
vendored := attrs [ "linguist-vendored" ] . Bool ( )
diffFile . IsVendored = vendored . Value ( )
gotVendor = vendored . Has ( )
generated := attrs [ "linguist-generated" ] . Bool ( )
diffFile . IsGenerated = generated . Value ( )
gotGenerated = generated . Has ( )
diffFile . Language = cmp . Or (
attrs [ "linguist-language" ] . String ( ) ,
attrs [ "gitlab-language" ] . Prefix ( ) ,
)
2021-09-10 01:43:36 +05:30
}
if ! gotVendor {
diffFile . IsVendored = analyze . IsVendor ( diffFile . Name )
}
if ! gotGenerated {
diffFile . IsGenerated = analyze . IsGenerated ( diffFile . Name )
}
2021-11-21 22:21:08 +05:30
tailSection := diffFile . GetTailSection ( gitRepo , opts . BeforeCommitID , opts . AfterCommitID )
2019-11-15 08:22:59 +05:30
if tailSection != nil {
diffFile . Sections = append ( diffFile . Sections , tailSection )
}
}
2015-12-02 11:40:13 +05:30
2021-09-27 17:49:34 +05:30
separator := "..."
2021-11-21 22:21:08 +05:30
if opts . DirectComparison {
2021-09-27 17:49:34 +05:30
separator = ".."
}
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
diffPaths := [ ] string { opts . BeforeCommitID + separator + opts . AfterCommitID }
2023-12-17 17:26:08 +05:30
if len ( opts . BeforeCommitID ) == 0 || opts . BeforeCommitID == objectFormat . EmptyObjectID ( ) . String ( ) {
2023-12-14 02:32:00 +05:30
diffPaths = [ ] string { objectFormat . EmptyTree ( ) . String ( ) , opts . AfterCommitID }
2020-05-30 02:44:00 +05:30
}
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
diff . NumFiles , diff . TotalAddition , diff . TotalDeletion , err = git . GetDiffShortStat ( gitRepo . Ctx , repoPath , nil , diffPaths ... )
2020-07-29 23:23:04 +05:30
if err != nil && strings . Contains ( err . Error ( ) , "no merge base" ) {
// git >= 2.28 now returns an error if base and head have become unrelated.
// previously it would return the results of git diff --shortstat base head so let's try that...
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
diffPaths = [ ] string { opts . BeforeCommitID , opts . AfterCommitID }
diff . NumFiles , diff . TotalAddition , diff . TotalDeletion , err = git . GetDiffShortStat ( gitRepo . Ctx , repoPath , nil , diffPaths ... )
2020-07-29 23:23:04 +05:30
}
2020-05-26 11:28:07 +05:30
if err != nil {
return nil , err
}
2015-12-02 11:40:13 +05:30
return diff , nil
2014-04-13 07:05:36 +05:30
}
2016-07-30 20:32:22 +05:30
2023-07-03 06:30:28 +05:30
type PullDiffStats struct {
TotalAddition , TotalDeletion int
}
// GetPullDiffStats
func GetPullDiffStats ( gitRepo * git . Repository , opts * DiffOptions ) ( * PullDiffStats , error ) {
repoPath := gitRepo . Path
diff := & PullDiffStats { }
separator := "..."
if opts . DirectComparison {
separator = ".."
}
2023-12-14 02:32:00 +05:30
objectFormat , err := gitRepo . GetObjectFormat ( )
if err != nil {
return nil , err
2023-07-03 06:30:28 +05:30
}
2023-12-14 02:32:00 +05:30
diffPaths := [ ] string { opts . BeforeCommitID + separator + opts . AfterCommitID }
2023-12-17 17:26:08 +05:30
if len ( opts . BeforeCommitID ) == 0 || opts . BeforeCommitID == objectFormat . EmptyObjectID ( ) . String ( ) {
2023-12-14 02:32:00 +05:30
diffPaths = [ ] string { objectFormat . EmptyTree ( ) . String ( ) , opts . AfterCommitID }
}
2023-07-03 06:30:28 +05:30
_ , diff . TotalAddition , diff . TotalDeletion , err = git . GetDiffShortStat ( gitRepo . Ctx , repoPath , nil , diffPaths ... )
if err != nil && strings . Contains ( err . Error ( ) , "no merge base" ) {
// git >= 2.28 now returns an error if base and head have become unrelated.
// previously it would return the results of git diff --shortstat base head so let's try that...
diffPaths = [ ] string { opts . BeforeCommitID , opts . AfterCommitID }
_ , diff . TotalAddition , diff . TotalDeletion , err = git . GetDiffShortStat ( gitRepo . Ctx , repoPath , nil , diffPaths ... )
}
if err != nil {
return nil , err
}
return diff , nil
}
2022-05-07 23:58:10 +05:30
// SyncAndGetUserSpecificDiff is like GetDiff, except that user specific data such as which files the given user has already viewed on the given PR will also be set
// Additionally, the database asynchronously is updated if files have changed since the last review
2022-06-13 15:07:59 +05:30
func SyncAndGetUserSpecificDiff ( ctx context . Context , userID int64 , pull * issues_model . PullRequest , gitRepo * git . Repository , opts * DiffOptions , files ... string ) ( * Diff , error ) {
2023-10-03 16:00:41 +05:30
diff , err := GetDiff ( ctx , gitRepo , opts , files ... )
2022-05-07 23:58:10 +05:30
if err != nil {
return nil , err
}
review , err := pull_model . GetNewestReviewState ( ctx , userID , pull . ID )
if err != nil || review == nil || review . UpdatedFiles == nil {
return diff , err
}
latestCommit := opts . AfterCommitID
if latestCommit == "" {
latestCommit = pull . HeadBranch // opts.AfterCommitID is preferred because it handles PRs from forks correctly and the branch name doesn't
}
changedFiles , err := gitRepo . GetFilesChangedBetween ( review . CommitSHA , latestCommit )
2022-10-20 13:59:40 +05:30
// There are way too many possible errors.
// Examples are various git errors such as the commit the review was based on was gc'ed and hence doesn't exist anymore as well as unrecoverable errors where we should serve a 500 response
// Due to the current architecture and physical limitation of needing to compare explicit error messages, we can only choose one approach without the code getting ugly
// For SOME of the errors such as the gc'ed commit, it would be best to mark all files as changed
// But as that does not work for all potential errors, we simply mark all files as unchanged and drop the error which always works, even if not as good as possible
2022-05-07 23:58:10 +05:30
if err != nil {
2022-10-20 13:59:40 +05:30
log . Error ( "Could not get changed files between %s and %s for pull request %d in repo with path %s. Assuming no changes. Error: %w" , review . CommitSHA , latestCommit , pull . Index , gitRepo . Path , err )
2022-05-07 23:58:10 +05:30
}
filesChangedSinceLastDiff := make ( map [ string ] pull_model . ViewedState )
outer :
for _ , diffFile := range diff . Files {
fileViewedState := review . UpdatedFiles [ diffFile . GetDiffFileName ( ) ]
// Check whether it was previously detected that the file has changed since the last review
if fileViewedState == pull_model . HasChanged {
diffFile . HasChangedSinceLastReview = true
continue
}
filename := diffFile . GetDiffFileName ( )
// Check explicitly whether the file has changed since the last review
for _ , changedFile := range changedFiles {
diffFile . HasChangedSinceLastReview = filename == changedFile
if diffFile . HasChangedSinceLastReview {
filesChangedSinceLastDiff [ filename ] = pull_model . HasChanged
continue outer // We don't want to check if the file is viewed here as that would fold the file, which is in this case unwanted
}
}
// Check whether the file has already been viewed
if fileViewedState == pull_model . Viewed {
diffFile . IsViewed = true
diff . NumViewedFiles ++
}
}
// Explicitly store files that have changed in the database, if any is present at all.
// This has the benefit that the "Has Changed" attribute will be present as long as the user does not explicitly mark this file as viewed, so it will even survive a page reload after marking another file as viewed.
// On the other hand, this means that even if a commit reverting an unseen change is committed, the file will still be seen as changed.
if len ( filesChangedSinceLastDiff ) > 0 {
err := pull_model . UpdateReviewState ( ctx , review . UserID , review . PullID , review . CommitSHA , filesChangedSinceLastDiff )
if err != nil {
log . Warn ( "Could not update review for user %d, pull %d, commit %s and the changed files %v: %v" , review . UserID , review . PullID , review . CommitSHA , filesChangedSinceLastDiff , err )
return nil , err
}
}
2023-09-21 01:58:17 +05:30
return diff , nil
2022-05-07 23:58:10 +05:30
}
2019-09-06 07:50:09 +05:30
// CommentAsDiff returns c.Patch as *Diff
2023-10-03 16:00:41 +05:30
func CommentAsDiff ( ctx context . Context , c * issues_model . Comment ) ( * Diff , error ) {
diff , err := ParsePatch ( ctx , setting . Git . MaxGitDiffLines ,
2021-11-20 19:20:00 +05:30
setting . Git . MaxGitDiffLineCharacters , setting . Git . MaxGitDiffFiles , strings . NewReader ( c . Patch ) , "" )
2019-09-06 07:50:09 +05:30
if err != nil {
2021-02-28 00:16:14 +05:30
log . Error ( "Unable to parse patch: %v" , err )
2019-09-06 07:50:09 +05:30
return nil , err
}
if len ( diff . Files ) == 0 {
return nil , fmt . Errorf ( "no file found for comment ID: %d" , c . ID )
}
secs := diff . Files [ 0 ] . Sections
if len ( secs ) == 0 {
return nil , fmt . Errorf ( "no sections found for comment ID: %d" , c . ID )
}
return diff , nil
}
// CommentMustAsDiff executes AsDiff and logs the error instead of returning
2023-10-03 16:00:41 +05:30
func CommentMustAsDiff ( ctx context . Context , c * issues_model . Comment ) * Diff {
2021-03-21 22:29:58 +05:30
if c == nil {
return nil
}
defer func ( ) {
if err := recover ( ) ; err != nil {
log . Error ( "PANIC whilst retrieving diff for comment[%d] Error: %v\nStack: %s" , c . ID , err , log . Stack ( 2 ) )
}
} ( )
2023-10-03 16:00:41 +05:30
diff , err := CommentAsDiff ( ctx , c )
2019-09-06 07:50:09 +05:30
if err != nil {
log . Warn ( "CommentMustAsDiff: %v" , err )
}
return diff
}
2021-02-13 10:05:43 +05:30
// GetWhitespaceFlag returns git diff flag for treating whitespaces
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
func GetWhitespaceFlag ( whitespaceBehavior string ) git . TrustedCmdArgs {
whitespaceFlags := map [ string ] git . TrustedCmdArgs {
"ignore-all" : { "-w" } ,
"ignore-change" : { "-b" } ,
"ignore-eol" : { "--ignore-space-at-eol" } ,
"show-all" : nil ,
2022-01-20 23:16:10 +05:30
}
2021-02-13 10:05:43 +05:30
2022-02-08 11:45:04 +05:30
if flag , ok := whitespaceFlags [ whitespaceBehavior ] ; ok {
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
return flag
2022-02-08 11:45:04 +05:30
}
log . Warn ( "unknown whitespace behavior: %q, default to 'show-all'" , whitespaceBehavior )
Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592)
## Review without space diff
https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1
## Purpose of this PR
1. Make git module command completely safe (risky user inputs won't be
passed as argument option anymore)
2. Avoid low-level mistakes like
https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918
3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg`
type
4. Simplify code when using git command
## The main idea of this PR
* Move the `git.CmdArg` to the `internal` package, then no other package
except `git` could use it. Then developers could never do
`AddArguments(git.CmdArg(userInput))` any more.
* Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already
trusted arguments. It's only used in a few cases, for example: use git
arguments from config file, help unit test with some arguments.
* Introduce `AddOptionValues` and `AddOptionFormat`, they make code more
clear and simple:
* Before: `AddArguments("-m").AddDynamicArguments(message)`
* After: `AddOptionValues("-m", message)`
* -
* Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'",
sig.Name, sig.Email)))`
* After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)`
## FAQ
### Why these changes were not done in #21535 ?
#21535 is mainly a search&replace, it did its best to not change too
much logic.
Making the framework better needs a lot of changes, so this separate PR
is needed as the second step.
### The naming of `AddOptionXxx`
According to git's manual, the `--xxx` part is called `option`.
### How can it guarantee that `internal.CmdArg` won't be not misused?
Go's specification guarantees that. Trying to access other package's
internal package causes compilation error.
And, `golangci-lint` also denies the git/internal package. Only the
`git/command.go` can use it carefully.
### There is still a `ToTrustedCmdArgs`, will it still allow developers
to make mistakes and pass untrusted arguments?
Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code
will be very complex (see the changes for examples). Then developers and
reviewers can know that something might be unreasonable.
### Why there was a `CmdArgCheck` and why it's removed?
At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck`
was introduced as a hacky patch. Now, almost all code could be written
as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for
`CmdArgCheck` anymore.
### Why many codes for `signArg == ""` is deleted?
Because in the old code, `signArg` could never be empty string, it's
either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just
dead code.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-04 08:00:43 +05:30
return nil
2021-02-13 10:05:43 +05:30
}