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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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. "strings"
  20. "code.gitea.io/gitea/models"
  21. "code.gitea.io/gitea/modules/charset"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/highlight"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/process"
  26. "code.gitea.io/gitea/modules/setting"
  27. "github.com/sergi/go-diff/diffmatchpatch"
  28. stdcharset "golang.org/x/net/html/charset"
  29. "golang.org/x/text/transform"
  30. )
  31. // DiffLineType represents the type of a DiffLine.
  32. type DiffLineType uint8
  33. // DiffLineType possible values.
  34. const (
  35. DiffLinePlain DiffLineType = iota + 1
  36. DiffLineAdd
  37. DiffLineDel
  38. DiffLineSection
  39. )
  40. // DiffFileType represents the type of a DiffFile.
  41. type DiffFileType uint8
  42. // DiffFileType possible values.
  43. const (
  44. DiffFileAdd DiffFileType = iota + 1
  45. DiffFileChange
  46. DiffFileDel
  47. DiffFileRename
  48. DiffFileCopy
  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 parameters.
  361. func ParsePatch(maxLines, maxLineCharacters, maxFiles int, reader io.Reader) (*Diff, error) {
  362. var curFile *DiffFile
  363. diff := &Diff{Files: make([]*DiffFile, 0)}
  364. sb := strings.Builder{}
  365. // OK let's set a reasonable buffer size.
  366. // This should be let's say at least the size of maxLineCharacters or 4096 whichever is larger.
  367. readerSize := maxLineCharacters
  368. if readerSize < 4096 {
  369. readerSize = 4096
  370. }
  371. input := bufio.NewReaderSize(reader, readerSize)
  372. line, err := input.ReadString('\n')
  373. if err != nil {
  374. if err == io.EOF {
  375. return diff, nil
  376. }
  377. return diff, err
  378. }
  379. parsingLoop:
  380. for {
  381. // 1. A patch file always begins with `diff --git ` + `a/path b/path` (possibly quoted)
  382. // if it does not we have bad input!
  383. if !strings.HasPrefix(line, cmdDiffHead) {
  384. return diff, fmt.Errorf("Invalid first file line: %s", line)
  385. }
  386. // TODO: Handle skipping first n files
  387. if len(diff.Files) >= maxFiles {
  388. diff.IsIncomplete = true
  389. _, err := io.Copy(ioutil.Discard, reader)
  390. if err != nil {
  391. // By the definition of io.Copy this never returns io.EOF
  392. return diff, fmt.Errorf("Copy: %v", err)
  393. }
  394. break parsingLoop
  395. }
  396. curFile = createDiffFile(diff, line)
  397. diff.Files = append(diff.Files, curFile)
  398. // 2. It is followed by one or more extended header lines:
  399. //
  400. // old mode <mode>
  401. // new mode <mode>
  402. // deleted file mode <mode>
  403. // new file mode <mode>
  404. // copy from <path>
  405. // copy to <path>
  406. // rename from <path>
  407. // rename to <path>
  408. // similarity index <number>
  409. // dissimilarity index <number>
  410. // index <hash>..<hash> <mode>
  411. //
  412. // * <mode> 6-digit octal numbers including the file type and file permission bits.
  413. // * <path> does not include the a/ and b/ prefixes
  414. // * <number> percentage of unchanged lines for similarity, percentage of changed
  415. // lines dissimilarity as integer rounded down with terminal %. 100% => equal files.
  416. // * The index line includes the blob object names before and after the change.
  417. // The <mode> is included if the file mode does not change; otherwise, separate
  418. // lines indicate the old and the new mode.
  419. // 3. Following this header the "standard unified" diff format header may be encountered: (but not for every case...)
  420. //
  421. // --- a/<path>
  422. // +++ b/<path>
  423. //
  424. // With multiple hunks
  425. //
  426. // @@ <hunk descriptor> @@
  427. // +added line
  428. // -removed line
  429. // unchanged line
  430. //
  431. // 4. Binary files get:
  432. //
  433. // Binary files a/<path> and b/<path> differ
  434. //
  435. // but one of a/<path> and b/<path> could be /dev/null.
  436. curFileLoop:
  437. for {
  438. line, err = input.ReadString('\n')
  439. if err != nil {
  440. if err != io.EOF {
  441. return diff, err
  442. }
  443. break parsingLoop
  444. }
  445. switch {
  446. case strings.HasPrefix(line, cmdDiffHead):
  447. break curFileLoop
  448. case strings.HasPrefix(line, "old mode ") ||
  449. strings.HasPrefix(line, "new mode "):
  450. if strings.HasSuffix(line, " 160000\n") {
  451. curFile.IsSubmodule = true
  452. }
  453. case strings.HasPrefix(line, "copy from "):
  454. curFile.IsRenamed = true
  455. curFile.Type = DiffFileCopy
  456. case strings.HasPrefix(line, "copy to "):
  457. curFile.IsRenamed = true
  458. curFile.Type = DiffFileCopy
  459. case strings.HasPrefix(line, "new file"):
  460. curFile.Type = DiffFileAdd
  461. curFile.IsCreated = true
  462. if strings.HasSuffix(line, " 160000\n") {
  463. curFile.IsSubmodule = true
  464. }
  465. case strings.HasPrefix(line, "deleted"):
  466. curFile.Type = DiffFileDel
  467. curFile.IsDeleted = true
  468. if strings.HasSuffix(line, " 160000\n") {
  469. curFile.IsSubmodule = true
  470. }
  471. case strings.HasPrefix(line, "index"):
  472. if strings.HasSuffix(line, " 160000\n") {
  473. curFile.IsSubmodule = true
  474. }
  475. case strings.HasPrefix(line, "similarity index 100%"):
  476. curFile.Type = DiffFileRename
  477. case strings.HasPrefix(line, "Binary"):
  478. curFile.IsBin = true
  479. case strings.HasPrefix(line, "--- "):
  480. // Do nothing with this line
  481. case strings.HasPrefix(line, "+++ "):
  482. // Do nothing with this line
  483. lineBytes, isFragment, err := parseHunks(curFile, maxLines, maxLineCharacters, input)
  484. diff.TotalAddition += curFile.Addition
  485. diff.TotalDeletion += curFile.Deletion
  486. if err != nil {
  487. if err != io.EOF {
  488. return diff, err
  489. }
  490. break parsingLoop
  491. }
  492. sb.Reset()
  493. _, _ = sb.Write(lineBytes)
  494. for isFragment {
  495. lineBytes, isFragment, err = input.ReadLine()
  496. if err != nil {
  497. // Now by the definition of ReadLine this cannot be io.EOF
  498. return diff, fmt.Errorf("Unable to ReadLine: %v", err)
  499. }
  500. _, _ = sb.Write(lineBytes)
  501. }
  502. line = sb.String()
  503. sb.Reset()
  504. break curFileLoop
  505. }
  506. }
  507. }
  508. // FIXME: There are numerous issues with this:
  509. // - we might want to consider detecting encoding while parsing but...
  510. // - we're likely to fail to get the correct encoding here anyway as we won't have enough information
  511. // - and this doesn't really account for changes in encoding
  512. var buf bytes.Buffer
  513. for _, f := range diff.Files {
  514. buf.Reset()
  515. for _, sec := range f.Sections {
  516. for _, l := range sec.Lines {
  517. if l.Type == DiffLineSection {
  518. continue
  519. }
  520. buf.WriteString(l.Content[1:])
  521. buf.WriteString("\n")
  522. }
  523. }
  524. charsetLabel, err := charset.DetectEncoding(buf.Bytes())
  525. if charsetLabel != "UTF-8" && err == nil {
  526. encoding, _ := stdcharset.Lookup(charsetLabel)
  527. if encoding != nil {
  528. d := encoding.NewDecoder()
  529. for _, sec := range f.Sections {
  530. for _, l := range sec.Lines {
  531. if l.Type == DiffLineSection {
  532. continue
  533. }
  534. if c, _, err := transform.String(d, l.Content[1:]); err == nil {
  535. l.Content = l.Content[0:1] + c
  536. }
  537. }
  538. }
  539. }
  540. }
  541. }
  542. return diff, nil
  543. }
  544. func parseHunks(curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio.Reader) (lineBytes []byte, isFragment bool, err error) {
  545. sb := strings.Builder{}
  546. var (
  547. curSection *DiffSection
  548. curFileLinesCount int
  549. curFileLFSPrefix bool
  550. )
  551. leftLine, rightLine := 1, 1
  552. for {
  553. sb.Reset()
  554. lineBytes, isFragment, err = input.ReadLine()
  555. if err != nil {
  556. if err == io.EOF {
  557. return
  558. }
  559. err = fmt.Errorf("Unable to ReadLine: %v", err)
  560. return
  561. }
  562. if lineBytes[0] == 'd' {
  563. // End of hunks
  564. return
  565. }
  566. switch lineBytes[0] {
  567. case '@':
  568. if curFileLinesCount >= maxLines {
  569. curFile.IsIncomplete = true
  570. continue
  571. }
  572. _, _ = sb.Write(lineBytes)
  573. for isFragment {
  574. // This is very odd indeed - we're in a section header and the line is too long
  575. // This really shouldn't happen...
  576. lineBytes, isFragment, err = input.ReadLine()
  577. if err != nil {
  578. // Now by the definition of ReadLine this cannot be io.EOF
  579. err = fmt.Errorf("Unable to ReadLine: %v", err)
  580. return
  581. }
  582. _, _ = sb.Write(lineBytes)
  583. }
  584. line := sb.String()
  585. // Create a new section to represent this hunk
  586. curSection = &DiffSection{}
  587. curFile.Sections = append(curFile.Sections, curSection)
  588. lineSectionInfo := getDiffLineSectionInfo(curFile.Name, line, leftLine-1, rightLine-1)
  589. diffLine := &DiffLine{
  590. Type: DiffLineSection,
  591. Content: line,
  592. SectionInfo: lineSectionInfo,
  593. }
  594. curSection.Lines = append(curSection.Lines, diffLine)
  595. // update line number.
  596. leftLine = lineSectionInfo.LeftIdx
  597. rightLine = lineSectionInfo.RightIdx
  598. continue
  599. case '\\':
  600. if curFileLinesCount >= maxLines {
  601. curFile.IsIncomplete = true
  602. continue
  603. }
  604. // This is used only to indicate that the current file does not have a terminal newline
  605. if !bytes.Equal(lineBytes, []byte("\\ No newline at end of file")) {
  606. err = fmt.Errorf("Unexpected line in hunk: %s", string(lineBytes))
  607. return
  608. }
  609. // Technically this should be the end the file!
  610. // FIXME: we should be putting a marker at the end of the file if there is no terminal new line
  611. continue
  612. case '+':
  613. curFileLinesCount++
  614. curFile.Addition++
  615. if curFileLinesCount >= maxLines {
  616. curFile.IsIncomplete = true
  617. continue
  618. }
  619. diffLine := &DiffLine{Type: DiffLineAdd, RightIdx: rightLine}
  620. rightLine++
  621. curSection.Lines = append(curSection.Lines, diffLine)
  622. case '-':
  623. curFileLinesCount++
  624. curFile.Deletion++
  625. if curFileLinesCount >= maxLines {
  626. curFile.IsIncomplete = true
  627. continue
  628. }
  629. diffLine := &DiffLine{Type: DiffLineDel, LeftIdx: leftLine}
  630. if leftLine > 0 {
  631. leftLine++
  632. }
  633. curSection.Lines = append(curSection.Lines, diffLine)
  634. case ' ':
  635. curFileLinesCount++
  636. if curFileLinesCount >= maxLines {
  637. curFile.IsIncomplete = true
  638. continue
  639. }
  640. diffLine := &DiffLine{Type: DiffLinePlain, LeftIdx: leftLine, RightIdx: rightLine}
  641. leftLine++
  642. rightLine++
  643. curSection.Lines = append(curSection.Lines, diffLine)
  644. default:
  645. // This is unexpected
  646. err = fmt.Errorf("Unexpected line in hunk: %s", string(lineBytes))
  647. return
  648. }
  649. line := string(lineBytes)
  650. if isFragment {
  651. curFile.IsIncomplete = true
  652. for isFragment {
  653. lineBytes, isFragment, err = input.ReadLine()
  654. if err != nil {
  655. // Now by the definition of ReadLine this cannot be io.EOF
  656. err = fmt.Errorf("Unable to ReadLine: %v", err)
  657. return
  658. }
  659. }
  660. }
  661. curSection.Lines[len(curSection.Lines)-1].Content = line
  662. // handle LFS
  663. if line[1:] == models.LFSMetaFileIdentifier {
  664. curFileLFSPrefix = true
  665. } else if curFileLFSPrefix && strings.HasPrefix(line[1:], models.LFSMetaFileOidPrefix) {
  666. oid := strings.TrimPrefix(line[1:], models.LFSMetaFileOidPrefix)
  667. if len(oid) == 64 {
  668. m := &models.LFSMetaObject{Oid: oid}
  669. count, err := models.Count(m)
  670. if err == nil && count > 0 {
  671. curFile.IsBin = true
  672. curFile.IsLFSFile = true
  673. curSection.Lines = nil
  674. }
  675. }
  676. }
  677. }
  678. }
  679. func createDiffFile(diff *Diff, line string) *DiffFile {
  680. // The a/ and b/ filenames are the same unless rename/copy is involved.
  681. // Especially, even for a creation or a deletion, /dev/null is not used
  682. // in place of the a/ or b/ filenames.
  683. //
  684. // When rename/copy is involved, file1 and file2 show the name of the
  685. // source file of the rename/copy and the name of the file that rename/copy
  686. // produces, respectively.
  687. //
  688. // Path names are quoted if necessary.
  689. //
  690. // This means that you should always be able to determine the file name even when there
  691. // there is potential ambiguity...
  692. //
  693. // but we can be simpler with our heuristics by just forcing git to prefix things nicely
  694. curFile := &DiffFile{
  695. Index: len(diff.Files) + 1,
  696. Type: DiffFileChange,
  697. Sections: make([]*DiffSection, 0, 10),
  698. }
  699. rd := strings.NewReader(line[len(cmdDiffHead):] + " ")
  700. curFile.Type = DiffFileChange
  701. curFile.OldName = readFileName(rd)
  702. curFile.Name = readFileName(rd)
  703. curFile.IsRenamed = curFile.Name != curFile.OldName
  704. return curFile
  705. }
  706. func readFileName(rd *strings.Reader) string {
  707. var name string
  708. char, _ := rd.ReadByte()
  709. _ = rd.UnreadByte()
  710. if char == '"' {
  711. fmt.Fscanf(rd, "%q ", &name)
  712. if name[0] == '\\' {
  713. name = name[1:]
  714. }
  715. } else {
  716. fmt.Fscanf(rd, "%s ", &name)
  717. }
  718. return name[2:]
  719. }
  720. // GetDiffRange builds a Diff between two commits of a repository.
  721. // passing the empty string as beforeCommitID returns a diff from the
  722. // parent commit.
  723. func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacters, maxFiles int) (*Diff, error) {
  724. return GetDiffRangeWithWhitespaceBehavior(repoPath, beforeCommitID, afterCommitID, maxLines, maxLineCharacters, maxFiles, "")
  725. }
  726. // GetDiffRangeWithWhitespaceBehavior builds a Diff between two commits of a repository.
  727. // Passing the empty string as beforeCommitID returns a diff from the parent commit.
  728. // The whitespaceBehavior is either an empty string or a git flag
  729. func GetDiffRangeWithWhitespaceBehavior(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacters, maxFiles int, whitespaceBehavior string) (*Diff, error) {
  730. gitRepo, err := git.OpenRepository(repoPath)
  731. if err != nil {
  732. return nil, err
  733. }
  734. defer gitRepo.Close()
  735. commit, err := gitRepo.GetCommit(afterCommitID)
  736. if err != nil {
  737. return nil, err
  738. }
  739. // FIXME: graceful: These commands should likely have a timeout
  740. ctx, cancel := context.WithCancel(git.DefaultContext)
  741. defer cancel()
  742. var cmd *exec.Cmd
  743. if (len(beforeCommitID) == 0 || beforeCommitID == git.EmptySHA) && commit.ParentCount() == 0 {
  744. diffArgs := []string{"diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M"}
  745. if len(whitespaceBehavior) != 0 {
  746. diffArgs = append(diffArgs, whitespaceBehavior)
  747. }
  748. // append empty tree ref
  749. diffArgs = append(diffArgs, "4b825dc642cb6eb9a060e54bf8d69288fbee4904")
  750. diffArgs = append(diffArgs, afterCommitID)
  751. cmd = exec.CommandContext(ctx, git.GitExecutable, diffArgs...)
  752. } else {
  753. actualBeforeCommitID := beforeCommitID
  754. if len(actualBeforeCommitID) == 0 {
  755. parentCommit, _ := commit.Parent(0)
  756. actualBeforeCommitID = parentCommit.ID.String()
  757. }
  758. diffArgs := []string{"diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M"}
  759. if len(whitespaceBehavior) != 0 {
  760. diffArgs = append(diffArgs, whitespaceBehavior)
  761. }
  762. diffArgs = append(diffArgs, actualBeforeCommitID)
  763. diffArgs = append(diffArgs, afterCommitID)
  764. cmd = exec.CommandContext(ctx, git.GitExecutable, diffArgs...)
  765. beforeCommitID = actualBeforeCommitID
  766. }
  767. cmd.Dir = repoPath
  768. cmd.Stderr = os.Stderr
  769. stdout, err := cmd.StdoutPipe()
  770. if err != nil {
  771. return nil, fmt.Errorf("StdoutPipe: %v", err)
  772. }
  773. if err = cmd.Start(); err != nil {
  774. return nil, fmt.Errorf("Start: %v", err)
  775. }
  776. pid := process.GetManager().Add(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath), cancel)
  777. defer process.GetManager().Remove(pid)
  778. diff, err := ParsePatch(maxLines, maxLineCharacters, maxFiles, stdout)
  779. if err != nil {
  780. return nil, fmt.Errorf("ParsePatch: %v", err)
  781. }
  782. for _, diffFile := range diff.Files {
  783. tailSection := diffFile.GetTailSection(gitRepo, beforeCommitID, afterCommitID)
  784. if tailSection != nil {
  785. diffFile.Sections = append(diffFile.Sections, tailSection)
  786. }
  787. }
  788. if err = cmd.Wait(); err != nil {
  789. return nil, fmt.Errorf("Wait: %v", err)
  790. }
  791. return diff, nil
  792. }
  793. // GetDiffCommit builds a Diff representing the given commitID.
  794. func GetDiffCommit(repoPath, commitID string, maxLines, maxLineCharacters, maxFiles int) (*Diff, error) {
  795. return GetDiffRange(repoPath, "", commitID, maxLines, maxLineCharacters, maxFiles)
  796. }
  797. // CommentAsDiff returns c.Patch as *Diff
  798. func CommentAsDiff(c *models.Comment) (*Diff, error) {
  799. diff, err := ParsePatch(setting.Git.MaxGitDiffLines,
  800. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.Patch))
  801. if err != nil {
  802. return nil, err
  803. }
  804. if len(diff.Files) == 0 {
  805. return nil, fmt.Errorf("no file found for comment ID: %d", c.ID)
  806. }
  807. secs := diff.Files[0].Sections
  808. if len(secs) == 0 {
  809. return nil, fmt.Errorf("no sections found for comment ID: %d", c.ID)
  810. }
  811. return diff, nil
  812. }
  813. // CommentMustAsDiff executes AsDiff and logs the error instead of returning
  814. func CommentMustAsDiff(c *models.Comment) *Diff {
  815. diff, err := CommentAsDiff(c)
  816. if err != nil {
  817. log.Warn("CommentMustAsDiff: %v", err)
  818. }
  819. return diff
  820. }