You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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", "gogitservice@gmail.com"); 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. DefaultBranch: "master",
  230. }
  231. repoPath := RepoPath(user.Name, repo.Name)
  232. sess := orm.NewSession()
  233. defer sess.Close()
  234. sess.Begin()
  235. if _, err = sess.Insert(repo); err != nil {
  236. if err2 := os.RemoveAll(repoPath); err2 != nil {
  237. log.Error("repo.CreateRepository(repo): %v", err)
  238. return nil, errors.New(fmt.Sprintf(
  239. "delete repo directory %s/%s failed(1): %v", user.Name, repo.Name, err2))
  240. }
  241. sess.Rollback()
  242. return nil, err
  243. }
  244. mode := AU_WRITABLE
  245. if mirror {
  246. mode = AU_READABLE
  247. }
  248. access := Access{
  249. UserName: user.LowerName,
  250. RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
  251. Mode: mode,
  252. }
  253. if _, err = sess.Insert(&access); err != nil {
  254. sess.Rollback()
  255. if err2 := os.RemoveAll(repoPath); err2 != nil {
  256. log.Error("repo.CreateRepository(access): %v", err)
  257. return nil, errors.New(fmt.Sprintf(
  258. "delete repo directory %s/%s failed(2): %v", user.Name, repo.Name, err2))
  259. }
  260. return nil, err
  261. }
  262. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  263. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  264. sess.Rollback()
  265. if err2 := os.RemoveAll(repoPath); err2 != nil {
  266. log.Error("repo.CreateRepository(repo count): %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 = sess.Commit(); err != nil {
  273. sess.Rollback()
  274. if err2 := os.RemoveAll(repoPath); err2 != nil {
  275. log.Error("repo.CreateRepository(commit): %v", err)
  276. return nil, errors.New(fmt.Sprintf(
  277. "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2))
  278. }
  279. return nil, err
  280. }
  281. if !repo.IsPrivate {
  282. if err = NewRepoAction(user, repo); err != nil {
  283. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  284. }
  285. }
  286. if err = WatchRepo(user.Id, repo.Id, true); err != nil {
  287. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  288. }
  289. // No need for init for mirror.
  290. if mirror {
  291. return repo, nil
  292. }
  293. if err = initRepository(repoPath, user, repo, initReadme, lang, license); err != nil {
  294. return nil, err
  295. }
  296. c := exec.Command("git", "update-server-info")
  297. c.Dir = repoPath
  298. if err = c.Run(); err != nil {
  299. log.Error("repo.CreateRepository(exec update-server-info): %v", err)
  300. }
  301. return repo, nil
  302. }
  303. // extractGitBareZip extracts git-bare.zip to repository path.
  304. func extractGitBareZip(repoPath string) error {
  305. z, err := zip.Open("conf/content/git-bare.zip")
  306. if err != nil {
  307. fmt.Println("shi?")
  308. return err
  309. }
  310. defer z.Close()
  311. return z.ExtractTo(repoPath)
  312. }
  313. // initRepoCommit temporarily changes with work directory.
  314. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  315. var stderr string
  316. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "add", "--all"); err != nil {
  317. return err
  318. }
  319. if len(stderr) > 0 {
  320. log.Trace("stderr(1): %s", stderr)
  321. }
  322. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  323. "-m", "Init commit"); err != nil {
  324. return err
  325. }
  326. if len(stderr) > 0 {
  327. log.Trace("stderr(2): %s", stderr)
  328. }
  329. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "push", "origin", "master"); err != nil {
  330. return err
  331. }
  332. if len(stderr) > 0 {
  333. log.Trace("stderr(3): %s", stderr)
  334. }
  335. return nil
  336. }
  337. func createHookUpdate(hookPath, content string) error {
  338. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  339. if err != nil {
  340. return err
  341. }
  342. defer pu.Close()
  343. _, err = pu.WriteString(content)
  344. return err
  345. }
  346. // SetRepoEnvs sets environment variables for command update.
  347. func SetRepoEnvs(userId int64, userName, repoName string) {
  348. os.Setenv("userId", base.ToStr(userId))
  349. os.Setenv("userName", userName)
  350. os.Setenv("repoName", repoName)
  351. }
  352. // InitRepository initializes README and .gitignore if needed.
  353. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  354. repoPath := RepoPath(user.Name, repo.Name)
  355. // Create bare new repository.
  356. if err := extractGitBareZip(repoPath); err != nil {
  357. return err
  358. }
  359. // hook/post-update
  360. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  361. fmt.Sprintf("#!/usr/bin/env bash\n%s update $1 $2 $3\n",
  362. strings.Replace(appPath, "\\", "/", -1))); err != nil {
  363. return err
  364. }
  365. // Initialize repository according to user's choice.
  366. fileName := map[string]string{}
  367. if initReadme {
  368. fileName["readme"] = "README.md"
  369. }
  370. if repoLang != "" {
  371. fileName["gitign"] = ".gitignore"
  372. }
  373. if license != "" {
  374. fileName["license"] = "LICENSE"
  375. }
  376. // Clone to temprory path and do the init commit.
  377. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  378. os.MkdirAll(tmpDir, os.ModePerm)
  379. _, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir)
  380. if err != nil {
  381. return err
  382. }
  383. if len(stderr) > 0 {
  384. log.Trace("repo.initRepository(git clone): %s", stderr)
  385. }
  386. // README
  387. if initReadme {
  388. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  389. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  390. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  391. []byte(defaultReadme), 0644); err != nil {
  392. return err
  393. }
  394. }
  395. // .gitignore
  396. if repoLang != "" {
  397. filePath := "conf/gitignore/" + repoLang
  398. if com.IsFile(filePath) {
  399. if _, err := com.Copy(filePath,
  400. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  401. return err
  402. }
  403. }
  404. }
  405. // LICENSE
  406. if license != "" {
  407. filePath := "conf/license/" + license
  408. if com.IsFile(filePath) {
  409. if _, err := com.Copy(filePath,
  410. filepath.Join(tmpDir, fileName["license"])); err != nil {
  411. return err
  412. }
  413. }
  414. }
  415. if len(fileName) == 0 {
  416. return nil
  417. }
  418. SetRepoEnvs(user.Id, user.Name, repo.Name)
  419. // Apply changes and commit.
  420. return initRepoCommit(tmpDir, user.NewGitSig())
  421. }
  422. // UserRepo reporesents a repository with user name.
  423. type UserRepo struct {
  424. *Repository
  425. UserName string
  426. }
  427. // GetRepos returns given number of repository objects with offset.
  428. func GetRepos(num, offset int) ([]UserRepo, error) {
  429. repos := make([]Repository, 0, num)
  430. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  431. return nil, err
  432. }
  433. urepos := make([]UserRepo, len(repos))
  434. for i := range repos {
  435. urepos[i].Repository = &repos[i]
  436. u := new(User)
  437. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  438. if err != nil {
  439. return nil, err
  440. } else if !has {
  441. return nil, ErrUserNotExist
  442. }
  443. urepos[i].UserName = u.Name
  444. }
  445. return urepos, nil
  446. }
  447. // RepoPath returns repository path by given user and repository name.
  448. func RepoPath(userName, repoName string) string {
  449. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  450. }
  451. // TransferOwnership transfers all corresponding setting from old user to new one.
  452. func TransferOwnership(user *User, newOwner string, repo *Repository) (err error) {
  453. newUser, err := GetUserByName(newOwner)
  454. if err != nil {
  455. return err
  456. }
  457. // Update accesses.
  458. accesses := make([]Access, 0, 10)
  459. if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil {
  460. return err
  461. }
  462. sess := orm.NewSession()
  463. defer sess.Close()
  464. if err = sess.Begin(); err != nil {
  465. return err
  466. }
  467. for i := range accesses {
  468. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  469. if accesses[i].UserName == user.LowerName {
  470. accesses[i].UserName = newUser.LowerName
  471. }
  472. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  473. return err
  474. }
  475. }
  476. // Update repository.
  477. repo.OwnerId = newUser.Id
  478. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  479. sess.Rollback()
  480. return err
  481. }
  482. // Update user repository number.
  483. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  484. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  485. sess.Rollback()
  486. return err
  487. }
  488. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  489. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  490. sess.Rollback()
  491. return err
  492. }
  493. // Add watch of new owner to repository.
  494. if !IsWatching(newUser.Id, repo.Id) {
  495. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  496. sess.Rollback()
  497. return err
  498. }
  499. }
  500. if err = TransferRepoAction(user, newUser, repo); err != nil {
  501. sess.Rollback()
  502. return err
  503. }
  504. // Change repository directory name.
  505. if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  506. sess.Rollback()
  507. return err
  508. }
  509. return sess.Commit()
  510. }
  511. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  512. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  513. // Update accesses.
  514. accesses := make([]Access, 0, 10)
  515. if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  516. return err
  517. }
  518. sess := orm.NewSession()
  519. defer sess.Close()
  520. if err = sess.Begin(); err != nil {
  521. return err
  522. }
  523. for i := range accesses {
  524. accesses[i].RepoName = userName + "/" + newRepoName
  525. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  526. return err
  527. }
  528. }
  529. // Change repository directory name.
  530. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  531. sess.Rollback()
  532. return err
  533. }
  534. return sess.Commit()
  535. }
  536. func UpdateRepository(repo *Repository) error {
  537. repo.LowerName = strings.ToLower(repo.Name)
  538. if len(repo.Description) > 255 {
  539. repo.Description = repo.Description[:255]
  540. }
  541. if len(repo.Website) > 255 {
  542. repo.Website = repo.Website[:255]
  543. }
  544. _, err := orm.Id(repo.Id).AllCols().Update(repo)
  545. return err
  546. }
  547. // DeleteRepository deletes a repository for a user or orgnaztion.
  548. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  549. repo := &Repository{Id: repoId, OwnerId: userId}
  550. has, err := orm.Get(repo)
  551. if err != nil {
  552. return err
  553. } else if !has {
  554. return ErrRepoNotExist
  555. }
  556. sess := orm.NewSession()
  557. defer sess.Close()
  558. if err = sess.Begin(); err != nil {
  559. return err
  560. }
  561. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  562. sess.Rollback()
  563. return err
  564. }
  565. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  566. sess.Rollback()
  567. return err
  568. }
  569. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  570. sess.Rollback()
  571. return err
  572. }
  573. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  574. sess.Rollback()
  575. return err
  576. }
  577. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  578. sess.Rollback()
  579. return err
  580. }
  581. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  582. if _, err = sess.Exec(rawSql, userId); err != nil {
  583. sess.Rollback()
  584. return err
  585. }
  586. if err = sess.Commit(); err != nil {
  587. sess.Rollback()
  588. return err
  589. }
  590. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  591. // TODO: log and delete manully
  592. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  593. return err
  594. }
  595. return nil
  596. }
  597. // GetRepositoryByName returns the repository by given name under user if exists.
  598. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  599. repo := &Repository{
  600. OwnerId: userId,
  601. LowerName: strings.ToLower(repoName),
  602. }
  603. has, err := orm.Get(repo)
  604. if err != nil {
  605. return nil, err
  606. } else if !has {
  607. return nil, ErrRepoNotExist
  608. }
  609. return repo, err
  610. }
  611. // GetRepositoryById returns the repository by given id if exists.
  612. func GetRepositoryById(id int64) (*Repository, error) {
  613. repo := &Repository{}
  614. has, err := orm.Id(id).Get(repo)
  615. if err != nil {
  616. return nil, err
  617. } else if !has {
  618. return nil, ErrRepoNotExist
  619. }
  620. return repo, err
  621. }
  622. // GetRepositories returns the list of repositories of given user.
  623. func GetRepositories(user *User, private bool) ([]Repository, error) {
  624. repos := make([]Repository, 0, 10)
  625. sess := orm.Desc("updated")
  626. if !private {
  627. sess.Where("is_private=?", false)
  628. }
  629. err := sess.Find(&repos, &Repository{OwnerId: user.Id})
  630. return repos, err
  631. }
  632. func GetRepositoryCount(user *User) (int64, error) {
  633. return orm.Count(&Repository{OwnerId: user.Id})
  634. }
  635. // Watch is connection request for receiving repository notifycation.
  636. type Watch struct {
  637. Id int64
  638. RepoId int64 `xorm:"UNIQUE(watch)"`
  639. UserId int64 `xorm:"UNIQUE(watch)"`
  640. }
  641. // Watch or unwatch repository.
  642. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  643. if watch {
  644. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  645. return err
  646. }
  647. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  648. _, err = orm.Exec(rawSql, repoId)
  649. } else {
  650. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  651. return err
  652. }
  653. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  654. _, err = orm.Exec(rawSql, repoId)
  655. }
  656. return err
  657. }
  658. // GetWatches returns all watches of given repository.
  659. func GetWatches(repoId int64) ([]Watch, error) {
  660. watches := make([]Watch, 0, 10)
  661. err := orm.Find(&watches, &Watch{RepoId: repoId})
  662. return watches, err
  663. }
  664. // NotifyWatchers creates batch of actions for every watcher.
  665. func NotifyWatchers(act *Action) error {
  666. // Add feeds for user self and all watchers.
  667. watches, err := GetWatches(act.RepoId)
  668. if err != nil {
  669. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  670. }
  671. // Add feed for actioner.
  672. act.UserId = act.ActUserId
  673. if _, err = orm.InsertOne(act); err != nil {
  674. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  675. }
  676. for i := range watches {
  677. if act.ActUserId == watches[i].UserId {
  678. continue
  679. }
  680. act.Id = 0
  681. act.UserId = watches[i].UserId
  682. if _, err = orm.InsertOne(act); err != nil {
  683. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  684. }
  685. }
  686. return nil
  687. }
  688. // IsWatching checks if user has watched given repository.
  689. func IsWatching(userId, repoId int64) bool {
  690. has, _ := orm.Get(&Watch{0, repoId, userId})
  691. return has
  692. }
  693. func ForkRepository(reposName string, userId int64) {
  694. }