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 20KB

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