repo.go 15 KB

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