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.

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