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.

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