repo.go 18 KB

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