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

repo.go 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. // NotifyWatchers creates batch of actions for every watcher.
  449. func NotifyWatchers(userId, repoId int64, opType int, userName, repoName, refName, content string) error {
  450. // Add feeds for user self and all watchers.
  451. watches, err := GetWatches(repoId)
  452. if err != nil {
  453. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  454. }
  455. watches = append(watches, Watch{UserId: userId})
  456. for i := range watches {
  457. if userId == watches[i].UserId && i > 0 {
  458. continue // Do not add twice in case author watches his/her repository.
  459. }
  460. _, err = orm.InsertOne(&Action{
  461. UserId: watches[i].UserId,
  462. ActUserId: userId,
  463. ActUserName: userName,
  464. OpType: opType,
  465. Content: content,
  466. RepoId: repoId,
  467. RepoName: repoName,
  468. RefName: refName,
  469. })
  470. if err != nil {
  471. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  472. }
  473. }
  474. return nil
  475. }
  476. // IsWatching checks if user has watched given repository.
  477. func IsWatching(userId, repoId int64) bool {
  478. has, _ := orm.Get(&Watch{0, repoId, userId})
  479. return has
  480. }
  481. func StarReposiory(user *User, repoName string) error {
  482. return nil
  483. }
  484. func UnStarRepository() {
  485. }
  486. func WatchRepository() {
  487. }
  488. func UnWatchRepository() {
  489. }
  490. func ForkRepository(reposName string, userId int64) {
  491. }
  492. // RepoFile represents a file object in git repository.
  493. type RepoFile struct {
  494. *git.TreeEntry
  495. Path string
  496. Size int64
  497. Repo *git.Repository
  498. Commit *git.Commit
  499. }
  500. // LookupBlob returns the content of an object.
  501. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  502. if file.Repo == nil {
  503. return nil, ErrRepoFileNotLoaded
  504. }
  505. return file.Repo.LookupBlob(file.Id)
  506. }
  507. // GetBranches returns all branches of given repository.
  508. func GetBranches(userName, reposName string) ([]string, error) {
  509. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  510. if err != nil {
  511. return nil, err
  512. }
  513. refs, err := repo.AllReferences()
  514. if err != nil {
  515. return nil, err
  516. }
  517. brs := make([]string, len(refs))
  518. for i, ref := range refs {
  519. brs[i] = ref.Name
  520. }
  521. return brs, nil
  522. }
  523. func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
  524. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  525. if err != nil {
  526. return nil, err
  527. }
  528. commit, err := repo.GetCommit(branchName, commitId)
  529. if err != nil {
  530. return nil, err
  531. }
  532. parts := strings.Split(path.Clean(rpath), "/")
  533. var entry *git.TreeEntry
  534. tree := commit.Tree
  535. for i, part := range parts {
  536. if i == len(parts)-1 {
  537. entry = tree.EntryByName(part)
  538. if entry == nil {
  539. return nil, ErrRepoFileNotExist
  540. }
  541. } else {
  542. tree, err = repo.SubTree(tree, part)
  543. if err != nil {
  544. return nil, err
  545. }
  546. }
  547. }
  548. size, err := repo.ObjectSize(entry.Id)
  549. if err != nil {
  550. return nil, err
  551. }
  552. repoFile := &RepoFile{
  553. entry,
  554. rpath,
  555. size,
  556. repo,
  557. commit,
  558. }
  559. return repoFile, nil
  560. }
  561. // GetReposFiles returns a list of file object in given directory of repository.
  562. func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
  563. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  564. if err != nil {
  565. return nil, err
  566. }
  567. commit, err := repo.GetCommit(branchName, commitId)
  568. if err != nil {
  569. return nil, err
  570. }
  571. var repodirs []*RepoFile
  572. var repofiles []*RepoFile
  573. commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  574. if dirname == rpath {
  575. // TODO: size get method shoule be improved
  576. size, err := repo.ObjectSize(entry.Id)
  577. if err != nil {
  578. return 0
  579. }
  580. var cm = commit
  581. var i int
  582. for {
  583. i = i + 1
  584. //fmt.Println(".....", i, cm.Id(), cm.ParentCount())
  585. if cm.ParentCount() == 0 {
  586. break
  587. } else if cm.ParentCount() == 1 {
  588. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  589. if pt == nil {
  590. break
  591. }
  592. pEntry := pt.EntryByName(entry.Name)
  593. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  594. break
  595. } else {
  596. cm = cm.Parent(0)
  597. }
  598. } else {
  599. var emptyCnt = 0
  600. var sameIdcnt = 0
  601. var lastSameCm *git.Commit
  602. //fmt.Println(".....", cm.ParentCount())
  603. for i := 0; i < cm.ParentCount(); i++ {
  604. //fmt.Println("parent", i, cm.Parent(i).Id())
  605. p := cm.Parent(i)
  606. pt, _ := repo.SubTree(p.Tree, dirname)
  607. var pEntry *git.TreeEntry
  608. if pt != nil {
  609. pEntry = pt.EntryByName(entry.Name)
  610. }
  611. //fmt.Println("pEntry", pEntry)
  612. if pEntry == nil {
  613. emptyCnt = emptyCnt + 1
  614. if emptyCnt+sameIdcnt == cm.ParentCount() {
  615. if lastSameCm == nil {
  616. goto loop
  617. } else {
  618. cm = lastSameCm
  619. break
  620. }
  621. }
  622. } else {
  623. //fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
  624. if !pEntry.Id.Equal(entry.Id) {
  625. goto loop
  626. } else {
  627. lastSameCm = cm.Parent(i)
  628. sameIdcnt = sameIdcnt + 1
  629. if emptyCnt+sameIdcnt == cm.ParentCount() {
  630. // TODO: now follow the first parent commit?
  631. cm = lastSameCm
  632. //fmt.Println("sameId...")
  633. break
  634. }
  635. }
  636. }
  637. }
  638. }
  639. }
  640. loop:
  641. rp := &RepoFile{
  642. entry,
  643. path.Join(dirname, entry.Name),
  644. size,
  645. repo,
  646. cm,
  647. }
  648. if entry.IsFile() {
  649. repofiles = append(repofiles, rp)
  650. } else if entry.IsDir() {
  651. repodirs = append(repodirs, rp)
  652. }
  653. }
  654. return 0
  655. })
  656. return append(repodirs, repofiles...), nil
  657. }
  658. func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
  659. repo, err := git.OpenRepository(RepoPath(userName, repoName))
  660. if err != nil {
  661. return nil, err
  662. }
  663. return repo.GetCommit(branchname, commitid)
  664. }
  665. // GetCommits returns all commits of given branch of repository.
  666. func GetCommits(userName, reposName, branchname string) (*list.List, error) {
  667. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  668. if err != nil {
  669. return nil, err
  670. }
  671. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  672. if err != nil {
  673. return nil, err
  674. }
  675. return r.AllCommits()
  676. }