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