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.

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