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 15KB

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