git.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. "container/list"
  8. "fmt"
  9. "io"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "strings"
  14. "github.com/gogits/git"
  15. )
  16. // RepoFile represents a file object in git repository.
  17. type RepoFile struct {
  18. *git.TreeEntry
  19. Path string
  20. Size int64
  21. Repo *git.Repository
  22. Commit *git.Commit
  23. }
  24. // LookupBlob returns the content of an object.
  25. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  26. if file.Repo == nil {
  27. return nil, ErrRepoFileNotLoaded
  28. }
  29. return file.Repo.LookupBlob(file.Id)
  30. }
  31. // GetBranches returns all branches of given repository.
  32. func GetBranches(userName, reposName string) ([]string, error) {
  33. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  34. if err != nil {
  35. return nil, err
  36. }
  37. refs, err := repo.AllReferences()
  38. if err != nil {
  39. return nil, err
  40. }
  41. brs := make([]string, len(refs))
  42. for i, ref := range refs {
  43. brs[i] = ref.Name
  44. }
  45. return brs, nil
  46. }
  47. func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
  48. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  49. if err != nil {
  50. return nil, err
  51. }
  52. commit, err := repo.GetCommit(branchName, commitId)
  53. if err != nil {
  54. return nil, err
  55. }
  56. parts := strings.Split(path.Clean(rpath), "/")
  57. var entry *git.TreeEntry
  58. tree := commit.Tree
  59. for i, part := range parts {
  60. if i == len(parts)-1 {
  61. entry = tree.EntryByName(part)
  62. if entry == nil {
  63. return nil, ErrRepoFileNotExist
  64. }
  65. } else {
  66. tree, err = repo.SubTree(tree, part)
  67. if err != nil {
  68. return nil, err
  69. }
  70. }
  71. }
  72. size, err := repo.ObjectSize(entry.Id)
  73. if err != nil {
  74. return nil, err
  75. }
  76. repoFile := &RepoFile{
  77. entry,
  78. rpath,
  79. size,
  80. repo,
  81. commit,
  82. }
  83. return repoFile, nil
  84. }
  85. // GetReposFiles returns a list of file object in given directory of repository.
  86. func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
  87. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  88. if err != nil {
  89. return nil, err
  90. }
  91. commit, err := repo.GetCommit(branchName, commitId)
  92. if err != nil {
  93. return nil, err
  94. }
  95. var repodirs []*RepoFile
  96. var repofiles []*RepoFile
  97. commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  98. if dirname == rpath {
  99. // TODO: size get method shoule be improved
  100. size, err := repo.ObjectSize(entry.Id)
  101. if err != nil {
  102. return 0
  103. }
  104. var cm = commit
  105. var i int
  106. for {
  107. i = i + 1
  108. //fmt.Println(".....", i, cm.Id(), cm.ParentCount())
  109. if cm.ParentCount() == 0 {
  110. break
  111. } else if cm.ParentCount() == 1 {
  112. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  113. if pt == nil {
  114. break
  115. }
  116. pEntry := pt.EntryByName(entry.Name)
  117. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  118. break
  119. } else {
  120. cm = cm.Parent(0)
  121. }
  122. } else {
  123. var emptyCnt = 0
  124. var sameIdcnt = 0
  125. var lastSameCm *git.Commit
  126. //fmt.Println(".....", cm.ParentCount())
  127. for i := 0; i < cm.ParentCount(); i++ {
  128. //fmt.Println("parent", i, cm.Parent(i).Id())
  129. p := cm.Parent(i)
  130. pt, _ := repo.SubTree(p.Tree, dirname)
  131. var pEntry *git.TreeEntry
  132. if pt != nil {
  133. pEntry = pt.EntryByName(entry.Name)
  134. }
  135. //fmt.Println("pEntry", pEntry)
  136. if pEntry == nil {
  137. emptyCnt = emptyCnt + 1
  138. if emptyCnt+sameIdcnt == cm.ParentCount() {
  139. if lastSameCm == nil {
  140. goto loop
  141. } else {
  142. cm = lastSameCm
  143. break
  144. }
  145. }
  146. } else {
  147. //fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
  148. if !pEntry.Id.Equal(entry.Id) {
  149. goto loop
  150. } else {
  151. lastSameCm = cm.Parent(i)
  152. sameIdcnt = sameIdcnt + 1
  153. if emptyCnt+sameIdcnt == cm.ParentCount() {
  154. // TODO: now follow the first parent commit?
  155. cm = lastSameCm
  156. //fmt.Println("sameId...")
  157. break
  158. }
  159. }
  160. }
  161. }
  162. }
  163. }
  164. loop:
  165. rp := &RepoFile{
  166. entry,
  167. path.Join(dirname, entry.Name),
  168. size,
  169. repo,
  170. cm,
  171. }
  172. if entry.IsFile() {
  173. repofiles = append(repofiles, rp)
  174. } else if entry.IsDir() {
  175. repodirs = append(repodirs, rp)
  176. }
  177. }
  178. return 0
  179. })
  180. return append(repodirs, repofiles...), nil
  181. }
  182. func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
  183. repo, err := git.OpenRepository(RepoPath(userName, repoName))
  184. if err != nil {
  185. return nil, err
  186. }
  187. return repo.GetCommit(branchname, commitid)
  188. }
  189. // GetCommits returns all commits of given branch of repository.
  190. func GetCommits(userName, reposName, branchname string) (*list.List, error) {
  191. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  192. if err != nil {
  193. return nil, err
  194. }
  195. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  196. if err != nil {
  197. return nil, err
  198. }
  199. return r.AllCommits()
  200. }
  201. // Diff line types.
  202. const (
  203. DIFF_LINE_PLAIN = iota + 1
  204. DIFF_LINE_ADD
  205. DIFF_LINE_DEL
  206. DIFF_LINE_SECTION
  207. )
  208. const (
  209. DIFF_FILE_ADD = iota + 1
  210. DIFF_FILE_CHANGE
  211. DIFF_FILE_DEL
  212. )
  213. type DiffLine struct {
  214. LeftIdx int
  215. RightIdx int
  216. Type int
  217. Content string
  218. }
  219. type DiffSection struct {
  220. Name string
  221. Lines []*DiffLine
  222. }
  223. type DiffFile struct {
  224. Name string
  225. Addition, Deletion int
  226. Type int
  227. Sections []*DiffSection
  228. }
  229. type Diff struct {
  230. TotalAddition, TotalDeletion int
  231. Files []*DiffFile
  232. }
  233. func (diff *Diff) NumFiles() int {
  234. return len(diff.Files)
  235. }
  236. const DIFF_HEAD = "diff --git "
  237. func ParsePatch(reader io.Reader) (*Diff, error) {
  238. scanner := bufio.NewScanner(reader)
  239. var totalAdd, totalDel int
  240. var curFile *DiffFile
  241. curSection := &DiffSection{
  242. Lines: make([]*DiffLine, 0, 10),
  243. }
  244. //var leftLine, rightLine int
  245. diff := &Diff{Files: make([]*DiffFile, 0)}
  246. var i int
  247. for scanner.Scan() {
  248. line := scanner.Text()
  249. fmt.Println(i, line)
  250. i = i + 1
  251. if line == "" {
  252. continue
  253. }
  254. if line[0] == ' ' {
  255. diffLine := &DiffLine{Type: DIFF_LINE_PLAIN, Content: line}
  256. curSection.Lines = append(curSection.Lines, diffLine)
  257. continue
  258. } else if line[0] == '@' {
  259. curSection = &DiffSection{}
  260. curFile.Sections = append(curFile.Sections, curSection)
  261. ss := strings.Split(line, "@@")
  262. diffLine := &DiffLine{Type: DIFF_LINE_SECTION, Content: "@@" + ss[len(ss)-2] + "@@"}
  263. curSection.Lines = append(curSection.Lines, diffLine)
  264. diffLine = &DiffLine{Type: DIFF_LINE_PLAIN, Content: ss[len(ss)-1]}
  265. curSection.Lines = append(curSection.Lines, diffLine)
  266. continue
  267. } else if line[0] == '+' {
  268. diffLine := &DiffLine{Type: DIFF_LINE_ADD, Content: line}
  269. curSection.Lines = append(curSection.Lines, diffLine)
  270. continue
  271. } else if line[0] == '-' {
  272. diffLine := &DiffLine{Type: DIFF_LINE_DEL, Content: line}
  273. curSection.Lines = append(curSection.Lines, diffLine)
  274. continue
  275. }
  276. if strings.HasPrefix(line, DIFF_HEAD) {
  277. if curFile != nil {
  278. curFile.Addition, totalAdd = totalAdd, 0
  279. curFile.Deletion, totalDel = totalDel, 0
  280. curFile = nil
  281. }
  282. fs := strings.Split(line[len(DIFF_HEAD):], " ")
  283. a := fs[0]
  284. curFile = &DiffFile{
  285. Name: a[strings.Index(a, "/")+1:],
  286. Type: DIFF_FILE_CHANGE,
  287. Sections: make([]*DiffSection, 0),
  288. }
  289. diff.Files = append(diff.Files, curFile)
  290. scanner.Scan()
  291. scanner.Scan()
  292. if scanner.Text() == "--- /dev/null" {
  293. curFile.Type = DIFF_FILE_ADD
  294. }
  295. scanner.Scan()
  296. }
  297. }
  298. return diff, nil
  299. }
  300. func GetDiff(repoPath, commitid string) (*Diff, error) {
  301. repo, err := git.OpenRepository(repoPath)
  302. if err != nil {
  303. return nil, err
  304. }
  305. commit, err := repo.GetCommit("", commitid)
  306. if err != nil {
  307. return nil, err
  308. }
  309. // ????
  310. if commit.ParentCount() == 0 {
  311. return &Diff{}, err
  312. }
  313. rd, wr := io.Pipe()
  314. go func() {
  315. cmd := exec.Command("git", "diff", commitid, commit.Parent(0).Oid.String())
  316. cmd.Dir = repoPath
  317. cmd.Stdout = wr
  318. cmd.Stdin = os.Stdin
  319. cmd.Stderr = os.Stderr
  320. cmd.Run()
  321. //if err != nil {
  322. // return nil, err
  323. //}
  324. wr.Close()
  325. }()
  326. defer rd.Close()
  327. return ParsePatch(rd)
  328. }
  329. /*func GetDiff(repoPath, commitid string) (*Diff, error) {
  330. stdout, _, err := com.ExecCmdDir(repoPath, "git", "show", commitid)
  331. if err != nil {
  332. return nil, err
  333. }
  334. // Sperate parts by file.
  335. startIndex := strings.Index(stdout, "diff --git ") + 12
  336. // First part is commit information.
  337. // Check if it's a merge.
  338. mergeIndex := strings.Index(stdout[:startIndex], "merge")
  339. if mergeIndex > -1 {
  340. mergeCommit := strings.SplitN(strings.Split(stdout[:startIndex], "\n")[1], "", 3)[2]
  341. return GetDiff(repoPath, mergeCommit)
  342. }
  343. parts := strings.Split(stdout[startIndex:], "diff --git ")
  344. diff := &Diff{NumFiles: len(parts)}
  345. diff.Files = make([]*DiffFile, 0, diff.NumFiles)
  346. for _, part := range parts {
  347. infos := strings.SplitN(part, "\n", 6)
  348. maxIndex := len(infos) - 1
  349. infos[maxIndex] = strings.TrimSuffix(strings.TrimSuffix(infos[maxIndex], "\n"), "\n\\ No newline at end of file")
  350. file := &DiffFile{
  351. Name: strings.TrimPrefix(strings.Split(infos[0], " ")[0], "a/"),
  352. Content: strings.Split(infos[maxIndex], "\n"),
  353. }
  354. diff.Files = append(diff.Files, file)
  355. }
  356. return diff, nil
  357. }*/