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.

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