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

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