git_diff.go 10 KB

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