repo.go 17 KB

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