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.

642 lines
17 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. sess := orm.NewSession()
  125. defer sess.Close()
  126. sess.Begin()
  127. if _, err = sess.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. sess.Rollback()
  134. return nil, err
  135. }
  136. access := Access{
  137. UserName: user.LowerName,
  138. RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
  139. Mode: AU_WRITABLE,
  140. }
  141. if _, err = sess.Insert(&access); err != nil {
  142. sess.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 = sess.Exec(rawSql, user.Id); err != nil {
  152. sess.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 = sess.Commit(); err != nil {
  161. sess.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. c := exec.Command("git", "update-server-info")
  170. c.Dir = repoPath
  171. if err = c.Run(); err != nil {
  172. log.Error("repo.CreateRepository(exec update-server-info): %v", err)
  173. }
  174. if err = NewRepoAction(user, repo); err != nil {
  175. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  176. }
  177. if err = WatchRepo(user.Id, repo.Id, true); err != nil {
  178. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  179. }
  180. if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
  181. return nil, 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. // for update use
  291. os.Setenv("userName", user.Name)
  292. os.Setenv("userId", base.ToStr(user.Id))
  293. os.Setenv("repoName", repo.Name)
  294. // Apply changes and commit.
  295. return initRepoCommit(tmpDir, user.NewGitSig())
  296. }
  297. // UserRepo reporesents a repository with user name.
  298. type UserRepo struct {
  299. *Repository
  300. UserName string
  301. }
  302. // GetRepos returns given number of repository objects with offset.
  303. func GetRepos(num, offset int) ([]UserRepo, error) {
  304. repos := make([]Repository, 0, num)
  305. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  306. return nil, err
  307. }
  308. urepos := make([]UserRepo, len(repos))
  309. for i := range repos {
  310. urepos[i].Repository = &repos[i]
  311. u := new(User)
  312. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  313. if err != nil {
  314. return nil, err
  315. } else if !has {
  316. return nil, ErrUserNotExist
  317. }
  318. urepos[i].UserName = u.Name
  319. }
  320. return urepos, nil
  321. }
  322. func RepoPath(userName, repoName string) string {
  323. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  324. }
  325. // TransferOwnership transfers all corresponding setting from old user to new one.
  326. func TransferOwnership(user *User, newOwner string, repo *Repository) (err error) {
  327. newUser, err := GetUserByName(newOwner)
  328. if err != nil {
  329. return err
  330. }
  331. // Update accesses.
  332. accesses := make([]Access, 0, 10)
  333. if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil {
  334. return err
  335. }
  336. sess := orm.NewSession()
  337. defer sess.Close()
  338. if err = sess.Begin(); err != nil {
  339. return err
  340. }
  341. for i := range accesses {
  342. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  343. if accesses[i].UserName == user.LowerName {
  344. accesses[i].UserName = newUser.LowerName
  345. }
  346. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  347. return err
  348. }
  349. }
  350. // Update repository.
  351. repo.OwnerId = newUser.Id
  352. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  353. sess.Rollback()
  354. return err
  355. }
  356. // Update user repository number.
  357. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  358. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  359. sess.Rollback()
  360. return err
  361. }
  362. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  363. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  364. sess.Rollback()
  365. return err
  366. }
  367. // Add watch of new owner to repository.
  368. if !IsWatching(newUser.Id, repo.Id) {
  369. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  370. sess.Rollback()
  371. return err
  372. }
  373. }
  374. if err = TransferRepoAction(user, newUser, repo); err != nil {
  375. sess.Rollback()
  376. return err
  377. }
  378. // Change repository directory name.
  379. if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  380. sess.Rollback()
  381. return err
  382. }
  383. return sess.Commit()
  384. }
  385. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  386. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  387. // Update accesses.
  388. accesses := make([]Access, 0, 10)
  389. if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  390. return err
  391. }
  392. sess := orm.NewSession()
  393. defer sess.Close()
  394. if err = sess.Begin(); err != nil {
  395. return err
  396. }
  397. for i := range accesses {
  398. accesses[i].RepoName = userName + "/" + newRepoName
  399. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  400. return err
  401. }
  402. }
  403. // Change repository directory name.
  404. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  405. sess.Rollback()
  406. return err
  407. }
  408. return sess.Commit()
  409. }
  410. func UpdateRepository(repo *Repository) error {
  411. repo.LowerName = strings.ToLower(repo.Name)
  412. if len(repo.Description) > 255 {
  413. repo.Description = repo.Description[:255]
  414. }
  415. if len(repo.Website) > 255 {
  416. repo.Website = repo.Website[:255]
  417. }
  418. _, err := orm.Id(repo.Id).AllCols().Update(repo)
  419. return err
  420. }
  421. // DeleteRepository deletes a repository for a user or orgnaztion.
  422. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  423. repo := &Repository{Id: repoId, OwnerId: userId}
  424. has, err := orm.Get(repo)
  425. if err != nil {
  426. return err
  427. } else if !has {
  428. return ErrRepoNotExist
  429. }
  430. sess := orm.NewSession()
  431. defer sess.Close()
  432. if err = sess.Begin(); err != nil {
  433. return err
  434. }
  435. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  436. sess.Rollback()
  437. return err
  438. }
  439. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  440. sess.Rollback()
  441. return err
  442. }
  443. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  444. if _, err = sess.Exec(rawSql, userId); err != nil {
  445. sess.Rollback()
  446. return err
  447. }
  448. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  449. sess.Rollback()
  450. return err
  451. }
  452. if err = sess.Commit(); err != nil {
  453. sess.Rollback()
  454. return err
  455. }
  456. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  457. // TODO: log and delete manully
  458. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  459. return err
  460. }
  461. return nil
  462. }
  463. // GetRepositoryByName returns the repository by given name under user if exists.
  464. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  465. repo := &Repository{
  466. OwnerId: userId,
  467. LowerName: strings.ToLower(repoName),
  468. }
  469. has, err := orm.Get(repo)
  470. if err != nil {
  471. return nil, err
  472. } else if !has {
  473. return nil, ErrRepoNotExist
  474. }
  475. return repo, err
  476. }
  477. // GetRepositoryById returns the repository by given id if exists.
  478. func GetRepositoryById(id int64) (*Repository, error) {
  479. repo := &Repository{}
  480. has, err := orm.Id(id).Get(repo)
  481. if err != nil {
  482. return nil, err
  483. } else if !has {
  484. return nil, ErrRepoNotExist
  485. }
  486. return repo, err
  487. }
  488. // GetRepositories returns the list of repositories of given user.
  489. func GetRepositories(user *User) ([]Repository, error) {
  490. repos := make([]Repository, 0, 10)
  491. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  492. return repos, err
  493. }
  494. func GetRepositoryCount(user *User) (int64, error) {
  495. return orm.Count(&Repository{OwnerId: user.Id})
  496. }
  497. // Watch is connection request for receiving repository notifycation.
  498. type Watch struct {
  499. Id int64
  500. RepoId int64 `xorm:"UNIQUE(watch)"`
  501. UserId int64 `xorm:"UNIQUE(watch)"`
  502. }
  503. // Watch or unwatch repository.
  504. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  505. if watch {
  506. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  507. return err
  508. }
  509. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  510. _, err = orm.Exec(rawSql, repoId)
  511. } else {
  512. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  513. return err
  514. }
  515. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  516. _, err = orm.Exec(rawSql, repoId)
  517. }
  518. return err
  519. }
  520. // GetWatches returns all watches of given repository.
  521. func GetWatches(repoId int64) ([]Watch, error) {
  522. watches := make([]Watch, 0, 10)
  523. err := orm.Find(&watches, &Watch{RepoId: repoId})
  524. return watches, err
  525. }
  526. // NotifyWatchers creates batch of actions for every watcher.
  527. func NotifyWatchers(act *Action) error {
  528. // Add feeds for user self and all watchers.
  529. watches, err := GetWatches(act.RepoId)
  530. if err != nil {
  531. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  532. }
  533. // Add feed for actioner.
  534. act.UserId = act.ActUserId
  535. if _, err = orm.InsertOne(act); err != nil {
  536. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  537. }
  538. for i := range watches {
  539. if act.ActUserId == watches[i].UserId {
  540. continue
  541. }
  542. act.Id = 0
  543. act.UserId = watches[i].UserId
  544. if _, err = orm.InsertOne(act); err != nil {
  545. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  546. }
  547. }
  548. return nil
  549. }
  550. // IsWatching checks if user has watched given repository.
  551. func IsWatching(userId, repoId int64) bool {
  552. has, _ := orm.Get(&Watch{0, repoId, userId})
  553. return has
  554. }
  555. func ForkRepository(reposName string, userId int64) {
  556. }