repo.go 18 KB

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