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