You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 18 kB

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