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.

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