A fork of Gitea (see branch `mj`) adding Majority Judgment Polls 𐄷 over Issues and Merge Requests. https://git.mieuxvoter.fr
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.

274 lines
8.1 KiB

  1. // Copyright 2020 The Gitea 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 git
  5. import (
  6. "bufio"
  7. "bytes"
  8. "context"
  9. "fmt"
  10. "io"
  11. "os/exec"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "code.gitea.io/gitea/modules/process"
  16. )
  17. // RawDiffType type of a raw diff.
  18. type RawDiffType string
  19. // RawDiffType possible values.
  20. const (
  21. RawDiffNormal RawDiffType = "diff"
  22. RawDiffPatch RawDiffType = "patch"
  23. )
  24. // GetRawDiff dumps diff results of repository in given commit ID to io.Writer.
  25. func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Writer) error {
  26. return GetRawDiffForFile(repoPath, "", commitID, diffType, "", writer)
  27. }
  28. // GetRawDiffForFile dumps diff results of file in given commit ID to io.Writer.
  29. func GetRawDiffForFile(repoPath, startCommit, endCommit string, diffType RawDiffType, file string, writer io.Writer) error {
  30. repo, err := OpenRepository(repoPath)
  31. if err != nil {
  32. return fmt.Errorf("OpenRepository: %v", err)
  33. }
  34. defer repo.Close()
  35. return GetRepoRawDiffForFile(repo, startCommit, endCommit, diffType, file, writer)
  36. }
  37. // GetRepoRawDiffForFile dumps diff results of file in given commit ID to io.Writer according given repository
  38. func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diffType RawDiffType, file string, writer io.Writer) error {
  39. commit, err := repo.GetCommit(endCommit)
  40. if err != nil {
  41. return err
  42. }
  43. fileArgs := make([]string, 0)
  44. if len(file) > 0 {
  45. fileArgs = append(fileArgs, "--", file)
  46. }
  47. // FIXME: graceful: These commands should have a timeout
  48. ctx, cancel := context.WithCancel(DefaultContext)
  49. defer cancel()
  50. var cmd *exec.Cmd
  51. switch diffType {
  52. case RawDiffNormal:
  53. if len(startCommit) != 0 {
  54. cmd = exec.CommandContext(ctx, GitExecutable, append([]string{"diff", "-M", startCommit, endCommit}, fileArgs...)...)
  55. } else if commit.ParentCount() == 0 {
  56. cmd = exec.CommandContext(ctx, GitExecutable, append([]string{"show", endCommit}, fileArgs...)...)
  57. } else {
  58. c, _ := commit.Parent(0)
  59. cmd = exec.CommandContext(ctx, GitExecutable, append([]string{"diff", "-M", c.ID.String(), endCommit}, fileArgs...)...)
  60. }
  61. case RawDiffPatch:
  62. if len(startCommit) != 0 {
  63. query := fmt.Sprintf("%s...%s", endCommit, startCommit)
  64. cmd = exec.CommandContext(ctx, GitExecutable, append([]string{"format-patch", "--no-signature", "--stdout", "--root", query}, fileArgs...)...)
  65. } else if commit.ParentCount() == 0 {
  66. cmd = exec.CommandContext(ctx, GitExecutable, append([]string{"format-patch", "--no-signature", "--stdout", "--root", endCommit}, fileArgs...)...)
  67. } else {
  68. c, _ := commit.Parent(0)
  69. query := fmt.Sprintf("%s...%s", endCommit, c.ID.String())
  70. cmd = exec.CommandContext(ctx, GitExecutable, append([]string{"format-patch", "--no-signature", "--stdout", query}, fileArgs...)...)
  71. }
  72. default:
  73. return fmt.Errorf("invalid diffType: %s", diffType)
  74. }
  75. stderr := new(bytes.Buffer)
  76. cmd.Dir = repo.Path
  77. cmd.Stdout = writer
  78. cmd.Stderr = stderr
  79. pid := process.GetManager().Add(fmt.Sprintf("GetRawDiffForFile: [repo_path: %s]", repo.Path), cancel)
  80. defer process.GetManager().Remove(pid)
  81. if err = cmd.Run(); err != nil {
  82. return fmt.Errorf("Run: %v - %s", err, stderr)
  83. }
  84. return nil
  85. }
  86. // ParseDiffHunkString parse the diffhunk content and return
  87. func ParseDiffHunkString(diffhunk string) (leftLine, leftHunk, rightLine, righHunk int) {
  88. ss := strings.Split(diffhunk, "@@")
  89. ranges := strings.Split(ss[1][1:], " ")
  90. leftRange := strings.Split(ranges[0], ",")
  91. leftLine, _ = strconv.Atoi(leftRange[0][1:])
  92. if len(leftRange) > 1 {
  93. leftHunk, _ = strconv.Atoi(leftRange[1])
  94. }
  95. if len(ranges) > 1 {
  96. rightRange := strings.Split(ranges[1], ",")
  97. rightLine, _ = strconv.Atoi(rightRange[0])
  98. if len(rightRange) > 1 {
  99. righHunk, _ = strconv.Atoi(rightRange[1])
  100. }
  101. } else {
  102. log("Parse line number failed: %v", diffhunk)
  103. rightLine = leftLine
  104. righHunk = leftHunk
  105. }
  106. return
  107. }
  108. // Example: @@ -1,8 +1,9 @@ => [..., 1, 8, 1, 9]
  109. var hunkRegex = regexp.MustCompile(`^@@ -(?P<beginOld>[0-9]+)(,(?P<endOld>[0-9]+))? \+(?P<beginNew>[0-9]+)(,(?P<endNew>[0-9]+))? @@`)
  110. const cmdDiffHead = "diff --git "
  111. func isHeader(lof string, inHunk bool) bool {
  112. return strings.HasPrefix(lof, cmdDiffHead) || (!inHunk && (strings.HasPrefix(lof, "---") || strings.HasPrefix(lof, "+++")))
  113. }
  114. // CutDiffAroundLine cuts a diff of a file in way that only the given line + numberOfLine above it will be shown
  115. // it also recalculates hunks and adds the appropriate headers to the new diff.
  116. // Warning: Only one-file diffs are allowed.
  117. func CutDiffAroundLine(originalDiff io.Reader, line int64, old bool, numbersOfLine int) (string, error) {
  118. if line == 0 || numbersOfLine == 0 {
  119. // no line or num of lines => no diff
  120. return "", nil
  121. }
  122. scanner := bufio.NewScanner(originalDiff)
  123. hunk := make([]string, 0)
  124. // begin is the start of the hunk containing searched line
  125. // end is the end of the hunk ...
  126. // currentLine is the line number on the side of the searched line (differentiated by old)
  127. // otherLine is the line number on the opposite side of the searched line (differentiated by old)
  128. var begin, end, currentLine, otherLine int64
  129. var headerLines int
  130. inHunk := false
  131. for scanner.Scan() {
  132. lof := scanner.Text()
  133. // Add header to enable parsing
  134. if isHeader(lof, inHunk) {
  135. if strings.HasPrefix(lof, cmdDiffHead) {
  136. inHunk = false
  137. }
  138. hunk = append(hunk, lof)
  139. headerLines++
  140. }
  141. if currentLine > line {
  142. break
  143. }
  144. // Detect "hunk" with contains commented lof
  145. if strings.HasPrefix(lof, "@@") {
  146. inHunk = true
  147. // Already got our hunk. End of hunk detected!
  148. if len(hunk) > headerLines {
  149. break
  150. }
  151. // A map with named groups of our regex to recognize them later more easily
  152. submatches := hunkRegex.FindStringSubmatch(lof)
  153. groups := make(map[string]string)
  154. for i, name := range hunkRegex.SubexpNames() {
  155. if i != 0 && name != "" {
  156. groups[name] = submatches[i]
  157. }
  158. }
  159. if old {
  160. begin, _ = strconv.ParseInt(groups["beginOld"], 10, 64)
  161. end, _ = strconv.ParseInt(groups["endOld"], 10, 64)
  162. // init otherLine with begin of opposite side
  163. otherLine, _ = strconv.ParseInt(groups["beginNew"], 10, 64)
  164. } else {
  165. begin, _ = strconv.ParseInt(groups["beginNew"], 10, 64)
  166. if groups["endNew"] != "" {
  167. end, _ = strconv.ParseInt(groups["endNew"], 10, 64)
  168. } else {
  169. end = 0
  170. }
  171. // init otherLine with begin of opposite side
  172. otherLine, _ = strconv.ParseInt(groups["beginOld"], 10, 64)
  173. }
  174. end += begin // end is for real only the number of lines in hunk
  175. // lof is between begin and end
  176. if begin <= line && end >= line {
  177. hunk = append(hunk, lof)
  178. currentLine = begin
  179. continue
  180. }
  181. } else if len(hunk) > headerLines {
  182. hunk = append(hunk, lof)
  183. // Count lines in context
  184. switch lof[0] {
  185. case '+':
  186. if !old {
  187. currentLine++
  188. } else {
  189. otherLine++
  190. }
  191. case '-':
  192. if old {
  193. currentLine++
  194. } else {
  195. otherLine++
  196. }
  197. default:
  198. currentLine++
  199. otherLine++
  200. }
  201. }
  202. }
  203. err := scanner.Err()
  204. if err != nil {
  205. return "", err
  206. }
  207. // No hunk found
  208. if currentLine == 0 {
  209. return "", nil
  210. }
  211. // headerLines + hunkLine (1) = totalNonCodeLines
  212. if len(hunk)-headerLines-1 <= numbersOfLine {
  213. // No need to cut the hunk => return existing hunk
  214. return strings.Join(hunk, "\n"), nil
  215. }
  216. var oldBegin, oldNumOfLines, newBegin, newNumOfLines int64
  217. if old {
  218. oldBegin = currentLine
  219. newBegin = otherLine
  220. } else {
  221. oldBegin = otherLine
  222. newBegin = currentLine
  223. }
  224. // headers + hunk header
  225. newHunk := make([]string, headerLines)
  226. // transfer existing headers
  227. copy(newHunk, hunk[:headerLines])
  228. // transfer last n lines
  229. newHunk = append(newHunk, hunk[len(hunk)-numbersOfLine-1:]...)
  230. // calculate newBegin, ... by counting lines
  231. for i := len(hunk) - 1; i >= len(hunk)-numbersOfLine; i-- {
  232. switch hunk[i][0] {
  233. case '+':
  234. newBegin--
  235. newNumOfLines++
  236. case '-':
  237. oldBegin--
  238. oldNumOfLines++
  239. default:
  240. oldBegin--
  241. newBegin--
  242. newNumOfLines++
  243. oldNumOfLines++
  244. }
  245. }
  246. // construct the new hunk header
  247. newHunk[headerLines] = fmt.Sprintf("@@ -%d,%d +%d,%d @@",
  248. oldBegin, oldNumOfLines, newBegin, newNumOfLines)
  249. return strings.Join(newHunk, "\n"), nil
  250. }