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.

784 lines
21 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
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 = errors.New("repo file not loaded")
  28. ErrMirrorNotExist = errors.New("Mirror does not exist")
  29. )
  30. var (
  31. LanguageIgns, Licenses []string
  32. )
  33. func LoadRepoConfig() {
  34. LanguageIgns = strings.Split(base.Cfg.MustValue("repository", "LANG_IGNS"), "|")
  35. Licenses = strings.Split(base.Cfg.MustValue("repository", "LICENSES"), "|")
  36. }
  37. func NewRepoContext() {
  38. zip.Verbose = false
  39. // Check if server has basic git setting.
  40. stdout, stderr, err := com.ExecCmd("git", "config", "--get", "user.name")
  41. if strings.Contains(stderr, "fatal:") {
  42. fmt.Printf("repo.NewRepoContext(fail to get git user.name): %s", stderr)
  43. os.Exit(2)
  44. } else if err != nil || len(strings.TrimSpace(stdout)) == 0 {
  45. if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil {
  46. fmt.Printf("repo.NewRepoContext(fail to set git user.email): %s", stderr)
  47. os.Exit(2)
  48. } else if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
  49. fmt.Printf("repo.NewRepoContext(fail to set git user.name): %s", stderr)
  50. os.Exit(2)
  51. }
  52. }
  53. }
  54. // Repository represents a git repository.
  55. type Repository struct {
  56. Id int64
  57. OwnerId int64 `xorm:"unique(s)"`
  58. Owner *User `xorm:"-"`
  59. ForkId int64
  60. LowerName string `xorm:"unique(s) index not null"`
  61. Name string `xorm:"index not null"`
  62. Description string
  63. Website string
  64. NumWatches int
  65. NumStars int
  66. NumForks int
  67. NumIssues int
  68. NumClosedIssues int
  69. NumOpenIssues int `xorm:"-"`
  70. NumTags int `xorm:"-"`
  71. IsPrivate bool
  72. IsMirror bool
  73. IsBare bool
  74. IsGoget bool
  75. DefaultBranch string
  76. Created time.Time `xorm:"created"`
  77. Updated time.Time `xorm:"updated"`
  78. }
  79. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  80. func IsRepositoryExist(user *User, repoName string) (bool, error) {
  81. repo := Repository{OwnerId: user.Id}
  82. has, err := orm.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  83. if err != nil {
  84. return has, err
  85. } else if !has {
  86. return false, nil
  87. }
  88. return com.IsDir(RepoPath(user.Name, repoName)), nil
  89. }
  90. var (
  91. illegalEquals = []string{"raw", "install", "api", "avatar", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"}
  92. illegalSuffixs = []string{".git"}
  93. )
  94. // IsLegalName returns false if name contains illegal characters.
  95. func IsLegalName(repoName string) bool {
  96. repoName = strings.ToLower(repoName)
  97. for _, char := range illegalEquals {
  98. if repoName == char {
  99. return false
  100. }
  101. }
  102. for _, char := range illegalSuffixs {
  103. if strings.HasSuffix(repoName, char) {
  104. return false
  105. }
  106. }
  107. return true
  108. }
  109. // Mirror represents a mirror information of repository.
  110. type Mirror struct {
  111. Id int64
  112. RepoId int64
  113. RepoName string // <user name>/<repo name>
  114. Interval int // Hour.
  115. Updated time.Time `xorm:"UPDATED"`
  116. NextUpdate time.Time
  117. }
  118. func GetMirror(repoId int64) (*Mirror, error) {
  119. m := &Mirror{RepoId: repoId}
  120. has, err := orm.Get(m)
  121. if err != nil {
  122. return nil, err
  123. } else if !has {
  124. return nil, ErrMirrorNotExist
  125. }
  126. return m, nil
  127. }
  128. func UpdateMirror(m *Mirror) error {
  129. _, err := orm.Id(m.Id).Update(m)
  130. return err
  131. }
  132. // MirrorUpdate checks and updates mirror repositories.
  133. func MirrorUpdate() {
  134. if err := orm.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  135. m := bean.(*Mirror)
  136. if m.NextUpdate.After(time.Now()) {
  137. return nil
  138. }
  139. repoPath := filepath.Join(base.RepoRootPath, m.RepoName+".git")
  140. _, stderr, err := com.ExecCmdDir(repoPath, "git", "remote", "update")
  141. if err != nil {
  142. return errors.New("git remote update: " + stderr)
  143. } else if err = git.UnpackRefs(repoPath); err != nil {
  144. return err
  145. }
  146. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  147. return UpdateMirror(m)
  148. }); err != nil {
  149. log.Error("repo.MirrorUpdate: %v", err)
  150. }
  151. }
  152. // MirrorRepository creates a mirror repository from source.
  153. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  154. _, stderr, err := com.ExecCmd("git", "clone", "--mirror", url, repoPath)
  155. if err != nil {
  156. return errors.New("git clone --mirror: " + stderr)
  157. }
  158. if _, err = orm.InsertOne(&Mirror{
  159. RepoId: repoId,
  160. RepoName: strings.ToLower(userName + "/" + repoName),
  161. Interval: 24,
  162. NextUpdate: time.Now().Add(24 * time.Hour),
  163. }); err != nil {
  164. return err
  165. }
  166. return git.UnpackRefs(repoPath)
  167. }
  168. // MigrateRepository migrates a existing repository from other project hosting.
  169. func MigrateRepository(user *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  170. repo, err := CreateRepository(user, name, desc, "", "", private, mirror, false)
  171. if err != nil {
  172. return nil, err
  173. }
  174. // Clone to temprory path and do the init commit.
  175. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  176. os.MkdirAll(tmpDir, os.ModePerm)
  177. repoPath := RepoPath(user.Name, name)
  178. repo.IsBare = false
  179. if mirror {
  180. if err = MirrorRepository(repo.Id, user.Name, repo.Name, repoPath, url); err != nil {
  181. return repo, err
  182. }
  183. repo.IsMirror = true
  184. return repo, UpdateRepository(repo)
  185. }
  186. // Clone from local repository.
  187. _, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir)
  188. if err != nil {
  189. return repo, errors.New("git clone: " + stderr)
  190. }
  191. // Pull data from source.
  192. _, stderr, err = com.ExecCmdDir(tmpDir, "git", "pull", url)
  193. if err != nil {
  194. return repo, errors.New("git pull: " + stderr)
  195. }
  196. // Push data to local repository.
  197. if _, stderr, err = com.ExecCmdDir(tmpDir, "git", "push", "origin", "master"); err != nil {
  198. return repo, errors.New("git push: " + stderr)
  199. }
  200. return repo, UpdateRepository(repo)
  201. }
  202. // CreateRepository creates a repository for given user or orgnaziation.
  203. func CreateRepository(user *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
  204. if !IsLegalName(name) {
  205. return nil, ErrRepoNameIllegal
  206. }
  207. isExist, err := IsRepositoryExist(user, name)
  208. if err != nil {
  209. return nil, err
  210. } else if isExist {
  211. return nil, ErrRepoAlreadyExist
  212. }
  213. repo := &Repository{
  214. OwnerId: user.Id,
  215. Name: name,
  216. LowerName: strings.ToLower(name),
  217. Description: desc,
  218. IsPrivate: private,
  219. IsBare: lang == "" && license == "" && !initReadme,
  220. DefaultBranch: "master",
  221. }
  222. repoPath := RepoPath(user.Name, repo.Name)
  223. sess := orm.NewSession()
  224. defer sess.Close()
  225. sess.Begin()
  226. if _, err = sess.Insert(repo); err != nil {
  227. if err2 := os.RemoveAll(repoPath); err2 != nil {
  228. log.Error("repo.CreateRepository(repo): %v", err)
  229. return nil, errors.New(fmt.Sprintf(
  230. "delete repo directory %s/%s failed(1): %v", user.Name, repo.Name, err2))
  231. }
  232. sess.Rollback()
  233. return nil, err
  234. }
  235. mode := AU_WRITABLE
  236. if mirror {
  237. mode = AU_READABLE
  238. }
  239. access := Access{
  240. UserName: user.LowerName,
  241. RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
  242. Mode: mode,
  243. }
  244. if _, err = sess.Insert(&access); err != nil {
  245. sess.Rollback()
  246. if err2 := os.RemoveAll(repoPath); err2 != nil {
  247. log.Error("repo.CreateRepository(access): %v", err)
  248. return nil, errors.New(fmt.Sprintf(
  249. "delete repo directory %s/%s failed(2): %v", user.Name, repo.Name, err2))
  250. }
  251. return nil, err
  252. }
  253. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  254. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  255. sess.Rollback()
  256. if err2 := os.RemoveAll(repoPath); err2 != nil {
  257. log.Error("repo.CreateRepository(repo count): %v", err)
  258. return nil, errors.New(fmt.Sprintf(
  259. "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2))
  260. }
  261. return nil, err
  262. }
  263. if err = sess.Commit(); err != nil {
  264. sess.Rollback()
  265. if err2 := os.RemoveAll(repoPath); err2 != nil {
  266. log.Error("repo.CreateRepository(commit): %v", err)
  267. return nil, errors.New(fmt.Sprintf(
  268. "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2))
  269. }
  270. return nil, err
  271. }
  272. if err = WatchRepo(user.Id, repo.Id, true); err != nil {
  273. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  274. }
  275. if err = NewRepoAction(user, repo); err != nil {
  276. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  277. }
  278. // No need for init for mirror.
  279. if mirror {
  280. return repo, nil
  281. }
  282. if err = initRepository(repoPath, user, repo, initReadme, lang, license); err != nil {
  283. return nil, err
  284. }
  285. c := exec.Command("git", "update-server-info")
  286. c.Dir = repoPath
  287. if err = c.Run(); err != nil {
  288. log.Error("repo.CreateRepository(exec update-server-info): %v", err)
  289. }
  290. return repo, nil
  291. }
  292. // extractGitBareZip extracts git-bare.zip to repository path.
  293. func extractGitBareZip(repoPath string) error {
  294. z, err := zip.Open("conf/content/git-bare.zip")
  295. if err != nil {
  296. return err
  297. }
  298. defer z.Close()
  299. return z.ExtractTo(repoPath)
  300. }
  301. // initRepoCommit temporarily changes with work directory.
  302. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  303. var stderr string
  304. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "add", "--all"); err != nil {
  305. return errors.New("git add: " + stderr)
  306. }
  307. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  308. "-m", "Init commit"); err != nil {
  309. return errors.New("git commit: " + stderr)
  310. }
  311. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "push", "origin", "master"); err != nil {
  312. return errors.New("git push: " + stderr)
  313. }
  314. return nil
  315. }
  316. func createHookUpdate(hookPath, content string) error {
  317. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  318. if err != nil {
  319. return err
  320. }
  321. defer pu.Close()
  322. _, err = pu.WriteString(content)
  323. return err
  324. }
  325. // SetRepoEnvs sets environment variables for command update.
  326. func SetRepoEnvs(userId int64, userName, repoName string) {
  327. os.Setenv("userId", base.ToStr(userId))
  328. os.Setenv("userName", userName)
  329. os.Setenv("repoName", repoName)
  330. }
  331. // InitRepository initializes README and .gitignore if needed.
  332. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  333. repoPath := RepoPath(user.Name, repo.Name)
  334. // Create bare new repository.
  335. if err := extractGitBareZip(repoPath); err != nil {
  336. return err
  337. }
  338. rp := strings.NewReplacer("\\", "/", " ", "\\ ")
  339. // hook/post-update
  340. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  341. fmt.Sprintf("#!/usr/bin/env %s\n%s update $1 $2 $3\n", base.ScriptType,
  342. rp.Replace(appPath))); err != nil {
  343. return err
  344. }
  345. // Initialize repository according to user's choice.
  346. fileName := map[string]string{}
  347. if initReadme {
  348. fileName["readme"] = "README.md"
  349. }
  350. if repoLang != "" {
  351. fileName["gitign"] = ".gitignore"
  352. }
  353. if license != "" {
  354. fileName["license"] = "LICENSE"
  355. }
  356. // Clone to temprory path and do the init commit.
  357. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  358. os.MkdirAll(tmpDir, os.ModePerm)
  359. _, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir)
  360. if err != nil {
  361. return errors.New("git clone: " + stderr)
  362. }
  363. // README
  364. if initReadme {
  365. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  366. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  367. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  368. []byte(defaultReadme), 0644); err != nil {
  369. return err
  370. }
  371. }
  372. // .gitignore
  373. if repoLang != "" {
  374. filePath := "conf/gitignore/" + repoLang
  375. if com.IsFile(filePath) {
  376. if err := com.Copy(filePath,
  377. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  378. return err
  379. }
  380. }
  381. }
  382. // LICENSE
  383. if license != "" {
  384. filePath := "conf/license/" + license
  385. if com.IsFile(filePath) {
  386. if err := com.Copy(filePath,
  387. filepath.Join(tmpDir, fileName["license"])); err != nil {
  388. return err
  389. }
  390. }
  391. }
  392. if len(fileName) == 0 {
  393. return nil
  394. }
  395. SetRepoEnvs(user.Id, user.Name, repo.Name)
  396. // Apply changes and commit.
  397. return initRepoCommit(tmpDir, user.NewGitSig())
  398. }
  399. // UserRepo reporesents a repository with user name.
  400. type UserRepo struct {
  401. *Repository
  402. UserName string
  403. }
  404. // GetRepos returns given number of repository objects with offset.
  405. func GetRepos(num, offset int) ([]UserRepo, error) {
  406. repos := make([]Repository, 0, num)
  407. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  408. return nil, err
  409. }
  410. urepos := make([]UserRepo, len(repos))
  411. for i := range repos {
  412. urepos[i].Repository = &repos[i]
  413. u := new(User)
  414. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  415. if err != nil {
  416. return nil, err
  417. } else if !has {
  418. return nil, ErrUserNotExist
  419. }
  420. urepos[i].UserName = u.Name
  421. }
  422. return urepos, nil
  423. }
  424. // RepoPath returns repository path by given user and repository name.
  425. func RepoPath(userName, repoName string) string {
  426. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  427. }
  428. // TransferOwnership transfers all corresponding setting from old user to new one.
  429. func TransferOwnership(user *User, newOwner string, repo *Repository) (err error) {
  430. newUser, err := GetUserByName(newOwner)
  431. if err != nil {
  432. return err
  433. }
  434. // Update accesses.
  435. accesses := make([]Access, 0, 10)
  436. if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil {
  437. return err
  438. }
  439. sess := orm.NewSession()
  440. defer sess.Close()
  441. if err = sess.Begin(); err != nil {
  442. return err
  443. }
  444. for i := range accesses {
  445. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  446. if accesses[i].UserName == user.LowerName {
  447. accesses[i].UserName = newUser.LowerName
  448. }
  449. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  450. return err
  451. }
  452. }
  453. // Update repository.
  454. repo.OwnerId = newUser.Id
  455. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  456. sess.Rollback()
  457. return err
  458. }
  459. // Update user repository number.
  460. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  461. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  462. sess.Rollback()
  463. return err
  464. }
  465. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  466. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  467. sess.Rollback()
  468. return err
  469. }
  470. // Add watch of new owner to repository.
  471. if !IsWatching(newUser.Id, repo.Id) {
  472. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  473. sess.Rollback()
  474. return err
  475. }
  476. }
  477. if err = TransferRepoAction(user, newUser, repo); err != nil {
  478. sess.Rollback()
  479. return err
  480. }
  481. // Change repository directory name.
  482. if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  483. sess.Rollback()
  484. return err
  485. }
  486. return sess.Commit()
  487. }
  488. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  489. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  490. // Update accesses.
  491. accesses := make([]Access, 0, 10)
  492. if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  493. return err
  494. }
  495. sess := orm.NewSession()
  496. defer sess.Close()
  497. if err = sess.Begin(); err != nil {
  498. return err
  499. }
  500. for i := range accesses {
  501. accesses[i].RepoName = userName + "/" + newRepoName
  502. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  503. return err
  504. }
  505. }
  506. // Change repository directory name.
  507. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  508. sess.Rollback()
  509. return err
  510. }
  511. return sess.Commit()
  512. }
  513. func UpdateRepository(repo *Repository) error {
  514. repo.LowerName = strings.ToLower(repo.Name)
  515. if len(repo.Description) > 255 {
  516. repo.Description = repo.Description[:255]
  517. }
  518. if len(repo.Website) > 255 {
  519. repo.Website = repo.Website[:255]
  520. }
  521. _, err := orm.Id(repo.Id).AllCols().Update(repo)
  522. return err
  523. }
  524. // DeleteRepository deletes a repository for a user or orgnaztion.
  525. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  526. repo := &Repository{Id: repoId, OwnerId: userId}
  527. has, err := orm.Get(repo)
  528. if err != nil {
  529. return err
  530. } else if !has {
  531. return ErrRepoNotExist
  532. }
  533. sess := orm.NewSession()
  534. defer sess.Close()
  535. if err = sess.Begin(); err != nil {
  536. return err
  537. }
  538. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  539. sess.Rollback()
  540. return err
  541. }
  542. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  543. sess.Rollback()
  544. return err
  545. }
  546. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  547. sess.Rollback()
  548. return err
  549. }
  550. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  551. sess.Rollback()
  552. return err
  553. }
  554. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  555. sess.Rollback()
  556. return err
  557. }
  558. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  559. if _, err = sess.Exec(rawSql, userId); err != nil {
  560. sess.Rollback()
  561. return err
  562. }
  563. if err = sess.Commit(); err != nil {
  564. sess.Rollback()
  565. return err
  566. }
  567. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  568. // TODO: log and delete manully
  569. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  570. return err
  571. }
  572. return nil
  573. }
  574. // GetRepositoryByName returns the repository by given name under user if exists.
  575. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  576. repo := &Repository{
  577. OwnerId: userId,
  578. LowerName: strings.ToLower(repoName),
  579. }
  580. has, err := orm.Get(repo)
  581. if err != nil {
  582. return nil, err
  583. } else if !has {
  584. return nil, ErrRepoNotExist
  585. }
  586. return repo, err
  587. }
  588. // GetRepositoryById returns the repository by given id if exists.
  589. func GetRepositoryById(id int64) (*Repository, error) {
  590. repo := &Repository{}
  591. has, err := orm.Id(id).Get(repo)
  592. if err != nil {
  593. return nil, err
  594. } else if !has {
  595. return nil, ErrRepoNotExist
  596. }
  597. return repo, err
  598. }
  599. // GetRepositories returns the list of repositories of given user.
  600. func GetRepositories(user *User, private bool) ([]Repository, error) {
  601. repos := make([]Repository, 0, 10)
  602. sess := orm.Desc("updated")
  603. if !private {
  604. sess.Where("is_private=?", false)
  605. }
  606. err := sess.Find(&repos, &Repository{OwnerId: user.Id})
  607. return repos, err
  608. }
  609. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  610. func GetRecentUpdatedRepositories() (repos []*Repository, err error) {
  611. err = orm.Where("is_private=?", false).Limit(5).Desc("updated").Find(&repos)
  612. return repos, err
  613. }
  614. // GetRepositoryCount returns the total number of repositories of user.
  615. func GetRepositoryCount(user *User) (int64, error) {
  616. return orm.Count(&Repository{OwnerId: user.Id})
  617. }
  618. // Watch is connection request for receiving repository notifycation.
  619. type Watch struct {
  620. Id int64
  621. RepoId int64 `xorm:"UNIQUE(watch)"`
  622. UserId int64 `xorm:"UNIQUE(watch)"`
  623. }
  624. // Watch or unwatch repository.
  625. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  626. if watch {
  627. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  628. return err
  629. }
  630. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  631. _, err = orm.Exec(rawSql, repoId)
  632. } else {
  633. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  634. return err
  635. }
  636. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  637. _, err = orm.Exec(rawSql, repoId)
  638. }
  639. return err
  640. }
  641. // GetWatches returns all watches of given repository.
  642. func GetWatches(repoId int64) ([]Watch, error) {
  643. watches := make([]Watch, 0, 10)
  644. err := orm.Find(&watches, &Watch{RepoId: repoId})
  645. return watches, err
  646. }
  647. // NotifyWatchers creates batch of actions for every watcher.
  648. func NotifyWatchers(act *Action) error {
  649. // Add feeds for user self and all watchers.
  650. watches, err := GetWatches(act.RepoId)
  651. if err != nil {
  652. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  653. }
  654. // Add feed for actioner.
  655. act.UserId = act.ActUserId
  656. if _, err = orm.InsertOne(act); err != nil {
  657. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  658. }
  659. for i := range watches {
  660. if act.ActUserId == watches[i].UserId {
  661. continue
  662. }
  663. act.Id = 0
  664. act.UserId = watches[i].UserId
  665. if _, err = orm.InsertOne(act); err != nil {
  666. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  667. }
  668. }
  669. return nil
  670. }
  671. // IsWatching checks if user has watched given repository.
  672. func IsWatching(userId, repoId int64) bool {
  673. has, _ := orm.Get(&Watch{0, repoId, userId})
  674. return has
  675. }
  676. func ForkRepository(reposName string, userId int64) {
  677. }