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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. // Initialize repository according to user's choice.
  232. fileName := map[string]string{}
  233. if initReadme {
  234. fileName["readme"] = "README.md"
  235. }
  236. if repoLang != "" {
  237. fileName["gitign"] = ".gitignore"
  238. }
  239. if license != "" {
  240. fileName["license"] = "LICENSE"
  241. }
  242. // Clone to temprory path and do the init commit.
  243. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  244. os.MkdirAll(tmpDir, os.ModePerm)
  245. if _, _, err := com.ExecCmd("git", "clone", repoPath, tmpDir); err != nil {
  246. return err
  247. }
  248. // README
  249. if initReadme {
  250. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  251. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  252. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  253. []byte(defaultReadme), 0644); err != nil {
  254. return err
  255. }
  256. }
  257. // .gitignore
  258. if repoLang != "" {
  259. filePath := "conf/gitignore/" + repoLang
  260. if com.IsFile(filePath) {
  261. if _, err := com.Copy(filePath,
  262. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  263. return err
  264. }
  265. }
  266. }
  267. // LICENSE
  268. if license != "" {
  269. filePath := "conf/license/" + license
  270. if com.IsFile(filePath) {
  271. if _, err := com.Copy(filePath,
  272. filepath.Join(tmpDir, fileName["license"])); err != nil {
  273. return err
  274. }
  275. }
  276. }
  277. if len(fileName) == 0 {
  278. return nil
  279. }
  280. // Apply changes and commit.
  281. if err := initRepoCommit(tmpDir, user.NewGitSig()); err != nil {
  282. return err
  283. }
  284. return nil
  285. }
  286. // UserRepo reporesents a repository with user name.
  287. type UserRepo struct {
  288. *Repository
  289. UserName string
  290. }
  291. // GetRepos returns given number of repository objects with offset.
  292. func GetRepos(num, offset int) ([]UserRepo, error) {
  293. repos := make([]Repository, 0, num)
  294. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  295. return nil, err
  296. }
  297. urepos := make([]UserRepo, len(repos))
  298. for i := range repos {
  299. urepos[i].Repository = &repos[i]
  300. u := new(User)
  301. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  302. if err != nil {
  303. return nil, err
  304. } else if !has {
  305. return nil, ErrUserNotExist
  306. }
  307. urepos[i].UserName = u.Name
  308. }
  309. return urepos, nil
  310. }
  311. func RepoPath(userName, repoName string) string {
  312. return filepath.Join(UserPath(userName), repoName+".git")
  313. }
  314. // DeleteRepository deletes a repository for a user or orgnaztion.
  315. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  316. repo := &Repository{Id: repoId, OwnerId: userId}
  317. has, err := orm.Get(repo)
  318. if err != nil {
  319. return err
  320. } else if !has {
  321. return ErrRepoNotExist
  322. }
  323. session := orm.NewSession()
  324. if err = session.Begin(); err != nil {
  325. return err
  326. }
  327. if _, err = session.Delete(&Repository{Id: repoId}); err != nil {
  328. session.Rollback()
  329. return err
  330. }
  331. if _, err := session.Delete(&Access{UserName: userName, RepoName: repo.Name}); err != nil {
  332. session.Rollback()
  333. return err
  334. }
  335. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  336. if _, err = session.Exec(rawSql, userId); err != nil {
  337. session.Rollback()
  338. return err
  339. }
  340. if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil {
  341. session.Rollback()
  342. return err
  343. }
  344. if err = session.Commit(); err != nil {
  345. session.Rollback()
  346. return err
  347. }
  348. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  349. // TODO: log and delete manully
  350. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  351. return err
  352. }
  353. return nil
  354. }
  355. // GetRepositoryByName returns the repository by given name under user if exists.
  356. func GetRepositoryByName(user *User, repoName string) (*Repository, error) {
  357. repo := &Repository{
  358. OwnerId: user.Id,
  359. LowerName: strings.ToLower(repoName),
  360. }
  361. has, err := orm.Get(repo)
  362. if err != nil {
  363. return nil, err
  364. } else if !has {
  365. return nil, ErrRepoNotExist
  366. }
  367. return repo, err
  368. }
  369. // GetRepositoryById returns the repository by given id if exists.
  370. func GetRepositoryById(id int64) (repo *Repository, err error) {
  371. has, err := orm.Id(id).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. // GetRepositories returns the list of repositories of given user.
  380. func GetRepositories(user *User) ([]Repository, error) {
  381. repos := make([]Repository, 0, 10)
  382. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  383. return repos, err
  384. }
  385. func GetRepositoryCount(user *User) (int64, error) {
  386. return orm.Count(&Repository{OwnerId: user.Id})
  387. }
  388. // Watch is connection request for receiving repository notifycation.
  389. type Watch struct {
  390. Id int64
  391. RepoId int64 `xorm:"UNIQUE(watch)"`
  392. UserId int64 `xorm:"UNIQUE(watch)"`
  393. }
  394. // Watch or unwatch repository.
  395. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  396. if watch {
  397. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  398. return err
  399. }
  400. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  401. _, err = orm.Exec(rawSql, repoId)
  402. } else {
  403. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  404. return err
  405. }
  406. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  407. _, err = orm.Exec(rawSql, repoId)
  408. }
  409. return err
  410. }
  411. // GetWatches returns all watches of given repository.
  412. func GetWatches(repoId int64) ([]Watch, error) {
  413. watches := make([]Watch, 0, 10)
  414. err := orm.Find(&watches, &Watch{RepoId: repoId})
  415. return watches, err
  416. }
  417. // IsWatching checks if user has watched given repository.
  418. func IsWatching(userId, repoId int64) bool {
  419. has, _ := orm.Get(&Watch{0, repoId, userId})
  420. return has
  421. }
  422. func StarReposiory(user *User, repoName string) error {
  423. return nil
  424. }
  425. func UnStarRepository() {
  426. }
  427. func WatchRepository() {
  428. }
  429. func UnWatchRepository() {
  430. }
  431. func ForkRepository(reposName string, userId int64) {
  432. }
  433. // RepoFile represents a file object in git repository.
  434. type RepoFile struct {
  435. *git.TreeEntry
  436. Path string
  437. Size int64
  438. Repo *git.Repository
  439. Commit *git.Commit
  440. }
  441. // LookupBlob returns the content of an object.
  442. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  443. if file.Repo == nil {
  444. return nil, ErrRepoFileNotLoaded
  445. }
  446. return file.Repo.LookupBlob(file.Id)
  447. }
  448. // GetBranches returns all branches of given repository.
  449. func GetBranches(userName, reposName string) ([]string, error) {
  450. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  451. if err != nil {
  452. return nil, err
  453. }
  454. refs, err := repo.AllReferences()
  455. if err != nil {
  456. return nil, err
  457. }
  458. brs := make([]string, len(refs))
  459. for i, ref := range refs {
  460. brs[i] = ref.Name
  461. }
  462. return brs, nil
  463. }
  464. func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
  465. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  466. if err != nil {
  467. return nil, err
  468. }
  469. commit, err := repo.GetCommit(branchName, commitId)
  470. if err != nil {
  471. return nil, err
  472. }
  473. parts := strings.Split(path.Clean(rpath), "/")
  474. var entry *git.TreeEntry
  475. tree := commit.Tree
  476. for i, part := range parts {
  477. if i == len(parts)-1 {
  478. entry = tree.EntryByName(part)
  479. if entry == nil {
  480. return nil, ErrRepoFileNotExist
  481. }
  482. } else {
  483. tree, err = repo.SubTree(tree, part)
  484. if err != nil {
  485. return nil, err
  486. }
  487. }
  488. }
  489. size, err := repo.ObjectSize(entry.Id)
  490. if err != nil {
  491. return nil, err
  492. }
  493. repoFile := &RepoFile{
  494. entry,
  495. rpath,
  496. size,
  497. repo,
  498. commit,
  499. }
  500. return repoFile, nil
  501. }
  502. // GetReposFiles returns a list of file object in given directory of repository.
  503. func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
  504. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  505. if err != nil {
  506. return nil, err
  507. }
  508. commit, err := repo.GetCommit(branchName, commitId)
  509. if err != nil {
  510. return nil, err
  511. }
  512. var repodirs []*RepoFile
  513. var repofiles []*RepoFile
  514. commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  515. if dirname == rpath {
  516. // TODO: size get method shoule be improved
  517. size, err := repo.ObjectSize(entry.Id)
  518. if err != nil {
  519. return 0
  520. }
  521. var cm = commit
  522. var i int
  523. for {
  524. i = i + 1
  525. //fmt.Println(".....", i, cm.Id(), cm.ParentCount())
  526. if cm.ParentCount() == 0 {
  527. break
  528. } else if cm.ParentCount() == 1 {
  529. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  530. if pt == nil {
  531. break
  532. }
  533. pEntry := pt.EntryByName(entry.Name)
  534. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  535. break
  536. } else {
  537. cm = cm.Parent(0)
  538. }
  539. } else {
  540. var emptyCnt = 0
  541. var sameIdcnt = 0
  542. var lastSameCm *git.Commit
  543. //fmt.Println(".....", cm.ParentCount())
  544. for i := 0; i < cm.ParentCount(); i++ {
  545. //fmt.Println("parent", i, cm.Parent(i).Id())
  546. p := cm.Parent(i)
  547. pt, _ := repo.SubTree(p.Tree, dirname)
  548. var pEntry *git.TreeEntry
  549. if pt != nil {
  550. pEntry = pt.EntryByName(entry.Name)
  551. }
  552. //fmt.Println("pEntry", pEntry)
  553. if pEntry == nil {
  554. emptyCnt = emptyCnt + 1
  555. if emptyCnt+sameIdcnt == cm.ParentCount() {
  556. if lastSameCm == nil {
  557. goto loop
  558. } else {
  559. cm = lastSameCm
  560. break
  561. }
  562. }
  563. } else {
  564. //fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
  565. if !pEntry.Id.Equal(entry.Id) {
  566. goto loop
  567. } else {
  568. lastSameCm = cm.Parent(i)
  569. sameIdcnt = sameIdcnt + 1
  570. if emptyCnt+sameIdcnt == cm.ParentCount() {
  571. // TODO: now follow the first parent commit?
  572. cm = lastSameCm
  573. //fmt.Println("sameId...")
  574. break
  575. }
  576. }
  577. }
  578. }
  579. }
  580. }
  581. loop:
  582. rp := &RepoFile{
  583. entry,
  584. path.Join(dirname, entry.Name),
  585. size,
  586. repo,
  587. cm,
  588. }
  589. if entry.IsFile() {
  590. repofiles = append(repofiles, rp)
  591. } else if entry.IsDir() {
  592. repodirs = append(repodirs, rp)
  593. }
  594. }
  595. return 0
  596. })
  597. return append(repodirs, repofiles...), nil
  598. }
  599. func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
  600. repo, err := git.OpenRepository(RepoPath(userName, repoName))
  601. if err != nil {
  602. return nil, err
  603. }
  604. return repo.GetCommit(branchname, commitid)
  605. }
  606. // GetCommits returns all commits of given branch of repository.
  607. func GetCommits(userName, reposName, branchname string) (*list.List, error) {
  608. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  609. if err != nil {
  610. return nil, err
  611. }
  612. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  613. if err != nil {
  614. return nil, err
  615. }
  616. return r.AllCommits()
  617. }