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.

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