repo.go 15 KB

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