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.

1763 lines
49 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
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 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
9 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
9 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
9 years ago
9 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. "bytes"
  7. "errors"
  8. "fmt"
  9. "html/template"
  10. "io/ioutil"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "regexp"
  16. "sort"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/Unknwon/cae/zip"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. "github.com/gogits/gogs/modules/base"
  24. "github.com/gogits/gogs/modules/bindata"
  25. "github.com/gogits/gogs/modules/git"
  26. "github.com/gogits/gogs/modules/log"
  27. "github.com/gogits/gogs/modules/process"
  28. "github.com/gogits/gogs/modules/setting"
  29. )
  30. const (
  31. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  32. )
  33. var (
  34. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  35. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  36. ErrMirrorNotExist = errors.New("Mirror does not exist")
  37. ErrInvalidReference = errors.New("Invalid reference specified")
  38. ErrNameEmpty = errors.New("Name is empty")
  39. )
  40. var (
  41. Gitignores, Licenses, Readmes []string
  42. )
  43. func LoadRepoConfig() {
  44. // Load .gitignore and license files and readme templates.
  45. types := []string{"gitignore", "license", "readme"}
  46. typeFiles := make([][]string, 3)
  47. for i, t := range types {
  48. files, err := bindata.AssetDir("conf/" + t)
  49. if err != nil {
  50. log.Fatal(4, "Fail to get %s files: %v", t, err)
  51. }
  52. customPath := path.Join(setting.CustomPath, "conf", t)
  53. if com.IsDir(customPath) {
  54. customFiles, err := com.StatDir(customPath)
  55. if err != nil {
  56. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  57. }
  58. for _, f := range customFiles {
  59. if !com.IsSliceContainsStr(files, f) {
  60. files = append(files, f)
  61. }
  62. }
  63. }
  64. typeFiles[i] = files
  65. }
  66. Gitignores = typeFiles[0]
  67. Licenses = typeFiles[1]
  68. Readmes = typeFiles[2]
  69. sort.Strings(Gitignores)
  70. sort.Strings(Licenses)
  71. sort.Strings(Readmes)
  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 `xorm:"pk autoincr"`
  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. BaseRepo *Repository `xorm:"-"`
  141. Created time.Time `xorm:"CREATED"`
  142. Updated time.Time `xorm:"UPDATED"`
  143. }
  144. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
  145. switch colName {
  146. case "num_closed_issues":
  147. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  148. case "num_closed_pulls":
  149. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  150. case "num_closed_milestones":
  151. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  152. case "updated":
  153. repo.Updated = regulateTimeZone(repo.Updated)
  154. }
  155. }
  156. func (repo *Repository) getOwner(e Engine) (err error) {
  157. if repo.Owner == nil {
  158. repo.Owner, err = getUserByID(e, repo.OwnerID)
  159. }
  160. return err
  161. }
  162. func (repo *Repository) GetOwner() error {
  163. return repo.getOwner(x)
  164. }
  165. // GetAssignees returns all users that have write access of repository.
  166. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  167. if err = repo.GetOwner(); err != nil {
  168. return nil, err
  169. }
  170. accesses := make([]*Access, 0, 10)
  171. if err = x.Where("repo_id=? AND mode>=?", repo.ID, ACCESS_MODE_WRITE).Find(&accesses); err != nil {
  172. return nil, err
  173. }
  174. users := make([]*User, 0, len(accesses)+1) // Just waste 1 unit does not matter.
  175. if !repo.Owner.IsOrganization() {
  176. users = append(users, repo.Owner)
  177. }
  178. var u *User
  179. for i := range accesses {
  180. u, err = GetUserByID(accesses[i].UserID)
  181. if err != nil {
  182. return nil, err
  183. }
  184. users = append(users, u)
  185. }
  186. return users, nil
  187. }
  188. // GetAssigneeByID returns the user that has write access of repository by given ID.
  189. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  190. return GetAssigneeByID(repo, userID)
  191. }
  192. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  193. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  194. return GetRepoMilestoneByID(repo.ID, milestoneID)
  195. }
  196. // IssueStats returns number of open and closed repository issues by given filter mode.
  197. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  198. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  199. }
  200. func (repo *Repository) GetMirror() (err error) {
  201. repo.Mirror, err = GetMirror(repo.ID)
  202. return err
  203. }
  204. func (repo *Repository) GetBaseRepo() (err error) {
  205. if !repo.IsFork {
  206. return nil
  207. }
  208. repo.BaseRepo, err = GetRepositoryByID(repo.ForkID)
  209. return err
  210. }
  211. func (repo *Repository) repoPath(e Engine) (string, error) {
  212. if err := repo.getOwner(e); err != nil {
  213. return "", err
  214. }
  215. return RepoPath(repo.Owner.Name, repo.Name), nil
  216. }
  217. func (repo *Repository) RepoPath() (string, error) {
  218. return repo.repoPath(x)
  219. }
  220. func (repo *Repository) RepoLink() (string, error) {
  221. if err := repo.GetOwner(); err != nil {
  222. return "", err
  223. }
  224. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  225. }
  226. func (repo *Repository) HasAccess(u *User) bool {
  227. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  228. return has
  229. }
  230. func (repo *Repository) IsOwnedBy(userID int64) bool {
  231. return repo.OwnerID == userID
  232. }
  233. // CanBeForked returns true if repository meets the requirements of being forked.
  234. func (repo *Repository) CanBeForked() bool {
  235. return !repo.IsBare && !repo.IsMirror
  236. }
  237. func (repo *Repository) NextIssueIndex() int64 {
  238. return int64(repo.NumIssues+repo.NumPulls) + 1
  239. }
  240. var (
  241. DescPattern = regexp.MustCompile(`https?://\S+`)
  242. )
  243. // DescriptionHtml does special handles to description and return HTML string.
  244. func (repo *Repository) DescriptionHtml() template.HTML {
  245. sanitize := func(s string) string {
  246. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  247. }
  248. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  249. }
  250. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  251. has, err := e.Get(&Repository{
  252. OwnerID: u.Id,
  253. LowerName: strings.ToLower(repoName),
  254. })
  255. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  256. }
  257. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  258. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  259. return isRepositoryExist(x, u, repoName)
  260. }
  261. // CloneLink represents different types of clone URLs of repository.
  262. type CloneLink struct {
  263. SSH string
  264. HTTPS string
  265. Git string
  266. }
  267. // CloneLink returns clone URLs of repository.
  268. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  269. if err = repo.GetOwner(); err != nil {
  270. return cl, err
  271. }
  272. if setting.SSHPort != 22 {
  273. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSHDomain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  274. } else {
  275. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSHDomain, repo.Owner.LowerName, repo.LowerName)
  276. }
  277. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  278. return cl, nil
  279. }
  280. var (
  281. reservedNames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  282. reservedPatterns = []string{"*.git", "*.keys"}
  283. )
  284. // IsUsableName checks if name is reserved or pattern of name is not allowed.
  285. func IsUsableName(name string) error {
  286. name = strings.TrimSpace(strings.ToLower(name))
  287. if utf8.RuneCountInString(name) == 0 {
  288. return ErrNameEmpty
  289. }
  290. for i := range reservedNames {
  291. if name == reservedNames[i] {
  292. return ErrNameReserved{name}
  293. }
  294. }
  295. for _, pat := range reservedPatterns {
  296. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  297. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  298. return ErrNamePatternNotAllowed{pat}
  299. }
  300. }
  301. return nil
  302. }
  303. // Mirror represents a mirror information of repository.
  304. type Mirror struct {
  305. ID int64 `xorm:"pk autoincr"`
  306. RepoID int64
  307. Repo *Repository `xorm:"-"`
  308. Interval int // Hour.
  309. Updated time.Time `xorm:"UPDATED"`
  310. NextUpdate time.Time
  311. }
  312. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  313. var err error
  314. switch colName {
  315. case "repo_id":
  316. m.Repo, err = GetRepositoryByID(m.RepoID)
  317. if err != nil {
  318. log.Error(3, "GetRepositoryByID[%d]: %v", m.ID, err)
  319. }
  320. }
  321. }
  322. func getMirror(e Engine, repoId int64) (*Mirror, error) {
  323. m := &Mirror{RepoID: repoId}
  324. has, err := e.Get(m)
  325. if err != nil {
  326. return nil, err
  327. } else if !has {
  328. return nil, ErrMirrorNotExist
  329. }
  330. return m, nil
  331. }
  332. // GetMirror returns mirror object by given repository ID.
  333. func GetMirror(repoId int64) (*Mirror, error) {
  334. return getMirror(x, repoId)
  335. }
  336. func updateMirror(e Engine, m *Mirror) error {
  337. _, err := e.Id(m.ID).Update(m)
  338. return err
  339. }
  340. func UpdateMirror(m *Mirror) error {
  341. return updateMirror(x, m)
  342. }
  343. // MirrorRepository creates a mirror repository from source.
  344. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  345. _, stderr, err := process.ExecTimeout(10*time.Minute,
  346. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  347. "git", "clone", "--mirror", url, repoPath)
  348. if err != nil {
  349. return errors.New("git clone --mirror: " + stderr)
  350. }
  351. if _, err = x.InsertOne(&Mirror{
  352. RepoID: repoId,
  353. Interval: 24,
  354. NextUpdate: time.Now().Add(24 * time.Hour),
  355. }); err != nil {
  356. return err
  357. }
  358. return nil
  359. }
  360. // MigrateRepository migrates a existing repository from other project hosting.
  361. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  362. repo, err := CreateRepository(u, CreateRepoOptions{
  363. Name: name,
  364. Description: desc,
  365. IsPrivate: private,
  366. IsMirror: mirror,
  367. })
  368. if err != nil {
  369. return nil, err
  370. }
  371. // Clone to temprory path and do the init commit.
  372. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  373. os.MkdirAll(tmpDir, os.ModePerm)
  374. repoPath := RepoPath(u.Name, name)
  375. if u.IsOrganization() {
  376. t, err := u.GetOwnerTeam()
  377. if err != nil {
  378. return nil, err
  379. }
  380. repo.NumWatches = t.NumMembers
  381. } else {
  382. repo.NumWatches = 1
  383. }
  384. repo.IsBare = false
  385. if mirror {
  386. if err = MirrorRepository(repo.ID, u.Name, repo.Name, repoPath, url); err != nil {
  387. return repo, err
  388. }
  389. repo.IsMirror = true
  390. return repo, UpdateRepository(repo, false)
  391. } else {
  392. os.RemoveAll(repoPath)
  393. }
  394. // FIXME: this command could for both migrate and mirror
  395. _, stderr, err := process.ExecTimeout(10*time.Minute,
  396. fmt.Sprintf("MigrateRepository: %s", repoPath),
  397. "git", "clone", "--mirror", "--bare", "--quiet", url, repoPath)
  398. if err != nil {
  399. return repo, fmt.Errorf("git clone --mirror --bare --quiet: %v", stderr)
  400. } else if err = createUpdateHook(repoPath); err != nil {
  401. return repo, fmt.Errorf("create update hook: %v", err)
  402. }
  403. // Check if repository is empty.
  404. _, stderr, err = com.ExecCmdDir(repoPath, "git", "log", "-1")
  405. if err != nil {
  406. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  407. repo.IsBare = true
  408. } else {
  409. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  410. }
  411. }
  412. // Check if repository has master branch, if so set it to default branch.
  413. gitRepo, err := git.OpenRepository(repoPath)
  414. if err != nil {
  415. return repo, fmt.Errorf("open git repository: %v", err)
  416. }
  417. if gitRepo.IsBranchExist("master") {
  418. repo.DefaultBranch = "master"
  419. }
  420. return repo, UpdateRepository(repo, false)
  421. }
  422. // initRepoCommit temporarily changes with work directory.
  423. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  424. var stderr string
  425. if _, stderr, err = process.ExecDir(-1,
  426. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  427. "git", "add", "--all"); err != nil {
  428. return fmt.Errorf("git add: %s", stderr)
  429. }
  430. if _, stderr, err = process.ExecDir(-1,
  431. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  432. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  433. "-m", "initial commit"); err != nil {
  434. return fmt.Errorf("git commit: %s", stderr)
  435. }
  436. if _, stderr, err = process.ExecDir(-1,
  437. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  438. "git", "push", "origin", "master"); err != nil {
  439. return fmt.Errorf("git push: %s", stderr)
  440. }
  441. return nil
  442. }
  443. func createUpdateHook(repoPath string) error {
  444. hookPath := path.Join(repoPath, "hooks/update")
  445. os.MkdirAll(path.Dir(hookPath), os.ModePerm)
  446. return ioutil.WriteFile(hookPath,
  447. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  448. }
  449. type CreateRepoOptions struct {
  450. Name string
  451. Description string
  452. Gitignores string
  453. License string
  454. Readme string
  455. IsPrivate bool
  456. IsMirror bool
  457. AutoInit bool
  458. }
  459. func getRepoInitFile(tp, name string) ([]byte, error) {
  460. relPath := path.Join("conf", tp, name)
  461. // Use custom file when available.
  462. customPath := path.Join(setting.CustomPath, relPath)
  463. if com.IsFile(customPath) {
  464. return ioutil.ReadFile(customPath)
  465. }
  466. return bindata.Asset(relPath)
  467. }
  468. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  469. // Clone to temprory path and do the init commit.
  470. _, stderr, err := process.Exec(
  471. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  472. if err != nil {
  473. return fmt.Errorf("git clone: %v - %s", err, stderr)
  474. }
  475. // README
  476. data, err := getRepoInitFile("readme", opts.Readme)
  477. if err != nil {
  478. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  479. }
  480. cloneLink, err := repo.CloneLink()
  481. if err != nil {
  482. return fmt.Errorf("CloneLink: %v", err)
  483. }
  484. match := map[string]string{
  485. "Name": repo.Name,
  486. "Description": repo.Description,
  487. "CloneURL.SSH": cloneLink.SSH,
  488. "CloneURL.HTTPS": cloneLink.HTTPS,
  489. }
  490. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  491. []byte(com.Expand(string(data), match)), 0644); err != nil {
  492. return fmt.Errorf("write README.md: %v", err)
  493. }
  494. // .gitignore
  495. if len(opts.Gitignores) > 0 {
  496. var buf bytes.Buffer
  497. names := strings.Split(opts.Gitignores, ",")
  498. for _, name := range names {
  499. data, err = getRepoInitFile("gitignore", name)
  500. if err != nil {
  501. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  502. }
  503. buf.WriteString("# ---> " + name + "\n")
  504. buf.Write(data)
  505. buf.WriteString("\n")
  506. }
  507. if buf.Len() > 0 {
  508. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  509. return fmt.Errorf("write .gitignore: %v", err)
  510. }
  511. }
  512. }
  513. // LICENSE
  514. if len(opts.License) > 0 {
  515. data, err = getRepoInitFile("license", opts.License)
  516. if err != nil {
  517. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  518. }
  519. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  520. return fmt.Errorf("write LICENSE: %v", err)
  521. }
  522. }
  523. return nil
  524. }
  525. // InitRepository initializes README and .gitignore if needed.
  526. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) error {
  527. // Somehow the directory could exist.
  528. if com.IsExist(repoPath) {
  529. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  530. }
  531. // Init bare new repository.
  532. os.MkdirAll(repoPath, os.ModePerm)
  533. _, stderr, err := process.ExecDir(-1, repoPath,
  534. fmt.Sprintf("initRepository(git init --bare): %s", repoPath), "git", "init", "--bare")
  535. if err != nil {
  536. return fmt.Errorf("git init --bare: %v - %s", err, stderr)
  537. }
  538. if err := createUpdateHook(repoPath); err != nil {
  539. return err
  540. }
  541. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  542. // Initialize repository according to user's choice.
  543. if opts.AutoInit {
  544. os.MkdirAll(tmpDir, os.ModePerm)
  545. defer os.RemoveAll(tmpDir)
  546. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  547. return fmt.Errorf("prepareRepoCommit: %v", err)
  548. }
  549. // Apply changes and commit.
  550. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  551. return fmt.Errorf("initRepoCommit: %v", err)
  552. }
  553. }
  554. // Re-fetch the repository from database before updating it (else it would
  555. // override changes that were done earlier with sql)
  556. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  557. return fmt.Errorf("getRepositoryByID: %v", err)
  558. }
  559. if !opts.AutoInit {
  560. repo.IsBare = true
  561. }
  562. repo.DefaultBranch = "master"
  563. if err = updateRepository(e, repo, false); err != nil {
  564. return fmt.Errorf("updateRepository: %v", err)
  565. }
  566. return nil
  567. }
  568. func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
  569. if err = IsUsableName(repo.Name); err != nil {
  570. return err
  571. }
  572. has, err := isRepositoryExist(e, u, repo.Name)
  573. if err != nil {
  574. return fmt.Errorf("IsRepositoryExist: %v", err)
  575. } else if has {
  576. return ErrRepoAlreadyExist{u.Name, repo.Name}
  577. }
  578. if _, err = e.Insert(repo); err != nil {
  579. return err
  580. }
  581. u.NumRepos++
  582. // Remember visibility preference.
  583. u.LastRepoVisibility = repo.IsPrivate
  584. if err = updateUser(e, u); err != nil {
  585. return fmt.Errorf("updateUser: %v", err)
  586. }
  587. // Give access to all members in owner team.
  588. if u.IsOrganization() {
  589. t, err := u.getOwnerTeam(e)
  590. if err != nil {
  591. return fmt.Errorf("getOwnerTeam: %v", err)
  592. } else if err = t.addRepository(e, repo); err != nil {
  593. return fmt.Errorf("addRepository: %v", err)
  594. }
  595. } else {
  596. // Organization automatically called this in addRepository method.
  597. if err = repo.recalculateAccesses(e); err != nil {
  598. return fmt.Errorf("recalculateAccesses: %v", err)
  599. }
  600. }
  601. if err = watchRepo(e, u.Id, repo.ID, true); err != nil {
  602. return fmt.Errorf("watchRepo: %v", err)
  603. } else if err = newRepoAction(e, u, repo); err != nil {
  604. return fmt.Errorf("newRepoAction: %v", err)
  605. }
  606. return nil
  607. }
  608. // CreateRepository creates a repository for given user or organization.
  609. func CreateRepository(u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  610. repo := &Repository{
  611. OwnerID: u.Id,
  612. Owner: u,
  613. Name: opts.Name,
  614. LowerName: strings.ToLower(opts.Name),
  615. Description: opts.Description,
  616. IsPrivate: opts.IsPrivate,
  617. }
  618. sess := x.NewSession()
  619. defer sessionRelease(sess)
  620. if err = sess.Begin(); err != nil {
  621. return nil, err
  622. }
  623. if err = createRepository(sess, u, repo); err != nil {
  624. return nil, err
  625. }
  626. // No need for init mirror.
  627. if !opts.IsMirror {
  628. repoPath := RepoPath(u.Name, repo.Name)
  629. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  630. if err2 := os.RemoveAll(repoPath); err2 != nil {
  631. log.Error(4, "initRepository: %v", err)
  632. return nil, fmt.Errorf(
  633. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  634. }
  635. return nil, fmt.Errorf("initRepository: %v", err)
  636. }
  637. _, stderr, err := process.ExecDir(-1,
  638. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  639. "git", "update-server-info")
  640. if err != nil {
  641. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  642. }
  643. }
  644. return repo, sess.Commit()
  645. }
  646. func countRepositories(showPrivate bool) int64 {
  647. sess := x.NewSession()
  648. if !showPrivate {
  649. sess.Where("is_private=", false)
  650. }
  651. count, _ := sess.Count(new(Repository))
  652. return count
  653. }
  654. // CountRepositories returns number of repositories.
  655. func CountRepositories() int64 {
  656. return countRepositories(true)
  657. }
  658. // CountPublicRepositories returns number of public repositories.
  659. func CountPublicRepositories() int64 {
  660. return countRepositories(false)
  661. }
  662. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  663. // It also auto-gets corresponding users.
  664. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  665. repos := make([]*Repository, 0, num)
  666. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  667. return nil, err
  668. }
  669. for _, repo := range repos {
  670. repo.Owner = &User{Id: repo.OwnerID}
  671. has, err := x.Get(repo.Owner)
  672. if err != nil {
  673. return nil, err
  674. } else if !has {
  675. return nil, ErrUserNotExist{repo.OwnerID, ""}
  676. }
  677. }
  678. return repos, nil
  679. }
  680. // RepoPath returns repository path by given user and repository name.
  681. func RepoPath(userName, repoName string) string {
  682. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  683. }
  684. // TransferOwnership transfers all corresponding setting from old user to new one.
  685. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  686. newOwner, err := GetUserByName(newOwnerName)
  687. if err != nil {
  688. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  689. }
  690. // Check if new owner has repository with same name.
  691. has, err := IsRepositoryExist(newOwner, repo.Name)
  692. if err != nil {
  693. return fmt.Errorf("IsRepositoryExist: %v", err)
  694. } else if has {
  695. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  696. }
  697. sess := x.NewSession()
  698. defer sessionRelease(sess)
  699. if err = sess.Begin(); err != nil {
  700. return fmt.Errorf("sess.Begin: %v", err)
  701. }
  702. owner := repo.Owner
  703. // Note: we have to set value here to make sure recalculate accesses is based on
  704. // new owner.
  705. repo.OwnerID = newOwner.Id
  706. repo.Owner = newOwner
  707. // Update repository.
  708. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  709. return fmt.Errorf("update owner: %v", err)
  710. }
  711. // Remove redundant collaborators.
  712. collaborators, err := repo.GetCollaborators()
  713. if err != nil {
  714. return fmt.Errorf("GetCollaborators: %v", err)
  715. }
  716. // Dummy object.
  717. collaboration := &Collaboration{RepoID: repo.ID}
  718. for _, c := range collaborators {
  719. collaboration.UserID = c.Id
  720. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  721. if _, err = sess.Delete(collaboration); err != nil {
  722. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  723. }
  724. }
  725. }
  726. // Remove old team-repository relations.
  727. if owner.IsOrganization() {
  728. if err = owner.getTeams(sess); err != nil {
  729. return fmt.Errorf("getTeams: %v", err)
  730. }
  731. for _, t := range owner.Teams {
  732. if !t.hasRepository(sess, repo.ID) {
  733. continue
  734. }
  735. t.NumRepos--
  736. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  737. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  738. }
  739. }
  740. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  741. return fmt.Errorf("removeOrgRepo: %v", err)
  742. }
  743. }
  744. if newOwner.IsOrganization() {
  745. t, err := newOwner.GetOwnerTeam()
  746. if err != nil {
  747. return fmt.Errorf("GetOwnerTeam: %v", err)
  748. } else if err = t.addRepository(sess, repo); err != nil {
  749. return fmt.Errorf("add to owner team: %v", err)
  750. }
  751. } else {
  752. // Organization called this in addRepository method.
  753. if err = repo.recalculateAccesses(sess); err != nil {
  754. return fmt.Errorf("recalculateAccesses: %v", err)
  755. }
  756. }
  757. // Update repository count.
  758. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  759. return fmt.Errorf("increase new owner repository count: %v", err)
  760. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  761. return fmt.Errorf("decrease old owner repository count: %v", err)
  762. }
  763. if err = watchRepo(sess, newOwner.Id, repo.ID, true); err != nil {
  764. return fmt.Errorf("watchRepo: %v", err)
  765. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  766. return fmt.Errorf("transferRepoAction: %v", err)
  767. }
  768. // Change repository directory name.
  769. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  770. return fmt.Errorf("rename directory: %v", err)
  771. }
  772. return sess.Commit()
  773. }
  774. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  775. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  776. oldRepoName = strings.ToLower(oldRepoName)
  777. newRepoName = strings.ToLower(newRepoName)
  778. if err = IsUsableName(newRepoName); err != nil {
  779. return err
  780. }
  781. has, err := IsRepositoryExist(u, newRepoName)
  782. if err != nil {
  783. return fmt.Errorf("IsRepositoryExist: %v", err)
  784. } else if has {
  785. return ErrRepoAlreadyExist{u.Name, newRepoName}
  786. }
  787. // Change repository directory name.
  788. return os.Rename(RepoPath(u.LowerName, oldRepoName), RepoPath(u.LowerName, newRepoName))
  789. }
  790. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  791. repos := make([]*Repository, 0, 10)
  792. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  793. }
  794. // GetRepositoriesByForkID returns all repositories with given fork ID.
  795. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  796. return getRepositoriesByForkID(x, forkID)
  797. }
  798. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  799. repo.LowerName = strings.ToLower(repo.Name)
  800. if len(repo.Description) > 255 {
  801. repo.Description = repo.Description[:255]
  802. }
  803. if len(repo.Website) > 255 {
  804. repo.Website = repo.Website[:255]
  805. }
  806. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  807. return fmt.Errorf("update: %v", err)
  808. }
  809. if visibilityChanged {
  810. if err = repo.getOwner(e); err != nil {
  811. return fmt.Errorf("getOwner: %v", err)
  812. }
  813. if !repo.Owner.IsOrganization() {
  814. return nil
  815. }
  816. // Organization repository need to recalculate access table when visivility is changed.
  817. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  818. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  819. }
  820. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  821. if err != nil {
  822. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  823. }
  824. for i := range forkRepos {
  825. forkRepos[i].IsPrivate = repo.IsPrivate
  826. if err = updateRepository(e, forkRepos[i], true); err != nil {
  827. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  828. }
  829. }
  830. }
  831. return nil
  832. }
  833. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  834. sess := x.NewSession()
  835. defer sessionRelease(sess)
  836. if err = sess.Begin(); err != nil {
  837. return err
  838. }
  839. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  840. return fmt.Errorf("updateRepository: %v", err)
  841. }
  842. return sess.Commit()
  843. }
  844. // DeleteRepository deletes a repository for a user or organization.
  845. func DeleteRepository(uid, repoID int64) error {
  846. repo := &Repository{ID: repoID, OwnerID: uid}
  847. has, err := x.Get(repo)
  848. if err != nil {
  849. return err
  850. } else if !has {
  851. return ErrRepoNotExist{repoID, uid, ""}
  852. }
  853. // In case is a organization.
  854. org, err := GetUserByID(uid)
  855. if err != nil {
  856. return err
  857. }
  858. if org.IsOrganization() {
  859. if err = org.GetTeams(); err != nil {
  860. return err
  861. }
  862. }
  863. sess := x.NewSession()
  864. defer sessionRelease(sess)
  865. if err = sess.Begin(); err != nil {
  866. return err
  867. }
  868. if org.IsOrganization() {
  869. for _, t := range org.Teams {
  870. if !t.hasRepository(sess, repoID) {
  871. continue
  872. } else if err = t.removeRepository(sess, repo, false); err != nil {
  873. return err
  874. }
  875. }
  876. }
  877. if _, err = sess.Delete(&Repository{ID: repoID}); err != nil {
  878. return err
  879. } else if _, err = sess.Delete(&Access{RepoID: repo.ID}); err != nil {
  880. return err
  881. } else if _, err = sess.Delete(&Action{RepoID: repo.ID}); err != nil {
  882. return err
  883. } else if _, err = sess.Delete(&Watch{RepoID: repoID}); err != nil {
  884. return err
  885. } else if _, err = sess.Delete(&Mirror{RepoID: repoID}); err != nil {
  886. return err
  887. } else if _, err = sess.Delete(&IssueUser{RepoID: repoID}); err != nil {
  888. return err
  889. } else if _, err = sess.Delete(&Milestone{RepoID: repoID}); err != nil {
  890. return err
  891. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  892. return err
  893. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  894. return err
  895. } else if _, err = sess.Delete(&PullRequest{BaseRepoID: repoID}); err != nil {
  896. return err
  897. }
  898. // Delete comments and attachments.
  899. issues := make([]*Issue, 0, 25)
  900. attachmentPaths := make([]string, 0, len(issues))
  901. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  902. return err
  903. }
  904. for i := range issues {
  905. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  906. return err
  907. }
  908. attachments := make([]*Attachment, 0, 5)
  909. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  910. return err
  911. }
  912. for j := range attachments {
  913. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  914. }
  915. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  916. return err
  917. }
  918. }
  919. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  920. return err
  921. }
  922. if repo.IsFork {
  923. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  924. return fmt.Errorf("decrease fork count: %v", err)
  925. }
  926. }
  927. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  928. return err
  929. }
  930. // Remove repository files.
  931. repoPath, err := repo.repoPath(sess)
  932. if err != nil {
  933. return fmt.Errorf("RepoPath: %v", err)
  934. }
  935. if err = os.RemoveAll(repoPath); err != nil {
  936. desc := fmt.Sprintf("delete repository files[%s]: %v", repoPath, err)
  937. log.Warn(desc)
  938. if err = CreateRepositoryNotice(desc); err != nil {
  939. log.Error(4, "add notice: %v", err)
  940. }
  941. }
  942. // Remove attachment files.
  943. for i := range attachmentPaths {
  944. if err = os.Remove(attachmentPaths[i]); err != nil {
  945. log.Warn("delete attachment: %v", err)
  946. }
  947. }
  948. if err = sess.Commit(); err != nil {
  949. return fmt.Errorf("Commit: %v", err)
  950. }
  951. if repo.NumForks > 0 {
  952. if repo.IsPrivate {
  953. forkRepos, err := GetRepositoriesByForkID(repo.ID)
  954. if err != nil {
  955. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  956. }
  957. for i := range forkRepos {
  958. if err = DeleteRepository(forkRepos[i].OwnerID, forkRepos[i].ID); err != nil {
  959. log.Error(4, "updateRepository[%d]: %v", forkRepos[i].ID, err)
  960. }
  961. }
  962. } else {
  963. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  964. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  965. }
  966. }
  967. }
  968. return nil
  969. }
  970. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  971. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  972. func GetRepositoryByRef(ref string) (*Repository, error) {
  973. n := strings.IndexByte(ref, byte('/'))
  974. if n < 2 {
  975. return nil, ErrInvalidReference
  976. }
  977. userName, repoName := ref[:n], ref[n+1:]
  978. user, err := GetUserByName(userName)
  979. if err != nil {
  980. return nil, err
  981. }
  982. return GetRepositoryByName(user.Id, repoName)
  983. }
  984. // GetRepositoryByName returns the repository by given name under user if exists.
  985. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  986. repo := &Repository{
  987. OwnerID: uid,
  988. LowerName: strings.ToLower(repoName),
  989. }
  990. has, err := x.Get(repo)
  991. if err != nil {
  992. return nil, err
  993. } else if !has {
  994. return nil, ErrRepoNotExist{0, uid, repoName}
  995. }
  996. return repo, err
  997. }
  998. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  999. repo := new(Repository)
  1000. has, err := e.Id(id).Get(repo)
  1001. if err != nil {
  1002. return nil, err
  1003. } else if !has {
  1004. return nil, ErrRepoNotExist{id, 0, ""}
  1005. }
  1006. return repo, nil
  1007. }
  1008. // GetRepositoryByID returns the repository by given id if exists.
  1009. func GetRepositoryByID(id int64) (*Repository, error) {
  1010. return getRepositoryByID(x, id)
  1011. }
  1012. // GetRepositories returns a list of repositories of given user.
  1013. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  1014. repos := make([]*Repository, 0, 10)
  1015. sess := x.Desc("updated")
  1016. if !private {
  1017. sess.Where("is_private=?", false)
  1018. }
  1019. return repos, sess.Find(&repos, &Repository{OwnerID: uid})
  1020. }
  1021. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1022. func GetRecentUpdatedRepositories(page int) (repos []*Repository, err error) {
  1023. return repos, x.Limit(setting.ExplorePagingNum, (page-1)*setting.ExplorePagingNum).
  1024. Where("is_private=?", false).Limit(setting.ExplorePagingNum).Desc("updated").Find(&repos)
  1025. }
  1026. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1027. return x.Count(&Repository{OwnerID: u.Id})
  1028. }
  1029. // GetRepositoryCount returns the total number of repositories of user.
  1030. func GetRepositoryCount(u *User) (int64, error) {
  1031. return getRepositoryCount(x, u)
  1032. }
  1033. type SearchOption struct {
  1034. Keyword string
  1035. Uid int64
  1036. Limit int
  1037. Private bool
  1038. }
  1039. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  1040. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  1041. if len(opt.Keyword) == 0 {
  1042. return repos, nil
  1043. }
  1044. opt.Keyword = strings.ToLower(opt.Keyword)
  1045. repos = make([]*Repository, 0, opt.Limit)
  1046. // Append conditions.
  1047. sess := x.Limit(opt.Limit)
  1048. if opt.Uid > 0 {
  1049. sess.Where("owner_id=?", opt.Uid)
  1050. }
  1051. if !opt.Private {
  1052. sess.And("is_private=false")
  1053. }
  1054. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  1055. return repos, err
  1056. }
  1057. // DeleteRepositoryArchives deletes all repositories' archives.
  1058. func DeleteRepositoryArchives() error {
  1059. return x.Where("id > 0").Iterate(new(Repository),
  1060. func(idx int, bean interface{}) error {
  1061. repo := bean.(*Repository)
  1062. if err := repo.GetOwner(); err != nil {
  1063. return err
  1064. }
  1065. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  1066. })
  1067. }
  1068. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1069. func RewriteRepositoryUpdateHook() error {
  1070. return 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. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  1077. })
  1078. }
  1079. var (
  1080. // Prevent duplicate running tasks.
  1081. isMirrorUpdating = false
  1082. isGitFscking = false
  1083. isCheckingRepos = false
  1084. )
  1085. // MirrorUpdate checks and updates mirror repositories.
  1086. func MirrorUpdate() {
  1087. if isMirrorUpdating {
  1088. return
  1089. }
  1090. isMirrorUpdating = true
  1091. defer func() { isMirrorUpdating = false }()
  1092. log.Trace("Doing: MirrorUpdate")
  1093. mirrors := make([]*Mirror, 0, 10)
  1094. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1095. m := bean.(*Mirror)
  1096. if m.NextUpdate.After(time.Now()) {
  1097. return nil
  1098. }
  1099. if m.Repo == nil {
  1100. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1101. return nil
  1102. }
  1103. repoPath, err := m.Repo.RepoPath()
  1104. if err != nil {
  1105. return fmt.Errorf("Repo.RepoPath: %v", err)
  1106. }
  1107. if _, stderr, err := process.ExecDir(10*time.Minute,
  1108. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1109. "git", "remote", "update", "--prune"); err != nil {
  1110. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1111. log.Error(4, desc)
  1112. if err = CreateRepositoryNotice(desc); err != nil {
  1113. log.Error(4, "CreateRepositoryNotice: %v", err)
  1114. }
  1115. return nil
  1116. }
  1117. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1118. mirrors = append(mirrors, m)
  1119. return nil
  1120. }); err != nil {
  1121. log.Error(4, "MirrorUpdate: %v", err)
  1122. }
  1123. for i := range mirrors {
  1124. if err := UpdateMirror(mirrors[i]); err != nil {
  1125. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1126. }
  1127. }
  1128. }
  1129. // GitFsck calls 'git fsck' to check repository health.
  1130. func GitFsck() {
  1131. if isGitFscking {
  1132. return
  1133. }
  1134. isGitFscking = true
  1135. defer func() { isGitFscking = false }()
  1136. log.Trace("Doing: GitFsck")
  1137. args := append([]string{"fsck"}, setting.Cron.RepoHealthCheck.Args...)
  1138. if err := x.Where("id>0").Iterate(new(Repository),
  1139. func(idx int, bean interface{}) error {
  1140. repo := bean.(*Repository)
  1141. repoPath, err := repo.RepoPath()
  1142. if err != nil {
  1143. return fmt.Errorf("RepoPath: %v", err)
  1144. }
  1145. _, _, err = process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  1146. if err != nil {
  1147. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1148. log.Warn(desc)
  1149. if err = CreateRepositoryNotice(desc); err != nil {
  1150. log.Error(4, "CreateRepositoryNotice: %v", err)
  1151. }
  1152. }
  1153. return nil
  1154. }); err != nil {
  1155. log.Error(4, "GitFsck: %v", err)
  1156. }
  1157. }
  1158. func GitGcRepos() error {
  1159. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1160. return x.Where("id > 0").Iterate(new(Repository),
  1161. func(idx int, bean interface{}) error {
  1162. repo := bean.(*Repository)
  1163. if err := repo.GetOwner(); err != nil {
  1164. return err
  1165. }
  1166. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1167. if err != nil {
  1168. return fmt.Errorf("%v: %v", err, stderr)
  1169. }
  1170. return nil
  1171. })
  1172. }
  1173. type repoChecker struct {
  1174. querySQL, correctSQL string
  1175. desc string
  1176. }
  1177. func repoStatsCheck(checker *repoChecker) {
  1178. results, err := x.Query(checker.querySQL)
  1179. if err != nil {
  1180. log.Error(4, "Select %s: %v", checker.desc, err)
  1181. return
  1182. }
  1183. for _, result := range results {
  1184. id := com.StrTo(result["id"]).MustInt64()
  1185. log.Trace("Updating %s: %d", checker.desc, id)
  1186. _, err = x.Exec(checker.correctSQL, id, id)
  1187. if err != nil {
  1188. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1189. }
  1190. }
  1191. }
  1192. func CheckRepoStats() {
  1193. if isCheckingRepos {
  1194. return
  1195. }
  1196. isCheckingRepos = true
  1197. defer func() { isCheckingRepos = false }()
  1198. log.Trace("Doing: CheckRepoStats")
  1199. checkers := []*repoChecker{
  1200. // Repository.NumWatches
  1201. {
  1202. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1203. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1204. "repository count 'num_watches'",
  1205. },
  1206. // Repository.NumStars
  1207. {
  1208. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1209. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1210. "repository count 'num_stars'",
  1211. },
  1212. // Label.NumIssues
  1213. {
  1214. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1215. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1216. "label count 'num_issues'",
  1217. },
  1218. // User.NumRepos
  1219. {
  1220. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1221. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1222. "user count 'num_repos'",
  1223. },
  1224. }
  1225. for i := range checkers {
  1226. repoStatsCheck(checkers[i])
  1227. }
  1228. // FIXME: use checker when v0.8, stop supporting old fork repo format.
  1229. // ***** START: Repository.NumForks *****
  1230. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1231. if err != nil {
  1232. log.Error(4, "Select repository count 'num_forks': %v", err)
  1233. } else {
  1234. for _, result := range results {
  1235. id := com.StrTo(result["id"]).MustInt64()
  1236. log.Trace("Updating repository count 'num_forks': %d", id)
  1237. repo, err := GetRepositoryByID(id)
  1238. if err != nil {
  1239. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1240. continue
  1241. }
  1242. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1243. if err != nil {
  1244. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1245. continue
  1246. }
  1247. repo.NumForks = int(parseCountResult(rawResult))
  1248. if err = UpdateRepository(repo, false); err != nil {
  1249. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1250. continue
  1251. }
  1252. }
  1253. }
  1254. // ***** END: Repository.NumForks *****
  1255. }
  1256. // _________ .__ .__ ___. __ .__
  1257. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  1258. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  1259. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  1260. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  1261. // \/ \/ \/ \/ \/
  1262. // A Collaboration is a relation between an individual and a repository
  1263. type Collaboration struct {
  1264. ID int64 `xorm:"pk autoincr"`
  1265. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1266. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1267. Created time.Time `xorm:"CREATED"`
  1268. }
  1269. // Add collaborator and accompanying access
  1270. func (repo *Repository) AddCollaborator(u *User) error {
  1271. collaboration := &Collaboration{
  1272. RepoID: repo.ID,
  1273. UserID: u.Id,
  1274. }
  1275. has, err := x.Get(collaboration)
  1276. if err != nil {
  1277. return err
  1278. } else if has {
  1279. return nil
  1280. }
  1281. if err = repo.GetOwner(); err != nil {
  1282. return fmt.Errorf("GetOwner: %v", err)
  1283. }
  1284. sess := x.NewSession()
  1285. defer sessionRelease(sess)
  1286. if err = sess.Begin(); err != nil {
  1287. return err
  1288. }
  1289. if _, err = sess.InsertOne(collaboration); err != nil {
  1290. return err
  1291. }
  1292. if repo.Owner.IsOrganization() {
  1293. err = repo.recalculateTeamAccesses(sess, 0)
  1294. } else {
  1295. err = repo.recalculateAccesses(sess)
  1296. }
  1297. if err != nil {
  1298. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1299. }
  1300. return sess.Commit()
  1301. }
  1302. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1303. collaborations := make([]*Collaboration, 0)
  1304. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.ID}); err != nil {
  1305. return nil, err
  1306. }
  1307. users := make([]*User, len(collaborations))
  1308. for i, c := range collaborations {
  1309. user, err := getUserByID(e, c.UserID)
  1310. if err != nil {
  1311. return nil, err
  1312. }
  1313. users[i] = user
  1314. }
  1315. return users, nil
  1316. }
  1317. // GetCollaborators returns the collaborators for a repository
  1318. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1319. return repo.getCollaborators(x)
  1320. }
  1321. // Delete collaborator and accompanying access
  1322. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1323. collaboration := &Collaboration{
  1324. RepoID: repo.ID,
  1325. UserID: u.Id,
  1326. }
  1327. sess := x.NewSession()
  1328. defer sessionRelease(sess)
  1329. if err = sess.Begin(); err != nil {
  1330. return err
  1331. }
  1332. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1333. return err
  1334. } else if err = repo.recalculateAccesses(sess); err != nil {
  1335. return err
  1336. }
  1337. return sess.Commit()
  1338. }
  1339. // __ __ __ .__
  1340. // / \ / \_____ _/ |_ ____ | |__
  1341. // \ \/\/ /\__ \\ __\/ ___\| | \
  1342. // \ / / __ \| | \ \___| Y \
  1343. // \__/\ / (____ /__| \___ >___| /
  1344. // \/ \/ \/ \/
  1345. // Watch is connection request for receiving repository notification.
  1346. type Watch struct {
  1347. ID int64 `xorm:"pk autoincr"`
  1348. UserID int64 `xorm:"UNIQUE(watch)"`
  1349. RepoID int64 `xorm:"UNIQUE(watch)"`
  1350. }
  1351. // IsWatching checks if user has watched given repository.
  1352. func IsWatching(uid, repoId int64) bool {
  1353. has, _ := x.Get(&Watch{0, uid, repoId})
  1354. return has
  1355. }
  1356. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1357. if watch {
  1358. if IsWatching(uid, repoId) {
  1359. return nil
  1360. }
  1361. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1362. return err
  1363. }
  1364. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1365. } else {
  1366. if !IsWatching(uid, repoId) {
  1367. return nil
  1368. }
  1369. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1370. return err
  1371. }
  1372. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1373. }
  1374. return err
  1375. }
  1376. // Watch or unwatch repository.
  1377. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1378. return watchRepo(x, uid, repoId, watch)
  1379. }
  1380. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1381. watches := make([]*Watch, 0, 10)
  1382. err := e.Find(&watches, &Watch{RepoID: rid})
  1383. return watches, err
  1384. }
  1385. // GetWatchers returns all watchers of given repository.
  1386. func GetWatchers(rid int64) ([]*Watch, error) {
  1387. return getWatchers(x, rid)
  1388. }
  1389. func notifyWatchers(e Engine, act *Action) error {
  1390. // Add feeds for user self and all watchers.
  1391. watches, err := getWatchers(e, act.RepoID)
  1392. if err != nil {
  1393. return fmt.Errorf("get watchers: %v", err)
  1394. }
  1395. // Add feed for actioner.
  1396. act.UserID = act.ActUserID
  1397. if _, err = e.InsertOne(act); err != nil {
  1398. return fmt.Errorf("insert new actioner: %v", err)
  1399. }
  1400. for i := range watches {
  1401. if act.ActUserID == watches[i].UserID {
  1402. continue
  1403. }
  1404. act.ID = 0
  1405. act.UserID = watches[i].UserID
  1406. if _, err = e.InsertOne(act); err != nil {
  1407. return fmt.Errorf("insert new action: %v", err)
  1408. }
  1409. }
  1410. return nil
  1411. }
  1412. // NotifyWatchers creates batch of actions for every watcher.
  1413. func NotifyWatchers(act *Action) error {
  1414. return notifyWatchers(x, act)
  1415. }
  1416. // _________ __
  1417. // / _____// |______ _______
  1418. // \_____ \\ __\__ \\_ __ \
  1419. // / \| | / __ \| | \/
  1420. // /_______ /|__| (____ /__|
  1421. // \/ \/
  1422. type Star struct {
  1423. ID int64 `xorm:"pk autoincr"`
  1424. UID int64 `xorm:"uid UNIQUE(s)"`
  1425. RepoID int64 `xorm:"UNIQUE(s)"`
  1426. }
  1427. // Star or unstar repository.
  1428. func StarRepo(uid, repoId int64, star bool) (err error) {
  1429. if star {
  1430. if IsStaring(uid, repoId) {
  1431. return nil
  1432. }
  1433. if _, err = x.Insert(&Star{UID: uid, RepoID: repoId}); err != nil {
  1434. return err
  1435. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1436. return err
  1437. }
  1438. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1439. } else {
  1440. if !IsStaring(uid, repoId) {
  1441. return nil
  1442. }
  1443. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1444. return err
  1445. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1446. return err
  1447. }
  1448. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1449. }
  1450. return err
  1451. }
  1452. // IsStaring checks if user has starred given repository.
  1453. func IsStaring(uid, repoId int64) bool {
  1454. has, _ := x.Get(&Star{0, uid, repoId})
  1455. return has
  1456. }
  1457. // ___________ __
  1458. // \_ _____/__________| | __
  1459. // | __)/ _ \_ __ \ |/ /
  1460. // | \( <_> ) | \/ <
  1461. // \___ / \____/|__| |__|_ \
  1462. // \/ \/
  1463. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1464. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1465. repo := new(Repository)
  1466. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1467. return repo, has
  1468. }
  1469. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1470. repo := &Repository{
  1471. OwnerID: u.Id,
  1472. Owner: u,
  1473. Name: name,
  1474. LowerName: strings.ToLower(name),
  1475. Description: desc,
  1476. DefaultBranch: oldRepo.DefaultBranch,
  1477. IsPrivate: oldRepo.IsPrivate,
  1478. IsFork: true,
  1479. ForkID: oldRepo.ID,
  1480. }
  1481. sess := x.NewSession()
  1482. defer sessionRelease(sess)
  1483. if err = sess.Begin(); err != nil {
  1484. return nil, err
  1485. }
  1486. if err = createRepository(sess, u, repo); err != nil {
  1487. return nil, err
  1488. }
  1489. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1490. return nil, err
  1491. }
  1492. oldRepoPath, err := oldRepo.RepoPath()
  1493. if err != nil {
  1494. return nil, fmt.Errorf("get old repository path: %v", err)
  1495. }
  1496. repoPath := RepoPath(u.Name, repo.Name)
  1497. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1498. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1499. "git", "clone", "--bare", oldRepoPath, repoPath)
  1500. if err != nil {
  1501. return nil, fmt.Errorf("git clone: %v", stderr)
  1502. }
  1503. _, stderr, err = process.ExecDir(-1,
  1504. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1505. "git", "update-server-info")
  1506. if err != nil {
  1507. return nil, fmt.Errorf("git update-server-info: %v", err)
  1508. }
  1509. if err = createUpdateHook(repoPath); err != nil {
  1510. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1511. }
  1512. return repo, sess.Commit()
  1513. }