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.

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