repo.go 22 KB

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