repo.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "sync"
  16. "time"
  17. "unicode/utf8"
  18. "github.com/Unknwon/cae/zip"
  19. "github.com/Unknwon/com"
  20. "github.com/gogits/git"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/log"
  23. )
  24. var (
  25. ErrRepoAlreadyExist = errors.New("Repository already exist")
  26. ErrRepoNotExist = errors.New("Repository does not exist")
  27. ErrRepoFileNotExist = errors.New("Target Repo file does not exist")
  28. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  29. ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded")
  30. )
  31. var gitInitLocker = sync.Mutex{}
  32. var (
  33. LanguageIgns, Licenses []string
  34. )
  35. func LoadRepoConfig() {
  36. LanguageIgns = strings.Split(base.Cfg.MustValue("repository", "LANG_IGNS"), "|")
  37. Licenses = strings.Split(base.Cfg.MustValue("repository", "LICENSES"), "|")
  38. }
  39. func NewRepoContext() {
  40. zip.Verbose = false
  41. // Check if server has basic git setting.
  42. stdout, _, err := com.ExecCmd("git", "config", "--get", "user.name")
  43. if err != nil {
  44. fmt.Printf("repo.init(fail to get git user.name): %v", err)
  45. os.Exit(2)
  46. } else if len(stdout) == 0 {
  47. if _, _, err = com.ExecCmd("git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil {
  48. fmt.Printf("repo.init(fail to set git user.email): %v", err)
  49. os.Exit(2)
  50. } else if _, _, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
  51. fmt.Printf("repo.init(fail to set git user.name): %v", err)
  52. os.Exit(2)
  53. }
  54. }
  55. // Initialize illegal patterns.
  56. for i := range illegalPatterns[1:] {
  57. pattern := ""
  58. for j := range illegalPatterns[i+1] {
  59. pattern += "[" + string(illegalPatterns[i+1][j]-32) + string(illegalPatterns[i+1][j]) + "]"
  60. }
  61. illegalPatterns[i+1] = pattern
  62. }
  63. }
  64. // Repository represents a git repository.
  65. type Repository struct {
  66. Id int64
  67. OwnerId int64 `xorm:"unique(s)"`
  68. ForkId int64
  69. LowerName string `xorm:"unique(s) index not null"`
  70. Name string `xorm:"index not null"`
  71. Description string
  72. Website string
  73. Private bool
  74. NumWatches int
  75. NumStars int
  76. NumForks int
  77. Created time.Time `xorm:"created"`
  78. Updated time.Time `xorm:"updated"`
  79. }
  80. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  81. func IsRepositoryExist(user *User, repoName string) (bool, error) {
  82. repo := Repository{OwnerId: user.Id}
  83. has, err := orm.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  84. if err != nil {
  85. return has, err
  86. }
  87. s, err := os.Stat(RepoPath(user.Name, repoName))
  88. if err != nil {
  89. return false, nil // Error simply means does not exist, but we don't want to show up.
  90. }
  91. return s.IsDir(), nil
  92. }
  93. var (
  94. // Define as all lower case!!
  95. illegalPatterns = []string{"[.][Gg][Ii][Tt]", "user", "help", "stars", "issues", "pulls", "commits", "admin", "repo", "template", "admin"}
  96. )
  97. // IsLegalName returns false if name contains illegal characters.
  98. func IsLegalName(repoName string) bool {
  99. for _, pattern := range illegalPatterns {
  100. has, _ := regexp.MatchString(pattern, repoName)
  101. if has {
  102. return false
  103. }
  104. }
  105. return true
  106. }
  107. // CreateRepository creates a repository for given user or orgnaziation.
  108. func CreateRepository(user *User, repoName, desc, repoLang, license string, private bool, initReadme bool) (*Repository, error) {
  109. if !IsLegalName(repoName) {
  110. return nil, ErrRepoNameIllegal
  111. }
  112. isExist, err := IsRepositoryExist(user, repoName)
  113. if err != nil {
  114. return nil, err
  115. } else if isExist {
  116. return nil, ErrRepoAlreadyExist
  117. }
  118. repo := &Repository{
  119. OwnerId: user.Id,
  120. Name: repoName,
  121. LowerName: strings.ToLower(repoName),
  122. Description: desc,
  123. Private: private,
  124. }
  125. repoPath := RepoPath(user.Name, repoName)
  126. if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
  127. return nil, err
  128. }
  129. session := orm.NewSession()
  130. defer session.Close()
  131. session.Begin()
  132. if _, err = session.Insert(repo); err != nil {
  133. if err2 := os.RemoveAll(repoPath); err2 != nil {
  134. log.Error("repo.CreateRepository(repo): %v", err)
  135. return nil, errors.New(fmt.Sprintf(
  136. "delete repo directory %s/%s failed(1): %v", user.Name, repoName, err2))
  137. }
  138. session.Rollback()
  139. return nil, err
  140. }
  141. access := Access{
  142. UserName: user.Name,
  143. RepoName: repo.Name,
  144. Mode: AU_WRITABLE,
  145. }
  146. if _, err = session.Insert(&access); err != nil {
  147. session.Rollback()
  148. if err2 := os.RemoveAll(repoPath); err2 != nil {
  149. log.Error("repo.CreateRepository(access): %v", err)
  150. return nil, errors.New(fmt.Sprintf(
  151. "delete repo directory %s/%s failed(2): %v", user.Name, repoName, err2))
  152. }
  153. return nil, err
  154. }
  155. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  156. if _, err = session.Exec(rawSql, user.Id); err != nil {
  157. session.Rollback()
  158. if err2 := os.RemoveAll(repoPath); err2 != nil {
  159. log.Error("repo.CreateRepository(repo count): %v", err)
  160. return nil, errors.New(fmt.Sprintf(
  161. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  162. }
  163. return nil, err
  164. }
  165. if err = session.Commit(); err != nil {
  166. session.Rollback()
  167. if err2 := os.RemoveAll(repoPath); err2 != nil {
  168. log.Error("repo.CreateRepository(commit): %v", err)
  169. return nil, errors.New(fmt.Sprintf(
  170. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  171. }
  172. return nil, err
  173. }
  174. return repo, NewRepoAction(user, repo)
  175. }
  176. // extractGitBareZip extracts git-bare.zip to repository path.
  177. func extractGitBareZip(repoPath string) error {
  178. z, err := zip.Open("conf/content/git-bare.zip")
  179. if err != nil {
  180. fmt.Println("shi?")
  181. return err
  182. }
  183. defer z.Close()
  184. return z.ExtractTo(repoPath)
  185. }
  186. // initRepoCommit temporarily changes with work directory.
  187. func initRepoCommit(tmpPath string, sig *git.Signature) error {
  188. gitInitLocker.Lock()
  189. defer gitInitLocker.Unlock()
  190. // Change work directory.
  191. curPath, err := os.Getwd()
  192. if err != nil {
  193. return err
  194. } else if err = os.Chdir(tmpPath); err != nil {
  195. return err
  196. }
  197. defer os.Chdir(curPath)
  198. var stderr string
  199. if _, stderr, err = com.ExecCmd("git", "add", "--all"); err != nil {
  200. return err
  201. }
  202. log.Info("stderr(1): %s", stderr)
  203. if _, stderr, err = com.ExecCmd("git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  204. "-m", "Init commit"); err != nil {
  205. return err
  206. }
  207. log.Info("stderr(2): %s", stderr)
  208. if _, stderr, err = com.ExecCmd("git", "push", "origin", "master"); err != nil {
  209. return err
  210. }
  211. log.Info("stderr(3): %s", stderr)
  212. return nil
  213. }
  214. // InitRepository initializes README and .gitignore if needed.
  215. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  216. repoPath := RepoPath(user.Name, repo.Name)
  217. // Create bare new repository.
  218. if err := extractGitBareZip(repoPath); err != nil {
  219. return err
  220. }
  221. // hook/post-update
  222. pu, err := os.OpenFile(filepath.Join(repoPath, "hooks", "post-update"), os.O_CREATE|os.O_WRONLY, 0777)
  223. if err != nil {
  224. return err
  225. }
  226. defer pu.Close()
  227. // TODO: Windows .bat
  228. if _, err = pu.WriteString(fmt.Sprintf("#!/usr/bin/env bash\n%s update\n", appPath)); err != nil {
  229. return err
  230. }
  231. // hook/post-update
  232. pu2, err := os.OpenFile(filepath.Join(repoPath, "hooks", "post-receive"), os.O_CREATE|os.O_WRONLY, 0777)
  233. if err != nil {
  234. return err
  235. }
  236. defer pu2.Close()
  237. // TODO: Windows .bat
  238. if _, err = pu2.WriteString("#!/usr/bin/env bash\ngit update-server-info\n"); err != nil {
  239. return err
  240. }
  241. // Initialize repository according to user's choice.
  242. fileName := map[string]string{}
  243. if initReadme {
  244. fileName["readme"] = "README.md"
  245. }
  246. if repoLang != "" {
  247. fileName["gitign"] = ".gitignore"
  248. }
  249. if license != "" {
  250. fileName["license"] = "LICENSE"
  251. }
  252. // Clone to temprory path and do the init commit.
  253. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  254. os.MkdirAll(tmpDir, os.ModePerm)
  255. if _, _, err := com.ExecCmd("git", "clone", repoPath, tmpDir); err != nil {
  256. return err
  257. }
  258. // README
  259. if initReadme {
  260. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  261. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  262. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  263. []byte(defaultReadme), 0644); err != nil {
  264. return err
  265. }
  266. }
  267. // .gitignore
  268. if repoLang != "" {
  269. filePath := "conf/gitignore/" + repoLang
  270. if com.IsFile(filePath) {
  271. if _, err := com.Copy(filePath,
  272. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  273. return err
  274. }
  275. }
  276. }
  277. // LICENSE
  278. if license != "" {
  279. filePath := "conf/license/" + license
  280. if com.IsFile(filePath) {
  281. if _, err := com.Copy(filePath,
  282. filepath.Join(tmpDir, fileName["license"])); err != nil {
  283. return err
  284. }
  285. }
  286. }
  287. if len(fileName) == 0 {
  288. return nil
  289. }
  290. // Apply changes and commit.
  291. if err := initRepoCommit(tmpDir, user.NewGitSig()); err != nil {
  292. return err
  293. }
  294. return nil
  295. }
  296. // UserRepo reporesents a repository with user name.
  297. type UserRepo struct {
  298. *Repository
  299. UserName string
  300. }
  301. // GetRepos returns given number of repository objects with offset.
  302. func GetRepos(num, offset int) ([]UserRepo, error) {
  303. repos := make([]Repository, 0, num)
  304. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  305. return nil, err
  306. }
  307. urepos := make([]UserRepo, len(repos))
  308. for i := range repos {
  309. urepos[i].Repository = &repos[i]
  310. u := new(User)
  311. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  312. if err != nil {
  313. return nil, err
  314. } else if !has {
  315. return nil, ErrUserNotExist
  316. }
  317. urepos[i].UserName = u.Name
  318. }
  319. return urepos, nil
  320. }
  321. func RepoPath(userName, repoName string) string {
  322. return filepath.Join(UserPath(userName), repoName+".git")
  323. }
  324. // DeleteRepository deletes a repository for a user or orgnaztion.
  325. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  326. repo := &Repository{Id: repoId, OwnerId: userId}
  327. has, err := orm.Get(repo)
  328. if err != nil {
  329. return err
  330. } else if !has {
  331. return ErrRepoNotExist
  332. }
  333. session := orm.NewSession()
  334. if err = session.Begin(); err != nil {
  335. return err
  336. }
  337. if _, err = session.Delete(&Repository{Id: repoId}); err != nil {
  338. session.Rollback()
  339. return err
  340. }
  341. if _, err := session.Delete(&Access{UserName: userName, RepoName: repo.Name}); err != nil {
  342. session.Rollback()
  343. return err
  344. }
  345. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  346. if _, err = session.Exec(rawSql, userId); err != nil {
  347. session.Rollback()
  348. return err
  349. }
  350. if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil {
  351. session.Rollback()
  352. return err
  353. }
  354. if err = session.Commit(); err != nil {
  355. session.Rollback()
  356. return err
  357. }
  358. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  359. // TODO: log and delete manully
  360. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  361. return err
  362. }
  363. return nil
  364. }
  365. // GetRepositoryByName returns the repository by given name under user if exists.
  366. func GetRepositoryByName(user *User, repoName string) (*Repository, error) {
  367. repo := &Repository{
  368. OwnerId: user.Id,
  369. LowerName: strings.ToLower(repoName),
  370. }
  371. has, err := orm.Get(repo)
  372. if err != nil {
  373. return nil, err
  374. } else if !has {
  375. return nil, ErrRepoNotExist
  376. }
  377. return repo, err
  378. }
  379. // GetRepositoryById returns the repository by given id if exists.
  380. func GetRepositoryById(id int64) (repo *Repository, err error) {
  381. has, err := orm.Id(id).Get(repo)
  382. if err != nil {
  383. return nil, err
  384. } else if !has {
  385. return nil, ErrRepoNotExist
  386. }
  387. return repo, err
  388. }
  389. // GetRepositories returns the list of repositories of given user.
  390. func GetRepositories(user *User) ([]Repository, error) {
  391. repos := make([]Repository, 0, 10)
  392. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  393. return repos, err
  394. }
  395. func GetRepositoryCount(user *User) (int64, error) {
  396. return orm.Count(&Repository{OwnerId: user.Id})
  397. }
  398. // Watch is connection request for receiving repository notifycation.
  399. type Watch struct {
  400. Id int64
  401. RepoId int64 `xorm:"UNIQUE(watch)"`
  402. UserId int64 `xorm:"UNIQUE(watch)"`
  403. }
  404. // Watch or unwatch repository.
  405. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  406. if watch {
  407. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  408. return err
  409. }
  410. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  411. _, err = orm.Exec(rawSql, repoId)
  412. } else {
  413. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  414. return err
  415. }
  416. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  417. _, err = orm.Exec(rawSql, repoId)
  418. }
  419. return err
  420. }
  421. // GetWatches returns all watches of given repository.
  422. func GetWatches(repoId int64) ([]Watch, error) {
  423. watches := make([]Watch, 0, 10)
  424. err := orm.Find(&watches, &Watch{RepoId: repoId})
  425. return watches, err
  426. }
  427. // IsWatching checks if user has watched given repository.
  428. func IsWatching(userId, repoId int64) bool {
  429. has, _ := orm.Get(&Watch{0, repoId, userId})
  430. return has
  431. }
  432. func StarReposiory(user *User, repoName string) error {
  433. return nil
  434. }
  435. func UnStarRepository() {
  436. }
  437. func WatchRepository() {
  438. }
  439. func UnWatchRepository() {
  440. }
  441. func ForkRepository(reposName string, userId int64) {
  442. }
  443. // RepoFile represents a file object in git repository.
  444. type RepoFile struct {
  445. *git.TreeEntry
  446. Path string
  447. Size int64
  448. Repo *git.Repository
  449. Commit *git.Commit
  450. }
  451. // LookupBlob returns the content of an object.
  452. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  453. if file.Repo == nil {
  454. return nil, ErrRepoFileNotLoaded
  455. }
  456. return file.Repo.LookupBlob(file.Id)
  457. }
  458. // GetBranches returns all branches of given repository.
  459. func GetBranches(userName, reposName string) ([]string, error) {
  460. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  461. if err != nil {
  462. return nil, err
  463. }
  464. refs, err := repo.AllReferences()
  465. if err != nil {
  466. return nil, err
  467. }
  468. brs := make([]string, len(refs))
  469. for i, ref := range refs {
  470. brs[i] = ref.Name
  471. }
  472. return brs, nil
  473. }
  474. func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
  475. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  476. if err != nil {
  477. return nil, err
  478. }
  479. commit, err := repo.GetCommit(branchName, commitId)
  480. if err != nil {
  481. return nil, err
  482. }
  483. parts := strings.Split(path.Clean(rpath), "/")
  484. var entry *git.TreeEntry
  485. tree := commit.Tree
  486. for i, part := range parts {
  487. if i == len(parts)-1 {
  488. entry = tree.EntryByName(part)
  489. if entry == nil {
  490. return nil, ErrRepoFileNotExist
  491. }
  492. } else {
  493. tree, err = repo.SubTree(tree, part)
  494. if err != nil {
  495. return nil, err
  496. }
  497. }
  498. }
  499. size, err := repo.ObjectSize(entry.Id)
  500. if err != nil {
  501. return nil, err
  502. }
  503. repoFile := &RepoFile{
  504. entry,
  505. rpath,
  506. size,
  507. repo,
  508. commit,
  509. }
  510. return repoFile, nil
  511. }
  512. // GetReposFiles returns a list of file object in given directory of repository.
  513. func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
  514. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  515. if err != nil {
  516. return nil, err
  517. }
  518. commit, err := repo.GetCommit(branchName, commitId)
  519. if err != nil {
  520. return nil, err
  521. }
  522. var repodirs []*RepoFile
  523. var repofiles []*RepoFile
  524. commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  525. if dirname == rpath {
  526. // TODO: size get method shoule be improved
  527. size, err := repo.ObjectSize(entry.Id)
  528. if err != nil {
  529. return 0
  530. }
  531. var cm = commit
  532. var i int
  533. for {
  534. i = i + 1
  535. //fmt.Println(".....", i, cm.Id(), cm.ParentCount())
  536. if cm.ParentCount() == 0 {
  537. break
  538. } else if cm.ParentCount() == 1 {
  539. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  540. if pt == nil {
  541. break
  542. }
  543. pEntry := pt.EntryByName(entry.Name)
  544. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  545. break
  546. } else {
  547. cm = cm.Parent(0)
  548. }
  549. } else {
  550. var emptyCnt = 0
  551. var sameIdcnt = 0
  552. var lastSameCm *git.Commit
  553. //fmt.Println(".....", cm.ParentCount())
  554. for i := 0; i < cm.ParentCount(); i++ {
  555. //fmt.Println("parent", i, cm.Parent(i).Id())
  556. p := cm.Parent(i)
  557. pt, _ := repo.SubTree(p.Tree, dirname)
  558. var pEntry *git.TreeEntry
  559. if pt != nil {
  560. pEntry = pt.EntryByName(entry.Name)
  561. }
  562. //fmt.Println("pEntry", pEntry)
  563. if pEntry == nil {
  564. emptyCnt = emptyCnt + 1
  565. if emptyCnt+sameIdcnt == cm.ParentCount() {
  566. if lastSameCm == nil {
  567. goto loop
  568. } else {
  569. cm = lastSameCm
  570. break
  571. }
  572. }
  573. } else {
  574. //fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
  575. if !pEntry.Id.Equal(entry.Id) {
  576. goto loop
  577. } else {
  578. lastSameCm = cm.Parent(i)
  579. sameIdcnt = sameIdcnt + 1
  580. if emptyCnt+sameIdcnt == cm.ParentCount() {
  581. // TODO: now follow the first parent commit?
  582. cm = lastSameCm
  583. //fmt.Println("sameId...")
  584. break
  585. }
  586. }
  587. }
  588. }
  589. }
  590. }
  591. loop:
  592. rp := &RepoFile{
  593. entry,
  594. path.Join(dirname, entry.Name),
  595. size,
  596. repo,
  597. cm,
  598. }
  599. if entry.IsFile() {
  600. repofiles = append(repofiles, rp)
  601. } else if entry.IsDir() {
  602. repodirs = append(repodirs, rp)
  603. }
  604. }
  605. return 0
  606. })
  607. return append(repodirs, repofiles...), nil
  608. }
  609. func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
  610. repo, err := git.OpenRepository(RepoPath(userName, repoName))
  611. if err != nil {
  612. return nil, err
  613. }
  614. return repo.GetCommit(branchname, commitid)
  615. }
  616. // GetCommits returns all commits of given branch of repository.
  617. func GetCommits(userName, reposName, branchname string) (*list.List, error) {
  618. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  619. if err != nil {
  620. return nil, err
  621. }
  622. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  623. if err != nil {
  624. return nil, err
  625. }
  626. return r.AllCommits()
  627. }