You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

gitdiff.go 43KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package gitdiff
  5. import (
  6. "bufio"
  7. "bytes"
  8. "context"
  9. "fmt"
  10. "html"
  11. "html/template"
  12. "io"
  13. "net/url"
  14. "sort"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/models/db"
  18. git_model "code.gitea.io/gitea/models/git"
  19. issues_model "code.gitea.io/gitea/models/issues"
  20. pull_model "code.gitea.io/gitea/models/pull"
  21. user_model "code.gitea.io/gitea/models/user"
  22. "code.gitea.io/gitea/modules/analyze"
  23. "code.gitea.io/gitea/modules/base"
  24. "code.gitea.io/gitea/modules/charset"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/highlight"
  27. "code.gitea.io/gitea/modules/lfs"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/optional"
  30. "code.gitea.io/gitea/modules/setting"
  31. "code.gitea.io/gitea/modules/translation"
  32. "github.com/sergi/go-diff/diffmatchpatch"
  33. stdcharset "golang.org/x/net/html/charset"
  34. "golang.org/x/text/encoding"
  35. "golang.org/x/text/transform"
  36. )
  37. // DiffLineType represents the type of DiffLine.
  38. type DiffLineType uint8
  39. // DiffLineType possible values.
  40. const (
  41. DiffLinePlain DiffLineType = iota + 1
  42. DiffLineAdd
  43. DiffLineDel
  44. DiffLineSection
  45. )
  46. // DiffFileType represents the type of DiffFile.
  47. type DiffFileType uint8
  48. // DiffFileType possible values.
  49. const (
  50. DiffFileAdd DiffFileType = iota + 1
  51. DiffFileChange
  52. DiffFileDel
  53. DiffFileRename
  54. DiffFileCopy
  55. )
  56. // DiffLineExpandDirection represents the DiffLineSection expand direction
  57. type DiffLineExpandDirection uint8
  58. // DiffLineExpandDirection possible values.
  59. const (
  60. DiffLineExpandNone DiffLineExpandDirection = iota + 1
  61. DiffLineExpandSingle
  62. DiffLineExpandUpDown
  63. DiffLineExpandUp
  64. DiffLineExpandDown
  65. )
  66. // DiffLine represents a line difference in a DiffSection.
  67. type DiffLine struct {
  68. LeftIdx int
  69. RightIdx int
  70. Match int
  71. Type DiffLineType
  72. Content string
  73. Comments []*issues_model.Comment
  74. SectionInfo *DiffLineSectionInfo
  75. }
  76. // DiffLineSectionInfo represents diff line section meta data
  77. type DiffLineSectionInfo struct {
  78. Path string
  79. LastLeftIdx int
  80. LastRightIdx int
  81. LeftIdx int
  82. RightIdx int
  83. LeftHunkSize int
  84. RightHunkSize int
  85. }
  86. // BlobExcerptChunkSize represent max lines of excerpt
  87. const BlobExcerptChunkSize = 20
  88. // GetType returns the type of DiffLine.
  89. func (d *DiffLine) GetType() int {
  90. return int(d.Type)
  91. }
  92. // GetHTMLDiffLineType returns the diff line type name for HTML
  93. func (d *DiffLine) GetHTMLDiffLineType() string {
  94. switch d.Type {
  95. case DiffLineAdd:
  96. return "add"
  97. case DiffLineDel:
  98. return "del"
  99. case DiffLineSection:
  100. return "tag"
  101. }
  102. return "same"
  103. }
  104. // CanComment returns whether a line can get commented
  105. func (d *DiffLine) CanComment() bool {
  106. return len(d.Comments) == 0 && d.Type != DiffLineSection
  107. }
  108. // GetCommentSide returns the comment side of the first comment, if not set returns empty string
  109. func (d *DiffLine) GetCommentSide() string {
  110. if len(d.Comments) == 0 {
  111. return ""
  112. }
  113. return d.Comments[0].DiffSide()
  114. }
  115. // GetLineTypeMarker returns the line type marker
  116. func (d *DiffLine) GetLineTypeMarker() string {
  117. if strings.IndexByte(" +-", d.Content[0]) > -1 {
  118. return d.Content[0:1]
  119. }
  120. return ""
  121. }
  122. // GetBlobExcerptQuery builds query string to get blob excerpt
  123. func (d *DiffLine) GetBlobExcerptQuery() string {
  124. query := fmt.Sprintf(
  125. "last_left=%d&last_right=%d&"+
  126. "left=%d&right=%d&"+
  127. "left_hunk_size=%d&right_hunk_size=%d&"+
  128. "path=%s",
  129. d.SectionInfo.LastLeftIdx, d.SectionInfo.LastRightIdx,
  130. d.SectionInfo.LeftIdx, d.SectionInfo.RightIdx,
  131. d.SectionInfo.LeftHunkSize, d.SectionInfo.RightHunkSize,
  132. url.QueryEscape(d.SectionInfo.Path))
  133. return query
  134. }
  135. // GetExpandDirection gets DiffLineExpandDirection
  136. func (d *DiffLine) GetExpandDirection() DiffLineExpandDirection {
  137. if d.Type != DiffLineSection || d.SectionInfo == nil || d.SectionInfo.LeftIdx-d.SectionInfo.LastLeftIdx <= 1 || d.SectionInfo.RightIdx-d.SectionInfo.LastRightIdx <= 1 {
  138. return DiffLineExpandNone
  139. }
  140. if d.SectionInfo.LastLeftIdx <= 0 && d.SectionInfo.LastRightIdx <= 0 {
  141. return DiffLineExpandUp
  142. } else if d.SectionInfo.RightIdx-d.SectionInfo.LastRightIdx > BlobExcerptChunkSize && d.SectionInfo.RightHunkSize > 0 {
  143. return DiffLineExpandUpDown
  144. } else if d.SectionInfo.LeftHunkSize <= 0 && d.SectionInfo.RightHunkSize <= 0 {
  145. return DiffLineExpandDown
  146. }
  147. return DiffLineExpandSingle
  148. }
  149. func getDiffLineSectionInfo(treePath, line string, lastLeftIdx, lastRightIdx int) *DiffLineSectionInfo {
  150. leftLine, leftHunk, rightLine, righHunk := git.ParseDiffHunkString(line)
  151. return &DiffLineSectionInfo{
  152. Path: treePath,
  153. LastLeftIdx: lastLeftIdx,
  154. LastRightIdx: lastRightIdx,
  155. LeftIdx: leftLine,
  156. RightIdx: rightLine,
  157. LeftHunkSize: leftHunk,
  158. RightHunkSize: righHunk,
  159. }
  160. }
  161. // escape a line's content or return <br> needed for copy/paste purposes
  162. func getLineContent(content string, locale translation.Locale) DiffInline {
  163. if len(content) > 0 {
  164. return DiffInlineWithUnicodeEscape(template.HTML(html.EscapeString(content)), locale)
  165. }
  166. return DiffInline{EscapeStatus: &charset.EscapeStatus{}, Content: "<br>"}
  167. }
  168. // DiffSection represents a section of a DiffFile.
  169. type DiffSection struct {
  170. file *DiffFile
  171. FileName string
  172. Name string
  173. Lines []*DiffLine
  174. }
  175. var (
  176. addedCodePrefix = []byte(`<span class="added-code">`)
  177. removedCodePrefix = []byte(`<span class="removed-code">`)
  178. codeTagSuffix = []byte(`</span>`)
  179. )
  180. func diffToHTML(lineWrapperTags []string, diffs []diffmatchpatch.Diff, lineType DiffLineType) string {
  181. buf := bytes.NewBuffer(nil)
  182. // restore the line wrapper tags <span class="line"> and <span class="cl">, if necessary
  183. for _, tag := range lineWrapperTags {
  184. buf.WriteString(tag)
  185. }
  186. for _, diff := range diffs {
  187. switch {
  188. case diff.Type == diffmatchpatch.DiffEqual:
  189. buf.WriteString(diff.Text)
  190. case diff.Type == diffmatchpatch.DiffInsert && lineType == DiffLineAdd:
  191. buf.Write(addedCodePrefix)
  192. buf.WriteString(diff.Text)
  193. buf.Write(codeTagSuffix)
  194. case diff.Type == diffmatchpatch.DiffDelete && lineType == DiffLineDel:
  195. buf.Write(removedCodePrefix)
  196. buf.WriteString(diff.Text)
  197. buf.Write(codeTagSuffix)
  198. }
  199. }
  200. for range lineWrapperTags {
  201. buf.WriteString("</span>")
  202. }
  203. return buf.String()
  204. }
  205. // GetLine gets a specific line by type (add or del) and file line number
  206. func (diffSection *DiffSection) GetLine(lineType DiffLineType, idx int) *DiffLine {
  207. var (
  208. difference = 0
  209. addCount = 0
  210. delCount = 0
  211. matchDiffLine *DiffLine
  212. )
  213. LOOP:
  214. for _, diffLine := range diffSection.Lines {
  215. switch diffLine.Type {
  216. case DiffLineAdd:
  217. addCount++
  218. case DiffLineDel:
  219. delCount++
  220. default:
  221. if matchDiffLine != nil {
  222. break LOOP
  223. }
  224. difference = diffLine.RightIdx - diffLine.LeftIdx
  225. addCount = 0
  226. delCount = 0
  227. }
  228. switch lineType {
  229. case DiffLineDel:
  230. if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference {
  231. matchDiffLine = diffLine
  232. }
  233. case DiffLineAdd:
  234. if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference {
  235. matchDiffLine = diffLine
  236. }
  237. }
  238. }
  239. if addCount == delCount {
  240. return matchDiffLine
  241. }
  242. return nil
  243. }
  244. var diffMatchPatch = diffmatchpatch.New()
  245. func init() {
  246. diffMatchPatch.DiffEditCost = 100
  247. }
  248. // DiffInline is a struct that has a content and escape status
  249. type DiffInline struct {
  250. EscapeStatus *charset.EscapeStatus
  251. Content template.HTML
  252. }
  253. // DiffInlineWithUnicodeEscape makes a DiffInline with hidden unicode characters escaped
  254. func DiffInlineWithUnicodeEscape(s template.HTML, locale translation.Locale) DiffInline {
  255. status, content := charset.EscapeControlHTML(s, locale)
  256. return DiffInline{EscapeStatus: status, Content: content}
  257. }
  258. // DiffInlineWithHighlightCode makes a DiffInline with code highlight and hidden unicode characters escaped
  259. func DiffInlineWithHighlightCode(fileName, language, code string, locale translation.Locale) DiffInline {
  260. highlighted, _ := highlight.Code(fileName, language, code)
  261. status, content := charset.EscapeControlHTML(highlighted, locale)
  262. return DiffInline{EscapeStatus: status, Content: content}
  263. }
  264. // GetComputedInlineDiffFor computes inline diff for the given line.
  265. func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine, locale translation.Locale) DiffInline {
  266. if setting.Git.DisableDiffHighlight {
  267. return getLineContent(diffLine.Content[1:], locale)
  268. }
  269. var (
  270. compareDiffLine *DiffLine
  271. diff1 string
  272. diff2 string
  273. )
  274. language := ""
  275. if diffSection.file != nil {
  276. language = diffSection.file.Language
  277. }
  278. // try to find equivalent diff line. ignore, otherwise
  279. switch diffLine.Type {
  280. case DiffLineSection:
  281. return getLineContent(diffLine.Content[1:], locale)
  282. case DiffLineAdd:
  283. compareDiffLine = diffSection.GetLine(DiffLineDel, diffLine.RightIdx)
  284. if compareDiffLine == nil {
  285. return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content[1:], locale)
  286. }
  287. diff1 = compareDiffLine.Content
  288. diff2 = diffLine.Content
  289. case DiffLineDel:
  290. compareDiffLine = diffSection.GetLine(DiffLineAdd, diffLine.LeftIdx)
  291. if compareDiffLine == nil {
  292. return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content[1:], locale)
  293. }
  294. diff1 = diffLine.Content
  295. diff2 = compareDiffLine.Content
  296. default:
  297. if strings.IndexByte(" +-", diffLine.Content[0]) > -1 {
  298. return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content[1:], locale)
  299. }
  300. return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content, locale)
  301. }
  302. hcd := newHighlightCodeDiff()
  303. diffRecord := hcd.diffWithHighlight(diffSection.FileName, language, diff1[1:], diff2[1:])
  304. // it seems that Gitea doesn't need the line wrapper of Chroma, so do not add them back
  305. // if the line wrappers are still needed in the future, it can be added back by "diffToHTML(hcd.lineWrapperTags. ...)"
  306. diffHTML := diffToHTML(nil, diffRecord, diffLine.Type)
  307. return DiffInlineWithUnicodeEscape(template.HTML(diffHTML), locale)
  308. }
  309. // DiffFile represents a file diff.
  310. type DiffFile struct {
  311. Name string
  312. NameHash string
  313. OldName string
  314. Index int
  315. Addition, Deletion int
  316. Type DiffFileType
  317. IsCreated bool
  318. IsDeleted bool
  319. IsBin bool
  320. IsLFSFile bool
  321. IsRenamed bool
  322. IsAmbiguous bool
  323. IsSubmodule bool
  324. Sections []*DiffSection
  325. IsIncomplete bool
  326. IsIncompleteLineTooLong bool
  327. IsProtected bool
  328. IsGenerated bool
  329. IsVendored bool
  330. IsViewed bool // User specific
  331. HasChangedSinceLastReview bool // User specific
  332. Language string
  333. Mode string
  334. OldMode string
  335. }
  336. // GetType returns type of diff file.
  337. func (diffFile *DiffFile) GetType() int {
  338. return int(diffFile.Type)
  339. }
  340. // GetTailSection creates a fake DiffLineSection if the last section is not the end of the file
  341. func (diffFile *DiffFile) GetTailSection(gitRepo *git.Repository, leftCommitID, rightCommitID string) *DiffSection {
  342. if len(diffFile.Sections) == 0 || diffFile.Type != DiffFileChange || diffFile.IsBin || diffFile.IsLFSFile {
  343. return nil
  344. }
  345. leftCommit, err := gitRepo.GetCommit(leftCommitID)
  346. if err != nil {
  347. return nil
  348. }
  349. rightCommit, err := gitRepo.GetCommit(rightCommitID)
  350. if err != nil {
  351. return nil
  352. }
  353. lastSection := diffFile.Sections[len(diffFile.Sections)-1]
  354. lastLine := lastSection.Lines[len(lastSection.Lines)-1]
  355. leftLineCount := getCommitFileLineCount(leftCommit, diffFile.Name)
  356. rightLineCount := getCommitFileLineCount(rightCommit, diffFile.Name)
  357. if leftLineCount <= lastLine.LeftIdx || rightLineCount <= lastLine.RightIdx {
  358. return nil
  359. }
  360. tailDiffLine := &DiffLine{
  361. Type: DiffLineSection,
  362. Content: " ",
  363. SectionInfo: &DiffLineSectionInfo{
  364. Path: diffFile.Name,
  365. LastLeftIdx: lastLine.LeftIdx,
  366. LastRightIdx: lastLine.RightIdx,
  367. LeftIdx: leftLineCount,
  368. RightIdx: rightLineCount,
  369. },
  370. }
  371. tailSection := &DiffSection{FileName: diffFile.Name, Lines: []*DiffLine{tailDiffLine}}
  372. return tailSection
  373. }
  374. // GetDiffFileName returns the name of the diff file, or its old name in case it was deleted
  375. func (diffFile *DiffFile) GetDiffFileName() string {
  376. if diffFile.Name == "" {
  377. return diffFile.OldName
  378. }
  379. return diffFile.Name
  380. }
  381. func (diffFile *DiffFile) ShouldBeHidden() bool {
  382. return diffFile.IsGenerated || diffFile.IsViewed
  383. }
  384. func (diffFile *DiffFile) ModeTranslationKey(mode string) string {
  385. switch mode {
  386. case "040000":
  387. return "git.filemode.directory"
  388. case "100644":
  389. return "git.filemode.normal_file"
  390. case "100755":
  391. return "git.filemode.executable_file"
  392. case "120000":
  393. return "git.filemode.symbolic_link"
  394. case "160000":
  395. return "git.filemode.submodule"
  396. default:
  397. return mode
  398. }
  399. }
  400. func getCommitFileLineCount(commit *git.Commit, filePath string) int {
  401. blob, err := commit.GetBlobByPath(filePath)
  402. if err != nil {
  403. return 0
  404. }
  405. lineCount, err := blob.GetBlobLineCount()
  406. if err != nil {
  407. return 0
  408. }
  409. return lineCount
  410. }
  411. // Diff represents a difference between two git trees.
  412. type Diff struct {
  413. Start, End string
  414. NumFiles int
  415. TotalAddition, TotalDeletion int
  416. Files []*DiffFile
  417. IsIncomplete bool
  418. NumViewedFiles int // user-specific
  419. }
  420. // LoadComments loads comments into each line
  421. func (diff *Diff) LoadComments(ctx context.Context, issue *issues_model.Issue, currentUser *user_model.User, showOutdatedComments bool) error {
  422. allComments, err := issues_model.FetchCodeComments(ctx, issue, currentUser, showOutdatedComments)
  423. if err != nil {
  424. return err
  425. }
  426. for _, file := range diff.Files {
  427. if lineCommits, ok := allComments[file.Name]; ok {
  428. for _, section := range file.Sections {
  429. for _, line := range section.Lines {
  430. if comments, ok := lineCommits[int64(line.LeftIdx*-1)]; ok {
  431. line.Comments = append(line.Comments, comments...)
  432. }
  433. if comments, ok := lineCommits[int64(line.RightIdx)]; ok {
  434. line.Comments = append(line.Comments, comments...)
  435. }
  436. sort.SliceStable(line.Comments, func(i, j int) bool {
  437. return line.Comments[i].CreatedUnix < line.Comments[j].CreatedUnix
  438. })
  439. }
  440. }
  441. }
  442. }
  443. return nil
  444. }
  445. const cmdDiffHead = "diff --git "
  446. // ParsePatch builds a Diff object from a io.Reader and some parameters.
  447. func ParsePatch(ctx context.Context, maxLines, maxLineCharacters, maxFiles int, reader io.Reader, skipToFile string) (*Diff, error) {
  448. log.Debug("ParsePatch(%d, %d, %d, ..., %s)", maxLines, maxLineCharacters, maxFiles, skipToFile)
  449. var curFile *DiffFile
  450. skipping := skipToFile != ""
  451. diff := &Diff{Files: make([]*DiffFile, 0)}
  452. sb := strings.Builder{}
  453. // OK let's set a reasonable buffer size.
  454. // This should be at least the size of maxLineCharacters or 4096 whichever is larger.
  455. readerSize := maxLineCharacters
  456. if readerSize < 4096 {
  457. readerSize = 4096
  458. }
  459. input := bufio.NewReaderSize(reader, readerSize)
  460. line, err := input.ReadString('\n')
  461. if err != nil {
  462. if err == io.EOF {
  463. return diff, nil
  464. }
  465. return diff, err
  466. }
  467. prepareValue := func(s, p string) string {
  468. return strings.TrimSpace(strings.TrimPrefix(s, p))
  469. }
  470. parsingLoop:
  471. for {
  472. // 1. A patch file always begins with `diff --git ` + `a/path b/path` (possibly quoted)
  473. // if it does not we have bad input!
  474. if !strings.HasPrefix(line, cmdDiffHead) {
  475. return diff, fmt.Errorf("invalid first file line: %s", line)
  476. }
  477. if maxFiles > -1 && len(diff.Files) >= maxFiles {
  478. lastFile := createDiffFile(diff, line)
  479. diff.End = lastFile.Name
  480. diff.IsIncomplete = true
  481. _, err := io.Copy(io.Discard, reader)
  482. if err != nil {
  483. // By the definition of io.Copy this never returns io.EOF
  484. return diff, fmt.Errorf("error during io.Copy: %w", err)
  485. }
  486. break parsingLoop
  487. }
  488. curFile = createDiffFile(diff, line)
  489. if skipping {
  490. if curFile.Name != skipToFile {
  491. line, err = skipToNextDiffHead(input)
  492. if err != nil {
  493. if err == io.EOF {
  494. return diff, nil
  495. }
  496. return diff, err
  497. }
  498. continue
  499. }
  500. skipping = false
  501. }
  502. diff.Files = append(diff.Files, curFile)
  503. // 2. It is followed by one or more extended header lines:
  504. //
  505. // old mode <mode>
  506. // new mode <mode>
  507. // deleted file mode <mode>
  508. // new file mode <mode>
  509. // copy from <path>
  510. // copy to <path>
  511. // rename from <path>
  512. // rename to <path>
  513. // similarity index <number>
  514. // dissimilarity index <number>
  515. // index <hash>..<hash> <mode>
  516. //
  517. // * <mode> 6-digit octal numbers including the file type and file permission bits.
  518. // * <path> does not include the a/ and b/ prefixes
  519. // * <number> percentage of unchanged lines for similarity, percentage of changed
  520. // lines dissimilarity as integer rounded down with terminal %. 100% => equal files.
  521. // * The index line includes the blob object names before and after the change.
  522. // The <mode> is included if the file mode does not change; otherwise, separate
  523. // lines indicate the old and the new mode.
  524. // 3. Following this header the "standard unified" diff format header may be encountered: (but not for every case...)
  525. //
  526. // --- a/<path>
  527. // +++ b/<path>
  528. //
  529. // With multiple hunks
  530. //
  531. // @@ <hunk descriptor> @@
  532. // +added line
  533. // -removed line
  534. // unchanged line
  535. //
  536. // 4. Binary files get:
  537. //
  538. // Binary files a/<path> and b/<path> differ
  539. //
  540. // but one of a/<path> and b/<path> could be /dev/null.
  541. curFileLoop:
  542. for {
  543. line, err = input.ReadString('\n')
  544. if err != nil {
  545. if err != io.EOF {
  546. return diff, err
  547. }
  548. break parsingLoop
  549. }
  550. switch {
  551. case strings.HasPrefix(line, cmdDiffHead):
  552. break curFileLoop
  553. case strings.HasPrefix(line, "old mode ") ||
  554. strings.HasPrefix(line, "new mode "):
  555. if strings.HasPrefix(line, "old mode ") {
  556. curFile.OldMode = prepareValue(line, "old mode ")
  557. }
  558. if strings.HasPrefix(line, "new mode ") {
  559. curFile.Mode = prepareValue(line, "new mode ")
  560. }
  561. if strings.HasSuffix(line, " 160000\n") {
  562. curFile.IsSubmodule = true
  563. }
  564. case strings.HasPrefix(line, "rename from "):
  565. curFile.IsRenamed = true
  566. curFile.Type = DiffFileRename
  567. if curFile.IsAmbiguous {
  568. curFile.OldName = prepareValue(line, "rename from ")
  569. }
  570. case strings.HasPrefix(line, "rename to "):
  571. curFile.IsRenamed = true
  572. curFile.Type = DiffFileRename
  573. if curFile.IsAmbiguous {
  574. curFile.Name = prepareValue(line, "rename to ")
  575. curFile.IsAmbiguous = false
  576. }
  577. case strings.HasPrefix(line, "copy from "):
  578. curFile.IsRenamed = true
  579. curFile.Type = DiffFileCopy
  580. if curFile.IsAmbiguous {
  581. curFile.OldName = prepareValue(line, "copy from ")
  582. }
  583. case strings.HasPrefix(line, "copy to "):
  584. curFile.IsRenamed = true
  585. curFile.Type = DiffFileCopy
  586. if curFile.IsAmbiguous {
  587. curFile.Name = prepareValue(line, "copy to ")
  588. curFile.IsAmbiguous = false
  589. }
  590. case strings.HasPrefix(line, "new file"):
  591. curFile.Type = DiffFileAdd
  592. curFile.IsCreated = true
  593. if strings.HasPrefix(line, "new file mode ") {
  594. curFile.Mode = prepareValue(line, "new file mode ")
  595. }
  596. if strings.HasSuffix(line, " 160000\n") {
  597. curFile.IsSubmodule = true
  598. }
  599. case strings.HasPrefix(line, "deleted"):
  600. curFile.Type = DiffFileDel
  601. curFile.IsDeleted = true
  602. if strings.HasSuffix(line, " 160000\n") {
  603. curFile.IsSubmodule = true
  604. }
  605. case strings.HasPrefix(line, "index"):
  606. if strings.HasSuffix(line, " 160000\n") {
  607. curFile.IsSubmodule = true
  608. }
  609. case strings.HasPrefix(line, "similarity index 100%"):
  610. curFile.Type = DiffFileRename
  611. case strings.HasPrefix(line, "Binary"):
  612. curFile.IsBin = true
  613. case strings.HasPrefix(line, "--- "):
  614. // Handle ambiguous filenames
  615. if curFile.IsAmbiguous {
  616. // The shortest string that can end up here is:
  617. // "--- a\t\n" without the quotes.
  618. // This line has a len() of 7 but doesn't contain a oldName.
  619. // So the amount that the line need is at least 8 or more.
  620. // The code will otherwise panic for a out-of-bounds.
  621. if len(line) > 7 && line[4] == 'a' {
  622. curFile.OldName = line[6 : len(line)-1]
  623. if line[len(line)-2] == '\t' {
  624. curFile.OldName = curFile.OldName[:len(curFile.OldName)-1]
  625. }
  626. } else {
  627. curFile.OldName = ""
  628. }
  629. }
  630. // Otherwise do nothing with this line
  631. case strings.HasPrefix(line, "+++ "):
  632. // Handle ambiguous filenames
  633. if curFile.IsAmbiguous {
  634. if len(line) > 6 && line[4] == 'b' {
  635. curFile.Name = line[6 : len(line)-1]
  636. if line[len(line)-2] == '\t' {
  637. curFile.Name = curFile.Name[:len(curFile.Name)-1]
  638. }
  639. if curFile.OldName == "" {
  640. curFile.OldName = curFile.Name
  641. }
  642. } else {
  643. curFile.Name = curFile.OldName
  644. }
  645. curFile.IsAmbiguous = false
  646. }
  647. // Otherwise do nothing with this line, but now switch to parsing hunks
  648. lineBytes, isFragment, err := parseHunks(ctx, curFile, maxLines, maxLineCharacters, input)
  649. diff.TotalAddition += curFile.Addition
  650. diff.TotalDeletion += curFile.Deletion
  651. if err != nil {
  652. if err != io.EOF {
  653. return diff, err
  654. }
  655. break parsingLoop
  656. }
  657. sb.Reset()
  658. _, _ = sb.Write(lineBytes)
  659. for isFragment {
  660. lineBytes, isFragment, err = input.ReadLine()
  661. if err != nil {
  662. // Now by the definition of ReadLine this cannot be io.EOF
  663. return diff, fmt.Errorf("unable to ReadLine: %w", err)
  664. }
  665. _, _ = sb.Write(lineBytes)
  666. }
  667. line = sb.String()
  668. sb.Reset()
  669. break curFileLoop
  670. }
  671. }
  672. }
  673. // TODO: There are numerous issues with this:
  674. // - we might want to consider detecting encoding while parsing but...
  675. // - we're likely to fail to get the correct encoding here anyway as we won't have enough information
  676. diffLineTypeBuffers := make(map[DiffLineType]*bytes.Buffer, 3)
  677. diffLineTypeDecoders := make(map[DiffLineType]*encoding.Decoder, 3)
  678. diffLineTypeBuffers[DiffLinePlain] = new(bytes.Buffer)
  679. diffLineTypeBuffers[DiffLineAdd] = new(bytes.Buffer)
  680. diffLineTypeBuffers[DiffLineDel] = new(bytes.Buffer)
  681. for _, f := range diff.Files {
  682. f.NameHash = base.EncodeSha1(f.Name)
  683. for _, buffer := range diffLineTypeBuffers {
  684. buffer.Reset()
  685. }
  686. for _, sec := range f.Sections {
  687. for _, l := range sec.Lines {
  688. if l.Type == DiffLineSection {
  689. continue
  690. }
  691. diffLineTypeBuffers[l.Type].WriteString(l.Content[1:])
  692. diffLineTypeBuffers[l.Type].WriteString("\n")
  693. }
  694. }
  695. for lineType, buffer := range diffLineTypeBuffers {
  696. diffLineTypeDecoders[lineType] = nil
  697. if buffer.Len() == 0 {
  698. continue
  699. }
  700. charsetLabel, err := charset.DetectEncoding(buffer.Bytes())
  701. if charsetLabel != "UTF-8" && err == nil {
  702. encoding, _ := stdcharset.Lookup(charsetLabel)
  703. if encoding != nil {
  704. diffLineTypeDecoders[lineType] = encoding.NewDecoder()
  705. }
  706. }
  707. }
  708. for _, sec := range f.Sections {
  709. for _, l := range sec.Lines {
  710. decoder := diffLineTypeDecoders[l.Type]
  711. if decoder != nil {
  712. if c, _, err := transform.String(decoder, l.Content[1:]); err == nil {
  713. l.Content = l.Content[0:1] + c
  714. }
  715. }
  716. }
  717. }
  718. }
  719. diff.NumFiles = len(diff.Files)
  720. return diff, nil
  721. }
  722. func skipToNextDiffHead(input *bufio.Reader) (line string, err error) {
  723. // need to skip until the next cmdDiffHead
  724. var isFragment, wasFragment bool
  725. var lineBytes []byte
  726. for {
  727. lineBytes, isFragment, err = input.ReadLine()
  728. if err != nil {
  729. return "", err
  730. }
  731. if wasFragment {
  732. wasFragment = isFragment
  733. continue
  734. }
  735. if bytes.HasPrefix(lineBytes, []byte(cmdDiffHead)) {
  736. break
  737. }
  738. wasFragment = isFragment
  739. }
  740. line = string(lineBytes)
  741. if isFragment {
  742. var tail string
  743. tail, err = input.ReadString('\n')
  744. if err != nil {
  745. return "", err
  746. }
  747. line += tail
  748. }
  749. return line, err
  750. }
  751. func parseHunks(ctx context.Context, curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio.Reader) (lineBytes []byte, isFragment bool, err error) {
  752. sb := strings.Builder{}
  753. var (
  754. curSection *DiffSection
  755. curFileLinesCount int
  756. curFileLFSPrefix bool
  757. )
  758. lastLeftIdx := -1
  759. leftLine, rightLine := 1, 1
  760. for {
  761. for isFragment {
  762. curFile.IsIncomplete = true
  763. curFile.IsIncompleteLineTooLong = true
  764. _, isFragment, err = input.ReadLine()
  765. if err != nil {
  766. // Now by the definition of ReadLine this cannot be io.EOF
  767. return nil, false, fmt.Errorf("unable to ReadLine: %w", err)
  768. }
  769. }
  770. sb.Reset()
  771. lineBytes, isFragment, err = input.ReadLine()
  772. if err != nil {
  773. if err == io.EOF {
  774. return lineBytes, isFragment, err
  775. }
  776. err = fmt.Errorf("unable to ReadLine: %w", err)
  777. return nil, false, err
  778. }
  779. if lineBytes[0] == 'd' {
  780. // End of hunks
  781. return lineBytes, isFragment, err
  782. }
  783. switch lineBytes[0] {
  784. case '@':
  785. if maxLines > -1 && curFileLinesCount >= maxLines {
  786. curFile.IsIncomplete = true
  787. continue
  788. }
  789. _, _ = sb.Write(lineBytes)
  790. for isFragment {
  791. // This is very odd indeed - we're in a section header and the line is too long
  792. // This really shouldn't happen...
  793. lineBytes, isFragment, err = input.ReadLine()
  794. if err != nil {
  795. // Now by the definition of ReadLine this cannot be io.EOF
  796. return nil, false, fmt.Errorf("unable to ReadLine: %w", err)
  797. }
  798. _, _ = sb.Write(lineBytes)
  799. }
  800. line := sb.String()
  801. // Create a new section to represent this hunk
  802. curSection = &DiffSection{file: curFile}
  803. lastLeftIdx = -1
  804. curFile.Sections = append(curFile.Sections, curSection)
  805. lineSectionInfo := getDiffLineSectionInfo(curFile.Name, line, leftLine-1, rightLine-1)
  806. diffLine := &DiffLine{
  807. Type: DiffLineSection,
  808. Content: line,
  809. SectionInfo: lineSectionInfo,
  810. }
  811. curSection.Lines = append(curSection.Lines, diffLine)
  812. curSection.FileName = curFile.Name
  813. // update line number.
  814. leftLine = lineSectionInfo.LeftIdx
  815. rightLine = lineSectionInfo.RightIdx
  816. continue
  817. case '\\':
  818. if maxLines > -1 && curFileLinesCount >= maxLines {
  819. curFile.IsIncomplete = true
  820. continue
  821. }
  822. // This is used only to indicate that the current file does not have a terminal newline
  823. if !bytes.Equal(lineBytes, []byte("\\ No newline at end of file")) {
  824. return nil, false, fmt.Errorf("unexpected line in hunk: %s", string(lineBytes))
  825. }
  826. // Technically this should be the end the file!
  827. // FIXME: we should be putting a marker at the end of the file if there is no terminal new line
  828. continue
  829. case '+':
  830. curFileLinesCount++
  831. curFile.Addition++
  832. if maxLines > -1 && curFileLinesCount >= maxLines {
  833. curFile.IsIncomplete = true
  834. continue
  835. }
  836. diffLine := &DiffLine{Type: DiffLineAdd, RightIdx: rightLine, Match: -1}
  837. rightLine++
  838. if curSection == nil {
  839. // Create a new section to represent this hunk
  840. curSection = &DiffSection{file: curFile}
  841. curFile.Sections = append(curFile.Sections, curSection)
  842. lastLeftIdx = -1
  843. }
  844. if lastLeftIdx > -1 {
  845. diffLine.Match = lastLeftIdx
  846. curSection.Lines[lastLeftIdx].Match = len(curSection.Lines)
  847. lastLeftIdx++
  848. if lastLeftIdx >= len(curSection.Lines) || curSection.Lines[lastLeftIdx].Type != DiffLineDel {
  849. lastLeftIdx = -1
  850. }
  851. }
  852. curSection.Lines = append(curSection.Lines, diffLine)
  853. case '-':
  854. curFileLinesCount++
  855. curFile.Deletion++
  856. if maxLines > -1 && curFileLinesCount >= maxLines {
  857. curFile.IsIncomplete = true
  858. continue
  859. }
  860. diffLine := &DiffLine{Type: DiffLineDel, LeftIdx: leftLine, Match: -1}
  861. if leftLine > 0 {
  862. leftLine++
  863. }
  864. if curSection == nil {
  865. // Create a new section to represent this hunk
  866. curSection = &DiffSection{file: curFile}
  867. curFile.Sections = append(curFile.Sections, curSection)
  868. lastLeftIdx = -1
  869. }
  870. if len(curSection.Lines) == 0 || curSection.Lines[len(curSection.Lines)-1].Type != DiffLineDel {
  871. lastLeftIdx = len(curSection.Lines)
  872. }
  873. curSection.Lines = append(curSection.Lines, diffLine)
  874. case ' ':
  875. curFileLinesCount++
  876. if maxLines > -1 && curFileLinesCount >= maxLines {
  877. curFile.IsIncomplete = true
  878. continue
  879. }
  880. diffLine := &DiffLine{Type: DiffLinePlain, LeftIdx: leftLine, RightIdx: rightLine}
  881. leftLine++
  882. rightLine++
  883. lastLeftIdx = -1
  884. if curSection == nil {
  885. // Create a new section to represent this hunk
  886. curSection = &DiffSection{file: curFile}
  887. curFile.Sections = append(curFile.Sections, curSection)
  888. }
  889. curSection.Lines = append(curSection.Lines, diffLine)
  890. default:
  891. // This is unexpected
  892. return nil, false, fmt.Errorf("unexpected line in hunk: %s", string(lineBytes))
  893. }
  894. line := string(lineBytes)
  895. if isFragment {
  896. curFile.IsIncomplete = true
  897. curFile.IsIncompleteLineTooLong = true
  898. for isFragment {
  899. lineBytes, isFragment, err = input.ReadLine()
  900. if err != nil {
  901. // Now by the definition of ReadLine this cannot be io.EOF
  902. return lineBytes, isFragment, fmt.Errorf("unable to ReadLine: %w", err)
  903. }
  904. }
  905. }
  906. if len(line) > maxLineCharacters {
  907. curFile.IsIncomplete = true
  908. curFile.IsIncompleteLineTooLong = true
  909. line = line[:maxLineCharacters]
  910. }
  911. curSection.Lines[len(curSection.Lines)-1].Content = line
  912. // handle LFS
  913. if line[1:] == lfs.MetaFileIdentifier {
  914. curFileLFSPrefix = true
  915. } else if curFileLFSPrefix && strings.HasPrefix(line[1:], lfs.MetaFileOidPrefix) {
  916. oid := strings.TrimPrefix(line[1:], lfs.MetaFileOidPrefix)
  917. if len(oid) == 64 {
  918. m := &git_model.LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}
  919. count, err := db.CountByBean(ctx, m)
  920. if err == nil && count > 0 {
  921. curFile.IsBin = true
  922. curFile.IsLFSFile = true
  923. curSection.Lines = nil
  924. lastLeftIdx = -1
  925. }
  926. }
  927. }
  928. }
  929. }
  930. func createDiffFile(diff *Diff, line string) *DiffFile {
  931. // The a/ and b/ filenames are the same unless rename/copy is involved.
  932. // Especially, even for a creation or a deletion, /dev/null is not used
  933. // in place of the a/ or b/ filenames.
  934. //
  935. // When rename/copy is involved, file1 and file2 show the name of the
  936. // source file of the rename/copy and the name of the file that rename/copy
  937. // produces, respectively.
  938. //
  939. // Path names are quoted if necessary.
  940. //
  941. // This means that you should always be able to determine the file name even when there
  942. // there is potential ambiguity...
  943. //
  944. // but we can be simpler with our heuristics by just forcing git to prefix things nicely
  945. curFile := &DiffFile{
  946. Index: len(diff.Files) + 1,
  947. Type: DiffFileChange,
  948. Sections: make([]*DiffSection, 0, 10),
  949. }
  950. rd := strings.NewReader(line[len(cmdDiffHead):] + " ")
  951. curFile.Type = DiffFileChange
  952. var oldNameAmbiguity, newNameAmbiguity bool
  953. curFile.OldName, oldNameAmbiguity = readFileName(rd)
  954. curFile.Name, newNameAmbiguity = readFileName(rd)
  955. if oldNameAmbiguity && newNameAmbiguity {
  956. curFile.IsAmbiguous = true
  957. // OK we should bet that the oldName and the newName are the same if they can be made to be same
  958. // So we need to start again ...
  959. if (len(line)-len(cmdDiffHead)-1)%2 == 0 {
  960. // diff --git a/b b/b b/b b/b b/b b/b
  961. //
  962. midpoint := (len(line) + len(cmdDiffHead) - 1) / 2
  963. newPart, oldPart := line[len(cmdDiffHead):midpoint], line[midpoint+1:]
  964. if len(newPart) > 2 && len(oldPart) > 2 && newPart[2:] == oldPart[2:] {
  965. curFile.OldName = oldPart[2:]
  966. curFile.Name = oldPart[2:]
  967. }
  968. }
  969. }
  970. curFile.IsRenamed = curFile.Name != curFile.OldName
  971. return curFile
  972. }
  973. func readFileName(rd *strings.Reader) (string, bool) {
  974. ambiguity := false
  975. var name string
  976. char, _ := rd.ReadByte()
  977. _ = rd.UnreadByte()
  978. if char == '"' {
  979. fmt.Fscanf(rd, "%q ", &name)
  980. if len(name) == 0 {
  981. log.Error("Reader has no file name: reader=%+v", rd)
  982. return "", true
  983. }
  984. if name[0] == '\\' {
  985. name = name[1:]
  986. }
  987. } else {
  988. // This technique is potentially ambiguous it may not be possible to uniquely identify the filenames from the diff line alone
  989. ambiguity = true
  990. fmt.Fscanf(rd, "%s ", &name)
  991. char, _ := rd.ReadByte()
  992. _ = rd.UnreadByte()
  993. for !(char == 0 || char == '"' || char == 'b') {
  994. var suffix string
  995. fmt.Fscanf(rd, "%s ", &suffix)
  996. name += " " + suffix
  997. char, _ = rd.ReadByte()
  998. _ = rd.UnreadByte()
  999. }
  1000. }
  1001. if len(name) < 2 {
  1002. log.Error("Unable to determine name from reader: reader=%+v", rd)
  1003. return "", true
  1004. }
  1005. return name[2:], ambiguity
  1006. }
  1007. // DiffOptions represents the options for a DiffRange
  1008. type DiffOptions struct {
  1009. BeforeCommitID string
  1010. AfterCommitID string
  1011. SkipTo string
  1012. MaxLines int
  1013. MaxLineCharacters int
  1014. MaxFiles int
  1015. WhitespaceBehavior git.TrustedCmdArgs
  1016. DirectComparison bool
  1017. }
  1018. // GetDiff builds a Diff between two commits of a repository.
  1019. // Passing the empty string as beforeCommitID returns a diff from the parent commit.
  1020. // The whitespaceBehavior is either an empty string or a git flag
  1021. func GetDiff(ctx context.Context, gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff, error) {
  1022. repoPath := gitRepo.Path
  1023. commit, err := gitRepo.GetCommit(opts.AfterCommitID)
  1024. if err != nil {
  1025. return nil, err
  1026. }
  1027. cmdDiff := git.NewCommand(gitRepo.Ctx)
  1028. objectFormat, err := gitRepo.GetObjectFormat()
  1029. if err != nil {
  1030. return nil, err
  1031. }
  1032. if (len(opts.BeforeCommitID) == 0 || opts.BeforeCommitID == objectFormat.EmptyObjectID().String()) && commit.ParentCount() == 0 {
  1033. cmdDiff.AddArguments("diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M").
  1034. AddArguments(opts.WhitespaceBehavior...).
  1035. AddDynamicArguments(objectFormat.EmptyTree().String()).
  1036. AddDynamicArguments(opts.AfterCommitID)
  1037. } else {
  1038. actualBeforeCommitID := opts.BeforeCommitID
  1039. if len(actualBeforeCommitID) == 0 {
  1040. parentCommit, _ := commit.Parent(0)
  1041. actualBeforeCommitID = parentCommit.ID.String()
  1042. }
  1043. cmdDiff.AddArguments("diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M").
  1044. AddArguments(opts.WhitespaceBehavior...).
  1045. AddDynamicArguments(actualBeforeCommitID, opts.AfterCommitID)
  1046. opts.BeforeCommitID = actualBeforeCommitID
  1047. }
  1048. // In git 2.31, git diff learned --skip-to which we can use to shortcut skip to file
  1049. // so if we are using at least this version of git we don't have to tell ParsePatch to do
  1050. // the skipping for us
  1051. parsePatchSkipToFile := opts.SkipTo
  1052. if opts.SkipTo != "" && git.DefaultFeatures().CheckVersionAtLeast("2.31") {
  1053. cmdDiff.AddOptionFormat("--skip-to=%s", opts.SkipTo)
  1054. parsePatchSkipToFile = ""
  1055. }
  1056. cmdDiff.AddDashesAndList(files...)
  1057. reader, writer := io.Pipe()
  1058. defer func() {
  1059. _ = reader.Close()
  1060. _ = writer.Close()
  1061. }()
  1062. go func() {
  1063. stderr := &bytes.Buffer{}
  1064. cmdDiff.SetDescription(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath))
  1065. if err := cmdDiff.Run(&git.RunOpts{
  1066. Timeout: time.Duration(setting.Git.Timeout.Default) * time.Second,
  1067. Dir: repoPath,
  1068. Stdout: writer,
  1069. Stderr: stderr,
  1070. }); err != nil {
  1071. log.Error("error during GetDiff(git diff dir: %s): %v, stderr: %s", repoPath, err, stderr.String())
  1072. }
  1073. _ = writer.Close()
  1074. }()
  1075. diff, err := ParsePatch(ctx, opts.MaxLines, opts.MaxLineCharacters, opts.MaxFiles, reader, parsePatchSkipToFile)
  1076. if err != nil {
  1077. return nil, fmt.Errorf("unable to ParsePatch: %w", err)
  1078. }
  1079. diff.Start = opts.SkipTo
  1080. checker, deferable := gitRepo.CheckAttributeReader(opts.AfterCommitID)
  1081. defer deferable()
  1082. for _, diffFile := range diff.Files {
  1083. isVendored := optional.None[bool]()
  1084. isGenerated := optional.None[bool]()
  1085. if checker != nil {
  1086. attrs, err := checker.CheckPath(diffFile.Name)
  1087. if err == nil {
  1088. isVendored = git.AttributeToBool(attrs, git.AttributeLinguistVendored)
  1089. isGenerated = git.AttributeToBool(attrs, git.AttributeLinguistGenerated)
  1090. language := git.TryReadLanguageAttribute(attrs)
  1091. if language.Has() {
  1092. diffFile.Language = language.Value()
  1093. }
  1094. }
  1095. }
  1096. if !isVendored.Has() {
  1097. isVendored = optional.Some(analyze.IsVendor(diffFile.Name))
  1098. }
  1099. diffFile.IsVendored = isVendored.Value()
  1100. if !isGenerated.Has() {
  1101. isGenerated = optional.Some(analyze.IsGenerated(diffFile.Name))
  1102. }
  1103. diffFile.IsGenerated = isGenerated.Value()
  1104. tailSection := diffFile.GetTailSection(gitRepo, opts.BeforeCommitID, opts.AfterCommitID)
  1105. if tailSection != nil {
  1106. diffFile.Sections = append(diffFile.Sections, tailSection)
  1107. }
  1108. }
  1109. separator := "..."
  1110. if opts.DirectComparison {
  1111. separator = ".."
  1112. }
  1113. diffPaths := []string{opts.BeforeCommitID + separator + opts.AfterCommitID}
  1114. if len(opts.BeforeCommitID) == 0 || opts.BeforeCommitID == objectFormat.EmptyObjectID().String() {
  1115. diffPaths = []string{objectFormat.EmptyTree().String(), opts.AfterCommitID}
  1116. }
  1117. diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, nil, diffPaths...)
  1118. if err != nil && strings.Contains(err.Error(), "no merge base") {
  1119. // git >= 2.28 now returns an error if base and head have become unrelated.
  1120. // previously it would return the results of git diff --shortstat base head so let's try that...
  1121. diffPaths = []string{opts.BeforeCommitID, opts.AfterCommitID}
  1122. diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, nil, diffPaths...)
  1123. }
  1124. if err != nil {
  1125. return nil, err
  1126. }
  1127. return diff, nil
  1128. }
  1129. type PullDiffStats struct {
  1130. TotalAddition, TotalDeletion int
  1131. }
  1132. // GetPullDiffStats
  1133. func GetPullDiffStats(gitRepo *git.Repository, opts *DiffOptions) (*PullDiffStats, error) {
  1134. repoPath := gitRepo.Path
  1135. diff := &PullDiffStats{}
  1136. separator := "..."
  1137. if opts.DirectComparison {
  1138. separator = ".."
  1139. }
  1140. objectFormat, err := gitRepo.GetObjectFormat()
  1141. if err != nil {
  1142. return nil, err
  1143. }
  1144. diffPaths := []string{opts.BeforeCommitID + separator + opts.AfterCommitID}
  1145. if len(opts.BeforeCommitID) == 0 || opts.BeforeCommitID == objectFormat.EmptyObjectID().String() {
  1146. diffPaths = []string{objectFormat.EmptyTree().String(), opts.AfterCommitID}
  1147. }
  1148. _, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, nil, diffPaths...)
  1149. if err != nil && strings.Contains(err.Error(), "no merge base") {
  1150. // git >= 2.28 now returns an error if base and head have become unrelated.
  1151. // previously it would return the results of git diff --shortstat base head so let's try that...
  1152. diffPaths = []string{opts.BeforeCommitID, opts.AfterCommitID}
  1153. _, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, nil, diffPaths...)
  1154. }
  1155. if err != nil {
  1156. return nil, err
  1157. }
  1158. return diff, nil
  1159. }
  1160. // 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
  1161. // Additionally, the database asynchronously is updated if files have changed since the last review
  1162. func SyncAndGetUserSpecificDiff(ctx context.Context, userID int64, pull *issues_model.PullRequest, gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff, error) {
  1163. diff, err := GetDiff(ctx, gitRepo, opts, files...)
  1164. if err != nil {
  1165. return nil, err
  1166. }
  1167. review, err := pull_model.GetNewestReviewState(ctx, userID, pull.ID)
  1168. if err != nil || review == nil || review.UpdatedFiles == nil {
  1169. return diff, err
  1170. }
  1171. latestCommit := opts.AfterCommitID
  1172. if latestCommit == "" {
  1173. latestCommit = pull.HeadBranch // opts.AfterCommitID is preferred because it handles PRs from forks correctly and the branch name doesn't
  1174. }
  1175. changedFiles, err := gitRepo.GetFilesChangedBetween(review.CommitSHA, latestCommit)
  1176. // There are way too many possible errors.
  1177. // 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
  1178. // 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
  1179. // For SOME of the errors such as the gc'ed commit, it would be best to mark all files as changed
  1180. // 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
  1181. if err != nil {
  1182. 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)
  1183. }
  1184. filesChangedSinceLastDiff := make(map[string]pull_model.ViewedState)
  1185. outer:
  1186. for _, diffFile := range diff.Files {
  1187. fileViewedState := review.UpdatedFiles[diffFile.GetDiffFileName()]
  1188. // Check whether it was previously detected that the file has changed since the last review
  1189. if fileViewedState == pull_model.HasChanged {
  1190. diffFile.HasChangedSinceLastReview = true
  1191. continue
  1192. }
  1193. filename := diffFile.GetDiffFileName()
  1194. // Check explicitly whether the file has changed since the last review
  1195. for _, changedFile := range changedFiles {
  1196. diffFile.HasChangedSinceLastReview = filename == changedFile
  1197. if diffFile.HasChangedSinceLastReview {
  1198. filesChangedSinceLastDiff[filename] = pull_model.HasChanged
  1199. 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
  1200. }
  1201. }
  1202. // Check whether the file has already been viewed
  1203. if fileViewedState == pull_model.Viewed {
  1204. diffFile.IsViewed = true
  1205. diff.NumViewedFiles++
  1206. }
  1207. }
  1208. // Explicitly store files that have changed in the database, if any is present at all.
  1209. // 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.
  1210. // 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.
  1211. if len(filesChangedSinceLastDiff) > 0 {
  1212. err := pull_model.UpdateReviewState(ctx, review.UserID, review.PullID, review.CommitSHA, filesChangedSinceLastDiff)
  1213. if err != nil {
  1214. 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)
  1215. return nil, err
  1216. }
  1217. }
  1218. return diff, nil
  1219. }
  1220. // CommentAsDiff returns c.Patch as *Diff
  1221. func CommentAsDiff(ctx context.Context, c *issues_model.Comment) (*Diff, error) {
  1222. diff, err := ParsePatch(ctx, setting.Git.MaxGitDiffLines,
  1223. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.Patch), "")
  1224. if err != nil {
  1225. log.Error("Unable to parse patch: %v", err)
  1226. return nil, err
  1227. }
  1228. if len(diff.Files) == 0 {
  1229. return nil, fmt.Errorf("no file found for comment ID: %d", c.ID)
  1230. }
  1231. secs := diff.Files[0].Sections
  1232. if len(secs) == 0 {
  1233. return nil, fmt.Errorf("no sections found for comment ID: %d", c.ID)
  1234. }
  1235. return diff, nil
  1236. }
  1237. // CommentMustAsDiff executes AsDiff and logs the error instead of returning
  1238. func CommentMustAsDiff(ctx context.Context, c *issues_model.Comment) *Diff {
  1239. if c == nil {
  1240. return nil
  1241. }
  1242. defer func() {
  1243. if err := recover(); err != nil {
  1244. log.Error("PANIC whilst retrieving diff for comment[%d] Error: %v\nStack: %s", c.ID, err, log.Stack(2))
  1245. }
  1246. }()
  1247. diff, err := CommentAsDiff(ctx, c)
  1248. if err != nil {
  1249. log.Warn("CommentMustAsDiff: %v", err)
  1250. }
  1251. return diff
  1252. }
  1253. // GetWhitespaceFlag returns git diff flag for treating whitespaces
  1254. func GetWhitespaceFlag(whitespaceBehavior string) git.TrustedCmdArgs {
  1255. whitespaceFlags := map[string]git.TrustedCmdArgs{
  1256. "ignore-all": {"-w"},
  1257. "ignore-change": {"-b"},
  1258. "ignore-eol": {"--ignore-space-at-eol"},
  1259. "show-all": nil,
  1260. }
  1261. if flag, ok := whitespaceFlags[whitespaceBehavior]; ok {
  1262. return flag
  1263. }
  1264. log.Warn("unknown whitespace behavior: %q, default to 'show-all'", whitespaceBehavior)
  1265. return nil
  1266. }