repo.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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. func UpdateRepository(repo *Repository) error {
  325. _, err := orm.Id(repo.Id).UseBool().Update(repo)
  326. return err
  327. }
  328. // DeleteRepository deletes a repository for a user or orgnaztion.
  329. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  330. repo := &Repository{Id: repoId, OwnerId: userId}
  331. has, err := orm.Get(repo)
  332. if err != nil {
  333. return err
  334. } else if !has {
  335. return ErrRepoNotExist
  336. }
  337. session := orm.NewSession()
  338. if err = session.Begin(); err != nil {
  339. return err
  340. }
  341. if _, err = session.Delete(&Repository{Id: repoId}); err != nil {
  342. session.Rollback()
  343. return err
  344. }
  345. if _, err := session.Delete(&Access{UserName: userName, RepoName: repo.Name}); err != nil {
  346. session.Rollback()
  347. return err
  348. }
  349. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  350. if _, err = session.Exec(rawSql, userId); err != nil {
  351. session.Rollback()
  352. return err
  353. }
  354. if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil {
  355. session.Rollback()
  356. return err
  357. }
  358. if err = session.Commit(); err != nil {
  359. session.Rollback()
  360. return err
  361. }
  362. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  363. // TODO: log and delete manully
  364. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  365. return err
  366. }
  367. return nil
  368. }
  369. // GetRepositoryByName returns the repository by given name under user if exists.
  370. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  371. repo := &Repository{
  372. OwnerId: userId,
  373. LowerName: strings.ToLower(repoName),
  374. }
  375. has, err := orm.Get(repo)
  376. if err != nil {
  377. return nil, err
  378. } else if !has {
  379. return nil, ErrRepoNotExist
  380. }
  381. return repo, err
  382. }
  383. // GetRepositoryById returns the repository by given id if exists.
  384. func GetRepositoryById(id int64) (repo *Repository, err error) {
  385. has, err := orm.Id(id).Get(repo)
  386. if err != nil {
  387. return nil, err
  388. } else if !has {
  389. return nil, ErrRepoNotExist
  390. }
  391. return repo, err
  392. }
  393. // GetRepositories returns the list of repositories of given user.
  394. func GetRepositories(user *User) ([]Repository, error) {
  395. repos := make([]Repository, 0, 10)
  396. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  397. return repos, err
  398. }
  399. func GetRepositoryCount(user *User) (int64, error) {
  400. return orm.Count(&Repository{OwnerId: user.Id})
  401. }
  402. // Watch is connection request for receiving repository notifycation.
  403. type Watch struct {
  404. Id int64
  405. RepoId int64 `xorm:"UNIQUE(watch)"`
  406. UserId int64 `xorm:"UNIQUE(watch)"`
  407. }
  408. // Watch or unwatch repository.
  409. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  410. if watch {
  411. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  412. return err
  413. }
  414. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  415. _, err = orm.Exec(rawSql, repoId)
  416. } else {
  417. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  418. return err
  419. }
  420. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  421. _, err = orm.Exec(rawSql, repoId)
  422. }
  423. return err
  424. }
  425. // GetWatches returns all watches of given repository.
  426. func GetWatches(repoId int64) ([]Watch, error) {
  427. watches := make([]Watch, 0, 10)
  428. err := orm.Find(&watches, &Watch{RepoId: repoId})
  429. return watches, err
  430. }
  431. // IsWatching checks if user has watched given repository.
  432. func IsWatching(userId, repoId int64) bool {
  433. has, _ := orm.Get(&Watch{0, repoId, userId})
  434. return has
  435. }
  436. func StarReposiory(user *User, repoName string) error {
  437. return nil
  438. }
  439. func UnStarRepository() {
  440. }
  441. func WatchRepository() {
  442. }
  443. func UnWatchRepository() {
  444. }
  445. func ForkRepository(reposName string, userId int64) {
  446. }
  447. // RepoFile represents a file object in git repository.
  448. type RepoFile struct {
  449. *git.TreeEntry
  450. Path string
  451. Size int64
  452. Repo *git.Repository
  453. Commit *git.Commit
  454. }
  455. // LookupBlob returns the content of an object.
  456. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  457. if file.Repo == nil {
  458. return nil, ErrRepoFileNotLoaded
  459. }
  460. return file.Repo.LookupBlob(file.Id)
  461. }
  462. // GetBranches returns all branches of given repository.
  463. func GetBranches(userName, reposName string) ([]string, error) {
  464. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  465. if err != nil {
  466. return nil, err
  467. }
  468. refs, err := repo.AllReferences()
  469. if err != nil {
  470. return nil, err
  471. }
  472. brs := make([]string, len(refs))
  473. for i, ref := range refs {
  474. brs[i] = ref.Name
  475. }
  476. return brs, nil
  477. }
  478. func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
  479. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  480. if err != nil {
  481. return nil, err
  482. }
  483. commit, err := repo.GetCommit(branchName, commitId)
  484. if err != nil {
  485. return nil, err
  486. }
  487. parts := strings.Split(path.Clean(rpath), "/")
  488. var entry *git.TreeEntry
  489. tree := commit.Tree
  490. for i, part := range parts {
  491. if i == len(parts)-1 {
  492. entry = tree.EntryByName(part)
  493. if entry == nil {
  494. return nil, ErrRepoFileNotExist
  495. }
  496. } else {
  497. tree, err = repo.SubTree(tree, part)
  498. if err != nil {
  499. return nil, err
  500. }
  501. }
  502. }
  503. size, err := repo.ObjectSize(entry.Id)
  504. if err != nil {
  505. return nil, err
  506. }
  507. repoFile := &RepoFile{
  508. entry,
  509. rpath,
  510. size,
  511. repo,
  512. commit,
  513. }
  514. return repoFile, nil
  515. }
  516. // GetReposFiles returns a list of file object in given directory of repository.
  517. func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
  518. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  519. if err != nil {
  520. return nil, err
  521. }
  522. commit, err := repo.GetCommit(branchName, commitId)
  523. if err != nil {
  524. return nil, err
  525. }
  526. var repodirs []*RepoFile
  527. var repofiles []*RepoFile
  528. commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  529. if dirname == rpath {
  530. // TODO: size get method shoule be improved
  531. size, err := repo.ObjectSize(entry.Id)
  532. if err != nil {
  533. return 0
  534. }
  535. var cm = commit
  536. var i int
  537. for {
  538. i = i + 1
  539. //fmt.Println(".....", i, cm.Id(), cm.ParentCount())
  540. if cm.ParentCount() == 0 {
  541. break
  542. } else if cm.ParentCount() == 1 {
  543. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  544. if pt == nil {
  545. break
  546. }
  547. pEntry := pt.EntryByName(entry.Name)
  548. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  549. break
  550. } else {
  551. cm = cm.Parent(0)
  552. }
  553. } else {
  554. var emptyCnt = 0
  555. var sameIdcnt = 0
  556. var lastSameCm *git.Commit
  557. //fmt.Println(".....", cm.ParentCount())
  558. for i := 0; i < cm.ParentCount(); i++ {
  559. //fmt.Println("parent", i, cm.Parent(i).Id())
  560. p := cm.Parent(i)
  561. pt, _ := repo.SubTree(p.Tree, dirname)
  562. var pEntry *git.TreeEntry
  563. if pt != nil {
  564. pEntry = pt.EntryByName(entry.Name)
  565. }
  566. //fmt.Println("pEntry", pEntry)
  567. if pEntry == nil {
  568. emptyCnt = emptyCnt + 1
  569. if emptyCnt+sameIdcnt == cm.ParentCount() {
  570. if lastSameCm == nil {
  571. goto loop
  572. } else {
  573. cm = lastSameCm
  574. break
  575. }
  576. }
  577. } else {
  578. //fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
  579. if !pEntry.Id.Equal(entry.Id) {
  580. goto loop
  581. } else {
  582. lastSameCm = cm.Parent(i)
  583. sameIdcnt = sameIdcnt + 1
  584. if emptyCnt+sameIdcnt == cm.ParentCount() {
  585. // TODO: now follow the first parent commit?
  586. cm = lastSameCm
  587. //fmt.Println("sameId...")
  588. break
  589. }
  590. }
  591. }
  592. }
  593. }
  594. }
  595. loop:
  596. rp := &RepoFile{
  597. entry,
  598. path.Join(dirname, entry.Name),
  599. size,
  600. repo,
  601. cm,
  602. }
  603. if entry.IsFile() {
  604. repofiles = append(repofiles, rp)
  605. } else if entry.IsDir() {
  606. repodirs = append(repodirs, rp)
  607. }
  608. }
  609. return 0
  610. })
  611. return append(repodirs, repofiles...), nil
  612. }
  613. func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
  614. repo, err := git.OpenRepository(RepoPath(userName, repoName))
  615. if err != nil {
  616. return nil, err
  617. }
  618. return repo.GetCommit(branchname, commitid)
  619. }
  620. // GetCommits returns all commits of given branch of repository.
  621. func GetCommits(userName, reposName, branchname string) (*list.List, error) {
  622. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  623. if err != nil {
  624. return nil, err
  625. }
  626. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  627. if err != nil {
  628. return nil, err
  629. }
  630. return r.AllCommits()
  631. }