repo.go 21 KB

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