git.go 9.5 KB

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