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.

1381 lines
38 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
9 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. "html/template"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/Unknwon/cae/zip"
  20. "github.com/Unknwon/com"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/git"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/process"
  25. "github.com/gogits/gogs/modules/setting"
  26. )
  27. const (
  28. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  29. )
  30. var (
  31. ErrRepoAlreadyExist = errors.New("Repository already exist")
  32. ErrRepoNotExist = errors.New("Repository does not exist")
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  35. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  36. ErrMirrorNotExist = errors.New("Mirror does not exist")
  37. ErrInvalidReference = errors.New("Invalid reference specified")
  38. )
  39. var (
  40. Gitignores, Licenses []string
  41. )
  42. var (
  43. DescPattern = regexp.MustCompile(`https?://\S+`)
  44. )
  45. func LoadRepoConfig() {
  46. // Load .gitignore and license files.
  47. types := []string{"gitignore", "license"}
  48. typeFiles := make([][]string, 2)
  49. for i, t := range types {
  50. files, err := com.StatDir(path.Join("conf", t))
  51. if err != nil {
  52. log.Fatal(4, "Fail to get %s files: %v", t, err)
  53. }
  54. customPath := path.Join(setting.CustomPath, "conf", t)
  55. if com.IsDir(customPath) {
  56. customFiles, err := com.StatDir(customPath)
  57. if err != nil {
  58. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  59. }
  60. for _, f := range customFiles {
  61. if !com.IsSliceContainsStr(files, f) {
  62. files = append(files, f)
  63. }
  64. }
  65. }
  66. typeFiles[i] = files
  67. }
  68. Gitignores = typeFiles[0]
  69. Licenses = typeFiles[1]
  70. sort.Strings(Gitignores)
  71. sort.Strings(Licenses)
  72. }
  73. func NewRepoContext() {
  74. zip.Verbose = false
  75. // Check Git installation.
  76. if _, err := exec.LookPath("git"); err != nil {
  77. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  78. }
  79. // Check Git version.
  80. ver, err := git.GetVersion()
  81. if err != nil {
  82. log.Fatal(4, "Fail to get Git version: %v", err)
  83. }
  84. reqVer, err := git.ParseVersion("1.7.1")
  85. if err != nil {
  86. log.Fatal(4, "Fail to parse required Git version: %v", err)
  87. }
  88. if ver.LessThan(reqVer) {
  89. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  90. }
  91. // Check if server has user.email and user.name set correctly and set if they're not.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogitservice@gmail.com"} {
  93. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  94. // ExitError indicates this config is not set
  95. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  96. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  97. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  98. }
  99. log.Info("Git config %s set to %s", configKey, defaultValue)
  100. } else {
  101. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  102. }
  103. }
  104. }
  105. // Set git some configurations.
  106. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  107. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  108. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  109. }
  110. }
  111. // Repository represents a git repository.
  112. type Repository struct {
  113. Id int64
  114. OwnerId int64 `xorm:"UNIQUE(s)"`
  115. Owner *User `xorm:"-"`
  116. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  117. Name string `xorm:"INDEX NOT NULL"`
  118. Description string
  119. Website string
  120. DefaultBranch string
  121. NumWatches int
  122. NumStars int
  123. NumForks int
  124. NumIssues int
  125. NumClosedIssues int
  126. NumOpenIssues int `xorm:"-"`
  127. NumPulls int
  128. NumClosedPulls int
  129. NumOpenPulls int `xorm:"-"`
  130. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  132. NumOpenMilestones int `xorm:"-"`
  133. NumTags int `xorm:"-"`
  134. IsPrivate bool
  135. IsBare bool
  136. IsMirror bool
  137. *Mirror `xorm:"-"`
  138. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  139. ForkId int64
  140. ForkRepo *Repository `xorm:"-"`
  141. Created time.Time `xorm:"CREATED"`
  142. Updated time.Time `xorm:"UPDATED"`
  143. }
  144. func (repo *Repository) getOwner(e Engine) (err error) {
  145. if repo.Owner == nil {
  146. repo.Owner, err = getUserById(e, repo.OwnerId)
  147. }
  148. return err
  149. }
  150. func (repo *Repository) GetOwner() (err error) {
  151. return repo.getOwner(x)
  152. }
  153. func (repo *Repository) GetMirror() (err error) {
  154. repo.Mirror, err = GetMirror(repo.Id)
  155. return err
  156. }
  157. func (repo *Repository) GetForkRepo() (err error) {
  158. if !repo.IsFork {
  159. return nil
  160. }
  161. repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
  162. return err
  163. }
  164. func (repo *Repository) RepoPath() (string, error) {
  165. if err := repo.GetOwner(); err != nil {
  166. return "", err
  167. }
  168. return RepoPath(repo.Owner.Name, repo.Name), nil
  169. }
  170. func (repo *Repository) RepoLink() (string, error) {
  171. if err := repo.GetOwner(); err != nil {
  172. return "", err
  173. }
  174. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  175. }
  176. func (repo *Repository) HasAccess(u *User) bool {
  177. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  178. return has
  179. }
  180. func (repo *Repository) IsOwnedBy(u *User) bool {
  181. return repo.OwnerId == u.Id
  182. }
  183. // DescriptionHtml does special handles to description and return HTML string.
  184. func (repo *Repository) DescriptionHtml() template.HTML {
  185. sanitize := func(s string) string {
  186. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  187. }
  188. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  189. }
  190. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  191. func IsRepositoryExist(u *User, repoName string) bool {
  192. has, _ := x.Get(&Repository{
  193. OwnerId: u.Id,
  194. LowerName: strings.ToLower(repoName),
  195. })
  196. return has && com.IsDir(RepoPath(u.Name, repoName))
  197. }
  198. // CloneLink represents different types of clone URLs of repository.
  199. type CloneLink struct {
  200. SSH string
  201. HTTPS string
  202. Git string
  203. }
  204. // CloneLink returns clone URLs of repository.
  205. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  206. if err = repo.GetOwner(); err != nil {
  207. return cl, err
  208. }
  209. if setting.SSHPort != 22 {
  210. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.Domain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  211. } else {
  212. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, repo.Owner.LowerName, repo.LowerName)
  213. }
  214. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  215. return cl, nil
  216. }
  217. var (
  218. illegalEquals = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  219. illegalSuffixs = []string{".git", ".keys"}
  220. )
  221. // IsLegalName returns false if name contains illegal characters.
  222. func IsLegalName(repoName string) bool {
  223. repoName = strings.ToLower(repoName)
  224. for _, char := range illegalEquals {
  225. if repoName == char {
  226. return false
  227. }
  228. }
  229. for _, char := range illegalSuffixs {
  230. if strings.HasSuffix(repoName, char) {
  231. return false
  232. }
  233. }
  234. return true
  235. }
  236. // Mirror represents a mirror information of repository.
  237. type Mirror struct {
  238. Id int64
  239. RepoId int64
  240. RepoName string // <user name>/<repo name>
  241. Interval int // Hour.
  242. Updated time.Time `xorm:"UPDATED"`
  243. NextUpdate time.Time
  244. }
  245. func GetMirror(repoId int64) (*Mirror, error) {
  246. m := &Mirror{RepoId: repoId}
  247. has, err := x.Get(m)
  248. if err != nil {
  249. return nil, err
  250. } else if !has {
  251. return nil, ErrMirrorNotExist
  252. }
  253. return m, nil
  254. }
  255. func UpdateMirror(m *Mirror) error {
  256. _, err := x.Id(m.Id).Update(m)
  257. return err
  258. }
  259. // MirrorRepository creates a mirror repository from source.
  260. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  261. _, stderr, err := process.ExecTimeout(10*time.Minute,
  262. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  263. "git", "clone", "--mirror", url, repoPath)
  264. if err != nil {
  265. return errors.New("git clone --mirror: " + stderr)
  266. }
  267. if _, err = x.InsertOne(&Mirror{
  268. RepoId: repoId,
  269. RepoName: strings.ToLower(userName + "/" + repoName),
  270. Interval: 24,
  271. NextUpdate: time.Now().Add(24 * time.Hour),
  272. }); err != nil {
  273. return err
  274. }
  275. return nil
  276. }
  277. // MigrateRepository migrates a existing repository from other project hosting.
  278. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  279. repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
  280. if err != nil {
  281. return nil, err
  282. }
  283. // Clone to temprory path and do the init commit.
  284. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  285. os.MkdirAll(tmpDir, os.ModePerm)
  286. repoPath := RepoPath(u.Name, name)
  287. if u.IsOrganization() {
  288. t, err := u.GetOwnerTeam()
  289. if err != nil {
  290. return nil, err
  291. }
  292. repo.NumWatches = t.NumMembers
  293. } else {
  294. repo.NumWatches = 1
  295. }
  296. repo.IsBare = false
  297. if mirror {
  298. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  299. return repo, err
  300. }
  301. repo.IsMirror = true
  302. return repo, UpdateRepository(repo)
  303. } else {
  304. os.RemoveAll(repoPath)
  305. }
  306. // FIXME: this command could for both migrate and mirror
  307. _, stderr, err := process.ExecTimeout(10*time.Minute,
  308. fmt.Sprintf("MigrateRepository: %s", repoPath),
  309. "git", "clone", "--mirror", "--bare", url, repoPath)
  310. if err != nil {
  311. return repo, fmt.Errorf("git clone --mirror --bare: %v", stderr)
  312. } else if err = createUpdateHook(repoPath); err != nil {
  313. return repo, fmt.Errorf("create update hook: %v", err)
  314. }
  315. return repo, UpdateRepository(repo)
  316. }
  317. // extractGitBareZip extracts git-bare.zip to repository path.
  318. func extractGitBareZip(repoPath string) error {
  319. z, err := zip.Open(path.Join(setting.ConfRootPath, "content/git-bare.zip"))
  320. if err != nil {
  321. return err
  322. }
  323. defer z.Close()
  324. return z.ExtractTo(repoPath)
  325. }
  326. // initRepoCommit temporarily changes with work directory.
  327. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  328. var stderr string
  329. if _, stderr, err = process.ExecDir(-1,
  330. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  331. "git", "add", "--all"); err != nil {
  332. return errors.New("git add: " + stderr)
  333. }
  334. if _, stderr, err = process.ExecDir(-1,
  335. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  336. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  337. "-m", "Init commit"); err != nil {
  338. return errors.New("git commit: " + stderr)
  339. }
  340. if _, stderr, err = process.ExecDir(-1,
  341. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  342. "git", "push", "origin", "master"); err != nil {
  343. return errors.New("git push: " + stderr)
  344. }
  345. return nil
  346. }
  347. func createUpdateHook(repoPath string) error {
  348. return ioutil.WriteFile(path.Join(repoPath, "hooks/update"),
  349. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  350. }
  351. // InitRepository initializes README and .gitignore if needed.
  352. func initRepository(e Engine, f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error {
  353. repoPath := RepoPath(u.Name, repo.Name)
  354. // Create bare new repository.
  355. if err := extractGitBareZip(repoPath); err != nil {
  356. return err
  357. }
  358. if err := createUpdateHook(repoPath); err != nil {
  359. return err
  360. }
  361. // Initialize repository according to user's choice.
  362. fileName := map[string]string{}
  363. if initReadme {
  364. fileName["readme"] = "README.md"
  365. }
  366. if repoLang != "" {
  367. fileName["gitign"] = ".gitignore"
  368. }
  369. if license != "" {
  370. fileName["license"] = "LICENSE"
  371. }
  372. // Clone to temprory path and do the init commit.
  373. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  374. os.MkdirAll(tmpDir, os.ModePerm)
  375. _, stderr, err := process.Exec(
  376. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  377. "git", "clone", repoPath, tmpDir)
  378. if err != nil {
  379. return errors.New("initRepository(git clone): " + stderr)
  380. }
  381. // README
  382. if initReadme {
  383. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  384. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  385. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  386. []byte(defaultReadme), 0644); err != nil {
  387. return err
  388. }
  389. }
  390. // .gitignore
  391. filePath := "conf/gitignore/" + repoLang
  392. if com.IsFile(filePath) {
  393. targetPath := path.Join(tmpDir, fileName["gitign"])
  394. if com.IsFile(filePath) {
  395. if err = com.Copy(filePath, targetPath); err != nil {
  396. return err
  397. }
  398. } else {
  399. // Check custom files.
  400. filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  401. if com.IsFile(filePath) {
  402. if err := com.Copy(filePath, targetPath); err != nil {
  403. return err
  404. }
  405. }
  406. }
  407. } else {
  408. delete(fileName, "gitign")
  409. }
  410. // LICENSE
  411. filePath = "conf/license/" + license
  412. if com.IsFile(filePath) {
  413. targetPath := path.Join(tmpDir, fileName["license"])
  414. if com.IsFile(filePath) {
  415. if err = com.Copy(filePath, targetPath); err != nil {
  416. return err
  417. }
  418. } else {
  419. // Check custom files.
  420. filePath = path.Join(setting.CustomPath, "conf/license", license)
  421. if com.IsFile(filePath) {
  422. if err := com.Copy(filePath, targetPath); err != nil {
  423. return err
  424. }
  425. }
  426. }
  427. } else {
  428. delete(fileName, "license")
  429. }
  430. if len(fileName) == 0 {
  431. // Re-fetch the repository from database before updating it (else it would
  432. // override changes that were done earlier with sql)
  433. if repo, err = getRepositoryById(e, repo.Id); err != nil {
  434. return err
  435. }
  436. repo.IsBare = true
  437. repo.DefaultBranch = "master"
  438. return updateRepository(e, repo)
  439. }
  440. // Apply changes and commit.
  441. return initRepoCommit(tmpDir, u.NewGitSig())
  442. }
  443. // CreateRepository creates a repository for given user or organization.
  444. func CreateRepository(u *User, name, desc, lang, license string, isPrivate, isMirror, initReadme bool) (_ *Repository, err error) {
  445. if !IsLegalName(name) {
  446. return nil, ErrRepoNameIllegal
  447. }
  448. if IsRepositoryExist(u, name) {
  449. return nil, ErrRepoAlreadyExist
  450. }
  451. repo := &Repository{
  452. OwnerId: u.Id,
  453. Owner: u,
  454. Name: name,
  455. LowerName: strings.ToLower(name),
  456. Description: desc,
  457. IsPrivate: isPrivate,
  458. }
  459. sess := x.NewSession()
  460. defer sessionRelease(sess)
  461. if err = sess.Begin(); err != nil {
  462. return nil, err
  463. }
  464. if _, err = sess.Insert(repo); err != nil {
  465. return nil, err
  466. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  467. return nil, err
  468. }
  469. // TODO fix code for mirrors?
  470. // Give access to all members in owner team.
  471. if u.IsOrganization() {
  472. t, err := u.getOwnerTeam(sess)
  473. if err != nil {
  474. return nil, fmt.Errorf("getOwnerTeam: %v", err)
  475. } else if err = t.addRepository(sess, repo); err != nil {
  476. return nil, fmt.Errorf("addRepository: %v", err)
  477. }
  478. } else {
  479. // Organization called this in addRepository method.
  480. if err = repo.recalculateAccesses(sess); err != nil {
  481. return nil, fmt.Errorf("recalculateAccesses: %v", err)
  482. }
  483. }
  484. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  485. return nil, fmt.Errorf("watchRepo: %v", err)
  486. } else if err = newRepoAction(sess, u, repo); err != nil {
  487. return nil, fmt.Errorf("newRepoAction: %v", err)
  488. }
  489. // No need for init mirror.
  490. if !isMirror {
  491. repoPath := RepoPath(u.Name, repo.Name)
  492. if err = initRepository(sess, repoPath, u, repo, initReadme, lang, license); err != nil {
  493. if err2 := os.RemoveAll(repoPath); err2 != nil {
  494. log.Error(4, "initRepository: %v", err)
  495. return nil, fmt.Errorf(
  496. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  497. }
  498. return nil, fmt.Errorf("initRepository: %v", err)
  499. }
  500. _, stderr, err := process.ExecDir(-1,
  501. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  502. "git", "update-server-info")
  503. if err != nil {
  504. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  505. }
  506. }
  507. return repo, sess.Commit()
  508. }
  509. // CountRepositories returns number of repositories.
  510. func CountRepositories() int64 {
  511. count, _ := x.Count(new(Repository))
  512. return count
  513. }
  514. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  515. // It also auto-gets corresponding users.
  516. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  517. repos := make([]*Repository, 0, num)
  518. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  519. return nil, err
  520. }
  521. for _, repo := range repos {
  522. repo.Owner = &User{Id: repo.OwnerId}
  523. has, err := x.Get(repo.Owner)
  524. if err != nil {
  525. return nil, err
  526. } else if !has {
  527. return nil, ErrUserNotExist
  528. }
  529. }
  530. return repos, nil
  531. }
  532. // RepoPath returns repository path by given user and repository name.
  533. func RepoPath(userName, repoName string) string {
  534. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  535. }
  536. // TransferOwnership transfers all corresponding setting from old user to new one.
  537. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  538. newOwner, err := GetUserByName(newOwnerName)
  539. if err != nil {
  540. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  541. }
  542. // Check if new owner has repository with same name.
  543. if IsRepositoryExist(newOwner, repo.Name) {
  544. return ErrRepoAlreadyExist
  545. }
  546. sess := x.NewSession()
  547. defer sessionRelease(sess)
  548. if err = sess.Begin(); err != nil {
  549. return fmt.Errorf("sess.Begin: %v", err)
  550. }
  551. owner := repo.Owner
  552. // Note: we have to set value here to make sure recalculate accesses is based on
  553. // new owner.
  554. repo.OwnerId = newOwner.Id
  555. repo.Owner = newOwner
  556. // Update repository.
  557. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  558. return fmt.Errorf("update owner: %v", err)
  559. }
  560. // Remove redundant collaborators.
  561. collaborators, err := repo.GetCollaborators()
  562. if err != nil {
  563. return fmt.Errorf("GetCollaborators: %v", err)
  564. }
  565. // Dummy object.
  566. collaboration := &Collaboration{RepoID: repo.Id}
  567. for _, c := range collaborators {
  568. collaboration.UserID = c.Id
  569. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  570. if _, err = sess.Delete(collaboration); err != nil {
  571. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  572. }
  573. }
  574. }
  575. // Remove old team-repository relations.
  576. if owner.IsOrganization() {
  577. if err = owner.getTeams(sess); err != nil {
  578. return fmt.Errorf("getTeams: %v", err)
  579. }
  580. for _, t := range owner.Teams {
  581. if !t.hasRepository(sess, repo.Id) {
  582. continue
  583. }
  584. t.NumRepos--
  585. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  586. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  587. }
  588. }
  589. if err = owner.removeOrgRepo(sess, repo.Id); err != nil {
  590. return fmt.Errorf("removeOrgRepo: %v", err)
  591. }
  592. }
  593. if newOwner.IsOrganization() {
  594. t, err := newOwner.GetOwnerTeam()
  595. if err != nil {
  596. return fmt.Errorf("GetOwnerTeam: %v", err)
  597. } else if err = t.addRepository(sess, repo); err != nil {
  598. return fmt.Errorf("add to owner team: %v", err)
  599. }
  600. } else {
  601. // Organization called this in addRepository method.
  602. if err = repo.recalculateAccesses(sess); err != nil {
  603. return fmt.Errorf("recalculateAccesses: %v", err)
  604. }
  605. }
  606. // Update repository count.
  607. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  608. return fmt.Errorf("increase new owner repository count: %v", err)
  609. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  610. return fmt.Errorf("decrease old owner repository count: %v", err)
  611. }
  612. if err = watchRepo(sess, newOwner.Id, repo.Id, true); err != nil {
  613. return fmt.Errorf("watchRepo: %v", err)
  614. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  615. return fmt.Errorf("transferRepoAction: %v", err)
  616. }
  617. // Change repository directory name.
  618. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  619. return fmt.Errorf("rename directory: %v", err)
  620. }
  621. return sess.Commit()
  622. }
  623. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  624. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  625. userName = strings.ToLower(userName)
  626. oldRepoName = strings.ToLower(oldRepoName)
  627. newRepoName = strings.ToLower(newRepoName)
  628. if !IsLegalName(newRepoName) {
  629. return ErrRepoNameIllegal
  630. }
  631. // Change repository directory name.
  632. return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName))
  633. }
  634. func updateRepository(e Engine, repo *Repository) error {
  635. repo.LowerName = strings.ToLower(repo.Name)
  636. if len(repo.Description) > 255 {
  637. repo.Description = repo.Description[:255]
  638. }
  639. if len(repo.Website) > 255 {
  640. repo.Website = repo.Website[:255]
  641. }
  642. _, err := e.Id(repo.Id).AllCols().Update(repo)
  643. return err
  644. }
  645. func UpdateRepository(repo *Repository) error {
  646. return updateRepository(x, repo)
  647. }
  648. // DeleteRepository deletes a repository for a user or organization.
  649. func DeleteRepository(uid, repoID int64, userName string) error {
  650. repo := &Repository{Id: repoID, OwnerId: uid}
  651. has, err := x.Get(repo)
  652. if err != nil {
  653. return err
  654. } else if !has {
  655. return ErrRepoNotExist
  656. }
  657. // In case is a organization.
  658. org, err := GetUserById(uid)
  659. if err != nil {
  660. return err
  661. }
  662. if org.IsOrganization() {
  663. if err = org.GetTeams(); err != nil {
  664. return err
  665. }
  666. }
  667. sess := x.NewSession()
  668. defer sessionRelease(sess)
  669. if err = sess.Begin(); err != nil {
  670. return err
  671. }
  672. if org.IsOrganization() {
  673. for _, t := range org.Teams {
  674. if !t.hasRepository(sess, repoID) {
  675. continue
  676. } else if err = t.removeRepository(sess, repo, false); err != nil {
  677. return err
  678. }
  679. }
  680. }
  681. if _, err = sess.Delete(&Repository{Id: repoID}); err != nil {
  682. return err
  683. } else if _, err = sess.Delete(&Access{RepoID: repo.Id}); err != nil {
  684. return err
  685. } else if _, err = sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  686. return err
  687. } else if _, err = sess.Delete(&Watch{RepoId: repoID}); err != nil {
  688. return err
  689. } else if _, err = sess.Delete(&Mirror{RepoId: repoID}); err != nil {
  690. return err
  691. } else if _, err = sess.Delete(&IssueUser{RepoId: repoID}); err != nil {
  692. return err
  693. } else if _, err = sess.Delete(&Milestone{RepoId: repoID}); err != nil {
  694. return err
  695. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  696. return err
  697. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  698. return err
  699. }
  700. // Delete comments.
  701. issues := make([]*Issue, 0, 25)
  702. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  703. return err
  704. }
  705. for i := range issues {
  706. if _, err = sess.Delete(&Comment{IssueId: issues[i].Id}); err != nil {
  707. return err
  708. }
  709. }
  710. if _, err = sess.Delete(&Issue{RepoId: repoID}); err != nil {
  711. return err
  712. }
  713. if repo.IsFork {
  714. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkId); err != nil {
  715. return err
  716. }
  717. }
  718. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  719. return err
  720. }
  721. // Remove repository files.
  722. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  723. desc := fmt.Sprintf("delete repository files(%s/%s): %v", userName, repo.Name, err)
  724. log.Warn(desc)
  725. if err = CreateRepositoryNotice(desc); err != nil {
  726. log.Error(4, "add notice: %v", err)
  727. }
  728. }
  729. return sess.Commit()
  730. }
  731. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  732. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  733. func GetRepositoryByRef(ref string) (*Repository, error) {
  734. n := strings.IndexByte(ref, byte('/'))
  735. if n < 2 {
  736. return nil, ErrInvalidReference
  737. }
  738. userName, repoName := ref[:n], ref[n+1:]
  739. user, err := GetUserByName(userName)
  740. if err != nil {
  741. return nil, err
  742. }
  743. return GetRepositoryByName(user.Id, repoName)
  744. }
  745. // GetRepositoryByName returns the repository by given name under user if exists.
  746. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  747. repo := &Repository{
  748. OwnerId: uid,
  749. LowerName: strings.ToLower(repoName),
  750. }
  751. has, err := x.Get(repo)
  752. if err != nil {
  753. return nil, err
  754. } else if !has {
  755. return nil, ErrRepoNotExist
  756. }
  757. return repo, err
  758. }
  759. func getRepositoryById(e Engine, id int64) (*Repository, error) {
  760. repo := &Repository{}
  761. has, err := e.Id(id).Get(repo)
  762. if err != nil {
  763. return nil, err
  764. } else if !has {
  765. return nil, ErrRepoNotExist
  766. }
  767. return repo, nil
  768. }
  769. // GetRepositoryById returns the repository by given id if exists.
  770. func GetRepositoryById(id int64) (*Repository, error) {
  771. return getRepositoryById(x, id)
  772. }
  773. // GetRepositories returns a list of repositories of given user.
  774. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  775. repos := make([]*Repository, 0, 10)
  776. sess := x.Desc("updated")
  777. if !private {
  778. sess.Where("is_private=?", false)
  779. }
  780. err := sess.Find(&repos, &Repository{OwnerId: uid})
  781. return repos, err
  782. }
  783. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  784. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  785. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  786. return repos, err
  787. }
  788. // GetRepositoryCount returns the total number of repositories of user.
  789. func GetRepositoryCount(user *User) (int64, error) {
  790. return x.Count(&Repository{OwnerId: user.Id})
  791. }
  792. type SearchOption struct {
  793. Keyword string
  794. Uid int64
  795. Limit int
  796. Private bool
  797. }
  798. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  799. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  800. if len(opt.Keyword) == 0 {
  801. return repos, nil
  802. }
  803. opt.Keyword = strings.ToLower(opt.Keyword)
  804. repos = make([]*Repository, 0, opt.Limit)
  805. // Append conditions.
  806. sess := x.Limit(opt.Limit)
  807. if opt.Uid > 0 {
  808. sess.Where("owner_id=?", opt.Uid)
  809. }
  810. if !opt.Private {
  811. sess.And("is_private=false")
  812. }
  813. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  814. return repos, err
  815. }
  816. // DeleteRepositoryArchives deletes all repositories' archives.
  817. func DeleteRepositoryArchives() error {
  818. return x.Where("id > 0").Iterate(new(Repository),
  819. func(idx int, bean interface{}) error {
  820. repo := bean.(*Repository)
  821. if err := repo.GetOwner(); err != nil {
  822. return err
  823. }
  824. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  825. })
  826. }
  827. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  828. func RewriteRepositoryUpdateHook() error {
  829. return x.Where("id > 0").Iterate(new(Repository),
  830. func(idx int, bean interface{}) error {
  831. repo := bean.(*Repository)
  832. if err := repo.GetOwner(); err != nil {
  833. return err
  834. }
  835. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  836. })
  837. }
  838. var (
  839. // Prevent duplicate tasks.
  840. isMirrorUpdating = false
  841. isGitFscking = false
  842. )
  843. // MirrorUpdate checks and updates mirror repositories.
  844. func MirrorUpdate() {
  845. if isMirrorUpdating {
  846. return
  847. }
  848. isMirrorUpdating = true
  849. defer func() { isMirrorUpdating = false }()
  850. mirrors := make([]*Mirror, 0, 10)
  851. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  852. m := bean.(*Mirror)
  853. if m.NextUpdate.After(time.Now()) {
  854. return nil
  855. }
  856. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  857. if _, stderr, err := process.ExecDir(10*time.Minute,
  858. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  859. "git", "remote", "update"); err != nil {
  860. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  861. log.Error(4, desc)
  862. if err = CreateRepositoryNotice(desc); err != nil {
  863. log.Error(4, "Fail to add notice: %v", err)
  864. }
  865. return nil
  866. }
  867. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  868. mirrors = append(mirrors, m)
  869. return nil
  870. }); err != nil {
  871. log.Error(4, "MirrorUpdate: %v", err)
  872. }
  873. for i := range mirrors {
  874. if err := UpdateMirror(mirrors[i]); err != nil {
  875. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  876. }
  877. }
  878. }
  879. // GitFsck calls 'git fsck' to check repository health.
  880. func GitFsck() {
  881. if isGitFscking {
  882. return
  883. }
  884. isGitFscking = true
  885. defer func() { isGitFscking = false }()
  886. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  887. if err := x.Where("id > 0").Iterate(new(Repository),
  888. func(idx int, bean interface{}) error {
  889. repo := bean.(*Repository)
  890. if err := repo.GetOwner(); err != nil {
  891. return err
  892. }
  893. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  894. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  895. if err != nil {
  896. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  897. log.Warn(desc)
  898. if err = CreateRepositoryNotice(desc); err != nil {
  899. log.Error(4, "Fail to add notice: %v", err)
  900. }
  901. }
  902. return nil
  903. }); err != nil {
  904. log.Error(4, "repo.Fsck: %v", err)
  905. }
  906. }
  907. func GitGcRepos() error {
  908. args := append([]string{"gc"}, setting.Git.GcArgs...)
  909. return x.Where("id > 0").Iterate(new(Repository),
  910. func(idx int, bean interface{}) error {
  911. repo := bean.(*Repository)
  912. if err := repo.GetOwner(); err != nil {
  913. return err
  914. }
  915. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  916. if err != nil {
  917. return fmt.Errorf("%v: %v", err, stderr)
  918. }
  919. return nil
  920. })
  921. }
  922. // _________ .__ .__ ___. __ .__
  923. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  924. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  925. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  926. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  927. // \/ \/ \/ \/ \/
  928. // A Collaboration is a relation between an individual and a repository
  929. type Collaboration struct {
  930. ID int64 `xorm:"pk autoincr"`
  931. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  932. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  933. Created time.Time `xorm:"CREATED"`
  934. }
  935. // Add collaborator and accompanying access
  936. func (repo *Repository) AddCollaborator(u *User) error {
  937. collaboration := &Collaboration{
  938. RepoID: repo.Id,
  939. UserID: u.Id,
  940. }
  941. has, err := x.Get(collaboration)
  942. if err != nil {
  943. return err
  944. } else if has {
  945. return nil
  946. }
  947. sess := x.NewSession()
  948. defer sessionRelease(sess)
  949. if err = sess.Begin(); err != nil {
  950. return err
  951. }
  952. if _, err = sess.InsertOne(collaboration); err != nil {
  953. return err
  954. } else if err = repo.recalculateAccesses(sess); err != nil {
  955. return err
  956. }
  957. return sess.Commit()
  958. }
  959. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  960. collaborations := make([]*Collaboration, 0)
  961. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil {
  962. return nil, err
  963. }
  964. users := make([]*User, len(collaborations))
  965. for i, c := range collaborations {
  966. user, err := getUserById(e, c.UserID)
  967. if err != nil {
  968. return nil, err
  969. }
  970. users[i] = user
  971. }
  972. return users, nil
  973. }
  974. // GetCollaborators returns the collaborators for a repository
  975. func (repo *Repository) GetCollaborators() ([]*User, error) {
  976. return repo.getCollaborators(x)
  977. }
  978. // Delete collaborator and accompanying access
  979. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  980. collaboration := &Collaboration{
  981. RepoID: repo.Id,
  982. UserID: u.Id,
  983. }
  984. sess := x.NewSession()
  985. defer sessionRelease(sess)
  986. if err = sess.Begin(); err != nil {
  987. return err
  988. }
  989. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  990. return err
  991. } else if err = repo.recalculateAccesses(sess); err != nil {
  992. return err
  993. }
  994. return sess.Commit()
  995. }
  996. // __ __ __ .__
  997. // / \ / \_____ _/ |_ ____ | |__
  998. // \ \/\/ /\__ \\ __\/ ___\| | \
  999. // \ / / __ \| | \ \___| Y \
  1000. // \__/\ / (____ /__| \___ >___| /
  1001. // \/ \/ \/ \/
  1002. // Watch is connection request for receiving repository notification.
  1003. type Watch struct {
  1004. Id int64
  1005. UserId int64 `xorm:"UNIQUE(watch)"`
  1006. RepoId int64 `xorm:"UNIQUE(watch)"`
  1007. }
  1008. // IsWatching checks if user has watched given repository.
  1009. func IsWatching(uid, repoId int64) bool {
  1010. has, _ := x.Get(&Watch{0, uid, repoId})
  1011. return has
  1012. }
  1013. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1014. if watch {
  1015. if IsWatching(uid, repoId) {
  1016. return nil
  1017. }
  1018. if _, err = e.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
  1019. return err
  1020. }
  1021. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1022. } else {
  1023. if !IsWatching(uid, repoId) {
  1024. return nil
  1025. }
  1026. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1027. return err
  1028. }
  1029. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
  1030. }
  1031. return err
  1032. }
  1033. // Watch or unwatch repository.
  1034. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1035. return watchRepo(x, uid, repoId, watch)
  1036. }
  1037. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1038. watches := make([]*Watch, 0, 10)
  1039. err := e.Find(&watches, &Watch{RepoId: rid})
  1040. return watches, err
  1041. }
  1042. // GetWatchers returns all watchers of given repository.
  1043. func GetWatchers(rid int64) ([]*Watch, error) {
  1044. return getWatchers(x, rid)
  1045. }
  1046. func notifyWatchers(e Engine, act *Action) error {
  1047. // Add feeds for user self and all watchers.
  1048. watches, err := getWatchers(e, act.RepoId)
  1049. if err != nil {
  1050. return fmt.Errorf("get watchers: %v", err)
  1051. }
  1052. // Add feed for actioner.
  1053. act.UserId = act.ActUserId
  1054. if _, err = e.InsertOne(act); err != nil {
  1055. return fmt.Errorf("insert new actioner: %v", err)
  1056. }
  1057. for i := range watches {
  1058. if act.ActUserId == watches[i].UserId {
  1059. continue
  1060. }
  1061. act.Id = 0
  1062. act.UserId = watches[i].UserId
  1063. if _, err = e.InsertOne(act); err != nil {
  1064. return fmt.Errorf("insert new action: %v", err)
  1065. }
  1066. }
  1067. return nil
  1068. }
  1069. // NotifyWatchers creates batch of actions for every watcher.
  1070. func NotifyWatchers(act *Action) error {
  1071. return notifyWatchers(x, act)
  1072. }
  1073. // _________ __
  1074. // / _____// |______ _______
  1075. // \_____ \\ __\__ \\_ __ \
  1076. // / \| | / __ \| | \/
  1077. // /_______ /|__| (____ /__|
  1078. // \/ \/
  1079. type Star struct {
  1080. Id int64
  1081. Uid int64 `xorm:"UNIQUE(s)"`
  1082. RepoId int64 `xorm:"UNIQUE(s)"`
  1083. }
  1084. // Star or unstar repository.
  1085. func StarRepo(uid, repoId int64, star bool) (err error) {
  1086. if star {
  1087. if IsStaring(uid, repoId) {
  1088. return nil
  1089. }
  1090. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1091. return err
  1092. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1093. return err
  1094. }
  1095. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1096. } else {
  1097. if !IsStaring(uid, repoId) {
  1098. return nil
  1099. }
  1100. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1101. return err
  1102. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1103. return err
  1104. }
  1105. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1106. }
  1107. return err
  1108. }
  1109. // IsStaring checks if user has starred given repository.
  1110. func IsStaring(uid, repoId int64) bool {
  1111. has, _ := x.Get(&Star{0, uid, repoId})
  1112. return has
  1113. }
  1114. // ___________ __
  1115. // \_ _____/__________| | __
  1116. // | __)/ _ \_ __ \ |/ /
  1117. // | \( <_> ) | \/ <
  1118. // \___ / \____/|__| |__|_ \
  1119. // \/ \/
  1120. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1121. if IsRepositoryExist(u, name) {
  1122. return nil, ErrRepoAlreadyExist
  1123. }
  1124. // In case the old repository is a fork.
  1125. if oldRepo.IsFork {
  1126. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1127. if err != nil {
  1128. return nil, err
  1129. }
  1130. }
  1131. repo := &Repository{
  1132. OwnerId: u.Id,
  1133. Owner: u,
  1134. Name: name,
  1135. LowerName: strings.ToLower(name),
  1136. Description: desc,
  1137. IsPrivate: oldRepo.IsPrivate,
  1138. IsFork: true,
  1139. ForkId: oldRepo.Id,
  1140. }
  1141. sess := x.NewSession()
  1142. defer sessionRelease(sess)
  1143. if err = sess.Begin(); err != nil {
  1144. return nil, err
  1145. }
  1146. if _, err = sess.Insert(repo); err != nil {
  1147. return nil, err
  1148. }
  1149. if err = repo.recalculateAccesses(sess); err != nil {
  1150. return nil, err
  1151. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1152. return nil, err
  1153. }
  1154. if u.IsOrganization() {
  1155. // Update owner team info and count.
  1156. t, err := u.getOwnerTeam(sess)
  1157. if err != nil {
  1158. return nil, fmt.Errorf("getOwnerTeam: %v", err)
  1159. } else if err = t.addRepository(sess, repo); err != nil {
  1160. return nil, fmt.Errorf("addRepository: %v", err)
  1161. }
  1162. } else {
  1163. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1164. return nil, fmt.Errorf("watchRepo: %v", err)
  1165. }
  1166. }
  1167. if err = newRepoAction(sess, u, repo); err != nil {
  1168. return nil, fmt.Errorf("newRepoAction: %v", err)
  1169. }
  1170. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.Id); err != nil {
  1171. return nil, err
  1172. }
  1173. oldRepoPath, err := oldRepo.RepoPath()
  1174. if err != nil {
  1175. return nil, fmt.Errorf("get old repository path: %v", err)
  1176. }
  1177. repoPath := RepoPath(u.Name, repo.Name)
  1178. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1179. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1180. "git", "clone", "--bare", oldRepoPath, repoPath)
  1181. if err != nil {
  1182. return nil, fmt.Errorf("git clone: %v", stderr)
  1183. }
  1184. _, stderr, err = process.ExecDir(-1,
  1185. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1186. "git", "update-server-info")
  1187. if err != nil {
  1188. return nil, fmt.Errorf("git update-server-info: %v", err)
  1189. }
  1190. return repo, sess.Commit()
  1191. }