git.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. "container/list"
  7. "fmt"
  8. "path"
  9. "strings"
  10. "io"
  11. "bufio"
  12. "os"
  13. "os/exec"
  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. const (
  202. PlainLine = iota + 1
  203. AddLine
  204. DelLine
  205. SectionLine
  206. )
  207. const (
  208. AddFile = iota + 1
  209. ChangeFile
  210. DelFile
  211. )
  212. type DiffLine struct {
  213. LeftIdx int
  214. RightIdx int
  215. Type int
  216. Content string
  217. }
  218. type DiffSection struct {
  219. Name string
  220. Lines []*DiffLine
  221. }
  222. type DiffFile struct {
  223. Name string
  224. Addition, Deletion int
  225. Type int
  226. Sections []*DiffSection
  227. }
  228. type Diff struct {
  229. TotalAddition, TotalDeletion int
  230. Files []*DiffFile
  231. }
  232. func (diff *Diff) NumFiles() int {
  233. return len(diff.Files)
  234. }
  235. const diffHead = "diff --git "
  236. func ParsePatch(reader io.Reader) (*Diff, error) {
  237. scanner := bufio.NewScanner(reader)
  238. var totalAdd, totalDel int
  239. var curFile *DiffFile
  240. var curSection * DiffSection
  241. //var leftLine, rightLine int
  242. diff := &Diff{Files:make([]*DiffFile, 0)}
  243. var i int
  244. for scanner.Scan() {
  245. line := scanner.Text()
  246. fmt.Println(i, line)
  247. i = i + 1
  248. if line == "" {
  249. continue
  250. }
  251. if line[0] == ' ' {
  252. diffLine := &DiffLine{Type: PlainLine, Content:line}
  253. curSection.Lines = append(curSection.Lines, diffLine)
  254. continue
  255. } else if line[0] == '@' {
  256. ss := strings.Split(line, "@@")
  257. diffLine := &DiffLine{Type: SectionLine, Content:"@@ "+ss[len(ss)-2]}
  258. curSection.Lines = append(curSection.Lines, diffLine)
  259. diffLine = &DiffLine{Type: PlainLine, Content:ss[len(ss)-1]}
  260. curSection.Lines = append(curSection.Lines, diffLine)
  261. continue
  262. } else if line[0] == '+' {
  263. diffLine := &DiffLine{Type: AddLine, Content:line}
  264. curSection.Lines = append(curSection.Lines, diffLine)
  265. continue
  266. } else if line[0] == '-' {
  267. diffLine := &DiffLine{Type: DelLine, Content:line}
  268. curSection.Lines = append(curSection.Lines, diffLine)
  269. continue
  270. }
  271. if strings.HasPrefix(line, diffHead) {
  272. if curFile != nil {
  273. curFile.Addition, totalAdd = totalAdd, 0
  274. curFile.Deletion, totalDel = totalDel, 0
  275. curFile = nil
  276. }
  277. fs := strings.Split(line[len(diffHead):], " ")
  278. a := fs[0]
  279. curFile = &DiffFile{
  280. Name:a[strings.Index(a, "/")+1:],
  281. Type: ChangeFile,
  282. Sections:make([]*DiffSection, 0),
  283. }
  284. diff.Files = append(diff.Files, curFile)
  285. scanner.Scan()
  286. scanner.Scan()
  287. if scanner.Text() == "--- /dev/null" {
  288. curFile.Type = AddFile
  289. }
  290. scanner.Scan()
  291. }
  292. }
  293. return diff, nil
  294. }
  295. func GetDiff(repoPath, commitid string) (*Diff, error) {
  296. repo, err := git.OpenRepository(repoPath)
  297. if err != nil {
  298. return nil, err
  299. }
  300. commit, err := repo.GetCommit("", commitid)
  301. if err != nil {
  302. return nil, err
  303. }
  304. if commit.ParentCount() == 0 {
  305. return nil, err
  306. }
  307. rd, wr := io.Pipe()
  308. go func() {
  309. cmd := exec.Command("git", "diff", commitid, commit.Parent(0).Oid.String())
  310. cmd.Dir = repoPath
  311. cmd.Stdout = wr
  312. cmd.Stdin = os.Stdin
  313. cmd.Stderr = os.Stderr
  314. cmd.Run()
  315. //if err != nil {
  316. // return nil, err
  317. //}
  318. wr.Close()
  319. }()
  320. defer rd.Close()
  321. return ParsePatch(rd)
  322. }
  323. /*func GetDiff(repoPath, commitid string) (*Diff, error) {
  324. stdout, _, err := com.ExecCmdDir(repoPath, "git", "show", commitid)
  325. if err != nil {
  326. return nil, err
  327. }
  328. // Sperate parts by file.
  329. startIndex := strings.Index(stdout, "diff --git ") + 12
  330. // First part is commit information.
  331. // Check if it's a merge.
  332. mergeIndex := strings.Index(stdout[:startIndex], "merge")
  333. if mergeIndex > -1 {
  334. mergeCommit := strings.SplitN(strings.Split(stdout[:startIndex], "\n")[1], "", 3)[2]
  335. return GetDiff(repoPath, mergeCommit)
  336. }
  337. parts := strings.Split(stdout[startIndex:], "diff --git ")
  338. diff := &Diff{NumFiles: len(parts)}
  339. diff.Files = make([]*DiffFile, 0, diff.NumFiles)
  340. for _, part := range parts {
  341. infos := strings.SplitN(part, "\n", 6)
  342. maxIndex := len(infos) - 1
  343. infos[maxIndex] = strings.TrimSuffix(strings.TrimSuffix(infos[maxIndex], "\n"), "\n\\ No newline at end of file")
  344. file := &DiffFile{
  345. Name: strings.TrimPrefix(strings.Split(infos[0], " ")[0], "a/"),
  346. Content: strings.Split(infos[maxIndex], "\n"),
  347. }
  348. diff.Files = append(diff.Files, file)
  349. }
  350. return diff, nil
  351. }*/