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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package gitdiff
  6. import (
  7. "bufio"
  8. "bytes"
  9. "context"
  10. "fmt"
  11. "html"
  12. "html/template"
  13. "io"
  14. "io/ioutil"
  15. "net/url"
  16. "os"
  17. "os/exec"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "code.gitea.io/gitea/models"
  22. "code.gitea.io/gitea/modules/charset"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/highlight"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/process"
  27. "code.gitea.io/gitea/modules/setting"
  28. "github.com/sergi/go-diff/diffmatchpatch"
  29. stdcharset "golang.org/x/net/html/charset"
  30. "golang.org/x/text/transform"
  31. )
  32. // DiffLineType represents the type of a DiffLine.
  33. type DiffLineType uint8
  34. // DiffLineType possible values.
  35. const (
  36. DiffLinePlain DiffLineType = iota + 1
  37. DiffLineAdd
  38. DiffLineDel
  39. DiffLineSection
  40. )
  41. // DiffFileType represents the type of a DiffFile.
  42. type DiffFileType uint8
  43. // DiffFileType possible values.
  44. const (
  45. DiffFileAdd DiffFileType = iota + 1
  46. DiffFileChange
  47. DiffFileDel
  48. DiffFileRename
  49. )
  50. // DiffLineExpandDirection represents the DiffLineSection expand direction
  51. type DiffLineExpandDirection uint8
  52. // DiffLineExpandDirection possible values.
  53. const (
  54. DiffLineExpandNone DiffLineExpandDirection = iota + 1
  55. DiffLineExpandSingle
  56. DiffLineExpandUpDown
  57. DiffLineExpandUp
  58. DiffLineExpandDown
  59. )
  60. // DiffLine represents a line difference in a DiffSection.
  61. type DiffLine struct {
  62. LeftIdx int
  63. RightIdx int
  64. Type DiffLineType
  65. Content string
  66. Comments []*models.Comment
  67. SectionInfo *DiffLineSectionInfo
  68. }
  69. // DiffLineSectionInfo represents diff line section meta data
  70. type DiffLineSectionInfo struct {
  71. Path string
  72. LastLeftIdx int
  73. LastRightIdx int
  74. LeftIdx int
  75. RightIdx int
  76. LeftHunkSize int
  77. RightHunkSize int
  78. }
  79. // BlobExceprtChunkSize represent max lines of excerpt
  80. const BlobExceprtChunkSize = 20
  81. // GetType returns the type of a DiffLine.
  82. func (d *DiffLine) GetType() int {
  83. return int(d.Type)
  84. }
  85. // CanComment returns whether or not a line can get commented
  86. func (d *DiffLine) CanComment() bool {
  87. return len(d.Comments) == 0 && d.Type != DiffLineSection
  88. }
  89. // GetCommentSide returns the comment side of the first comment, if not set returns empty string
  90. func (d *DiffLine) GetCommentSide() string {
  91. if len(d.Comments) == 0 {
  92. return ""
  93. }
  94. return d.Comments[0].DiffSide()
  95. }
  96. // GetLineTypeMarker returns the line type marker
  97. func (d *DiffLine) GetLineTypeMarker() string {
  98. if strings.IndexByte(" +-", d.Content[0]) > -1 {
  99. return d.Content[0:1]
  100. }
  101. return ""
  102. }
  103. // GetBlobExcerptQuery builds query string to get blob excerpt
  104. func (d *DiffLine) GetBlobExcerptQuery() string {
  105. query := fmt.Sprintf(
  106. "last_left=%d&last_right=%d&"+
  107. "left=%d&right=%d&"+
  108. "left_hunk_size=%d&right_hunk_size=%d&"+
  109. "path=%s",
  110. d.SectionInfo.LastLeftIdx, d.SectionInfo.LastRightIdx,
  111. d.SectionInfo.LeftIdx, d.SectionInfo.RightIdx,
  112. d.SectionInfo.LeftHunkSize, d.SectionInfo.RightHunkSize,
  113. url.QueryEscape(d.SectionInfo.Path))
  114. return query
  115. }
  116. // GetExpandDirection gets DiffLineExpandDirection
  117. func (d *DiffLine) GetExpandDirection() DiffLineExpandDirection {
  118. if d.Type != DiffLineSection || d.SectionInfo == nil || d.SectionInfo.RightIdx-d.SectionInfo.LastRightIdx <= 1 {
  119. return DiffLineExpandNone
  120. }
  121. if d.SectionInfo.LastLeftIdx <= 0 && d.SectionInfo.LastRightIdx <= 0 {
  122. return DiffLineExpandUp
  123. } else if d.SectionInfo.RightIdx-d.SectionInfo.LastRightIdx > BlobExceprtChunkSize && d.SectionInfo.RightHunkSize > 0 {
  124. return DiffLineExpandUpDown
  125. } else if d.SectionInfo.LeftHunkSize <= 0 && d.SectionInfo.RightHunkSize <= 0 {
  126. return DiffLineExpandDown
  127. }
  128. return DiffLineExpandSingle
  129. }
  130. func getDiffLineSectionInfo(treePath, line string, lastLeftIdx, lastRightIdx int) *DiffLineSectionInfo {
  131. leftLine, leftHunk, rightLine, righHunk := git.ParseDiffHunkString(line)
  132. return &DiffLineSectionInfo{
  133. Path: treePath,
  134. LastLeftIdx: lastLeftIdx,
  135. LastRightIdx: lastRightIdx,
  136. LeftIdx: leftLine,
  137. RightIdx: rightLine,
  138. LeftHunkSize: leftHunk,
  139. RightHunkSize: righHunk,
  140. }
  141. }
  142. // escape a line's content or return <br> needed for copy/paste purposes
  143. func getLineContent(content string) string {
  144. if len(content) > 0 {
  145. return html.EscapeString(content)
  146. }
  147. return "<br>"
  148. }
  149. // DiffSection represents a section of a DiffFile.
  150. type DiffSection struct {
  151. Name string
  152. Lines []*DiffLine
  153. }
  154. var (
  155. addedCodePrefix = []byte(`<span class="added-code">`)
  156. removedCodePrefix = []byte(`<span class="removed-code">`)
  157. codeTagSuffix = []byte(`</span>`)
  158. )
  159. func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML {
  160. buf := bytes.NewBuffer(nil)
  161. for i := range diffs {
  162. switch {
  163. case diffs[i].Type == diffmatchpatch.DiffInsert && lineType == DiffLineAdd:
  164. buf.Write(addedCodePrefix)
  165. buf.WriteString(getLineContent(diffs[i].Text))
  166. buf.Write(codeTagSuffix)
  167. case diffs[i].Type == diffmatchpatch.DiffDelete && lineType == DiffLineDel:
  168. buf.Write(removedCodePrefix)
  169. buf.WriteString(getLineContent(diffs[i].Text))
  170. buf.Write(codeTagSuffix)
  171. case diffs[i].Type == diffmatchpatch.DiffEqual:
  172. buf.WriteString(getLineContent(diffs[i].Text))
  173. }
  174. }
  175. return template.HTML(buf.Bytes())
  176. }
  177. // GetLine gets a specific line by type (add or del) and file line number
  178. func (diffSection *DiffSection) GetLine(lineType DiffLineType, idx int) *DiffLine {
  179. var (
  180. difference = 0
  181. addCount = 0
  182. delCount = 0
  183. matchDiffLine *DiffLine
  184. )
  185. LOOP:
  186. for _, diffLine := range diffSection.Lines {
  187. switch diffLine.Type {
  188. case DiffLineAdd:
  189. addCount++
  190. case DiffLineDel:
  191. delCount++
  192. default:
  193. if matchDiffLine != nil {
  194. break LOOP
  195. }
  196. difference = diffLine.RightIdx - diffLine.LeftIdx
  197. addCount = 0
  198. delCount = 0
  199. }
  200. switch lineType {
  201. case DiffLineDel:
  202. if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference {
  203. matchDiffLine = diffLine
  204. }
  205. case DiffLineAdd:
  206. if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference {
  207. matchDiffLine = diffLine
  208. }
  209. }
  210. }
  211. if addCount == delCount {
  212. return matchDiffLine
  213. }
  214. return nil
  215. }
  216. var diffMatchPatch = diffmatchpatch.New()
  217. func init() {
  218. diffMatchPatch.DiffEditCost = 100
  219. }
  220. // GetComputedInlineDiffFor computes inline diff for the given line.
  221. func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) template.HTML {
  222. if setting.Git.DisableDiffHighlight {
  223. return template.HTML(getLineContent(diffLine.Content[1:]))
  224. }
  225. var (
  226. compareDiffLine *DiffLine
  227. diff1 string
  228. diff2 string
  229. )
  230. // try to find equivalent diff line. ignore, otherwise
  231. switch diffLine.Type {
  232. case DiffLineAdd:
  233. compareDiffLine = diffSection.GetLine(DiffLineDel, diffLine.RightIdx)
  234. if compareDiffLine == nil {
  235. return template.HTML(getLineContent(diffLine.Content[1:]))
  236. }
  237. diff1 = compareDiffLine.Content
  238. diff2 = diffLine.Content
  239. case DiffLineDel:
  240. compareDiffLine = diffSection.GetLine(DiffLineAdd, diffLine.LeftIdx)
  241. if compareDiffLine == nil {
  242. return template.HTML(getLineContent(diffLine.Content[1:]))
  243. }
  244. diff1 = diffLine.Content
  245. diff2 = compareDiffLine.Content
  246. default:
  247. if strings.IndexByte(" +-", diffLine.Content[0]) > -1 {
  248. return template.HTML(getLineContent(diffLine.Content[1:]))
  249. }
  250. return template.HTML(getLineContent(diffLine.Content))
  251. }
  252. diffRecord := diffMatchPatch.DiffMain(diff1[1:], diff2[1:], true)
  253. diffRecord = diffMatchPatch.DiffCleanupEfficiency(diffRecord)
  254. return diffToHTML(diffRecord, diffLine.Type)
  255. }
  256. // DiffFile represents a file diff.
  257. type DiffFile struct {
  258. Name string
  259. OldName string
  260. Index int
  261. Addition, Deletion int
  262. Type DiffFileType
  263. IsCreated bool
  264. IsDeleted bool
  265. IsBin bool
  266. IsLFSFile bool
  267. IsRenamed bool
  268. IsSubmodule bool
  269. Sections []*DiffSection
  270. IsIncomplete bool
  271. }
  272. // GetType returns type of diff file.
  273. func (diffFile *DiffFile) GetType() int {
  274. return int(diffFile.Type)
  275. }
  276. // GetHighlightClass returns highlight class for a filename.
  277. func (diffFile *DiffFile) GetHighlightClass() string {
  278. return highlight.FileNameToHighlightClass(diffFile.Name)
  279. }
  280. // GetTailSection creates a fake DiffLineSection if the last section is not the end of the file
  281. func (diffFile *DiffFile) GetTailSection(gitRepo *git.Repository, leftCommitID, rightCommitID string) *DiffSection {
  282. if len(diffFile.Sections) == 0 || diffFile.Type != DiffFileChange || diffFile.IsBin || diffFile.IsLFSFile {
  283. return nil
  284. }
  285. leftCommit, err := gitRepo.GetCommit(leftCommitID)
  286. if err != nil {
  287. return nil
  288. }
  289. rightCommit, err := gitRepo.GetCommit(rightCommitID)
  290. if err != nil {
  291. return nil
  292. }
  293. lastSection := diffFile.Sections[len(diffFile.Sections)-1]
  294. lastLine := lastSection.Lines[len(lastSection.Lines)-1]
  295. leftLineCount := getCommitFileLineCount(leftCommit, diffFile.Name)
  296. rightLineCount := getCommitFileLineCount(rightCommit, diffFile.Name)
  297. if leftLineCount <= lastLine.LeftIdx || rightLineCount <= lastLine.RightIdx {
  298. return nil
  299. }
  300. tailDiffLine := &DiffLine{
  301. Type: DiffLineSection,
  302. Content: " ",
  303. SectionInfo: &DiffLineSectionInfo{
  304. Path: diffFile.Name,
  305. LastLeftIdx: lastLine.LeftIdx,
  306. LastRightIdx: lastLine.RightIdx,
  307. LeftIdx: leftLineCount,
  308. RightIdx: rightLineCount,
  309. }}
  310. tailSection := &DiffSection{Lines: []*DiffLine{tailDiffLine}}
  311. return tailSection
  312. }
  313. func getCommitFileLineCount(commit *git.Commit, filePath string) int {
  314. blob, err := commit.GetBlobByPath(filePath)
  315. if err != nil {
  316. return 0
  317. }
  318. lineCount, err := blob.GetBlobLineCount()
  319. if err != nil {
  320. return 0
  321. }
  322. return lineCount
  323. }
  324. // Diff represents a difference between two git trees.
  325. type Diff struct {
  326. NumFiles, TotalAddition, TotalDeletion int
  327. Files []*DiffFile
  328. IsIncomplete bool
  329. }
  330. // LoadComments loads comments into each line
  331. func (diff *Diff) LoadComments(issue *models.Issue, currentUser *models.User) error {
  332. allComments, err := models.FetchCodeComments(issue, currentUser)
  333. if err != nil {
  334. return err
  335. }
  336. for _, file := range diff.Files {
  337. if lineCommits, ok := allComments[file.Name]; ok {
  338. for _, section := range file.Sections {
  339. for _, line := range section.Lines {
  340. if comments, ok := lineCommits[int64(line.LeftIdx*-1)]; ok {
  341. line.Comments = append(line.Comments, comments...)
  342. }
  343. if comments, ok := lineCommits[int64(line.RightIdx)]; ok {
  344. line.Comments = append(line.Comments, comments...)
  345. }
  346. sort.SliceStable(line.Comments, func(i, j int) bool {
  347. return line.Comments[i].CreatedUnix < line.Comments[j].CreatedUnix
  348. })
  349. }
  350. }
  351. }
  352. }
  353. return nil
  354. }
  355. const cmdDiffHead = "diff --git "
  356. // ParsePatch builds a Diff object from a io.Reader and some
  357. // parameters.
  358. // TODO: move this function to gogits/git-module
  359. func ParsePatch(maxLines, maxLineCharacters, maxFiles int, reader io.Reader) (*Diff, error) {
  360. var (
  361. diff = &Diff{Files: make([]*DiffFile, 0)}
  362. curFile = &DiffFile{}
  363. curSection = &DiffSection{
  364. Lines: make([]*DiffLine, 0, 10),
  365. }
  366. leftLine, rightLine int
  367. lineCount int
  368. curFileLinesCount int
  369. curFileLFSPrefix bool
  370. )
  371. input := bufio.NewReader(reader)
  372. isEOF := false
  373. for !isEOF {
  374. var linebuf bytes.Buffer
  375. for {
  376. b, err := input.ReadByte()
  377. if err != nil {
  378. if err == io.EOF {
  379. isEOF = true
  380. break
  381. } else {
  382. return nil, fmt.Errorf("ReadByte: %v", err)
  383. }
  384. }
  385. if b == '\n' {
  386. break
  387. }
  388. if linebuf.Len() < maxLineCharacters {
  389. linebuf.WriteByte(b)
  390. } else if linebuf.Len() == maxLineCharacters {
  391. curFile.IsIncomplete = true
  392. }
  393. }
  394. line := linebuf.String()
  395. if strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- ") || len(line) == 0 {
  396. continue
  397. }
  398. trimLine := strings.Trim(line, "+- ")
  399. if trimLine == models.LFSMetaFileIdentifier {
  400. curFileLFSPrefix = true
  401. }
  402. if curFileLFSPrefix && strings.HasPrefix(trimLine, models.LFSMetaFileOidPrefix) {
  403. oid := strings.TrimPrefix(trimLine, models.LFSMetaFileOidPrefix)
  404. if len(oid) == 64 {
  405. m := &models.LFSMetaObject{Oid: oid}
  406. count, err := models.Count(m)
  407. if err == nil && count > 0 {
  408. curFile.IsBin = true
  409. curFile.IsLFSFile = true
  410. curSection.Lines = nil
  411. }
  412. }
  413. }
  414. curFileLinesCount++
  415. lineCount++
  416. // Diff data too large, we only show the first about maxLines lines
  417. if curFileLinesCount >= maxLines {
  418. curFile.IsIncomplete = true
  419. }
  420. switch {
  421. case line[0] == ' ':
  422. diffLine := &DiffLine{Type: DiffLinePlain, Content: line, LeftIdx: leftLine, RightIdx: rightLine}
  423. leftLine++
  424. rightLine++
  425. curSection.Lines = append(curSection.Lines, diffLine)
  426. continue
  427. case line[0] == '@':
  428. curSection = &DiffSection{}
  429. curFile.Sections = append(curFile.Sections, curSection)
  430. lineSectionInfo := getDiffLineSectionInfo(curFile.Name, line, leftLine-1, rightLine-1)
  431. diffLine := &DiffLine{
  432. Type: DiffLineSection,
  433. Content: line,
  434. SectionInfo: lineSectionInfo,
  435. }
  436. curSection.Lines = append(curSection.Lines, diffLine)
  437. // update line number.
  438. leftLine = lineSectionInfo.LeftIdx
  439. rightLine = lineSectionInfo.RightIdx
  440. continue
  441. case line[0] == '+':
  442. curFile.Addition++
  443. diff.TotalAddition++
  444. diffLine := &DiffLine{Type: DiffLineAdd, Content: line, RightIdx: rightLine}
  445. rightLine++
  446. curSection.Lines = append(curSection.Lines, diffLine)
  447. continue
  448. case line[0] == '-':
  449. curFile.Deletion++
  450. diff.TotalDeletion++
  451. diffLine := &DiffLine{Type: DiffLineDel, Content: line, LeftIdx: leftLine}
  452. if leftLine > 0 {
  453. leftLine++
  454. }
  455. curSection.Lines = append(curSection.Lines, diffLine)
  456. case strings.HasPrefix(line, "Binary"):
  457. curFile.IsBin = true
  458. continue
  459. }
  460. // Get new file.
  461. if strings.HasPrefix(line, cmdDiffHead) {
  462. if len(diff.Files) >= maxFiles {
  463. diff.IsIncomplete = true
  464. _, err := io.Copy(ioutil.Discard, reader)
  465. if err != nil {
  466. return nil, fmt.Errorf("Copy: %v", err)
  467. }
  468. break
  469. }
  470. var middle int
  471. // Note: In case file name is surrounded by double quotes (it happens only in git-shell).
  472. // e.g. diff --git "a/xxx" "b/xxx"
  473. hasQuote := line[len(cmdDiffHead)] == '"'
  474. if hasQuote {
  475. middle = strings.Index(line, ` "b/`)
  476. } else {
  477. middle = strings.Index(line, " b/")
  478. }
  479. beg := len(cmdDiffHead)
  480. a := line[beg+2 : middle]
  481. b := line[middle+3:]
  482. if hasQuote {
  483. // Keep the entire string in double quotes for now
  484. a = line[beg:middle]
  485. b = line[middle+1:]
  486. var err error
  487. a, err = strconv.Unquote(a)
  488. if err != nil {
  489. return nil, fmt.Errorf("Unquote: %v", err)
  490. }
  491. b, err = strconv.Unquote(b)
  492. if err != nil {
  493. return nil, fmt.Errorf("Unquote: %v", err)
  494. }
  495. // Now remove the /a /b
  496. a = a[2:]
  497. b = b[2:]
  498. }
  499. curFile = &DiffFile{
  500. Name: b,
  501. OldName: a,
  502. Index: len(diff.Files) + 1,
  503. Type: DiffFileChange,
  504. Sections: make([]*DiffSection, 0, 10),
  505. IsRenamed: a != b,
  506. }
  507. diff.Files = append(diff.Files, curFile)
  508. curFileLinesCount = 0
  509. leftLine = 1
  510. rightLine = 1
  511. curFileLFSPrefix = false
  512. // Check file diff type and is submodule.
  513. for {
  514. line, err := input.ReadString('\n')
  515. if err != nil {
  516. if err == io.EOF {
  517. isEOF = true
  518. } else {
  519. return nil, fmt.Errorf("ReadString: %v", err)
  520. }
  521. }
  522. switch {
  523. case strings.HasPrefix(line, "new file"):
  524. curFile.Type = DiffFileAdd
  525. curFile.IsCreated = true
  526. case strings.HasPrefix(line, "deleted"):
  527. curFile.Type = DiffFileDel
  528. curFile.IsDeleted = true
  529. case strings.HasPrefix(line, "index"):
  530. curFile.Type = DiffFileChange
  531. case strings.HasPrefix(line, "similarity index 100%"):
  532. curFile.Type = DiffFileRename
  533. }
  534. if curFile.Type > 0 {
  535. if strings.HasSuffix(line, " 160000\n") {
  536. curFile.IsSubmodule = true
  537. }
  538. break
  539. }
  540. }
  541. }
  542. }
  543. // FIXME: detect encoding while parsing.
  544. var buf bytes.Buffer
  545. for _, f := range diff.Files {
  546. buf.Reset()
  547. for _, sec := range f.Sections {
  548. for _, l := range sec.Lines {
  549. buf.WriteString(l.Content)
  550. buf.WriteString("\n")
  551. }
  552. }
  553. charsetLabel, err := charset.DetectEncoding(buf.Bytes())
  554. if charsetLabel != "UTF-8" && err == nil {
  555. encoding, _ := stdcharset.Lookup(charsetLabel)
  556. if encoding != nil {
  557. d := encoding.NewDecoder()
  558. for _, sec := range f.Sections {
  559. for _, l := range sec.Lines {
  560. if c, _, err := transform.String(d, l.Content); err == nil {
  561. l.Content = c
  562. }
  563. }
  564. }
  565. }
  566. }
  567. }
  568. diff.NumFiles = len(diff.Files)
  569. return diff, nil
  570. }
  571. // GetDiffRange builds a Diff between two commits of a repository.
  572. // passing the empty string as beforeCommitID returns a diff from the
  573. // parent commit.
  574. func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacters, maxFiles int) (*Diff, error) {
  575. return GetDiffRangeWithWhitespaceBehavior(repoPath, beforeCommitID, afterCommitID, maxLines, maxLineCharacters, maxFiles, "")
  576. }
  577. // GetDiffRangeWithWhitespaceBehavior builds a Diff between two commits of a repository.
  578. // Passing the empty string as beforeCommitID returns a diff from the parent commit.
  579. // The whitespaceBehavior is either an empty string or a git flag
  580. func GetDiffRangeWithWhitespaceBehavior(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacters, maxFiles int, whitespaceBehavior string) (*Diff, error) {
  581. gitRepo, err := git.OpenRepository(repoPath)
  582. if err != nil {
  583. return nil, err
  584. }
  585. defer gitRepo.Close()
  586. commit, err := gitRepo.GetCommit(afterCommitID)
  587. if err != nil {
  588. return nil, err
  589. }
  590. // FIXME: graceful: These commands should likely have a timeout
  591. ctx, cancel := context.WithCancel(git.DefaultContext)
  592. defer cancel()
  593. var cmd *exec.Cmd
  594. if (len(beforeCommitID) == 0 || beforeCommitID == git.EmptySHA) && commit.ParentCount() == 0 {
  595. cmd = exec.CommandContext(ctx, git.GitExecutable, "show", afterCommitID)
  596. } else {
  597. actualBeforeCommitID := beforeCommitID
  598. if len(actualBeforeCommitID) == 0 {
  599. parentCommit, _ := commit.Parent(0)
  600. actualBeforeCommitID = parentCommit.ID.String()
  601. }
  602. diffArgs := []string{"diff", "-M"}
  603. if len(whitespaceBehavior) != 0 {
  604. diffArgs = append(diffArgs, whitespaceBehavior)
  605. }
  606. diffArgs = append(diffArgs, actualBeforeCommitID)
  607. diffArgs = append(diffArgs, afterCommitID)
  608. cmd = exec.CommandContext(ctx, git.GitExecutable, diffArgs...)
  609. beforeCommitID = actualBeforeCommitID
  610. }
  611. cmd.Dir = repoPath
  612. cmd.Stderr = os.Stderr
  613. stdout, err := cmd.StdoutPipe()
  614. if err != nil {
  615. return nil, fmt.Errorf("StdoutPipe: %v", err)
  616. }
  617. if err = cmd.Start(); err != nil {
  618. return nil, fmt.Errorf("Start: %v", err)
  619. }
  620. pid := process.GetManager().Add(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath), cancel)
  621. defer process.GetManager().Remove(pid)
  622. diff, err := ParsePatch(maxLines, maxLineCharacters, maxFiles, stdout)
  623. if err != nil {
  624. return nil, fmt.Errorf("ParsePatch: %v", err)
  625. }
  626. for _, diffFile := range diff.Files {
  627. tailSection := diffFile.GetTailSection(gitRepo, beforeCommitID, afterCommitID)
  628. if tailSection != nil {
  629. diffFile.Sections = append(diffFile.Sections, tailSection)
  630. }
  631. }
  632. if err = cmd.Wait(); err != nil {
  633. return nil, fmt.Errorf("Wait: %v", err)
  634. }
  635. shortstatArgs := []string{beforeCommitID + "..." + afterCommitID}
  636. if len(beforeCommitID) == 0 || beforeCommitID == git.EmptySHA {
  637. shortstatArgs = []string{git.EmptyTreeSHA, afterCommitID}
  638. }
  639. diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(repoPath, shortstatArgs...)
  640. if err != nil {
  641. return nil, err
  642. }
  643. return diff, nil
  644. }
  645. // GetDiffCommit builds a Diff representing the given commitID.
  646. func GetDiffCommit(repoPath, commitID string, maxLines, maxLineCharacters, maxFiles int) (*Diff, error) {
  647. return GetDiffRange(repoPath, "", commitID, maxLines, maxLineCharacters, maxFiles)
  648. }
  649. // CommentAsDiff returns c.Patch as *Diff
  650. func CommentAsDiff(c *models.Comment) (*Diff, error) {
  651. diff, err := ParsePatch(setting.Git.MaxGitDiffLines,
  652. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.Patch))
  653. if err != nil {
  654. return nil, err
  655. }
  656. if len(diff.Files) == 0 {
  657. return nil, fmt.Errorf("no file found for comment ID: %d", c.ID)
  658. }
  659. secs := diff.Files[0].Sections
  660. if len(secs) == 0 {
  661. return nil, fmt.Errorf("no sections found for comment ID: %d", c.ID)
  662. }
  663. return diff, nil
  664. }
  665. // CommentMustAsDiff executes AsDiff and logs the error instead of returning
  666. func CommentMustAsDiff(c *models.Comment) *Diff {
  667. diff, err := CommentAsDiff(c)
  668. if err != nil {
  669. log.Warn("CommentMustAsDiff: %v", err)
  670. }
  671. return diff
  672. }