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 16 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "strings"
  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. var (
  23. ErrRepoAlreadyExist = errors.New("Repository already exist")
  24. ErrRepoNotExist = errors.New("Repository does not exist")
  25. ErrRepoFileNotExist = errors.New("Target Repo file does not exist")
  26. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  27. ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded")
  28. )
  29. var (
  30. LanguageIgns, Licenses []string
  31. )
  32. func LoadRepoConfig() {
  33. LanguageIgns = strings.Split(base.Cfg.MustValue("repository", "LANG_IGNS"), "|")
  34. Licenses = strings.Split(base.Cfg.MustValue("repository", "LICENSES"), "|")
  35. }
  36. func NewRepoContext() {
  37. zip.Verbose = false
  38. // Check if server has basic git setting.
  39. stdout, _, err := com.ExecCmd("git", "config", "--get", "user.name")
  40. if err != nil {
  41. fmt.Printf("repo.init(fail to get git user.name): %v", err)
  42. os.Exit(2)
  43. } else if len(stdout) == 0 {
  44. if _, _, err = com.ExecCmd("git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil {
  45. fmt.Printf("repo.init(fail to set git user.email): %v", err)
  46. os.Exit(2)
  47. } else if _, _, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
  48. fmt.Printf("repo.init(fail to set git user.name): %v", err)
  49. os.Exit(2)
  50. }
  51. }
  52. }
  53. // Repository represents a git repository.
  54. type Repository struct {
  55. Id int64
  56. OwnerId int64 `xorm:"unique(s)"`
  57. ForkId int64
  58. LowerName string `xorm:"unique(s) index not null"`
  59. Name string `xorm:"index not null"`
  60. Description string
  61. Website string
  62. NumWatches int
  63. NumStars int
  64. NumForks int
  65. NumIssues int
  66. NumReleases int `xorm:"NOT NULL"`
  67. NumClosedIssues int
  68. NumOpenIssues int `xorm:"-"`
  69. IsPrivate bool
  70. IsBare bool
  71. Created time.Time `xorm:"created"`
  72. Updated time.Time `xorm:"updated"`
  73. }
  74. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  75. func IsRepositoryExist(user *User, repoName string) (bool, error) {
  76. repo := Repository{OwnerId: user.Id}
  77. has, err := orm.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  78. if err != nil {
  79. return has, err
  80. } else if !has {
  81. return false, nil
  82. }
  83. return com.IsDir(RepoPath(user.Name, repoName)), nil
  84. }
  85. var (
  86. illegalEquals = []string{"raw", "install", "api", "avatar", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"}
  87. illegalSuffixs = []string{".git"}
  88. )
  89. // IsLegalName returns false if name contains illegal characters.
  90. func IsLegalName(repoName string) bool {
  91. repoName = strings.ToLower(repoName)
  92. for _, char := range illegalEquals {
  93. if repoName == char {
  94. return false
  95. }
  96. }
  97. for _, char := range illegalSuffixs {
  98. if strings.HasSuffix(repoName, char) {
  99. return false
  100. }
  101. }
  102. return true
  103. }
  104. // CreateRepository creates a repository for given user or orgnaziation.
  105. func CreateRepository(user *User, repoName, desc, repoLang, license string, private bool, initReadme bool) (*Repository, error) {
  106. if !IsLegalName(repoName) {
  107. return nil, ErrRepoNameIllegal
  108. }
  109. isExist, err := IsRepositoryExist(user, repoName)
  110. if err != nil {
  111. return nil, err
  112. } else if isExist {
  113. return nil, ErrRepoAlreadyExist
  114. }
  115. repo := &Repository{
  116. OwnerId: user.Id,
  117. Name: repoName,
  118. LowerName: strings.ToLower(repoName),
  119. Description: desc,
  120. IsPrivate: private,
  121. IsBare: repoLang == "" && license == "" && !initReadme,
  122. }
  123. repoPath := RepoPath(user.Name, repoName)
  124. if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
  125. return nil, err
  126. }
  127. sess := orm.NewSession()
  128. defer sess.Close()
  129. sess.Begin()
  130. if _, err = sess.Insert(repo); err != nil {
  131. if err2 := os.RemoveAll(repoPath); err2 != nil {
  132. log.Error("repo.CreateRepository(repo): %v", err)
  133. return nil, errors.New(fmt.Sprintf(
  134. "delete repo directory %s/%s failed(1): %v", user.Name, repoName, err2))
  135. }
  136. sess.Rollback()
  137. return nil, err
  138. }
  139. access := Access{
  140. UserName: user.LowerName,
  141. RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
  142. Mode: AU_WRITABLE,
  143. }
  144. if _, err = sess.Insert(&access); err != nil {
  145. sess.Rollback()
  146. if err2 := os.RemoveAll(repoPath); err2 != nil {
  147. log.Error("repo.CreateRepository(access): %v", err)
  148. return nil, errors.New(fmt.Sprintf(
  149. "delete repo directory %s/%s failed(2): %v", user.Name, repoName, err2))
  150. }
  151. return nil, err
  152. }
  153. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  154. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  155. sess.Rollback()
  156. if err2 := os.RemoveAll(repoPath); err2 != nil {
  157. log.Error("repo.CreateRepository(repo count): %v", err)
  158. return nil, errors.New(fmt.Sprintf(
  159. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  160. }
  161. return nil, err
  162. }
  163. if err = sess.Commit(); err != nil {
  164. sess.Rollback()
  165. if err2 := os.RemoveAll(repoPath); err2 != nil {
  166. log.Error("repo.CreateRepository(commit): %v", err)
  167. return nil, errors.New(fmt.Sprintf(
  168. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  169. }
  170. return nil, err
  171. }
  172. c := exec.Command("git", "update-server-info")
  173. c.Dir = repoPath
  174. if err = c.Run(); err != nil {
  175. log.Error("repo.CreateRepository(exec update-server-info): %v", err)
  176. }
  177. if err = NewRepoAction(user, repo); err != nil {
  178. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  179. }
  180. if err = WatchRepo(user.Id, repo.Id, true); err != nil {
  181. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  182. }
  183. return repo, nil
  184. }
  185. // extractGitBareZip extracts git-bare.zip to repository path.
  186. func extractGitBareZip(repoPath string) error {
  187. z, err := zip.Open("conf/content/git-bare.zip")
  188. if err != nil {
  189. fmt.Println("shi?")
  190. return err
  191. }
  192. defer z.Close()
  193. return z.ExtractTo(repoPath)
  194. }
  195. // initRepoCommit temporarily changes with work directory.
  196. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  197. var stderr string
  198. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "add", "--all"); err != nil {
  199. return err
  200. }
  201. if len(stderr) > 0 {
  202. log.Trace("stderr(1): %s", stderr)
  203. }
  204. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  205. "-m", "Init commit"); err != nil {
  206. return err
  207. }
  208. if len(stderr) > 0 {
  209. log.Trace("stderr(2): %s", stderr)
  210. }
  211. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "push", "origin", "master"); err != nil {
  212. return err
  213. }
  214. if len(stderr) > 0 {
  215. log.Trace("stderr(3): %s", stderr)
  216. }
  217. return nil
  218. }
  219. func createHookUpdate(hookPath, content string) error {
  220. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  221. if err != nil {
  222. return err
  223. }
  224. defer pu.Close()
  225. _, err = pu.WriteString(content)
  226. return err
  227. }
  228. // InitRepository initializes README and .gitignore if needed.
  229. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  230. repoPath := RepoPath(user.Name, repo.Name)
  231. // Create bare new repository.
  232. if err := extractGitBareZip(repoPath); err != nil {
  233. return err
  234. }
  235. // hook/post-update
  236. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  237. fmt.Sprintf("#!/usr/bin/env bash\n%s update $1 $2 $3\n",
  238. strings.Replace(appPath, "\\", "/", -1))); err != nil {
  239. return err
  240. }
  241. // Initialize repository according to user's choice.
  242. fileName := map[string]string{}
  243. if initReadme {
  244. fileName["readme"] = "README.md"
  245. }
  246. if repoLang != "" {
  247. fileName["gitign"] = ".gitignore"
  248. }
  249. if license != "" {
  250. fileName["license"] = "LICENSE"
  251. }
  252. // Clone to temprory path and do the init commit.
  253. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  254. os.MkdirAll(tmpDir, os.ModePerm)
  255. if _, _, err := com.ExecCmd("git", "clone", repoPath, tmpDir); err != nil {
  256. return err
  257. }
  258. // README
  259. if initReadme {
  260. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  261. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  262. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  263. []byte(defaultReadme), 0644); err != nil {
  264. return err
  265. }
  266. }
  267. // .gitignore
  268. if repoLang != "" {
  269. filePath := "conf/gitignore/" + repoLang
  270. if com.IsFile(filePath) {
  271. if _, err := com.Copy(filePath,
  272. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  273. return err
  274. }
  275. }
  276. }
  277. // LICENSE
  278. if license != "" {
  279. filePath := "conf/license/" + license
  280. if com.IsFile(filePath) {
  281. if _, err := com.Copy(filePath,
  282. filepath.Join(tmpDir, fileName["license"])); err != nil {
  283. return err
  284. }
  285. }
  286. }
  287. if len(fileName) == 0 {
  288. return nil
  289. }
  290. // Apply changes and commit.
  291. return initRepoCommit(tmpDir, user.NewGitSig())
  292. }
  293. // UserRepo reporesents a repository with user name.
  294. type UserRepo struct {
  295. *Repository
  296. UserName string
  297. }
  298. // GetRepos returns given number of repository objects with offset.
  299. func GetRepos(num, offset int) ([]UserRepo, error) {
  300. repos := make([]Repository, 0, num)
  301. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  302. return nil, err
  303. }
  304. urepos := make([]UserRepo, len(repos))
  305. for i := range repos {
  306. urepos[i].Repository = &repos[i]
  307. u := new(User)
  308. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  309. if err != nil {
  310. return nil, err
  311. } else if !has {
  312. return nil, ErrUserNotExist
  313. }
  314. urepos[i].UserName = u.Name
  315. }
  316. return urepos, nil
  317. }
  318. func RepoPath(userName, repoName string) string {
  319. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  320. }
  321. // TransferOwnership transfers all corresponding setting from old user to new one.
  322. func TransferOwnership(user *User, newOwner string, repo *Repository) (err error) {
  323. newUser, err := GetUserByName(newOwner)
  324. if err != nil {
  325. return err
  326. }
  327. // Update accesses.
  328. accesses := make([]Access, 0, 10)
  329. if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil {
  330. return err
  331. }
  332. for i := range accesses {
  333. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  334. if accesses[i].UserName == user.LowerName {
  335. accesses[i].UserName = newUser.LowerName
  336. }
  337. if err = UpdateAccess(&accesses[i]); err != nil {
  338. return err
  339. }
  340. }
  341. // Update repository.
  342. repo.OwnerId = newUser.Id
  343. if _, err := orm.Id(repo.Id).Update(repo); err != nil {
  344. return err
  345. }
  346. // Update user repository number.
  347. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  348. if _, err = orm.Exec(rawSql, newUser.Id); err != nil {
  349. return err
  350. }
  351. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  352. if _, err = orm.Exec(rawSql, user.Id); err != nil {
  353. return err
  354. }
  355. // Add watch of new owner to repository.
  356. if !IsWatching(newUser.Id, repo.Id) {
  357. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  358. return err
  359. }
  360. }
  361. if err = TransferRepoAction(user, newUser, repo); err != nil {
  362. return err
  363. }
  364. // Change repository directory name.
  365. return os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name))
  366. }
  367. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  368. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  369. // Update accesses.
  370. accesses := make([]Access, 0, 10)
  371. if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  372. return err
  373. }
  374. for i := range accesses {
  375. accesses[i].RepoName = userName + "/" + newRepoName
  376. if err = UpdateAccess(&accesses[i]); err != nil {
  377. return err
  378. }
  379. }
  380. // Change repository directory name.
  381. return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName))
  382. }
  383. func UpdateRepository(repo *Repository) error {
  384. repo.LowerName = strings.ToLower(repo.Name)
  385. if len(repo.Description) > 255 {
  386. repo.Description = repo.Description[:255]
  387. }
  388. if len(repo.Website) > 255 {
  389. repo.Website = repo.Website[:255]
  390. }
  391. _, err := orm.Id(repo.Id).AllCols().Update(repo)
  392. return err
  393. }
  394. // DeleteRepository deletes a repository for a user or orgnaztion.
  395. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  396. repo := &Repository{Id: repoId, OwnerId: userId}
  397. has, err := orm.Get(repo)
  398. if err != nil {
  399. return err
  400. } else if !has {
  401. return ErrRepoNotExist
  402. }
  403. sess := orm.NewSession()
  404. defer sess.Close()
  405. if err = sess.Begin(); err != nil {
  406. return err
  407. }
  408. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  409. sess.Rollback()
  410. return err
  411. }
  412. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  413. sess.Rollback()
  414. return err
  415. }
  416. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  417. if _, err = sess.Exec(rawSql, userId); err != nil {
  418. sess.Rollback()
  419. return err
  420. }
  421. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  422. sess.Rollback()
  423. return err
  424. }
  425. if err = sess.Commit(); err != nil {
  426. sess.Rollback()
  427. return err
  428. }
  429. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  430. // TODO: log and delete manully
  431. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  432. return err
  433. }
  434. return nil
  435. }
  436. // GetRepositoryByName returns the repository by given name under user if exists.
  437. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  438. repo := &Repository{
  439. OwnerId: userId,
  440. LowerName: strings.ToLower(repoName),
  441. }
  442. has, err := orm.Get(repo)
  443. if err != nil {
  444. return nil, err
  445. } else if !has {
  446. return nil, ErrRepoNotExist
  447. }
  448. return repo, err
  449. }
  450. // GetRepositoryById returns the repository by given id if exists.
  451. func GetRepositoryById(id int64) (*Repository, error) {
  452. repo := &Repository{}
  453. has, err := orm.Id(id).Get(repo)
  454. if err != nil {
  455. return nil, err
  456. } else if !has {
  457. return nil, ErrRepoNotExist
  458. }
  459. return repo, err
  460. }
  461. // GetRepositories returns the list of repositories of given user.
  462. func GetRepositories(user *User) ([]Repository, error) {
  463. repos := make([]Repository, 0, 10)
  464. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  465. return repos, err
  466. }
  467. func GetRepositoryCount(user *User) (int64, error) {
  468. return orm.Count(&Repository{OwnerId: user.Id})
  469. }
  470. // Watch is connection request for receiving repository notifycation.
  471. type Watch struct {
  472. Id int64
  473. RepoId int64 `xorm:"UNIQUE(watch)"`
  474. UserId int64 `xorm:"UNIQUE(watch)"`
  475. }
  476. // Watch or unwatch repository.
  477. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  478. if watch {
  479. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  480. return err
  481. }
  482. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  483. _, err = orm.Exec(rawSql, repoId)
  484. } else {
  485. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  486. return err
  487. }
  488. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  489. _, err = orm.Exec(rawSql, repoId)
  490. }
  491. return err
  492. }
  493. // GetWatches returns all watches of given repository.
  494. func GetWatches(repoId int64) ([]Watch, error) {
  495. watches := make([]Watch, 0, 10)
  496. err := orm.Find(&watches, &Watch{RepoId: repoId})
  497. return watches, err
  498. }
  499. // NotifyWatchers creates batch of actions for every watcher.
  500. func NotifyWatchers(act *Action) error {
  501. // Add feeds for user self and all watchers.
  502. watches, err := GetWatches(act.RepoId)
  503. if err != nil {
  504. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  505. }
  506. // Add feed for actioner.
  507. act.UserId = act.ActUserId
  508. if _, err = orm.InsertOne(act); err != nil {
  509. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  510. }
  511. for i := range watches {
  512. if act.ActUserId == watches[i].UserId {
  513. continue
  514. }
  515. act.Id = 0
  516. act.UserId = watches[i].UserId
  517. if _, err = orm.InsertOne(act); err != nil {
  518. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  519. }
  520. }
  521. return nil
  522. }
  523. // IsWatching checks if user has watched given repository.
  524. func IsWatching(userId, repoId int64) bool {
  525. has, _ := orm.Get(&Watch{0, repoId, userId})
  526. return has
  527. }
  528. func ForkRepository(reposName string, userId int64) {
  529. }