repo.go 21 KB

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