git.go 8.8 KB

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