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