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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. sess := orm.NewSession()
  333. defer sess.Close()
  334. if err = sess.Begin(); err != nil {
  335. return err
  336. }
  337. for i := range accesses {
  338. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  339. if accesses[i].UserName == user.LowerName {
  340. accesses[i].UserName = newUser.LowerName
  341. }
  342. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  343. return err
  344. }
  345. }
  346. // Update repository.
  347. repo.OwnerId = newUser.Id
  348. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  349. sess.Rollback()
  350. return err
  351. }
  352. // Update user repository number.
  353. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  354. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  355. sess.Rollback()
  356. return err
  357. }
  358. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  359. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  360. sess.Rollback()
  361. return err
  362. }
  363. // Add watch of new owner to repository.
  364. if !IsWatching(newUser.Id, repo.Id) {
  365. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  366. sess.Rollback()
  367. return err
  368. }
  369. }
  370. if err = TransferRepoAction(user, newUser, repo); err != nil {
  371. sess.Rollback()
  372. return err
  373. }
  374. // Change repository directory name.
  375. if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  376. sess.Rollback()
  377. return err
  378. }
  379. return sess.Commit()
  380. }
  381. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  382. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  383. // Update accesses.
  384. accesses := make([]Access, 0, 10)
  385. if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  386. return err
  387. }
  388. sess := orm.NewSession()
  389. defer sess.Close()
  390. if err = sess.Begin(); err != nil {
  391. return err
  392. }
  393. for i := range accesses {
  394. accesses[i].RepoName = userName + "/" + newRepoName
  395. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  396. return err
  397. }
  398. }
  399. // Change repository directory name.
  400. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  401. sess.Rollback()
  402. return err
  403. }
  404. return sess.Commit()
  405. }
  406. func UpdateRepository(repo *Repository) error {
  407. repo.LowerName = strings.ToLower(repo.Name)
  408. if len(repo.Description) > 255 {
  409. repo.Description = repo.Description[:255]
  410. }
  411. if len(repo.Website) > 255 {
  412. repo.Website = repo.Website[:255]
  413. }
  414. _, err := orm.Id(repo.Id).AllCols().Update(repo)
  415. return err
  416. }
  417. // DeleteRepository deletes a repository for a user or orgnaztion.
  418. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  419. repo := &Repository{Id: repoId, OwnerId: userId}
  420. has, err := orm.Get(repo)
  421. if err != nil {
  422. return err
  423. } else if !has {
  424. return ErrRepoNotExist
  425. }
  426. sess := orm.NewSession()
  427. defer sess.Close()
  428. if err = sess.Begin(); err != nil {
  429. return err
  430. }
  431. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  432. sess.Rollback()
  433. return err
  434. }
  435. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  436. sess.Rollback()
  437. return err
  438. }
  439. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  440. if _, err = sess.Exec(rawSql, userId); err != nil {
  441. sess.Rollback()
  442. return err
  443. }
  444. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  445. sess.Rollback()
  446. return err
  447. }
  448. if err = sess.Commit(); err != nil {
  449. sess.Rollback()
  450. return err
  451. }
  452. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  453. // TODO: log and delete manully
  454. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  455. return err
  456. }
  457. return nil
  458. }
  459. // GetRepositoryByName returns the repository by given name under user if exists.
  460. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  461. repo := &Repository{
  462. OwnerId: userId,
  463. LowerName: strings.ToLower(repoName),
  464. }
  465. has, err := orm.Get(repo)
  466. if err != nil {
  467. return nil, err
  468. } else if !has {
  469. return nil, ErrRepoNotExist
  470. }
  471. return repo, err
  472. }
  473. // GetRepositoryById returns the repository by given id if exists.
  474. func GetRepositoryById(id int64) (*Repository, error) {
  475. repo := &Repository{}
  476. has, err := orm.Id(id).Get(repo)
  477. if err != nil {
  478. return nil, err
  479. } else if !has {
  480. return nil, ErrRepoNotExist
  481. }
  482. return repo, err
  483. }
  484. // GetRepositories returns the list of repositories of given user.
  485. func GetRepositories(user *User) ([]Repository, error) {
  486. repos := make([]Repository, 0, 10)
  487. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  488. return repos, err
  489. }
  490. func GetRepositoryCount(user *User) (int64, error) {
  491. return orm.Count(&Repository{OwnerId: user.Id})
  492. }
  493. // Watch is connection request for receiving repository notifycation.
  494. type Watch struct {
  495. Id int64
  496. RepoId int64 `xorm:"UNIQUE(watch)"`
  497. UserId int64 `xorm:"UNIQUE(watch)"`
  498. }
  499. // Watch or unwatch repository.
  500. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  501. if watch {
  502. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  503. return err
  504. }
  505. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  506. _, err = orm.Exec(rawSql, repoId)
  507. } else {
  508. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  509. return err
  510. }
  511. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  512. _, err = orm.Exec(rawSql, repoId)
  513. }
  514. return err
  515. }
  516. // GetWatches returns all watches of given repository.
  517. func GetWatches(repoId int64) ([]Watch, error) {
  518. watches := make([]Watch, 0, 10)
  519. err := orm.Find(&watches, &Watch{RepoId: repoId})
  520. return watches, err
  521. }
  522. // NotifyWatchers creates batch of actions for every watcher.
  523. func NotifyWatchers(act *Action) error {
  524. // Add feeds for user self and all watchers.
  525. watches, err := GetWatches(act.RepoId)
  526. if err != nil {
  527. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  528. }
  529. // Add feed for actioner.
  530. act.UserId = act.ActUserId
  531. if _, err = orm.InsertOne(act); err != nil {
  532. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  533. }
  534. for i := range watches {
  535. if act.ActUserId == watches[i].UserId {
  536. continue
  537. }
  538. act.Id = 0
  539. act.UserId = watches[i].UserId
  540. if _, err = orm.InsertOne(act); err != nil {
  541. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  542. }
  543. }
  544. return nil
  545. }
  546. // IsWatching checks if user has watched given repository.
  547. func IsWatching(userId, repoId int64) bool {
  548. has, _ := orm.Get(&Watch{0, repoId, userId})
  549. return has
  550. }
  551. func ForkRepository(reposName string, userId int64) {
  552. }