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.

418 lines
10 KiB

10 years ago
10 years ago
8 years ago
8 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. 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. 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 diff of each diff line and set the HTML on diffLine.ParsedContent
  97. func (diffSection *DiffSection) ComputeLinesDiff() {
  98. for _, diffLine := range diffSection.Lines {
  99. var compareDiffLine *DiffLine
  100. var diff1, diff2 string
  101. diffLine.ParsedContent = template.HTML(html.EscapeString(diffLine.Content[1:]))
  102. // just compute diff for adds and removes
  103. if diffLine.Type != DIFF_LINE_ADD && diffLine.Type != DIFF_LINE_DEL {
  104. continue
  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. continue
  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. continue
  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. diffLine.ParsedContent = diffToHTML(diffRecord, diffLine.Type)
  126. }
  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. }
  140. func (diffFile *DiffFile) GetType() int {
  141. return int(diffFile.Type)
  142. }
  143. type Diff struct {
  144. TotalAddition, TotalDeletion int
  145. Files []*DiffFile
  146. }
  147. func (diff *Diff) NumFiles() int {
  148. return len(diff.Files)
  149. }
  150. const DIFF_HEAD = "diff --git "
  151. func ParsePatch(maxlines int, reader io.Reader) (*Diff, error) {
  152. var (
  153. diff = &Diff{Files: make([]*DiffFile, 0)}
  154. curFile *DiffFile
  155. curSection = &DiffSection{
  156. Lines: make([]*DiffLine, 0, 10),
  157. }
  158. leftLine, rightLine int
  159. lineCount int
  160. )
  161. input := bufio.NewReader(reader)
  162. isEOF := false
  163. for {
  164. if isEOF {
  165. break
  166. }
  167. line, err := input.ReadString('\n')
  168. if err != nil {
  169. if err == io.EOF {
  170. isEOF = true
  171. } else {
  172. return nil, fmt.Errorf("ReadString: %v", err)
  173. }
  174. }
  175. if len(line) > 0 && line[len(line)-1] == '\n' {
  176. // Remove line break.
  177. line = line[:len(line)-1]
  178. }
  179. if strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- ") {
  180. continue
  181. } else if len(line) == 0 {
  182. continue
  183. }
  184. lineCount++
  185. // Diff data too large, we only show the first about maxlines lines
  186. if lineCount >= maxlines {
  187. log.Warn("Diff data too large")
  188. io.Copy(ioutil.Discard, reader)
  189. diff.Files = nil
  190. return diff, nil
  191. }
  192. switch {
  193. case line[0] == ' ':
  194. diffLine := &DiffLine{Type: DIFF_LINE_PLAIN, Content: line, LeftIdx: leftLine, RightIdx: rightLine}
  195. leftLine++
  196. rightLine++
  197. curSection.Lines = append(curSection.Lines, diffLine)
  198. continue
  199. case line[0] == '@':
  200. curSection = &DiffSection{}
  201. curFile.Sections = append(curFile.Sections, curSection)
  202. ss := strings.Split(line, "@@")
  203. diffLine := &DiffLine{Type: DIFF_LINE_SECTION, Content: line}
  204. curSection.Lines = append(curSection.Lines, diffLine)
  205. // Parse line number.
  206. ranges := strings.Split(ss[1][1:], " ")
  207. leftLine, _ = com.StrTo(strings.Split(ranges[0], ",")[0][1:]).Int()
  208. if len(ranges) > 1 {
  209. rightLine, _ = com.StrTo(strings.Split(ranges[1], ",")[0]).Int()
  210. } else {
  211. log.Warn("Parse line number failed: %v", line)
  212. rightLine = leftLine
  213. }
  214. continue
  215. case line[0] == '+':
  216. curFile.Addition++
  217. diff.TotalAddition++
  218. diffLine := &DiffLine{Type: DIFF_LINE_ADD, Content: line, RightIdx: rightLine}
  219. rightLine++
  220. curSection.Lines = append(curSection.Lines, diffLine)
  221. continue
  222. case line[0] == '-':
  223. curFile.Deletion++
  224. diff.TotalDeletion++
  225. diffLine := &DiffLine{Type: DIFF_LINE_DEL, Content: line, LeftIdx: leftLine}
  226. if leftLine > 0 {
  227. leftLine++
  228. }
  229. curSection.Lines = append(curSection.Lines, diffLine)
  230. case strings.HasPrefix(line, "Binary"):
  231. curFile.IsBin = true
  232. continue
  233. }
  234. // Get new file.
  235. if strings.HasPrefix(line, DIFF_HEAD) {
  236. middle := -1
  237. // Note: In case file name is surrounded by double quotes (it happens only in git-shell).
  238. // e.g. diff --git "a/xxx" "b/xxx"
  239. hasQuote := line[len(DIFF_HEAD)] == '"'
  240. if hasQuote {
  241. middle = strings.Index(line, ` "b/`)
  242. } else {
  243. middle = strings.Index(line, " b/")
  244. }
  245. beg := len(DIFF_HEAD)
  246. a := line[beg+2 : middle]
  247. b := line[middle+3:]
  248. if hasQuote {
  249. a = string(git.UnescapeChars([]byte(a[1 : len(a)-1])))
  250. b = string(git.UnescapeChars([]byte(b[1 : len(b)-1])))
  251. }
  252. curFile = &DiffFile{
  253. Name: a,
  254. Index: len(diff.Files) + 1,
  255. Type: DIFF_FILE_CHANGE,
  256. Sections: make([]*DiffSection, 0, 10),
  257. }
  258. diff.Files = append(diff.Files, curFile)
  259. // Check file diff type.
  260. for {
  261. line, err := input.ReadString('\n')
  262. if err != nil {
  263. if err == io.EOF {
  264. isEOF = true
  265. } else {
  266. return nil, fmt.Errorf("ReadString: %v", err)
  267. }
  268. }
  269. switch {
  270. case strings.HasPrefix(line, "new file"):
  271. curFile.Type = DIFF_FILE_ADD
  272. curFile.IsCreated = true
  273. case strings.HasPrefix(line, "deleted"):
  274. curFile.Type = DIFF_FILE_DEL
  275. curFile.IsDeleted = true
  276. case strings.HasPrefix(line, "index"):
  277. curFile.Type = DIFF_FILE_CHANGE
  278. case strings.HasPrefix(line, "similarity index 100%"):
  279. curFile.Type = DIFF_FILE_RENAME
  280. curFile.IsRenamed = true
  281. curFile.OldName = curFile.Name
  282. curFile.Name = b
  283. }
  284. if curFile.Type > 0 {
  285. break
  286. }
  287. }
  288. }
  289. }
  290. // FIXME: detect encoding while parsing.
  291. var buf bytes.Buffer
  292. for _, f := range diff.Files {
  293. buf.Reset()
  294. for _, sec := range f.Sections {
  295. for _, l := range sec.Lines {
  296. buf.WriteString(l.Content)
  297. buf.WriteString("\n")
  298. }
  299. }
  300. charsetLabel, err := base.DetectEncoding(buf.Bytes())
  301. if charsetLabel != "UTF-8" && err == nil {
  302. encoding, _ := charset.Lookup(charsetLabel)
  303. if encoding != nil {
  304. d := encoding.NewDecoder()
  305. for _, sec := range f.Sections {
  306. for _, l := range sec.Lines {
  307. if c, _, err := transform.String(d, l.Content); err == nil {
  308. l.Content = c
  309. }
  310. }
  311. }
  312. }
  313. }
  314. }
  315. return diff, nil
  316. }
  317. func GetDiffRange(repoPath, beforeCommitID string, afterCommitID string, maxlines int) (*Diff, error) {
  318. repo, err := git.OpenRepository(repoPath)
  319. if err != nil {
  320. return nil, err
  321. }
  322. commit, err := repo.GetCommit(afterCommitID)
  323. if err != nil {
  324. return nil, err
  325. }
  326. var cmd *exec.Cmd
  327. // if "after" commit given
  328. if len(beforeCommitID) == 0 {
  329. // First commit of repository.
  330. if commit.ParentCount() == 0 {
  331. cmd = exec.Command("git", "show", afterCommitID)
  332. } else {
  333. c, _ := commit.Parent(0)
  334. cmd = exec.Command("git", "diff", "-M", c.ID.String(), afterCommitID)
  335. }
  336. } else {
  337. cmd = exec.Command("git", "diff", "-M", beforeCommitID, afterCommitID)
  338. }
  339. cmd.Dir = repoPath
  340. cmd.Stderr = os.Stderr
  341. stdout, err := cmd.StdoutPipe()
  342. if err != nil {
  343. return nil, fmt.Errorf("StdoutPipe: %v", err)
  344. }
  345. if err = cmd.Start(); err != nil {
  346. return nil, fmt.Errorf("Start: %v", err)
  347. }
  348. pid := process.Add(fmt.Sprintf("GetDiffRange (%s)", repoPath), cmd)
  349. defer process.Remove(pid)
  350. diff, err := ParsePatch(maxlines, stdout)
  351. if err != nil {
  352. return nil, fmt.Errorf("ParsePatch: %v", err)
  353. }
  354. if err = cmd.Wait(); err != nil {
  355. return nil, fmt.Errorf("Wait: %v", err)
  356. }
  357. return diff, nil
  358. }
  359. func GetDiffCommit(repoPath, commitId string, maxlines int) (*Diff, error) {
  360. return GetDiffRange(repoPath, "", commitId, maxlines)
  361. }