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

repo.go 26 kB

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