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.

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