git_diff.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bufio"
  7. "bytes"
  8. "fmt"
  9. "html"
  10. "html/template"
  11. "io"
  12. "io/ioutil"
  13. "os"
  14. "os/exec"
  15. "strings"
  16. "github.com/Unknwon/com"
  17. "github.com/sergi/go-diff/diffmatchpatch"
  18. "golang.org/x/net/html/charset"
  19. "golang.org/x/text/transform"
  20. "github.com/gogits/git-module"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/process"
  24. "github.com/gogits/gogs/modules/template/highlight"
  25. )
  26. type DiffLineType uint8
  27. const (
  28. DIFF_LINE_PLAIN DiffLineType = iota + 1
  29. DIFF_LINE_ADD
  30. DIFF_LINE_DEL
  31. DIFF_LINE_SECTION
  32. )
  33. type DiffFileType uint8
  34. const (
  35. DIFF_FILE_ADD DiffFileType = iota + 1
  36. DIFF_FILE_CHANGE
  37. DIFF_FILE_DEL
  38. DIFF_FILE_RENAME
  39. )
  40. type DiffLine struct {
  41. LeftIdx int
  42. RightIdx int
  43. Type DiffLineType
  44. Content string
  45. }
  46. func (d *DiffLine) GetType() int {
  47. return int(d.Type)
  48. }
  49. type DiffSection struct {
  50. Name string
  51. Lines []*DiffLine
  52. }
  53. var (
  54. addedCodePrefix = []byte("<span class=\"added-code\">")
  55. removedCodePrefix = []byte("<span class=\"removed-code\">")
  56. codeTagSuffix = []byte("</span>")
  57. )
  58. func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML {
  59. var buf bytes.Buffer
  60. for i := range diffs {
  61. if diffs[i].Type == diffmatchpatch.DiffInsert && lineType == DIFF_LINE_ADD {
  62. buf.Write(addedCodePrefix)
  63. buf.WriteString(html.EscapeString(diffs[i].Text))
  64. buf.Write(codeTagSuffix)
  65. } else if diffs[i].Type == diffmatchpatch.DiffDelete && lineType == DIFF_LINE_DEL {
  66. buf.Write(removedCodePrefix)
  67. buf.WriteString(html.EscapeString(diffs[i].Text))
  68. buf.Write(codeTagSuffix)
  69. } else if diffs[i].Type == diffmatchpatch.DiffEqual {
  70. buf.WriteString(html.EscapeString(diffs[i].Text))
  71. }
  72. }
  73. return template.HTML(buf.Bytes())
  74. }
  75. // get an specific line by type (add or del) and file line number
  76. func (diffSection *DiffSection) GetLine(lineType DiffLineType, idx int) *DiffLine {
  77. difference := 0
  78. for _, diffLine := range diffSection.Lines {
  79. if diffLine.Type == DIFF_LINE_PLAIN {
  80. // get the difference of line numbers between ADD and DEL versions
  81. difference = diffLine.RightIdx - diffLine.LeftIdx
  82. continue
  83. }
  84. if lineType == DIFF_LINE_DEL {
  85. if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference {
  86. return diffLine
  87. }
  88. } else if lineType == DIFF_LINE_ADD {
  89. if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference {
  90. return diffLine
  91. }
  92. }
  93. }
  94. return nil
  95. }
  96. // computes inline diff for the given line
  97. func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) template.HTML {
  98. var compareDiffLine *DiffLine
  99. var diff1, diff2 string
  100. getDefaultReturn := func() template.HTML {
  101. return template.HTML(html.EscapeString(diffLine.Content[1:]))
  102. }
  103. // just compute diff for adds and removes
  104. if diffLine.Type != DIFF_LINE_ADD && diffLine.Type != DIFF_LINE_DEL {
  105. return getDefaultReturn()
  106. }
  107. // try to find equivalent diff line. ignore, otherwise
  108. if diffLine.Type == DIFF_LINE_ADD {
  109. compareDiffLine = diffSection.GetLine(DIFF_LINE_DEL, diffLine.RightIdx)
  110. if compareDiffLine == nil {
  111. return getDefaultReturn()
  112. }
  113. diff1 = compareDiffLine.Content
  114. diff2 = diffLine.Content
  115. } else {
  116. compareDiffLine = diffSection.GetLine(DIFF_LINE_ADD, diffLine.LeftIdx)
  117. if compareDiffLine == nil {
  118. return getDefaultReturn()
  119. }
  120. diff1 = diffLine.Content
  121. diff2 = compareDiffLine.Content
  122. }
  123. dmp := diffmatchpatch.New()
  124. diffRecord := dmp.DiffMain(diff1[1:], diff2[1:], true)
  125. diffRecord = dmp.DiffCleanupSemantic(diffRecord)
  126. return diffToHTML(diffRecord, diffLine.Type)
  127. }
  128. type DiffFile struct {
  129. Name string
  130. OldName string
  131. Index int
  132. Addition, Deletion int
  133. Type DiffFileType
  134. IsCreated bool
  135. IsDeleted bool
  136. IsBin bool
  137. IsRenamed bool
  138. Sections []*DiffSection
  139. HighlightClass string
  140. }
  141. func (diffFile *DiffFile) GetType() int {
  142. return int(diffFile.Type)
  143. }
  144. func (diffFile *DiffFile) GetHighlightClass() string {
  145. if diffFile.HighlightClass == "" {
  146. diffFile.HighlightClass = highlight.FileNameToHighlightClass(diffFile.Name)
  147. }
  148. return diffFile.HighlightClass
  149. }
  150. type Diff struct {
  151. TotalAddition, TotalDeletion int
  152. Files []*DiffFile
  153. }
  154. func (diff *Diff) NumFiles() int {
  155. return len(diff.Files)
  156. }
  157. const DIFF_HEAD = "diff --git "
  158. func ParsePatch(maxlines int, reader io.Reader) (*Diff, error) {
  159. var (
  160. diff = &Diff{Files: make([]*DiffFile, 0)}
  161. curFile *DiffFile
  162. curSection = &DiffSection{
  163. Lines: make([]*DiffLine, 0, 10),
  164. }
  165. leftLine, rightLine int
  166. lineCount int
  167. )
  168. input := bufio.NewReader(reader)
  169. isEOF := false
  170. for {
  171. if isEOF {
  172. break
  173. }
  174. line, err := input.ReadString('\n')
  175. if err != nil {
  176. if err == io.EOF {
  177. isEOF = true
  178. } else {
  179. return nil, fmt.Errorf("ReadString: %v", err)
  180. }
  181. }
  182. if len(line) > 0 && line[len(line)-1] == '\n' {
  183. // Remove line break.
  184. line = line[:len(line)-1]
  185. }
  186. if strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- ") {
  187. continue
  188. } else if len(line) == 0 {
  189. continue
  190. }
  191. lineCount++
  192. // Diff data too large, we only show the first about maxlines lines
  193. if lineCount >= maxlines {
  194. log.Warn("Diff data too large")
  195. io.Copy(ioutil.Discard, reader)
  196. diff.Files = nil
  197. return diff, nil
  198. }
  199. switch {
  200. case line[0] == ' ':
  201. diffLine := &DiffLine{Type: DIFF_LINE_PLAIN, Content: line, LeftIdx: leftLine, RightIdx: rightLine}
  202. leftLine++
  203. rightLine++
  204. curSection.Lines = append(curSection.Lines, diffLine)
  205. continue
  206. case line[0] == '@':
  207. curSection = &DiffSection{}
  208. curFile.Sections = append(curFile.Sections, curSection)
  209. ss := strings.Split(line, "@@")
  210. diffLine := &DiffLine{Type: DIFF_LINE_SECTION, Content: line}
  211. curSection.Lines = append(curSection.Lines, diffLine)
  212. // Parse line number.
  213. ranges := strings.Split(ss[1][1:], " ")
  214. leftLine, _ = com.StrTo(strings.Split(ranges[0], ",")[0][1:]).Int()
  215. if len(ranges) > 1 {
  216. rightLine, _ = com.StrTo(strings.Split(ranges[1], ",")[0]).Int()
  217. } else {
  218. log.Warn("Parse line number failed: %v", line)
  219. rightLine = leftLine
  220. }
  221. continue
  222. case line[0] == '+':
  223. curFile.Addition++
  224. diff.TotalAddition++
  225. diffLine := &DiffLine{Type: DIFF_LINE_ADD, Content: line, RightIdx: rightLine}
  226. rightLine++
  227. curSection.Lines = append(curSection.Lines, diffLine)
  228. continue
  229. case line[0] == '-':
  230. curFile.Deletion++
  231. diff.TotalDeletion++
  232. diffLine := &DiffLine{Type: DIFF_LINE_DEL, Content: line, LeftIdx: leftLine}
  233. if leftLine > 0 {
  234. leftLine++
  235. }
  236. curSection.Lines = append(curSection.Lines, diffLine)
  237. case strings.HasPrefix(line, "Binary"):
  238. curFile.IsBin = true
  239. continue
  240. }
  241. // Get new file.
  242. if strings.HasPrefix(line, DIFF_HEAD) {
  243. middle := -1
  244. // Note: In case file name is surrounded by double quotes (it happens only in git-shell).
  245. // e.g. diff --git "a/xxx" "b/xxx"
  246. hasQuote := line[len(DIFF_HEAD)] == '"'
  247. if hasQuote {
  248. middle = strings.Index(line, ` "b/`)
  249. } else {
  250. middle = strings.Index(line, " b/")
  251. }
  252. beg := len(DIFF_HEAD)
  253. a := line[beg+2 : middle]
  254. b := line[middle+3:]
  255. if hasQuote {
  256. a = string(git.UnescapeChars([]byte(a[1 : len(a)-1])))
  257. b = string(git.UnescapeChars([]byte(b[1 : len(b)-1])))
  258. }
  259. curFile = &DiffFile{
  260. Name: a,
  261. Index: len(diff.Files) + 1,
  262. Type: DIFF_FILE_CHANGE,
  263. Sections: make([]*DiffSection, 0, 10),
  264. }
  265. diff.Files = append(diff.Files, curFile)
  266. // Check file diff type.
  267. for {
  268. line, err := input.ReadString('\n')
  269. if err != nil {
  270. if err == io.EOF {
  271. isEOF = true
  272. } else {
  273. return nil, fmt.Errorf("ReadString: %v", err)
  274. }
  275. }
  276. switch {
  277. case strings.HasPrefix(line, "new file"):
  278. curFile.Type = DIFF_FILE_ADD
  279. curFile.IsCreated = true
  280. case strings.HasPrefix(line, "deleted"):
  281. curFile.Type = DIFF_FILE_DEL
  282. curFile.IsDeleted = true
  283. case strings.HasPrefix(line, "index"):
  284. curFile.Type = DIFF_FILE_CHANGE
  285. case strings.HasPrefix(line, "similarity index 100%"):
  286. curFile.Type = DIFF_FILE_RENAME
  287. curFile.IsRenamed = true
  288. curFile.OldName = curFile.Name
  289. curFile.Name = b
  290. }
  291. if curFile.Type > 0 {
  292. break
  293. }
  294. }
  295. }
  296. }
  297. // FIXME: detect encoding while parsing.
  298. var buf bytes.Buffer
  299. for _, f := range diff.Files {
  300. buf.Reset()
  301. for _, sec := range f.Sections {
  302. for _, l := range sec.Lines {
  303. buf.WriteString(l.Content)
  304. buf.WriteString("\n")
  305. }
  306. }
  307. charsetLabel, err := base.DetectEncoding(buf.Bytes())
  308. if charsetLabel != "UTF-8" && err == nil {
  309. encoding, _ := charset.Lookup(charsetLabel)
  310. if encoding != nil {
  311. d := encoding.NewDecoder()
  312. for _, sec := range f.Sections {
  313. for _, l := range sec.Lines {
  314. if c, _, err := transform.String(d, l.Content); err == nil {
  315. l.Content = c
  316. }
  317. }
  318. }
  319. }
  320. }
  321. }
  322. return diff, nil
  323. }
  324. func GetDiffRange(repoPath, beforeCommitID string, afterCommitID string, maxlines int) (*Diff, error) {
  325. repo, err := git.OpenRepository(repoPath)
  326. if err != nil {
  327. return nil, err
  328. }
  329. commit, err := repo.GetCommit(afterCommitID)
  330. if err != nil {
  331. return nil, err
  332. }
  333. var cmd *exec.Cmd
  334. // if "after" commit given
  335. if len(beforeCommitID) == 0 {
  336. // First commit of repository.
  337. if commit.ParentCount() == 0 {
  338. cmd = exec.Command("git", "show", afterCommitID)
  339. } else {
  340. c, _ := commit.Parent(0)
  341. cmd = exec.Command("git", "diff", "-M", c.ID.String(), afterCommitID)
  342. }
  343. } else {
  344. cmd = exec.Command("git", "diff", "-M", beforeCommitID, afterCommitID)
  345. }
  346. cmd.Dir = repoPath
  347. cmd.Stderr = os.Stderr
  348. stdout, err := cmd.StdoutPipe()
  349. if err != nil {
  350. return nil, fmt.Errorf("StdoutPipe: %v", err)
  351. }
  352. if err = cmd.Start(); err != nil {
  353. return nil, fmt.Errorf("Start: %v", err)
  354. }
  355. pid := process.Add(fmt.Sprintf("GetDiffRange (%s)", repoPath), cmd)
  356. defer process.Remove(pid)
  357. diff, err := ParsePatch(maxlines, stdout)
  358. if err != nil {
  359. return nil, fmt.Errorf("ParsePatch: %v", err)
  360. }
  361. if err = cmd.Wait(); err != nil {
  362. return nil, fmt.Errorf("Wait: %v", err)
  363. }
  364. return diff, nil
  365. }
  366. func GetDiffCommit(repoPath, commitId string, maxlines int) (*Diff, error) {
  367. return GetDiffRange(repoPath, "", commitId, maxlines)
  368. }