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