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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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. 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. // NumFiles returns number of files changes in a diff.
  356. func (diff *Diff) NumFiles() int {
  357. return len(diff.Files)
  358. }
  359. const cmdDiffHead = "diff --git "
  360. // ParsePatch builds a Diff object from a io.Reader and some
  361. // parameters.
  362. // TODO: move this function to gogits/git-module
  363. func ParsePatch(maxLines, maxLineCharacters, maxFiles int, reader io.Reader) (*Diff, error) {
  364. var (
  365. diff = &Diff{Files: make([]*DiffFile, 0)}
  366. curFile = &DiffFile{}
  367. curSection = &DiffSection{
  368. Lines: make([]*DiffLine, 0, 10),
  369. }
  370. leftLine, rightLine int
  371. lineCount int
  372. curFileLinesCount int
  373. curFileLFSPrefix bool
  374. )
  375. input := bufio.NewReader(reader)
  376. isEOF := false
  377. for !isEOF {
  378. var linebuf bytes.Buffer
  379. for {
  380. b, err := input.ReadByte()
  381. if err != nil {
  382. if err == io.EOF {
  383. isEOF = true
  384. break
  385. } else {
  386. return nil, fmt.Errorf("ReadByte: %v", err)
  387. }
  388. }
  389. if b == '\n' {
  390. break
  391. }
  392. if linebuf.Len() < maxLineCharacters {
  393. linebuf.WriteByte(b)
  394. } else if linebuf.Len() == maxLineCharacters {
  395. curFile.IsIncomplete = true
  396. }
  397. }
  398. line := linebuf.String()
  399. if strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- ") || len(line) == 0 {
  400. continue
  401. }
  402. trimLine := strings.Trim(line, "+- ")
  403. if trimLine == models.LFSMetaFileIdentifier {
  404. curFileLFSPrefix = true
  405. }
  406. if curFileLFSPrefix && strings.HasPrefix(trimLine, models.LFSMetaFileOidPrefix) {
  407. oid := strings.TrimPrefix(trimLine, models.LFSMetaFileOidPrefix)
  408. if len(oid) == 64 {
  409. m := &models.LFSMetaObject{Oid: oid}
  410. count, err := models.Count(m)
  411. if err == nil && count > 0 {
  412. curFile.IsBin = true
  413. curFile.IsLFSFile = true
  414. curSection.Lines = nil
  415. }
  416. }
  417. }
  418. curFileLinesCount++
  419. lineCount++
  420. // Diff data too large, we only show the first about maxLines lines
  421. if curFileLinesCount >= maxLines {
  422. curFile.IsIncomplete = true
  423. }
  424. switch {
  425. case line[0] == ' ':
  426. diffLine := &DiffLine{Type: DiffLinePlain, Content: line, LeftIdx: leftLine, RightIdx: rightLine}
  427. leftLine++
  428. rightLine++
  429. curSection.Lines = append(curSection.Lines, diffLine)
  430. continue
  431. case line[0] == '@':
  432. curSection = &DiffSection{}
  433. curFile.Sections = append(curFile.Sections, curSection)
  434. lineSectionInfo := getDiffLineSectionInfo(curFile.Name, line, leftLine-1, rightLine-1)
  435. diffLine := &DiffLine{
  436. Type: DiffLineSection,
  437. Content: line,
  438. SectionInfo: lineSectionInfo,
  439. }
  440. curSection.Lines = append(curSection.Lines, diffLine)
  441. // update line number.
  442. leftLine = lineSectionInfo.LeftIdx
  443. rightLine = lineSectionInfo.RightIdx
  444. continue
  445. case line[0] == '+':
  446. curFile.Addition++
  447. diff.TotalAddition++
  448. diffLine := &DiffLine{Type: DiffLineAdd, Content: line, RightIdx: rightLine}
  449. rightLine++
  450. curSection.Lines = append(curSection.Lines, diffLine)
  451. continue
  452. case line[0] == '-':
  453. curFile.Deletion++
  454. diff.TotalDeletion++
  455. diffLine := &DiffLine{Type: DiffLineDel, Content: line, LeftIdx: leftLine}
  456. if leftLine > 0 {
  457. leftLine++
  458. }
  459. curSection.Lines = append(curSection.Lines, diffLine)
  460. case strings.HasPrefix(line, "Binary"):
  461. curFile.IsBin = true
  462. continue
  463. }
  464. // Get new file.
  465. if strings.HasPrefix(line, cmdDiffHead) {
  466. if len(diff.Files) >= maxFiles {
  467. diff.IsIncomplete = true
  468. _, err := io.Copy(ioutil.Discard, reader)
  469. if err != nil {
  470. return nil, fmt.Errorf("Copy: %v", err)
  471. }
  472. break
  473. }
  474. var middle int
  475. // Note: In case file name is surrounded by double quotes (it happens only in git-shell).
  476. // e.g. diff --git "a/xxx" "b/xxx"
  477. hasQuote := line[len(cmdDiffHead)] == '"'
  478. if hasQuote {
  479. middle = strings.Index(line, ` "b/`)
  480. } else {
  481. middle = strings.Index(line, " b/")
  482. }
  483. beg := len(cmdDiffHead)
  484. a := line[beg+2 : middle]
  485. b := line[middle+3:]
  486. if hasQuote {
  487. // Keep the entire string in double quotes for now
  488. a = line[beg:middle]
  489. b = line[middle+1:]
  490. var err error
  491. a, err = strconv.Unquote(a)
  492. if err != nil {
  493. return nil, fmt.Errorf("Unquote: %v", err)
  494. }
  495. b, err = strconv.Unquote(b)
  496. if err != nil {
  497. return nil, fmt.Errorf("Unquote: %v", err)
  498. }
  499. // Now remove the /a /b
  500. a = a[2:]
  501. b = b[2:]
  502. }
  503. curFile = &DiffFile{
  504. Name: b,
  505. OldName: a,
  506. Index: len(diff.Files) + 1,
  507. Type: DiffFileChange,
  508. Sections: make([]*DiffSection, 0, 10),
  509. IsRenamed: a != b,
  510. }
  511. diff.Files = append(diff.Files, curFile)
  512. curFileLinesCount = 0
  513. leftLine = 1
  514. rightLine = 1
  515. curFileLFSPrefix = false
  516. // Check file diff type and is submodule.
  517. for {
  518. line, err := input.ReadString('\n')
  519. if err != nil {
  520. if err == io.EOF {
  521. isEOF = true
  522. } else {
  523. return nil, fmt.Errorf("ReadString: %v", err)
  524. }
  525. }
  526. switch {
  527. case strings.HasPrefix(line, "new file"):
  528. curFile.Type = DiffFileAdd
  529. curFile.IsCreated = true
  530. case strings.HasPrefix(line, "deleted"):
  531. curFile.Type = DiffFileDel
  532. curFile.IsDeleted = true
  533. case strings.HasPrefix(line, "index"):
  534. curFile.Type = DiffFileChange
  535. case strings.HasPrefix(line, "similarity index 100%"):
  536. curFile.Type = DiffFileRename
  537. }
  538. if curFile.Type > 0 {
  539. if strings.HasSuffix(line, " 160000\n") {
  540. curFile.IsSubmodule = true
  541. }
  542. break
  543. }
  544. }
  545. }
  546. }
  547. // FIXME: detect encoding while parsing.
  548. var buf bytes.Buffer
  549. for _, f := range diff.Files {
  550. buf.Reset()
  551. for _, sec := range f.Sections {
  552. for _, l := range sec.Lines {
  553. buf.WriteString(l.Content)
  554. buf.WriteString("\n")
  555. }
  556. }
  557. charsetLabel, err := charset.DetectEncoding(buf.Bytes())
  558. if charsetLabel != "UTF-8" && err == nil {
  559. encoding, _ := stdcharset.Lookup(charsetLabel)
  560. if encoding != nil {
  561. d := encoding.NewDecoder()
  562. for _, sec := range f.Sections {
  563. for _, l := range sec.Lines {
  564. if c, _, err := transform.String(d, l.Content); err == nil {
  565. l.Content = c
  566. }
  567. }
  568. }
  569. }
  570. }
  571. }
  572. return diff, nil
  573. }
  574. // GetDiffRange builds a Diff between two commits of a repository.
  575. // passing the empty string as beforeCommitID returns a diff from the
  576. // parent commit.
  577. func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacters, maxFiles int) (*Diff, error) {
  578. return GetDiffRangeWithWhitespaceBehavior(repoPath, beforeCommitID, afterCommitID, maxLines, maxLineCharacters, maxFiles, "")
  579. }
  580. // GetDiffRangeWithWhitespaceBehavior builds a Diff between two commits of a repository.
  581. // Passing the empty string as beforeCommitID returns a diff from the parent commit.
  582. // The whitespaceBehavior is either an empty string or a git flag
  583. func GetDiffRangeWithWhitespaceBehavior(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacters, maxFiles int, whitespaceBehavior string) (*Diff, error) {
  584. gitRepo, err := git.OpenRepository(repoPath)
  585. if err != nil {
  586. return nil, err
  587. }
  588. defer gitRepo.Close()
  589. commit, err := gitRepo.GetCommit(afterCommitID)
  590. if err != nil {
  591. return nil, err
  592. }
  593. // FIXME: graceful: These commands should likely have a timeout
  594. ctx, cancel := context.WithCancel(git.DefaultContext)
  595. defer cancel()
  596. var cmd *exec.Cmd
  597. if len(beforeCommitID) == 0 && commit.ParentCount() == 0 {
  598. cmd = exec.CommandContext(ctx, git.GitExecutable, "show", afterCommitID)
  599. } else {
  600. actualBeforeCommitID := beforeCommitID
  601. if len(actualBeforeCommitID) == 0 {
  602. parentCommit, _ := commit.Parent(0)
  603. actualBeforeCommitID = parentCommit.ID.String()
  604. }
  605. diffArgs := []string{"diff", "-M"}
  606. if len(whitespaceBehavior) != 0 {
  607. diffArgs = append(diffArgs, whitespaceBehavior)
  608. }
  609. diffArgs = append(diffArgs, actualBeforeCommitID)
  610. diffArgs = append(diffArgs, afterCommitID)
  611. cmd = exec.CommandContext(ctx, git.GitExecutable, diffArgs...)
  612. beforeCommitID = actualBeforeCommitID
  613. }
  614. cmd.Dir = repoPath
  615. cmd.Stderr = os.Stderr
  616. stdout, err := cmd.StdoutPipe()
  617. if err != nil {
  618. return nil, fmt.Errorf("StdoutPipe: %v", err)
  619. }
  620. if err = cmd.Start(); err != nil {
  621. return nil, fmt.Errorf("Start: %v", err)
  622. }
  623. pid := process.GetManager().Add(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath), cancel)
  624. defer process.GetManager().Remove(pid)
  625. diff, err := ParsePatch(maxLines, maxLineCharacters, maxFiles, stdout)
  626. if err != nil {
  627. return nil, fmt.Errorf("ParsePatch: %v", err)
  628. }
  629. for _, diffFile := range diff.Files {
  630. tailSection := diffFile.GetTailSection(gitRepo, beforeCommitID, afterCommitID)
  631. if tailSection != nil {
  632. diffFile.Sections = append(diffFile.Sections, tailSection)
  633. }
  634. }
  635. if err = cmd.Wait(); err != nil {
  636. return nil, fmt.Errorf("Wait: %v", err)
  637. }
  638. return diff, nil
  639. }
  640. // GetDiffCommit builds a Diff representing the given commitID.
  641. func GetDiffCommit(repoPath, commitID string, maxLines, maxLineCharacters, maxFiles int) (*Diff, error) {
  642. return GetDiffRange(repoPath, "", commitID, maxLines, maxLineCharacters, maxFiles)
  643. }
  644. // CommentAsDiff returns c.Patch as *Diff
  645. func CommentAsDiff(c *models.Comment) (*Diff, error) {
  646. diff, err := ParsePatch(setting.Git.MaxGitDiffLines,
  647. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.Patch))
  648. if err != nil {
  649. return nil, err
  650. }
  651. if len(diff.Files) == 0 {
  652. return nil, fmt.Errorf("no file found for comment ID: %d", c.ID)
  653. }
  654. secs := diff.Files[0].Sections
  655. if len(secs) == 0 {
  656. return nil, fmt.Errorf("no sections found for comment ID: %d", c.ID)
  657. }
  658. return diff, nil
  659. }
  660. // CommentMustAsDiff executes AsDiff and logs the error instead of returning
  661. func CommentMustAsDiff(c *models.Comment) *Diff {
  662. diff, err := CommentAsDiff(c)
  663. if err != nil {
  664. log.Warn("CommentMustAsDiff: %v", err)
  665. }
  666. return diff
  667. }