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.

1003 lines
26 KiB

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