git.go 9.8 KB

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