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.

git_diff.go 9.8KB

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