repo.go 20 KB

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