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 14 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strings"
  13. "sync"
  14. "time"
  15. "unicode/utf8"
  16. "github.com/Unknwon/cae/zip"
  17. "github.com/Unknwon/com"
  18. "github.com/gogits/git"
  19. "github.com/gogits/gogs/modules/base"
  20. "github.com/gogits/gogs/modules/log"
  21. )
  22. // Repository represents a git repository.
  23. type Repository struct {
  24. Id int64
  25. OwnerId int64 `xorm:"unique(s)"`
  26. ForkId int64
  27. LowerName string `xorm:"unique(s) index not null"`
  28. Name string `xorm:"index not null"`
  29. Description string
  30. Private bool
  31. NumWatchs int
  32. NumStars int
  33. NumForks int
  34. Created time.Time `xorm:"created"`
  35. Updated time.Time `xorm:"updated"`
  36. }
  37. type Star struct {
  38. Id int64
  39. RepoId int64
  40. UserId int64
  41. Created time.Time `xorm:"created"`
  42. }
  43. var (
  44. gitInitLocker = sync.Mutex{}
  45. LanguageIgns, Licenses []string
  46. )
  47. var (
  48. ErrRepoAlreadyExist = errors.New("Repository already exist")
  49. ErrRepoNotExist = errors.New("Repository does not exist")
  50. )
  51. func init() {
  52. LanguageIgns = strings.Split(base.Cfg.MustValue("repository", "LANG_IGNS"), "|")
  53. Licenses = strings.Split(base.Cfg.MustValue("repository", "LICENSES"), "|")
  54. zip.Verbose = false
  55. }
  56. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  57. func IsRepositoryExist(user *User, repoName string) (bool, error) {
  58. repo := Repository{OwnerId: user.Id}
  59. has, err := orm.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  60. if err != nil {
  61. return has, err
  62. }
  63. s, err := os.Stat(RepoPath(user.Name, repoName))
  64. if err != nil {
  65. return false, nil // Error simply means does not exist, but we don't want to show up.
  66. }
  67. return s.IsDir(), nil
  68. }
  69. // CreateRepository creates a repository for given user or orgnaziation.
  70. func CreateRepository(user *User, repoName, desc, repoLang, license string, private bool, initReadme bool) (*Repository, error) {
  71. isExist, err := IsRepositoryExist(user, repoName)
  72. if err != nil {
  73. return nil, err
  74. } else if isExist {
  75. return nil, ErrRepoAlreadyExist
  76. }
  77. repo := &Repository{
  78. OwnerId: user.Id,
  79. Name: repoName,
  80. LowerName: strings.ToLower(repoName),
  81. Description: desc,
  82. Private: private,
  83. }
  84. repoPath := RepoPath(user.Name, repoName)
  85. if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
  86. return nil, err
  87. }
  88. session := orm.NewSession()
  89. defer session.Close()
  90. session.Begin()
  91. if _, err = session.Insert(repo); err != nil {
  92. if err2 := os.RemoveAll(repoPath); err2 != nil {
  93. log.Error("repo.CreateRepository(repo): %v", err)
  94. return nil, errors.New(fmt.Sprintf(
  95. "delete repo directory %s/%s failed(1): %v", user.Name, repoName, err2))
  96. }
  97. session.Rollback()
  98. return nil, err
  99. }
  100. access := Access{
  101. UserName: user.Name,
  102. RepoName: repo.Name,
  103. Mode: AU_WRITABLE,
  104. }
  105. if _, err = session.Insert(&access); err != nil {
  106. session.Rollback()
  107. if err2 := os.RemoveAll(repoPath); err2 != nil {
  108. log.Error("repo.CreateRepository(access): %v", err)
  109. return nil, errors.New(fmt.Sprintf(
  110. "delete repo directory %s/%s failed(2): %v", user.Name, repoName, err2))
  111. }
  112. return nil, err
  113. }
  114. rawSql := "UPDATE user SET num_repos = num_repos + 1 WHERE id = ?"
  115. if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
  116. rawSql = "UPDATE \"user\" SET num_repos = num_repos + 1 WHERE id = ?"
  117. }
  118. if _, err = session.Exec(rawSql, user.Id); err != nil {
  119. session.Rollback()
  120. if err2 := os.RemoveAll(repoPath); err2 != nil {
  121. log.Error("repo.CreateRepository(repo count): %v", err)
  122. return nil, errors.New(fmt.Sprintf(
  123. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  124. }
  125. return nil, err
  126. }
  127. if err = session.Commit(); err != nil {
  128. session.Rollback()
  129. if err2 := os.RemoveAll(repoPath); err2 != nil {
  130. log.Error("repo.CreateRepository(commit): %v", err)
  131. return nil, errors.New(fmt.Sprintf(
  132. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  133. }
  134. return nil, err
  135. }
  136. return repo, NewRepoAction(user, repo)
  137. }
  138. // extractGitBareZip extracts git-bare.zip to repository path.
  139. func extractGitBareZip(repoPath string) error {
  140. z, err := zip.Open("conf/content/git-bare.zip")
  141. if err != nil {
  142. fmt.Println("shi?")
  143. return err
  144. }
  145. defer z.Close()
  146. return z.ExtractTo(repoPath)
  147. }
  148. // initRepoCommit temporarily changes with work directory.
  149. func initRepoCommit(tmpPath string, sig *git.Signature) error {
  150. gitInitLocker.Lock()
  151. defer gitInitLocker.Unlock()
  152. // Change work directory.
  153. curPath, err := os.Getwd()
  154. if err != nil {
  155. return err
  156. } else if err = os.Chdir(tmpPath); err != nil {
  157. return err
  158. }
  159. defer os.Chdir(curPath)
  160. if _, _, err := com.ExecCmd("git", "add", "--all"); err != nil {
  161. return err
  162. }
  163. if _, _, err := com.ExecCmd("git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  164. "-m", "Init commit"); err != nil {
  165. return err
  166. }
  167. if _, _, err := com.ExecCmd("git", "push", "origin", "master"); err != nil {
  168. return err
  169. }
  170. return nil
  171. }
  172. // InitRepository initializes README and .gitignore if needed.
  173. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  174. repoPath := RepoPath(user.Name, repo.Name)
  175. // Create bare new repository.
  176. if err := extractGitBareZip(repoPath); err != nil {
  177. return err
  178. }
  179. // Initialize repository according to user's choice.
  180. fileName := map[string]string{}
  181. if initReadme {
  182. fileName["readme"] = "README.md"
  183. }
  184. if repoLang != "" {
  185. fileName["gitign"] = ".gitignore"
  186. }
  187. if license != "" {
  188. fileName["license"] = "LICENSE"
  189. }
  190. // Clone to temprory path and do the init commit.
  191. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  192. os.MkdirAll(tmpDir, os.ModePerm)
  193. if _, _, err := com.ExecCmd("git", "clone", repoPath, tmpDir); err != nil {
  194. return err
  195. }
  196. // README
  197. if initReadme {
  198. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  199. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  200. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  201. []byte(defaultReadme), 0644); err != nil {
  202. return err
  203. }
  204. }
  205. // .gitignore
  206. if repoLang != "" {
  207. filePath := "conf/gitignore/" + repoLang
  208. if com.IsFile(filePath) {
  209. if _, err := com.Copy(filePath,
  210. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  211. return err
  212. }
  213. }
  214. }
  215. // LICENSE
  216. if license != "" {
  217. filePath := "conf/license/" + license
  218. if com.IsFile(filePath) {
  219. if _, err := com.Copy(filePath,
  220. filepath.Join(tmpDir, fileName["license"])); err != nil {
  221. return err
  222. }
  223. }
  224. }
  225. // Apply changes and commit.
  226. if err := initRepoCommit(tmpDir, user.NewGitSig()); err != nil {
  227. return err
  228. }
  229. return nil
  230. }
  231. // GetRepositoryByName returns the repository by given name under user if exists.
  232. func GetRepositoryByName(user *User, repoName string) (*Repository, error) {
  233. repo := &Repository{
  234. OwnerId: user.Id,
  235. LowerName: strings.ToLower(repoName),
  236. }
  237. has, err := orm.Get(repo)
  238. if err != nil {
  239. return nil, err
  240. } else if !has {
  241. return nil, ErrRepoNotExist
  242. }
  243. return repo, err
  244. }
  245. // GetRepositoryById returns the repository by given id if exists.
  246. func GetRepositoryById(id int64) (repo *Repository, err error) {
  247. has, err := orm.Id(id).Get(repo)
  248. if err != nil {
  249. return nil, err
  250. } else if !has {
  251. return nil, ErrRepoNotExist
  252. }
  253. return repo, err
  254. }
  255. // GetRepositories returns the list of repositories of given user.
  256. func GetRepositories(user *User) ([]Repository, error) {
  257. repos := make([]Repository, 0, 10)
  258. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  259. return repos, err
  260. }
  261. func GetRepositoryCount(user *User) (int64, error) {
  262. return orm.Count(&Repository{OwnerId: user.Id})
  263. }
  264. func StarReposiory(user *User, repoName string) error {
  265. return nil
  266. }
  267. func UnStarRepository() {
  268. }
  269. func WatchRepository() {
  270. }
  271. func UnWatchRepository() {
  272. }
  273. func ForkRepository(reposName string, userId int64) {
  274. }
  275. func RepoPath(userName, repoName string) string {
  276. return filepath.Join(UserPath(userName), repoName+".git")
  277. }
  278. // DeleteRepository deletes a repository for a user or orgnaztion.
  279. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  280. repo := &Repository{Id: repoId, OwnerId: userId}
  281. has, err := orm.Get(repo)
  282. if err != nil {
  283. return err
  284. } else if !has {
  285. return ErrRepoNotExist
  286. }
  287. session := orm.NewSession()
  288. if err = session.Begin(); err != nil {
  289. return err
  290. }
  291. if _, err = session.Delete(&Repository{Id: repoId}); err != nil {
  292. session.Rollback()
  293. return err
  294. }
  295. if _, err := session.Delete(&Access{UserName: userName, RepoName: repo.Name}); err != nil {
  296. session.Rollback()
  297. return err
  298. }
  299. rawSql := "UPDATE user SET num_repos = num_repos - 1 WHERE id = ?"
  300. if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
  301. rawSql = "UPDATE \"user\" SET num_repos = num_repos - 1 WHERE id = ?"
  302. }
  303. if _, err = session.Exec(rawSql, userId); err != nil {
  304. session.Rollback()
  305. return err
  306. }
  307. if err = session.Commit(); err != nil {
  308. session.Rollback()
  309. return err
  310. }
  311. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  312. // TODO: log and delete manully
  313. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  314. return err
  315. }
  316. return nil
  317. }
  318. // Commit represents a git commit.
  319. type Commit struct {
  320. Author string
  321. Email string
  322. Date time.Time
  323. SHA string
  324. Message string
  325. }
  326. var (
  327. ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded")
  328. )
  329. // RepoFile represents a file object in git repository.
  330. type RepoFile struct {
  331. *git.TreeEntry
  332. Path string
  333. Message string
  334. Created time.Time
  335. Size int64
  336. Repo *git.Repository
  337. LastCommit string
  338. }
  339. // LookupBlob returns the content of an object.
  340. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  341. if file.Repo == nil {
  342. return nil, ErrRepoFileNotLoaded
  343. }
  344. return file.Repo.LookupBlob(file.Id)
  345. }
  346. // GetBranches returns all branches of given repository.
  347. func GetBranches(userName, reposName string) ([]string, error) {
  348. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  349. if err != nil {
  350. return nil, err
  351. }
  352. refs, err := repo.AllReferences()
  353. if err != nil {
  354. return nil, err
  355. }
  356. brs := make([]string, len(refs))
  357. for i, ref := range refs {
  358. brs[i] = ref.Name
  359. }
  360. return brs, nil
  361. }
  362. // GetReposFiles returns a list of file object in given directory of repository.
  363. func GetReposFiles(userName, reposName, branchName, rpath string) ([]*RepoFile, error) {
  364. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  365. if err != nil {
  366. return nil, err
  367. }
  368. ref, err := repo.LookupReference("refs/heads/" + branchName)
  369. if err != nil {
  370. return nil, err
  371. }
  372. lastCommit, err := repo.LookupCommit(ref.Oid)
  373. if err != nil {
  374. return nil, err
  375. }
  376. var repodirs []*RepoFile
  377. var repofiles []*RepoFile
  378. lastCommit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  379. if dirname == rpath {
  380. size, err := repo.ObjectSize(entry.Id)
  381. if err != nil {
  382. return 0
  383. }
  384. var cm = lastCommit
  385. for {
  386. if cm.ParentCount() == 0 {
  387. break
  388. } else if cm.ParentCount() == 1 {
  389. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  390. if pt == nil {
  391. break
  392. }
  393. pEntry := pt.EntryByName(entry.Name)
  394. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  395. break
  396. } else {
  397. cm = cm.Parent(0)
  398. }
  399. } else {
  400. var emptyCnt = 0
  401. var sameIdcnt = 0
  402. for i := 0; i < cm.ParentCount(); i++ {
  403. p := cm.Parent(i)
  404. pt, _ := repo.SubTree(p.Tree, dirname)
  405. var pEntry *git.TreeEntry
  406. if pt != nil {
  407. pEntry = pt.EntryByName(entry.Name)
  408. }
  409. if pEntry == nil {
  410. if emptyCnt == cm.ParentCount()-1 {
  411. goto loop
  412. } else {
  413. emptyCnt = emptyCnt + 1
  414. continue
  415. }
  416. } else {
  417. if !pEntry.Id.Equal(entry.Id) {
  418. goto loop
  419. } else {
  420. if sameIdcnt == cm.ParentCount()-1 {
  421. // TODO: now follow the first parent commit?
  422. cm = cm.Parent(0)
  423. break
  424. }
  425. sameIdcnt = sameIdcnt + 1
  426. }
  427. }
  428. }
  429. }
  430. }
  431. loop:
  432. rp := &RepoFile{
  433. entry,
  434. path.Join(dirname, entry.Name),
  435. cm.Message(),
  436. cm.Committer.When,
  437. size,
  438. repo,
  439. cm.Id().String(),
  440. }
  441. if entry.IsFile() {
  442. repofiles = append(repofiles, rp)
  443. } else if entry.IsDir() {
  444. repodirs = append(repodirs, rp)
  445. }
  446. }
  447. return 0
  448. })
  449. return append(repodirs, repofiles...), nil
  450. }
  451. // GetLastestCommit returns the latest commit of given repository.
  452. func GetLastestCommit(userName, repoName string) (*Commit, error) {
  453. stdout, _, err := com.ExecCmd("git", "--git-dir="+RepoPath(userName, repoName), "log", "-1")
  454. if err != nil {
  455. return nil, err
  456. }
  457. commit := new(Commit)
  458. for _, line := range strings.Split(stdout, "\n") {
  459. if len(line) == 0 {
  460. continue
  461. }
  462. switch {
  463. case line[0] == 'c':
  464. commit.SHA = line[7:]
  465. case line[0] == 'A':
  466. infos := strings.SplitN(line, " ", 3)
  467. commit.Author = infos[1]
  468. commit.Email = infos[2][1 : len(infos[2])-1]
  469. case line[0] == 'D':
  470. commit.Date, err = time.Parse("Mon Jan 02 15:04:05 2006 -0700", line[8:])
  471. if err != nil {
  472. return nil, err
  473. }
  474. case line[:4] == " ":
  475. commit.Message = line[4:]
  476. }
  477. }
  478. return commit, nil
  479. }
  480. // GetCommits returns all commits of given branch of repository.
  481. func GetCommits(userName, reposName, branchname string) ([]*git.Commit, error) {
  482. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  483. if err != nil {
  484. return nil, err
  485. }
  486. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  487. if err != nil {
  488. return nil, err
  489. }
  490. return r.AllCommits()
  491. }