git_diff.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. "os"
  11. "os/exec"
  12. "strings"
  13. "time"
  14. "golang.org/x/net/html/charset"
  15. "golang.org/x/text/transform"
  16. "github.com/Unknwon/com"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/git"
  19. "github.com/gogits/gogs/modules/log"
  20. "github.com/gogits/gogs/modules/process"
  21. )
  22. // Diff line types.
  23. const (
  24. DIFF_LINE_PLAIN = iota + 1
  25. DIFF_LINE_ADD
  26. DIFF_LINE_DEL
  27. DIFF_LINE_SECTION
  28. )
  29. const (
  30. DIFF_FILE_ADD = iota + 1
  31. DIFF_FILE_CHANGE
  32. DIFF_FILE_DEL
  33. )
  34. type DiffLine struct {
  35. LeftIdx int
  36. RightIdx int
  37. Type int
  38. Content string
  39. }
  40. func (d DiffLine) GetType() int {
  41. return d.Type
  42. }
  43. type DiffSection struct {
  44. Name string
  45. Lines []*DiffLine
  46. }
  47. type DiffFile struct {
  48. Name string
  49. Index int
  50. Addition, Deletion int
  51. Type int
  52. IsBin bool
  53. Sections []*DiffSection
  54. }
  55. type Diff struct {
  56. TotalAddition, TotalDeletion int
  57. Files []*DiffFile
  58. }
  59. func (diff *Diff) NumFiles() int {
  60. return len(diff.Files)
  61. }
  62. const DIFF_HEAD = "diff --git "
  63. func ParsePatch(pid int64, maxlines int, cmd *exec.Cmd, reader io.Reader) (*Diff, error) {
  64. scanner := bufio.NewScanner(reader)
  65. var (
  66. curFile *DiffFile
  67. curSection = &DiffSection{
  68. Lines: make([]*DiffLine, 0, 10),
  69. }
  70. leftLine, rightLine int
  71. isTooLong bool
  72. // FIXME: use first 30 lines to detect file encoding. Should use cache in the future.
  73. buf bytes.Buffer
  74. )
  75. diff := &Diff{Files: make([]*DiffFile, 0)}
  76. var i int
  77. for scanner.Scan() {
  78. line := scanner.Text()
  79. // fmt.Println(i, line)
  80. if strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- ") {
  81. continue
  82. }
  83. if line == "" {
  84. continue
  85. }
  86. i = i + 1
  87. // FIXME: use first 30 lines to detect file encoding.
  88. if i <= 30 {
  89. buf.WriteString(line)
  90. }
  91. // Diff data too large, we only show the first about maxlines lines
  92. if i == maxlines {
  93. isTooLong = true
  94. log.Warn("Diff data too large")
  95. //return &Diff{}, nil
  96. }
  97. switch {
  98. case line[0] == ' ':
  99. diffLine := &DiffLine{Type: DIFF_LINE_PLAIN, Content: line, LeftIdx: leftLine, RightIdx: rightLine}
  100. leftLine++
  101. rightLine++
  102. curSection.Lines = append(curSection.Lines, diffLine)
  103. continue
  104. case line[0] == '@':
  105. if isTooLong {
  106. return diff, nil
  107. }
  108. curSection = &DiffSection{}
  109. curFile.Sections = append(curFile.Sections, curSection)
  110. ss := strings.Split(line, "@@")
  111. diffLine := &DiffLine{Type: DIFF_LINE_SECTION, Content: line}
  112. curSection.Lines = append(curSection.Lines, diffLine)
  113. // Parse line number.
  114. ranges := strings.Split(ss[len(ss)-2][1:], " ")
  115. leftLine, _ = com.StrTo(strings.Split(ranges[0], ",")[0][1:]).Int()
  116. rightLine, _ = com.StrTo(strings.Split(ranges[1], ",")[0]).Int()
  117. continue
  118. case line[0] == '+':
  119. curFile.Addition++
  120. diff.TotalAddition++
  121. diffLine := &DiffLine{Type: DIFF_LINE_ADD, Content: line, RightIdx: rightLine}
  122. rightLine++
  123. curSection.Lines = append(curSection.Lines, diffLine)
  124. continue
  125. case line[0] == '-':
  126. curFile.Deletion++
  127. diff.TotalDeletion++
  128. diffLine := &DiffLine{Type: DIFF_LINE_DEL, Content: line, LeftIdx: leftLine}
  129. if leftLine > 0 {
  130. leftLine++
  131. }
  132. curSection.Lines = append(curSection.Lines, diffLine)
  133. case strings.HasPrefix(line, "Binary"):
  134. curFile.IsBin = true
  135. continue
  136. }
  137. // Get new file.
  138. if strings.HasPrefix(line, DIFF_HEAD) {
  139. if isTooLong {
  140. return diff, nil
  141. }
  142. fs := strings.Split(line[len(DIFF_HEAD):], " ")
  143. a := fs[0]
  144. curFile = &DiffFile{
  145. Name: a[strings.Index(a, "/")+1:],
  146. Index: len(diff.Files) + 1,
  147. Type: DIFF_FILE_CHANGE,
  148. Sections: make([]*DiffSection, 0, 10),
  149. }
  150. diff.Files = append(diff.Files, curFile)
  151. // Check file diff type.
  152. for scanner.Scan() {
  153. switch {
  154. case strings.HasPrefix(scanner.Text(), "new file"):
  155. curFile.Type = DIFF_FILE_ADD
  156. case strings.HasPrefix(scanner.Text(), "deleted"):
  157. curFile.Type = DIFF_FILE_DEL
  158. case strings.HasPrefix(scanner.Text(), "index"):
  159. curFile.Type = DIFF_FILE_CHANGE
  160. }
  161. if curFile.Type > 0 {
  162. break
  163. }
  164. }
  165. }
  166. }
  167. // FIXME: use first 30 lines to detect file encoding.
  168. charsetLabel, err := base.DetectEncoding(buf.Bytes())
  169. if charsetLabel != "utf8" && err == nil {
  170. encoding, _ := charset.Lookup(charsetLabel)
  171. if encoding != nil {
  172. d := encoding.NewDecoder()
  173. for _, f := range diff.Files {
  174. for _, sec := range f.Sections {
  175. for _, l := range sec.Lines {
  176. if c, _, err := transform.String(d, l.Content); err == nil {
  177. l.Content = c
  178. }
  179. }
  180. }
  181. }
  182. }
  183. }
  184. return diff, nil
  185. }
  186. func GetDiffRange(repoPath, beforeCommitId string, afterCommitId string, maxlines int) (*Diff, error) {
  187. repo, err := git.OpenRepository(repoPath)
  188. if err != nil {
  189. return nil, err
  190. }
  191. commit, err := repo.GetCommit(afterCommitId)
  192. if err != nil {
  193. return nil, err
  194. }
  195. rd, wr := io.Pipe()
  196. var cmd *exec.Cmd
  197. // if "after" commit given
  198. if beforeCommitId == "" {
  199. // First commit of repository.
  200. if commit.ParentCount() == 0 {
  201. cmd = exec.Command("git", "show", afterCommitId)
  202. } else {
  203. c, _ := commit.Parent(0)
  204. cmd = exec.Command("git", "diff", c.Id.String(), afterCommitId)
  205. }
  206. } else {
  207. cmd = exec.Command("git", "diff", beforeCommitId, afterCommitId)
  208. }
  209. cmd.Dir = repoPath
  210. cmd.Stdout = wr
  211. cmd.Stdin = os.Stdin
  212. cmd.Stderr = os.Stderr
  213. done := make(chan error)
  214. go func() {
  215. cmd.Start()
  216. done <- cmd.Wait()
  217. wr.Close()
  218. }()
  219. defer rd.Close()
  220. desc := fmt.Sprintf("GetDiffRange(%s)", repoPath)
  221. pid := process.Add(desc, cmd)
  222. go func() {
  223. // In case process became zombie.
  224. select {
  225. case <-time.After(5 * time.Minute):
  226. if errKill := process.Kill(pid); errKill != nil {
  227. log.Error(4, "git_diff.ParsePatch(Kill): %v", err)
  228. }
  229. <-done
  230. // return "", ErrExecTimeout.Error(), ErrExecTimeout
  231. case err = <-done:
  232. process.Remove(pid)
  233. }
  234. }()
  235. return ParsePatch(pid, maxlines, cmd, rd)
  236. }
  237. func GetDiffCommit(repoPath, commitId string, maxlines int) (*Diff, error) {
  238. return GetDiffRange(repoPath, "", commitId, maxlines)
  239. }