本站源代码
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.

2817 lines
83KB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "bytes"
  8. "crypto/md5"
  9. "errors"
  10. "fmt"
  11. "html/template"
  12. // Needed for jpeg support
  13. _ "image/jpeg"
  14. "image/png"
  15. "io/ioutil"
  16. "net/url"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "code.gitea.io/gitea/modules/avatar"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/markup"
  28. "code.gitea.io/gitea/modules/options"
  29. "code.gitea.io/gitea/modules/process"
  30. "code.gitea.io/gitea/modules/setting"
  31. "code.gitea.io/gitea/modules/structs"
  32. api "code.gitea.io/gitea/modules/structs"
  33. "code.gitea.io/gitea/modules/sync"
  34. "code.gitea.io/gitea/modules/timeutil"
  35. "github.com/mcuadros/go-version"
  36. "github.com/unknwon/com"
  37. ini "gopkg.in/ini.v1"
  38. "xorm.io/builder"
  39. "xorm.io/xorm"
  40. )
  41. var repoWorkingPool = sync.NewExclusivePool()
  42. var (
  43. // ErrMirrorNotExist mirror does not exist error
  44. ErrMirrorNotExist = errors.New("Mirror does not exist")
  45. // ErrNameEmpty name is empty error
  46. ErrNameEmpty = errors.New("Name is empty")
  47. )
  48. var (
  49. // Gitignores contains the gitiginore files
  50. Gitignores []string
  51. // Licenses contains the license files
  52. Licenses []string
  53. // Readmes contains the readme files
  54. Readmes []string
  55. // LabelTemplates contains the label template files
  56. LabelTemplates []string
  57. // ItemsPerPage maximum items per page in forks, watchers and stars of a repo
  58. ItemsPerPage = 40
  59. )
  60. // loadRepoConfig loads the repository config
  61. func loadRepoConfig() {
  62. // Load .gitignore and license files and readme templates.
  63. types := []string{"gitignore", "license", "readme", "label"}
  64. typeFiles := make([][]string, 4)
  65. for i, t := range types {
  66. files, err := options.Dir(t)
  67. if err != nil {
  68. log.Fatal("Failed to get %s files: %v", t, err)
  69. }
  70. customPath := path.Join(setting.CustomPath, "options", t)
  71. if com.IsDir(customPath) {
  72. customFiles, err := com.StatDir(customPath)
  73. if err != nil {
  74. log.Fatal("Failed to get custom %s files: %v", t, err)
  75. }
  76. for _, f := range customFiles {
  77. if !com.IsSliceContainsStr(files, f) {
  78. files = append(files, f)
  79. }
  80. }
  81. }
  82. typeFiles[i] = files
  83. }
  84. Gitignores = typeFiles[0]
  85. Licenses = typeFiles[1]
  86. Readmes = typeFiles[2]
  87. LabelTemplates = typeFiles[3]
  88. sort.Strings(Gitignores)
  89. sort.Strings(Licenses)
  90. sort.Strings(Readmes)
  91. sort.Strings(LabelTemplates)
  92. // Filter out invalid names and promote preferred licenses.
  93. sortedLicenses := make([]string, 0, len(Licenses))
  94. for _, name := range setting.Repository.PreferredLicenses {
  95. if com.IsSliceContainsStr(Licenses, name) {
  96. sortedLicenses = append(sortedLicenses, name)
  97. }
  98. }
  99. for _, name := range Licenses {
  100. if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) {
  101. sortedLicenses = append(sortedLicenses, name)
  102. }
  103. }
  104. Licenses = sortedLicenses
  105. }
  106. // NewRepoContext creates a new repository context
  107. func NewRepoContext() {
  108. loadRepoConfig()
  109. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
  110. }
  111. // RepositoryStatus defines the status of repository
  112. type RepositoryStatus int
  113. // all kinds of RepositoryStatus
  114. const (
  115. RepositoryReady RepositoryStatus = iota // a normal repository
  116. RepositoryBeingMigrated // repository is migrating
  117. )
  118. // Repository represents a git repository.
  119. type Repository struct {
  120. ID int64 `xorm:"pk autoincr"`
  121. OwnerID int64 `xorm:"UNIQUE(s) index"`
  122. OwnerName string `xorm:"-"`
  123. Owner *User `xorm:"-"`
  124. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  125. Name string `xorm:"INDEX NOT NULL"`
  126. Description string `xorm:"TEXT"`
  127. Website string `xorm:"VARCHAR(2048)"`
  128. Percent int64
  129. Point int64
  130. FundingToCollaboration int64
  131. NextPoint int64
  132. OriginalServiceType structs.GitServiceType `xorm:"index"`
  133. OriginalURL string `xorm:"VARCHAR(2048)"`
  134. DefaultBranch string
  135. NumWatches int
  136. NumStars int
  137. NumForks int
  138. NumIssues int
  139. NumClosedIssues int
  140. NumOpenIssues int `xorm:"-"`
  141. NumPulls int
  142. NumClosedPulls int
  143. NumOpenPulls int `xorm:"-"`
  144. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  145. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  146. NumOpenMilestones int `xorm:"-"`
  147. NumReleases int `xorm:"-"`
  148. IsPrivate bool `xorm:"INDEX"`
  149. IsEmpty bool `xorm:"INDEX"`
  150. IsArchived bool `xorm:"INDEX"`
  151. IsMirror bool `xorm:"INDEX"`
  152. *Mirror `xorm:"-"`
  153. Status RepositoryStatus `xorm:"NOT NULL DEFAULT 0"`
  154. ExternalMetas map[string]string `xorm:"-"`
  155. Units []*RepoUnit `xorm:"-"`
  156. IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"`
  157. ForkID int64 `xorm:"INDEX"`
  158. BaseRepo *Repository `xorm:"-"`
  159. Size int64 `xorm:"NOT NULL DEFAULT 0"`
  160. IndexerStatus *RepoIndexerStatus `xorm:"-"`
  161. IsFsckEnabled bool `xorm:"NOT NULL DEFAULT true"`
  162. CloseIssuesViaCommitInAnyBranch bool `xorm:"NOT NULL DEFAULT false"`
  163. Topics []string `xorm:"TEXT JSON"`
  164. // Avatar: ID(10-20)-md5(32) - must fit into 64 symbols
  165. Avatar string `xorm:"VARCHAR(64)"`
  166. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  167. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  168. }
  169. // ColorFormat returns a colored string to represent this repo
  170. func (repo *Repository) ColorFormat(s fmt.State) {
  171. var ownerName interface{}
  172. if repo.OwnerName != "" {
  173. ownerName = repo.OwnerName
  174. } else if repo.Owner != nil {
  175. ownerName = repo.Owner.Name
  176. } else {
  177. ownerName = log.NewColoredIDValue(strconv.FormatInt(repo.OwnerID, 10))
  178. }
  179. log.ColorFprintf(s, "%d:%s/%s",
  180. log.NewColoredIDValue(repo.ID),
  181. ownerName,
  182. repo.Name)
  183. }
  184. // IsBeingMigrated indicates that repository is being migtated
  185. func (repo *Repository) IsBeingMigrated() bool {
  186. return repo.Status == RepositoryBeingMigrated
  187. }
  188. // IsBeingCreated indicates that repository is being migrated or forked
  189. func (repo *Repository) IsBeingCreated() bool {
  190. return repo.IsBeingMigrated()
  191. }
  192. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  193. func (repo *Repository) AfterLoad() {
  194. // FIXME: use models migration to solve all at once.
  195. if len(repo.DefaultBranch) == 0 {
  196. repo.DefaultBranch = "master"
  197. }
  198. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  199. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  200. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  201. }
  202. // MustOwner always returns a valid *User object to avoid
  203. // conceptually impossible error handling.
  204. // It creates a fake object that contains error details
  205. // when error occurs.
  206. func (repo *Repository) MustOwner() *User {
  207. return repo.mustOwner(x)
  208. }
  209. // MustOwnerName always returns valid owner name to avoid
  210. // conceptually impossible error handling.
  211. // It returns "error" and logs error details when error
  212. // occurs.
  213. func (repo *Repository) MustOwnerName() string {
  214. return repo.mustOwnerName(x)
  215. }
  216. // FullName returns the repository full name
  217. func (repo *Repository) FullName() string {
  218. return repo.MustOwnerName() + "/" + repo.Name
  219. }
  220. // HTMLURL returns the repository HTML URL
  221. func (repo *Repository) HTMLURL() string {
  222. return setting.AppURL + repo.FullName()
  223. }
  224. // APIURL returns the repository API URL
  225. func (repo *Repository) APIURL() string {
  226. return setting.AppURL + path.Join("api/v1/repos", repo.FullName())
  227. }
  228. // APIFormat converts a Repository to api.Repository
  229. func (repo *Repository) APIFormat(mode AccessMode) *api.Repository {
  230. return repo.innerAPIFormat(x, mode, false)
  231. }
  232. // GetCommitsCountCacheKey returns cache key used for commits count caching.
  233. func (repo *Repository) GetCommitsCountCacheKey(contextName string, isRef bool) string {
  234. var prefix string
  235. if isRef {
  236. prefix = "ref"
  237. } else {
  238. prefix = "commit"
  239. }
  240. return fmt.Sprintf("commits-count-%d-%s-%s", repo.ID, prefix, contextName)
  241. }
  242. func (repo *Repository) innerAPIFormat(e Engine, mode AccessMode, isParent bool) *api.Repository {
  243. var parent *api.Repository
  244. cloneLink := repo.cloneLink(e, false)
  245. permission := &api.Permission{
  246. Admin: mode >= AccessModeAdmin,
  247. Push: mode >= AccessModeWrite,
  248. Pull: mode >= AccessModeRead,
  249. }
  250. if !isParent {
  251. err := repo.getBaseRepo(e)
  252. if err != nil {
  253. log.Error("APIFormat: %v", err)
  254. }
  255. if repo.BaseRepo != nil {
  256. parent = repo.BaseRepo.innerAPIFormat(e, mode, true)
  257. }
  258. }
  259. hasIssues := false
  260. var externalTracker *api.ExternalTracker
  261. var internalTracker *api.InternalTracker
  262. if unit, err := repo.getUnit(e, UnitTypeIssues); err == nil {
  263. config := unit.IssuesConfig()
  264. hasIssues = true
  265. internalTracker = &api.InternalTracker{
  266. EnableTimeTracker: config.EnableTimetracker,
  267. AllowOnlyContributorsToTrackTime: config.AllowOnlyContributorsToTrackTime,
  268. EnableIssueDependencies: config.EnableDependencies,
  269. }
  270. } else if unit, err := repo.getUnit(e, UnitTypeExternalTracker); err == nil {
  271. config := unit.ExternalTrackerConfig()
  272. hasIssues = true
  273. externalTracker = &api.ExternalTracker{
  274. ExternalTrackerURL: config.ExternalTrackerURL,
  275. ExternalTrackerFormat: config.ExternalTrackerFormat,
  276. ExternalTrackerStyle: config.ExternalTrackerStyle,
  277. }
  278. }
  279. hasWiki := false
  280. var externalWiki *api.ExternalWiki
  281. if _, err := repo.getUnit(e, UnitTypeWiki); err == nil {
  282. hasWiki = true
  283. } else if unit, err := repo.getUnit(e, UnitTypeExternalWiki); err == nil {
  284. hasWiki = true
  285. config := unit.ExternalWikiConfig()
  286. externalWiki = &api.ExternalWiki{
  287. ExternalWikiURL: config.ExternalWikiURL,
  288. }
  289. }
  290. hasPullRequests := false
  291. ignoreWhitespaceConflicts := false
  292. allowMerge := false
  293. allowRebase := false
  294. allowRebaseMerge := false
  295. allowSquash := false
  296. if unit, err := repo.getUnit(e, UnitTypePullRequests); err == nil {
  297. config := unit.PullRequestsConfig()
  298. hasPullRequests = true
  299. ignoreWhitespaceConflicts = config.IgnoreWhitespaceConflicts
  300. allowMerge = config.AllowMerge
  301. allowRebase = config.AllowRebase
  302. allowRebaseMerge = config.AllowRebaseMerge
  303. allowSquash = config.AllowSquash
  304. }
  305. return &api.Repository{
  306. ID: repo.ID,
  307. Owner: repo.Owner.APIFormat(),
  308. Name: repo.Name,
  309. FullName: repo.FullName(),
  310. Description: repo.Description,
  311. Private: repo.IsPrivate,
  312. Empty: repo.IsEmpty,
  313. Archived: repo.IsArchived,
  314. Size: int(repo.Size / 1024),
  315. Fork: repo.IsFork,
  316. Parent: parent,
  317. Mirror: repo.IsMirror,
  318. HTMLURL: repo.HTMLURL(),
  319. SSHURL: cloneLink.SSH,
  320. CloneURL: cloneLink.HTTPS,
  321. Website: repo.Website,
  322. Stars: repo.NumStars,
  323. Forks: repo.NumForks,
  324. Watchers: repo.NumWatches,
  325. OpenIssues: repo.NumOpenIssues,
  326. DefaultBranch: repo.DefaultBranch,
  327. Created: repo.CreatedUnix.AsTime(),
  328. Updated: repo.UpdatedUnix.AsTime(),
  329. Permissions: permission,
  330. HasIssues: hasIssues,
  331. ExternalTracker: externalTracker,
  332. InternalTracker: internalTracker,
  333. HasWiki: hasWiki,
  334. ExternalWiki: externalWiki,
  335. HasPullRequests: hasPullRequests,
  336. IgnoreWhitespaceConflicts: ignoreWhitespaceConflicts,
  337. AllowMerge: allowMerge,
  338. AllowRebase: allowRebase,
  339. AllowRebaseMerge: allowRebaseMerge,
  340. AllowSquash: allowSquash,
  341. AvatarURL: repo.avatarLink(e),
  342. }
  343. }
  344. func (repo *Repository) getUnits(e Engine) (err error) {
  345. if repo.Units != nil {
  346. return nil
  347. }
  348. repo.Units, err = getUnitsByRepoID(e, repo.ID)
  349. return err
  350. }
  351. // CheckUnitUser check whether user could visit the unit of this repository
  352. func (repo *Repository) CheckUnitUser(userID int64, isAdmin bool, unitType UnitType) bool {
  353. return repo.checkUnitUser(x, userID, isAdmin, unitType)
  354. }
  355. func (repo *Repository) checkUnitUser(e Engine, userID int64, isAdmin bool, unitType UnitType) bool {
  356. if isAdmin {
  357. return true
  358. }
  359. user, err := getUserByID(e, userID)
  360. if err != nil {
  361. return false
  362. }
  363. perm, err := getUserRepoPermission(e, repo, user)
  364. if err != nil {
  365. return false
  366. }
  367. return perm.CanRead(unitType)
  368. }
  369. // UnitEnabled if this repository has the given unit enabled
  370. func (repo *Repository) UnitEnabled(tp UnitType) bool {
  371. if err := repo.getUnits(x); err != nil {
  372. log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error())
  373. }
  374. for _, unit := range repo.Units {
  375. if unit.Type == tp {
  376. return true
  377. }
  378. }
  379. return false
  380. }
  381. // ErrUnitTypeNotExist represents a "UnitTypeNotExist" kind of error.
  382. type ErrUnitTypeNotExist struct {
  383. UT UnitType
  384. }
  385. // IsErrUnitTypeNotExist checks if an error is a ErrUnitNotExist.
  386. func IsErrUnitTypeNotExist(err error) bool {
  387. _, ok := err.(ErrUnitTypeNotExist)
  388. return ok
  389. }
  390. func (err ErrUnitTypeNotExist) Error() string {
  391. return fmt.Sprintf("Unit type does not exist: %s", err.UT.String())
  392. }
  393. // MustGetUnit always returns a RepoUnit object
  394. func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit {
  395. ru, err := repo.GetUnit(tp)
  396. if err == nil {
  397. return ru
  398. }
  399. if tp == UnitTypeExternalWiki {
  400. return &RepoUnit{
  401. Type: tp,
  402. Config: new(ExternalWikiConfig),
  403. }
  404. } else if tp == UnitTypeExternalTracker {
  405. return &RepoUnit{
  406. Type: tp,
  407. Config: new(ExternalTrackerConfig),
  408. }
  409. } else if tp == UnitTypePullRequests {
  410. return &RepoUnit{
  411. Type: tp,
  412. Config: new(PullRequestsConfig),
  413. }
  414. } else if tp == UnitTypeIssues {
  415. return &RepoUnit{
  416. Type: tp,
  417. Config: new(IssuesConfig),
  418. }
  419. }
  420. return &RepoUnit{
  421. Type: tp,
  422. Config: new(UnitConfig),
  423. }
  424. }
  425. // GetUnit returns a RepoUnit object
  426. func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) {
  427. return repo.getUnit(x, tp)
  428. }
  429. func (repo *Repository) getUnit(e Engine, tp UnitType) (*RepoUnit, error) {
  430. if err := repo.getUnits(e); err != nil {
  431. return nil, err
  432. }
  433. for _, unit := range repo.Units {
  434. if unit.Type == tp {
  435. return unit, nil
  436. }
  437. }
  438. return nil, ErrUnitTypeNotExist{tp}
  439. }
  440. func (repo *Repository) getOwner(e Engine) (err error) {
  441. if repo.Owner != nil {
  442. return nil
  443. }
  444. repo.Owner, err = getUserByID(e, repo.OwnerID)
  445. return err
  446. }
  447. // GetOwner returns the repository owner
  448. func (repo *Repository) GetOwner() error {
  449. return repo.getOwner(x)
  450. }
  451. func (repo *Repository) mustOwner(e Engine) *User {
  452. if err := repo.getOwner(e); err != nil {
  453. return &User{
  454. Name: "error",
  455. FullName: err.Error(),
  456. }
  457. }
  458. return repo.Owner
  459. }
  460. func (repo *Repository) getOwnerName(e Engine) error {
  461. if len(repo.OwnerName) > 0 {
  462. return nil
  463. }
  464. if repo.Owner != nil {
  465. repo.OwnerName = repo.Owner.Name
  466. return nil
  467. }
  468. u := new(User)
  469. has, err := e.ID(repo.OwnerID).Cols("name").Get(u)
  470. if err != nil {
  471. return err
  472. } else if !has {
  473. return ErrUserNotExist{repo.OwnerID, "", 0}
  474. }
  475. repo.OwnerName = u.Name
  476. return nil
  477. }
  478. // GetOwnerName returns the repository owner name
  479. func (repo *Repository) GetOwnerName() error {
  480. return repo.getOwnerName(x)
  481. }
  482. func (repo *Repository) mustOwnerName(e Engine) string {
  483. if err := repo.getOwnerName(e); err != nil {
  484. log.Error("Error loading repository owner name: %v", err)
  485. return "error"
  486. }
  487. return repo.OwnerName
  488. }
  489. // ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers.
  490. func (repo *Repository) ComposeMetas() map[string]string {
  491. if repo.ExternalMetas == nil {
  492. repo.ExternalMetas = map[string]string{
  493. "user": repo.MustOwner().Name,
  494. "repo": repo.Name,
  495. "repoPath": repo.RepoPath(),
  496. }
  497. unit, err := repo.GetUnit(UnitTypeExternalTracker)
  498. if err != nil {
  499. return repo.ExternalMetas
  500. }
  501. repo.ExternalMetas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat
  502. switch unit.ExternalTrackerConfig().ExternalTrackerStyle {
  503. case markup.IssueNameStyleAlphanumeric:
  504. repo.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
  505. default:
  506. repo.ExternalMetas["style"] = markup.IssueNameStyleNumeric
  507. }
  508. }
  509. return repo.ExternalMetas
  510. }
  511. // DeleteWiki removes the actual and local copy of repository wiki.
  512. func (repo *Repository) DeleteWiki() error {
  513. return repo.deleteWiki(x)
  514. }
  515. func (repo *Repository) deleteWiki(e Engine) error {
  516. wikiPaths := []string{repo.WikiPath()}
  517. for _, wikiPath := range wikiPaths {
  518. removeAllWithNotice(e, "Delete repository wiki", wikiPath)
  519. }
  520. _, err := e.Where("repo_id = ?", repo.ID).And("type = ?", UnitTypeWiki).Delete(new(RepoUnit))
  521. return err
  522. }
  523. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  524. if err = repo.getOwner(e); err != nil {
  525. return nil, err
  526. }
  527. accesses := make([]*Access, 0, 10)
  528. if err = e.
  529. Where("repo_id = ? AND mode >= ?", repo.ID, AccessModeWrite).
  530. Find(&accesses); err != nil {
  531. return nil, err
  532. }
  533. // Leave a seat for owner itself to append later, but if owner is an organization
  534. // and just waste 1 unit is cheaper than re-allocate memory once.
  535. users := make([]*User, 0, len(accesses)+1)
  536. if len(accesses) > 0 {
  537. userIDs := make([]int64, len(accesses))
  538. for i := 0; i < len(accesses); i++ {
  539. userIDs[i] = accesses[i].UserID
  540. }
  541. if err = e.In("id", userIDs).Find(&users); err != nil {
  542. return nil, err
  543. }
  544. }
  545. if !repo.Owner.IsOrganization() {
  546. users = append(users, repo.Owner)
  547. }
  548. return users, nil
  549. }
  550. // GetAssignees returns all users that have write access and can be assigned to issues
  551. // of the repository,
  552. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  553. return repo.getAssignees(x)
  554. }
  555. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  556. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  557. return GetMilestoneByRepoID(repo.ID, milestoneID)
  558. }
  559. // IssueStats returns number of open and closed repository issues by given filter mode.
  560. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  561. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  562. }
  563. // GetMirror sets the repository mirror, returns an error upon failure
  564. func (repo *Repository) GetMirror() (err error) {
  565. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  566. return err
  567. }
  568. // GetBaseRepo populates repo.BaseRepo for a fork repository and
  569. // returns an error on failure (NOTE: no error is returned for
  570. // non-fork repositories, and BaseRepo will be left untouched)
  571. func (repo *Repository) GetBaseRepo() (err error) {
  572. return repo.getBaseRepo(x)
  573. }
  574. func (repo *Repository) getBaseRepo(e Engine) (err error) {
  575. if !repo.IsFork {
  576. return nil
  577. }
  578. repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
  579. return err
  580. }
  581. func (repo *Repository) repoPath(e Engine) string {
  582. return RepoPath(repo.mustOwnerName(e), repo.Name)
  583. }
  584. // RepoPath returns the repository path
  585. func (repo *Repository) RepoPath() string {
  586. return repo.repoPath(x)
  587. }
  588. // GitConfigPath returns the path to a repository's git config/ directory
  589. func GitConfigPath(repoPath string) string {
  590. return filepath.Join(repoPath, "config")
  591. }
  592. // GitConfigPath returns the repository git config path
  593. func (repo *Repository) GitConfigPath() string {
  594. return GitConfigPath(repo.RepoPath())
  595. }
  596. // RelLink returns the repository relative link
  597. func (repo *Repository) RelLink() string {
  598. return "/" + repo.FullName()
  599. }
  600. // Link returns the repository link
  601. func (repo *Repository) Link() string {
  602. return setting.AppSubURL + "/" + repo.FullName()
  603. }
  604. // ComposeCompareURL returns the repository comparison URL
  605. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  606. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  607. }
  608. // UpdateDefaultBranch updates the default branch
  609. func (repo *Repository) UpdateDefaultBranch() error {
  610. _, err := x.ID(repo.ID).Cols("default_branch").Update(repo)
  611. return err
  612. }
  613. // IsOwnedBy returns true when user owns this repository
  614. func (repo *Repository) IsOwnedBy(userID int64) bool {
  615. return repo.OwnerID == userID
  616. }
  617. func (repo *Repository) updateSize(e Engine) error {
  618. repoInfoSize, err := git.GetRepoSize(repo.repoPath(e))
  619. if err != nil {
  620. return fmt.Errorf("UpdateSize: %v", err)
  621. }
  622. repo.Size = repoInfoSize.Size + repoInfoSize.SizePack
  623. _, err = e.ID(repo.ID).Cols("size").Update(repo)
  624. return err
  625. }
  626. // UpdateSize updates the repository size, calculating it using git.GetRepoSize
  627. func (repo *Repository) UpdateSize() error {
  628. return repo.updateSize(x)
  629. }
  630. // CanUserFork returns true if specified user can fork repository.
  631. func (repo *Repository) CanUserFork(user *User) (bool, error) {
  632. if user == nil {
  633. return false, nil
  634. }
  635. if repo.OwnerID != user.ID && !user.HasForkedRepo(repo.ID) {
  636. return true, nil
  637. }
  638. if err := user.GetOwnedOrganizations(); err != nil {
  639. return false, err
  640. }
  641. for _, org := range user.OwnedOrgs {
  642. if repo.OwnerID != org.ID && !org.HasForkedRepo(repo.ID) {
  643. return true, nil
  644. }
  645. }
  646. return false, nil
  647. }
  648. // CanUserDelete returns true if user could delete the repository
  649. func (repo *Repository) CanUserDelete(user *User) (bool, error) {
  650. if user.IsAdmin || user.ID == repo.OwnerID {
  651. return true, nil
  652. }
  653. if err := repo.GetOwner(); err != nil {
  654. return false, err
  655. }
  656. if repo.Owner.IsOrganization() {
  657. isOwner, err := repo.Owner.IsOwnedBy(user.ID)
  658. if err != nil {
  659. return false, err
  660. } else if isOwner {
  661. return true, nil
  662. }
  663. }
  664. return false, nil
  665. }
  666. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  667. func (repo *Repository) CanEnablePulls() bool {
  668. return !repo.IsMirror && !repo.IsEmpty
  669. }
  670. // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  671. func (repo *Repository) AllowsPulls() bool {
  672. return repo.CanEnablePulls() && repo.UnitEnabled(UnitTypePullRequests)
  673. }
  674. // CanEnableEditor returns true if repository meets the requirements of web editor.
  675. func (repo *Repository) CanEnableEditor() bool {
  676. return !repo.IsMirror
  677. }
  678. // GetReaders returns all users that have explicit read access or higher to the repository.
  679. func (repo *Repository) GetReaders() (_ []*User, err error) {
  680. return repo.getUsersWithAccessMode(x, AccessModeRead)
  681. }
  682. // GetWriters returns all users that have write access to the repository.
  683. func (repo *Repository) GetWriters() (_ []*User, err error) {
  684. return repo.getUsersWithAccessMode(x, AccessModeWrite)
  685. }
  686. // IsReader returns true if user has explicit read access or higher to the repository.
  687. func (repo *Repository) IsReader(userID int64) (bool, error) {
  688. if repo.OwnerID == userID {
  689. return true, nil
  690. }
  691. return x.Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, AccessModeRead).Get(&Access{})
  692. }
  693. // getUsersWithAccessMode returns users that have at least given access mode to the repository.
  694. func (repo *Repository) getUsersWithAccessMode(e Engine, mode AccessMode) (_ []*User, err error) {
  695. if err = repo.getOwner(e); err != nil {
  696. return nil, err
  697. }
  698. accesses := make([]*Access, 0, 10)
  699. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  700. return nil, err
  701. }
  702. // Leave a seat for owner itself to append later, but if owner is an organization
  703. // and just waste 1 unit is cheaper than re-allocate memory once.
  704. users := make([]*User, 0, len(accesses)+1)
  705. if len(accesses) > 0 {
  706. userIDs := make([]int64, len(accesses))
  707. for i := 0; i < len(accesses); i++ {
  708. userIDs[i] = accesses[i].UserID
  709. }
  710. if err = e.In("id", userIDs).Find(&users); err != nil {
  711. return nil, err
  712. }
  713. }
  714. if !repo.Owner.IsOrganization() {
  715. users = append(users, repo.Owner)
  716. }
  717. return users, nil
  718. }
  719. // DescriptionHTML does special handles to description and return HTML string.
  720. func (repo *Repository) DescriptionHTML() template.HTML {
  721. desc, err := markup.RenderDescriptionHTML([]byte(repo.Description), repo.HTMLURL(), repo.ComposeMetas())
  722. if err != nil {
  723. log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err)
  724. return template.HTML(markup.Sanitize(repo.Description))
  725. }
  726. return template.HTML(markup.Sanitize(string(desc)))
  727. }
  728. // PatchPath returns corresponding patch file path of repository by given issue ID.
  729. func (repo *Repository) PatchPath(index int64) (string, error) {
  730. return repo.patchPath(x, index)
  731. }
  732. func (repo *Repository) patchPath(e Engine, index int64) (string, error) {
  733. if err := repo.getOwner(e); err != nil {
  734. return "", err
  735. }
  736. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  737. }
  738. // SavePatch saves patch data to corresponding location by given issue ID.
  739. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  740. return repo.savePatch(x, index, patch)
  741. }
  742. func (repo *Repository) savePatch(e Engine, index int64, patch []byte) error {
  743. patchPath, err := repo.patchPath(e, index)
  744. if err != nil {
  745. return fmt.Errorf("PatchPath: %v", err)
  746. }
  747. dir := filepath.Dir(patchPath)
  748. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  749. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  750. }
  751. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  752. return fmt.Errorf("WriteFile: %v", err)
  753. }
  754. return nil
  755. }
  756. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  757. has, err := e.Get(&Repository{
  758. OwnerID: u.ID,
  759. LowerName: strings.ToLower(repoName),
  760. })
  761. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  762. }
  763. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  764. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  765. return isRepositoryExist(x, u, repoName)
  766. }
  767. // CloneLink represents different types of clone URLs of repository.
  768. type CloneLink struct {
  769. SSH string
  770. HTTPS string
  771. Git string
  772. }
  773. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  774. func ComposeHTTPSCloneURL(owner, repo string) string {
  775. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, url.PathEscape(owner), url.PathEscape(repo))
  776. }
  777. func (repo *Repository) cloneLink(e Engine, isWiki bool) *CloneLink {
  778. repoName := repo.Name
  779. if isWiki {
  780. repoName += ".wiki"
  781. }
  782. sshUser := setting.RunUser
  783. if setting.SSH.StartBuiltinServer {
  784. sshUser = setting.SSH.BuiltinServerUser
  785. }
  786. repo.Owner = repo.mustOwner(e)
  787. cl := new(CloneLink)
  788. if setting.SSH.Port != 22 {
  789. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", sshUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  790. } else if setting.Repository.UseCompatSSHURI {
  791. cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  792. } else {
  793. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  794. }
  795. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  796. return cl
  797. }
  798. // CloneLink returns clone URLs of repository.
  799. func (repo *Repository) CloneLink() (cl *CloneLink) {
  800. return repo.cloneLink(x, false)
  801. }
  802. /*
  803. GitHub, GitLab, Gogs: *.wiki.git
  804. BitBucket: *.git/wiki
  805. */
  806. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  807. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  808. // Otherwise, it returns an empty string.
  809. func wikiRemoteURL(remote string) string {
  810. remote = strings.TrimSuffix(remote, ".git")
  811. for _, suffix := range commonWikiURLSuffixes {
  812. wikiURL := remote + suffix
  813. if git.IsRepoURLAccessible(wikiURL) {
  814. return wikiURL
  815. }
  816. }
  817. return ""
  818. }
  819. // CheckCreateRepository check if could created a repository
  820. func CheckCreateRepository(doer, u *User, name string) error {
  821. if !doer.CanCreateRepo() {
  822. return ErrReachLimitOfRepo{u.MaxRepoCreation}
  823. }
  824. if err := IsUsableRepoName(name); err != nil {
  825. return err
  826. }
  827. has, err := isRepositoryExist(x, u, name)
  828. if err != nil {
  829. return fmt.Errorf("IsRepositoryExist: %v", err)
  830. } else if has {
  831. return ErrRepoAlreadyExist{u.Name, name}
  832. }
  833. return nil
  834. }
  835. // MigrateRepositoryGitData starts migrating git related data after created migrating repository
  836. func MigrateRepositoryGitData(doer, u *User, repo *Repository, opts api.MigrateRepoOption) (*Repository, error) {
  837. repoPath := RepoPath(u.Name, opts.RepoName)
  838. if u.IsOrganization() {
  839. t, err := u.GetOwnerTeam()
  840. if err != nil {
  841. return nil, err
  842. }
  843. repo.NumWatches = t.NumMembers
  844. } else {
  845. repo.NumWatches = 1
  846. }
  847. migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second
  848. var err error
  849. if err = os.RemoveAll(repoPath); err != nil {
  850. return repo, fmt.Errorf("Failed to remove %s: %v", repoPath, err)
  851. }
  852. if err = git.Clone(opts.CloneAddr, repoPath, git.CloneRepoOptions{
  853. Mirror: true,
  854. Quiet: true,
  855. Timeout: migrateTimeout,
  856. }); err != nil {
  857. return repo, fmt.Errorf("Clone: %v", err)
  858. }
  859. if opts.Wiki {
  860. wikiPath := WikiPath(u.Name, opts.RepoName)
  861. wikiRemotePath := wikiRemoteURL(opts.CloneAddr)
  862. if len(wikiRemotePath) > 0 {
  863. if err := os.RemoveAll(wikiPath); err != nil {
  864. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  865. }
  866. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{
  867. Mirror: true,
  868. Quiet: true,
  869. Timeout: migrateTimeout,
  870. Branch: "master",
  871. }); err != nil {
  872. log.Warn("Clone wiki: %v", err)
  873. if err := os.RemoveAll(wikiPath); err != nil {
  874. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  875. }
  876. }
  877. }
  878. }
  879. gitRepo, err := git.OpenRepository(repoPath)
  880. if err != nil {
  881. return repo, fmt.Errorf("OpenRepository: %v", err)
  882. }
  883. repo.IsEmpty, err = gitRepo.IsEmpty()
  884. if err != nil {
  885. return repo, fmt.Errorf("git.IsEmpty: %v", err)
  886. }
  887. if !opts.Releases && !repo.IsEmpty {
  888. // Try to get HEAD branch and set it as default branch.
  889. headBranch, err := gitRepo.GetHEADBranch()
  890. if err != nil {
  891. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  892. }
  893. if headBranch != nil {
  894. repo.DefaultBranch = headBranch.Name
  895. }
  896. if err = SyncReleasesWithTags(repo, gitRepo); err != nil {
  897. log.Error("Failed to synchronize tags to releases for repository: %v", err)
  898. }
  899. }
  900. if err = repo.UpdateSize(); err != nil {
  901. log.Error("Failed to update size for repository: %v", err)
  902. }
  903. if opts.Mirror {
  904. if _, err = x.InsertOne(&Mirror{
  905. RepoID: repo.ID,
  906. Interval: setting.Mirror.DefaultInterval,
  907. EnablePrune: true,
  908. NextUpdateUnix: timeutil.TimeStampNow().AddDuration(setting.Mirror.DefaultInterval),
  909. }); err != nil {
  910. return repo, fmt.Errorf("InsertOne: %v", err)
  911. }
  912. repo.IsMirror = true
  913. err = UpdateRepository(repo, false)
  914. } else {
  915. repo, err = CleanUpMigrateInfo(repo)
  916. }
  917. if err != nil && !repo.IsEmpty {
  918. UpdateRepoIndexer(repo)
  919. }
  920. return repo, err
  921. }
  922. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  923. // This also removes possible user credentials.
  924. func cleanUpMigrateGitConfig(configPath string) error {
  925. cfg, err := ini.Load(configPath)
  926. if err != nil {
  927. return fmt.Errorf("open config file: %v", err)
  928. }
  929. cfg.DeleteSection("remote \"origin\"")
  930. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  931. return fmt.Errorf("save config file: %v", err)
  932. }
  933. return nil
  934. }
  935. // createDelegateHooks creates all the hooks scripts for the repo
  936. func createDelegateHooks(repoPath string) (err error) {
  937. var (
  938. hookNames = []string{"pre-receive", "update", "post-receive"}
  939. hookTpls = []string{
  940. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  941. fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  942. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  943. }
  944. giteaHookTpls = []string{
  945. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  946. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  947. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  948. }
  949. )
  950. hookDir := filepath.Join(repoPath, "hooks")
  951. for i, hookName := range hookNames {
  952. oldHookPath := filepath.Join(hookDir, hookName)
  953. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  954. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  955. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  956. }
  957. // WARNING: This will override all old server-side hooks
  958. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  959. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  960. }
  961. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  962. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  963. }
  964. }
  965. return nil
  966. }
  967. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.
  968. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  969. repoPath := repo.RepoPath()
  970. if err := createDelegateHooks(repoPath); err != nil {
  971. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  972. }
  973. if repo.HasWiki() {
  974. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  975. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  976. }
  977. }
  978. _, err := git.NewCommand("remote", "rm", "origin").RunInDir(repoPath)
  979. if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
  980. return repo, fmt.Errorf("CleanUpMigrateInfo: %v", err)
  981. }
  982. if repo.HasWiki() {
  983. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  984. return repo, fmt.Errorf("cleanUpMigrateGitConfig (wiki): %v", err)
  985. }
  986. }
  987. return repo, UpdateRepository(repo, false)
  988. }
  989. // initRepoCommit temporarily changes with work directory.
  990. func initRepoCommit(tmpPath string, u *User) (err error) {
  991. commitTimeStr := time.Now().Format(time.RFC3339)
  992. sig := u.NewGitSig()
  993. // Because this may call hooks we should pass in the environment
  994. env := append(os.Environ(),
  995. "GIT_AUTHOR_NAME="+sig.Name,
  996. "GIT_AUTHOR_EMAIL="+sig.Email,
  997. "GIT_AUTHOR_DATE="+commitTimeStr,
  998. "GIT_COMMITTER_NAME="+sig.Name,
  999. "GIT_COMMITTER_EMAIL="+sig.Email,
  1000. "GIT_COMMITTER_DATE="+commitTimeStr,
  1001. )
  1002. var stderr string
  1003. if _, stderr, err = process.GetManager().ExecDir(-1,
  1004. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  1005. git.GitExecutable, "add", "--all"); err != nil {
  1006. return fmt.Errorf("git add: %s", stderr)
  1007. }
  1008. binVersion, err := git.BinVersion()
  1009. if err != nil {
  1010. return fmt.Errorf("Unable to get git version: %v", err)
  1011. }
  1012. args := []string{
  1013. "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  1014. "-m", "Initial commit",
  1015. }
  1016. if version.Compare(binVersion, "1.7.9", ">=") {
  1017. sign, keyID := SignInitialCommit(tmpPath, u)
  1018. if sign {
  1019. args = append(args, "-S"+keyID)
  1020. } else if version.Compare(binVersion, "2.0.0", ">=") {
  1021. args = append(args, "--no-gpg-sign")
  1022. }
  1023. }
  1024. if _, stderr, err = process.GetManager().ExecDirEnv(-1,
  1025. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  1026. env,
  1027. git.GitExecutable, args...); err != nil {
  1028. return fmt.Errorf("git commit: %s", stderr)
  1029. }
  1030. if _, stderr, err = process.GetManager().ExecDir(-1,
  1031. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  1032. git.GitExecutable, "push", "origin", "master"); err != nil {
  1033. return fmt.Errorf("git push: %s", stderr)
  1034. }
  1035. return nil
  1036. }
  1037. // CreateRepoOptions contains the create repository options
  1038. type CreateRepoOptions struct {
  1039. Name string
  1040. Description string
  1041. OriginalURL string
  1042. Gitignores string
  1043. IssueLabels string
  1044. License string
  1045. Readme string
  1046. IsPrivate bool
  1047. IsMirror bool
  1048. AutoInit bool
  1049. Status RepositoryStatus
  1050. }
  1051. func getRepoInitFile(tp, name string) ([]byte, error) {
  1052. cleanedName := strings.TrimLeft(path.Clean("/"+name), "/")
  1053. relPath := path.Join("options", tp, cleanedName)
  1054. // Use custom file when available.
  1055. customPath := path.Join(setting.CustomPath, relPath)
  1056. if com.IsFile(customPath) {
  1057. return ioutil.ReadFile(customPath)
  1058. }
  1059. switch tp {
  1060. case "readme":
  1061. return options.Readme(cleanedName)
  1062. case "gitignore":
  1063. return options.Gitignore(cleanedName)
  1064. case "license":
  1065. return options.License(cleanedName)
  1066. case "label":
  1067. return options.Labels(cleanedName)
  1068. default:
  1069. return []byte{}, fmt.Errorf("Invalid init file type")
  1070. }
  1071. }
  1072. func prepareRepoCommit(e Engine, repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  1073. commitTimeStr := time.Now().Format(time.RFC3339)
  1074. authorSig := repo.Owner.NewGitSig()
  1075. // Because this may call hooks we should pass in the environment
  1076. env := append(os.Environ(),
  1077. "GIT_AUTHOR_NAME="+authorSig.Name,
  1078. "GIT_AUTHOR_EMAIL="+authorSig.Email,
  1079. "GIT_AUTHOR_DATE="+commitTimeStr,
  1080. "GIT_COMMITTER_NAME="+authorSig.Name,
  1081. "GIT_COMMITTER_EMAIL="+authorSig.Email,
  1082. "GIT_COMMITTER_DATE="+commitTimeStr,
  1083. )
  1084. // Clone to temporary path and do the init commit.
  1085. _, stderr, err := process.GetManager().ExecDirEnv(
  1086. -1, "",
  1087. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  1088. env,
  1089. git.GitExecutable, "clone", repoPath, tmpDir,
  1090. )
  1091. if err != nil {
  1092. return fmt.Errorf("git clone: %v - %s", err, stderr)
  1093. }
  1094. // README
  1095. data, err := getRepoInitFile("readme", opts.Readme)
  1096. if err != nil {
  1097. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  1098. }
  1099. cloneLink := repo.cloneLink(e, false)
  1100. match := map[string]string{
  1101. "Name": repo.Name,
  1102. "Description": repo.Description,
  1103. "CloneURL.SSH": cloneLink.SSH,
  1104. "CloneURL.HTTPS": cloneLink.HTTPS,
  1105. }
  1106. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  1107. []byte(com.Expand(string(data), match)), 0644); err != nil {
  1108. return fmt.Errorf("write README.md: %v", err)
  1109. }
  1110. // .gitignore
  1111. if len(opts.Gitignores) > 0 {
  1112. var buf bytes.Buffer
  1113. names := strings.Split(opts.Gitignores, ",")
  1114. for _, name := range names {
  1115. data, err = getRepoInitFile("gitignore", name)
  1116. if err != nil {
  1117. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  1118. }
  1119. buf.WriteString("# ---> " + name + "\n")
  1120. buf.Write(data)
  1121. buf.WriteString("\n")
  1122. }
  1123. if buf.Len() > 0 {
  1124. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  1125. return fmt.Errorf("write .gitignore: %v", err)
  1126. }
  1127. }
  1128. }
  1129. // LICENSE
  1130. if len(opts.License) > 0 {
  1131. data, err = getRepoInitFile("license", opts.License)
  1132. if err != nil {
  1133. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  1134. }
  1135. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  1136. return fmt.Errorf("write LICENSE: %v", err)
  1137. }
  1138. }
  1139. return nil
  1140. }
  1141. // InitRepository initializes README and .gitignore if needed.
  1142. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  1143. // Somehow the directory could exist.
  1144. if com.IsExist(repoPath) {
  1145. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  1146. }
  1147. // Init git bare new repository.
  1148. if err = git.InitRepository(repoPath, true); err != nil {
  1149. return fmt.Errorf("InitRepository: %v", err)
  1150. } else if err = createDelegateHooks(repoPath); err != nil {
  1151. return fmt.Errorf("createDelegateHooks: %v", err)
  1152. }
  1153. tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  1154. // Initialize repository according to user's choice.
  1155. if opts.AutoInit {
  1156. if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
  1157. return fmt.Errorf("Failed to create dir %s: %v", tmpDir, err)
  1158. }
  1159. defer os.RemoveAll(tmpDir)
  1160. if err = prepareRepoCommit(e, repo, tmpDir, repoPath, opts); err != nil {
  1161. return fmt.Errorf("prepareRepoCommit: %v", err)
  1162. }
  1163. // Apply changes and commit.
  1164. if err = initRepoCommit(tmpDir, u); err != nil {
  1165. return fmt.Errorf("initRepoCommit: %v", err)
  1166. }
  1167. }
  1168. // Re-fetch the repository from database before updating it (else it would
  1169. // override changes that were done earlier with sql)
  1170. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  1171. return fmt.Errorf("getRepositoryByID: %v", err)
  1172. }
  1173. if !opts.AutoInit {
  1174. repo.IsEmpty = true
  1175. }
  1176. repo.DefaultBranch = "master"
  1177. if err = updateRepository(e, repo, false); err != nil {
  1178. return fmt.Errorf("updateRepository: %v", err)
  1179. }
  1180. return nil
  1181. }
  1182. var (
  1183. reservedRepoNames = []string{".", ".."}
  1184. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  1185. )
  1186. // IsUsableRepoName returns true when repository is usable
  1187. func IsUsableRepoName(name string) error {
  1188. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  1189. }
  1190. func createRepository(e *xorm.Session, doer, u *User, repo *Repository) (err error) {
  1191. if err = IsUsableRepoName(repo.Name); err != nil {
  1192. return err
  1193. }
  1194. has, err := isRepositoryExist(e, u, repo.Name)
  1195. if err != nil {
  1196. return fmt.Errorf("IsRepositoryExist: %v", err)
  1197. } else if has {
  1198. return ErrRepoAlreadyExist{u.Name, repo.Name}
  1199. }
  1200. if _, err = e.Insert(repo); err != nil {
  1201. return err
  1202. }
  1203. if err = deleteRepoRedirect(e, u.ID, repo.Name); err != nil {
  1204. return err
  1205. }
  1206. // insert units for repo
  1207. var units = make([]RepoUnit, 0, len(DefaultRepoUnits))
  1208. for _, tp := range DefaultRepoUnits {
  1209. if tp == UnitTypeIssues {
  1210. units = append(units, RepoUnit{
  1211. RepoID: repo.ID,
  1212. Type: tp,
  1213. Config: &IssuesConfig{
  1214. EnableTimetracker: setting.Service.DefaultEnableTimetracking,
  1215. AllowOnlyContributorsToTrackTime: setting.Service.DefaultAllowOnlyContributorsToTrackTime,
  1216. EnableDependencies: setting.Service.DefaultEnableDependencies,
  1217. },
  1218. })
  1219. } else if tp == UnitTypePullRequests {
  1220. units = append(units, RepoUnit{
  1221. RepoID: repo.ID,
  1222. Type: tp,
  1223. Config: &PullRequestsConfig{AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true},
  1224. })
  1225. } else {
  1226. units = append(units, RepoUnit{
  1227. RepoID: repo.ID,
  1228. Type: tp,
  1229. })
  1230. }
  1231. }
  1232. if _, err = e.Insert(&units); err != nil {
  1233. return err
  1234. }
  1235. // Remember visibility preference.
  1236. u.LastRepoVisibility = repo.IsPrivate
  1237. if err = updateUserCols(e, u, "last_repo_visibility"); err != nil {
  1238. return fmt.Errorf("updateUser: %v", err)
  1239. }
  1240. if _, err = e.Incr("num_repos").ID(u.ID).Update(new(User)); err != nil {
  1241. return fmt.Errorf("increment user total_repos: %v", err)
  1242. }
  1243. u.NumRepos++
  1244. // Give access to all members in owner team.
  1245. if u.IsOrganization() {
  1246. t, err := u.getOwnerTeam(e)
  1247. if err != nil {
  1248. return fmt.Errorf("getOwnerTeam: %v", err)
  1249. }
  1250. if err = t.addRepository(e, repo); err != nil {
  1251. return fmt.Errorf("addRepository: %v", err)
  1252. }
  1253. } else if err = repo.recalculateAccesses(e); err != nil {
  1254. // Organization automatically called this in addRepository method.
  1255. return fmt.Errorf("recalculateAccesses: %v", err)
  1256. }
  1257. if setting.Service.AutoWatchNewRepos {
  1258. if err = watchRepo(e, doer.ID, repo.ID, true); err != nil {
  1259. return fmt.Errorf("watchRepo: %v", err)
  1260. }
  1261. }
  1262. if err = newRepoAction(e, doer, repo); err != nil {
  1263. return fmt.Errorf("newRepoAction: %v", err)
  1264. }
  1265. if err = copyDefaultWebhooksToRepo(e, repo.ID); err != nil {
  1266. return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err)
  1267. }
  1268. return nil
  1269. }
  1270. // CreateRepository creates a repository for the user/organization.
  1271. func CreateRepository(doer, u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  1272. if !doer.IsAdmin && !u.CanCreateRepo() {
  1273. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  1274. }
  1275. repo := &Repository{
  1276. OwnerID: u.ID,
  1277. Owner: u,
  1278. Name: opts.Name,
  1279. LowerName: strings.ToLower(opts.Name),
  1280. Description: opts.Description,
  1281. OriginalURL: opts.OriginalURL,
  1282. IsPrivate: opts.IsPrivate,
  1283. IsFsckEnabled: !opts.IsMirror,
  1284. CloseIssuesViaCommitInAnyBranch: setting.Repository.DefaultCloseIssuesViaCommitsInAnyBranch,
  1285. Status: opts.Status,
  1286. IsEmpty: !opts.AutoInit,
  1287. }
  1288. sess := x.NewSession()
  1289. defer sess.Close()
  1290. if err = sess.Begin(); err != nil {
  1291. return nil, err
  1292. }
  1293. if err = createRepository(sess, doer, u, repo); err != nil {
  1294. return nil, err
  1295. }
  1296. // No need for init mirror.
  1297. if !opts.IsMirror {
  1298. repoPath := RepoPath(u.Name, repo.Name)
  1299. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  1300. if err2 := os.RemoveAll(repoPath); err2 != nil {
  1301. log.Error("initRepository: %v", err)
  1302. return nil, fmt.Errorf(
  1303. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  1304. }
  1305. return nil, fmt.Errorf("initRepository: %v", err)
  1306. }
  1307. // Initialize Issue Labels if selected
  1308. if len(opts.IssueLabels) > 0 {
  1309. if err = initalizeLabels(sess, repo.ID, opts.IssueLabels); err != nil {
  1310. return nil, fmt.Errorf("initalizeLabels: %v", err)
  1311. }
  1312. }
  1313. _, stderr, err := process.GetManager().ExecDir(-1,
  1314. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  1315. git.GitExecutable, "update-server-info")
  1316. if err != nil {
  1317. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  1318. }
  1319. }
  1320. if err = sess.Commit(); err != nil {
  1321. return nil, err
  1322. }
  1323. return repo, err
  1324. }
  1325. func countRepositories(userID int64, private bool) int64 {
  1326. sess := x.Where("id > 0")
  1327. if userID > 0 {
  1328. sess.And("owner_id = ?", userID)
  1329. }
  1330. if !private {
  1331. sess.And("is_private=?", false)
  1332. }
  1333. count, err := sess.Count(new(Repository))
  1334. if err != nil {
  1335. log.Error("countRepositories: %v", err)
  1336. }
  1337. return count
  1338. }
  1339. // CountRepositories returns number of repositories.
  1340. // Argument private only takes effect when it is false,
  1341. // set it true to count all repositories.
  1342. func CountRepositories(private bool) int64 {
  1343. return countRepositories(-1, private)
  1344. }
  1345. // CountUserRepositories returns number of repositories user owns.
  1346. // Argument private only takes effect when it is false,
  1347. // set it true to count all repositories.
  1348. func CountUserRepositories(userID int64, private bool) int64 {
  1349. return countRepositories(userID, private)
  1350. }
  1351. // RepoPath returns repository path by given user and repository name.
  1352. func RepoPath(userName, repoName string) string {
  1353. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1354. }
  1355. // TransferOwnership transfers all corresponding setting from old user to new one.
  1356. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1357. newOwner, err := GetUserByName(newOwnerName)
  1358. if err != nil {
  1359. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1360. }
  1361. // Check if new owner has repository with same name.
  1362. has, err := IsRepositoryExist(newOwner, repo.Name)
  1363. if err != nil {
  1364. return fmt.Errorf("IsRepositoryExist: %v", err)
  1365. } else if has {
  1366. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1367. }
  1368. sess := x.NewSession()
  1369. defer sess.Close()
  1370. if err = sess.Begin(); err != nil {
  1371. return fmt.Errorf("sess.Begin: %v", err)
  1372. }
  1373. owner := repo.Owner
  1374. // Note: we have to set value here to make sure recalculate accesses is based on
  1375. // new owner.
  1376. repo.OwnerID = newOwner.ID
  1377. repo.Owner = newOwner
  1378. // Update repository.
  1379. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1380. return fmt.Errorf("update owner: %v", err)
  1381. }
  1382. // Remove redundant collaborators.
  1383. collaborators, err := repo.getCollaborators(sess)
  1384. if err != nil {
  1385. return fmt.Errorf("getCollaborators: %v", err)
  1386. }
  1387. // Dummy object.
  1388. collaboration := &Collaboration{RepoID: repo.ID}
  1389. for _, c := range collaborators {
  1390. if c.ID != newOwner.ID {
  1391. isMember, err := isOrganizationMember(sess, newOwner.ID, c.ID)
  1392. if err != nil {
  1393. return fmt.Errorf("IsOrgMember: %v", err)
  1394. } else if !isMember {
  1395. continue
  1396. }
  1397. }
  1398. collaboration.UserID = c.ID
  1399. if _, err = sess.Delete(collaboration); err != nil {
  1400. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1401. }
  1402. }
  1403. // Remove old team-repository relations.
  1404. if owner.IsOrganization() {
  1405. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1406. return fmt.Errorf("removeOrgRepo: %v", err)
  1407. }
  1408. }
  1409. if newOwner.IsOrganization() {
  1410. t, err := newOwner.getOwnerTeam(sess)
  1411. if err != nil {
  1412. return fmt.Errorf("getOwnerTeam: %v", err)
  1413. } else if err = t.addRepository(sess, repo); err != nil {
  1414. return fmt.Errorf("add to owner team: %v", err)
  1415. }
  1416. } else if err = repo.recalculateAccesses(sess); err != nil {
  1417. // Organization called this in addRepository method.
  1418. return fmt.Errorf("recalculateAccesses: %v", err)
  1419. }
  1420. // Update repository count.
  1421. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1422. return fmt.Errorf("increase new owner repository count: %v", err)
  1423. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1424. return fmt.Errorf("decrease old owner repository count: %v", err)
  1425. }
  1426. if err = watchRepo(sess, doer.ID, repo.ID, true); err != nil {
  1427. return fmt.Errorf("watchRepo: %v", err)
  1428. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1429. return fmt.Errorf("transferRepoAction: %v", err)
  1430. }
  1431. // Rename remote repository to new path and delete local copy.
  1432. dir := UserPath(newOwner.Name)
  1433. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  1434. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  1435. }
  1436. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1437. return fmt.Errorf("rename repository directory: %v", err)
  1438. }
  1439. // Rename remote wiki repository to new path and delete local copy.
  1440. wikiPath := WikiPath(owner.Name, repo.Name)
  1441. if com.IsExist(wikiPath) {
  1442. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1443. return fmt.Errorf("rename repository wiki: %v", err)
  1444. }
  1445. }
  1446. // If there was previously a redirect at this location, remove it.
  1447. if err = deleteRepoRedirect(sess, newOwner.ID, repo.Name); err != nil {
  1448. return fmt.Errorf("delete repo redirect: %v", err)
  1449. }
  1450. return sess.Commit()
  1451. }
  1452. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1453. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1454. oldRepoName = strings.ToLower(oldRepoName)
  1455. newRepoName = strings.ToLower(newRepoName)
  1456. if err = IsUsableRepoName(newRepoName); err != nil {
  1457. return err
  1458. }
  1459. has, err := IsRepositoryExist(u, newRepoName)
  1460. if err != nil {
  1461. return fmt.Errorf("IsRepositoryExist: %v", err)
  1462. } else if has {
  1463. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1464. }
  1465. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1466. if err != nil {
  1467. return fmt.Errorf("GetRepositoryByName: %v", err)
  1468. }
  1469. // Change repository directory name. We must lock the local copy of the
  1470. // repo so that we can atomically rename the repo path and updates the
  1471. // local copy's origin accordingly.
  1472. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  1473. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  1474. newRepoPath := RepoPath(u.Name, newRepoName)
  1475. if err = os.Rename(repo.RepoPath(), newRepoPath); err != nil {
  1476. return fmt.Errorf("rename repository directory: %v", err)
  1477. }
  1478. wikiPath := repo.WikiPath()
  1479. if com.IsExist(wikiPath) {
  1480. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1481. return fmt.Errorf("rename repository wiki: %v", err)
  1482. }
  1483. }
  1484. sess := x.NewSession()
  1485. defer sess.Close()
  1486. if err = sess.Begin(); err != nil {
  1487. return fmt.Errorf("sess.Begin: %v", err)
  1488. }
  1489. // If there was previously a redirect at this location, remove it.
  1490. if err = deleteRepoRedirect(sess, u.ID, newRepoName); err != nil {
  1491. return fmt.Errorf("delete repo redirect: %v", err)
  1492. }
  1493. return sess.Commit()
  1494. }
  1495. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1496. repos := make([]*Repository, 0, 10)
  1497. return repos, e.
  1498. Where("fork_id=?", forkID).
  1499. Find(&repos)
  1500. }
  1501. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1502. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1503. return getRepositoriesByForkID(x, forkID)
  1504. }
  1505. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1506. repo.LowerName = strings.ToLower(repo.Name)
  1507. if len(repo.Description) > 255 {
  1508. repo.Description = repo.Description[:255]
  1509. }
  1510. if len(repo.Website) > 255 {
  1511. repo.Website = repo.Website[:255]
  1512. }
  1513. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1514. return fmt.Errorf("update: %v", err)
  1515. }
  1516. if visibilityChanged {
  1517. if err = repo.getOwner(e); err != nil {
  1518. return fmt.Errorf("getOwner: %v", err)
  1519. }
  1520. if repo.Owner.IsOrganization() {
  1521. // Organization repository need to recalculate access table when visibility is changed.
  1522. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1523. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1524. }
  1525. }
  1526. // If repo has become private, we need to set its actions to private.
  1527. if repo.IsPrivate {
  1528. _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{
  1529. IsPrivate: true,
  1530. })
  1531. if err != nil {
  1532. return err
  1533. }
  1534. }
  1535. // Create/Remove git-daemon-export-ok for git-daemon...
  1536. daemonExportFile := path.Join(repo.repoPath(e), `git-daemon-export-ok`)
  1537. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1538. if err = os.Remove(daemonExportFile); err != nil {
  1539. log.Error("Failed to remove %s: %v", daemonExportFile, err)
  1540. }
  1541. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1542. if f, err := os.Create(daemonExportFile); err != nil {
  1543. log.Error("Failed to create %s: %v", daemonExportFile, err)
  1544. } else {
  1545. f.Close()
  1546. }
  1547. }
  1548. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1549. if err != nil {
  1550. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1551. }
  1552. for i := range forkRepos {
  1553. forkRepos[i].IsPrivate = repo.IsPrivate
  1554. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1555. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1556. }
  1557. }
  1558. if err = repo.updateSize(e); err != nil {
  1559. log.Error("Failed to update size for repository: %v", err)
  1560. }
  1561. }
  1562. return nil
  1563. }
  1564. // UpdateRepository updates a repository
  1565. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1566. sess := x.NewSession()
  1567. defer sess.Close()
  1568. if err = sess.Begin(); err != nil {
  1569. return err
  1570. }
  1571. if err = updateRepository(sess, repo, visibilityChanged); err != nil {
  1572. return fmt.Errorf("updateRepository: %v", err)
  1573. }
  1574. return sess.Commit()
  1575. }
  1576. // UpdateRepositoryUpdatedTime updates a repository's updated time
  1577. func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error {
  1578. _, err := x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID)
  1579. return err
  1580. }
  1581. // UpdateRepositoryUnits updates a repository's units
  1582. func UpdateRepositoryUnits(repo *Repository, units []RepoUnit) (err error) {
  1583. sess := x.NewSession()
  1584. defer sess.Close()
  1585. if err = sess.Begin(); err != nil {
  1586. return err
  1587. }
  1588. if _, err = sess.Where("repo_id = ?", repo.ID).Delete(new(RepoUnit)); err != nil {
  1589. return err
  1590. }
  1591. if _, err = sess.Insert(units); err != nil {
  1592. return err
  1593. }
  1594. return sess.Commit()
  1595. }
  1596. // DeleteRepository deletes a repository for a user or organization.
  1597. func DeleteRepository(doer *User, uid, repoID int64) error {
  1598. // In case is a organization.
  1599. org, err := GetUserByID(uid)
  1600. if err != nil {
  1601. return err
  1602. }
  1603. if org.IsOrganization() {
  1604. if err = org.GetTeams(); err != nil {
  1605. return err
  1606. }
  1607. }
  1608. sess := x.NewSession()
  1609. defer sess.Close()
  1610. if err = sess.Begin(); err != nil {
  1611. return err
  1612. }
  1613. repo := &Repository{ID: repoID, OwnerID: uid}
  1614. has, err := sess.Get(repo)
  1615. if err != nil {
  1616. return err
  1617. } else if !has {
  1618. return ErrRepoNotExist{repoID, uid, "", ""}
  1619. }
  1620. // Delete Deploy Keys
  1621. deployKeys, err := listDeployKeys(sess, repo.ID)
  1622. if err != nil {
  1623. return fmt.Errorf("listDeployKeys: %v", err)
  1624. }
  1625. for _, dKey := range deployKeys {
  1626. if err := deleteDeployKey(sess, doer, dKey.ID); err != nil {
  1627. return fmt.Errorf("deleteDeployKeys: %v", err)
  1628. }
  1629. }
  1630. if cnt, err := sess.ID(repoID).Delete(&Repository{}); err != nil {
  1631. return err
  1632. } else if cnt != 1 {
  1633. return ErrRepoNotExist{repoID, uid, "", ""}
  1634. }
  1635. if org.IsOrganization() {
  1636. for _, t := range org.Teams {
  1637. if !t.hasRepository(sess, repoID) {
  1638. continue
  1639. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1640. return err
  1641. }
  1642. }
  1643. }
  1644. if err = deleteBeans(sess,
  1645. &Access{RepoID: repo.ID},
  1646. &Action{RepoID: repo.ID},
  1647. &Watch{RepoID: repoID},
  1648. &Star{RepoID: repoID},
  1649. &Mirror{RepoID: repoID},
  1650. &Milestone{RepoID: repoID},
  1651. &Release{RepoID: repoID},
  1652. &Collaboration{RepoID: repoID},
  1653. &PullRequest{BaseRepoID: repoID},
  1654. &RepoUnit{RepoID: repoID},
  1655. &RepoRedirect{RedirectRepoID: repoID},
  1656. &Webhook{RepoID: repoID},
  1657. &HookTask{RepoID: repoID},
  1658. &Notification{RepoID: repoID},
  1659. &CommitStatus{RepoID: repoID},
  1660. &RepoIndexerStatus{RepoID: repoID},
  1661. &Comment{RefRepoID: repoID},
  1662. &Task{RepoID: repoID},
  1663. ); err != nil {
  1664. return fmt.Errorf("deleteBeans: %v", err)
  1665. }
  1666. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"repo_id": repoID})
  1667. // Delete comments and attachments
  1668. if _, err = sess.In("issue_id", deleteCond).
  1669. Delete(&Comment{}); err != nil {
  1670. return err
  1671. }
  1672. if _, err = sess.In("issue_id", deleteCond).
  1673. Delete(&IssueUser{}); err != nil {
  1674. return err
  1675. }
  1676. if _, err = sess.In("issue_id", deleteCond).
  1677. Delete(&Reaction{}); err != nil {
  1678. return err
  1679. }
  1680. if _, err = sess.In("issue_id", deleteCond).
  1681. Delete(&IssueWatch{}); err != nil {
  1682. return err
  1683. }
  1684. if _, err = sess.In("issue_id", deleteCond).
  1685. Delete(&Stopwatch{}); err != nil {
  1686. return err
  1687. }
  1688. attachmentPaths := make([]string, 0, 20)
  1689. attachments := make([]*Attachment, 0, len(attachmentPaths))
  1690. if err = sess.Join("INNER", "issue", "issue.id = attachment.issue_id").
  1691. Where("issue.repo_id = ?", repoID).
  1692. Find(&attachments); err != nil {
  1693. return err
  1694. }
  1695. for j := range attachments {
  1696. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1697. }
  1698. if _, err = sess.In("issue_id", deleteCond).
  1699. Delete(&Attachment{}); err != nil {
  1700. return err
  1701. }
  1702. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1703. return err
  1704. }
  1705. if _, err = sess.Where("repo_id = ?", repoID).Delete(new(RepoUnit)); err != nil {
  1706. return err
  1707. }
  1708. if repo.IsFork {
  1709. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1710. return fmt.Errorf("decrease fork count: %v", err)
  1711. }
  1712. }
  1713. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1714. return err
  1715. }
  1716. // FIXME: Remove repository files should be executed after transaction succeed.
  1717. repoPath := repo.repoPath(sess)
  1718. removeAllWithNotice(sess, "Delete repository files", repoPath)
  1719. err = repo.deleteWiki(sess)
  1720. if err != nil {
  1721. return err
  1722. }
  1723. // Remove attachment files.
  1724. for i := range attachmentPaths {
  1725. removeAllWithNotice(sess, "Delete attachment", attachmentPaths[i])
  1726. }
  1727. // Remove LFS objects
  1728. var lfsObjects []*LFSMetaObject
  1729. if err = sess.Where("repository_id=?", repoID).Find(&lfsObjects); err != nil {
  1730. return err
  1731. }
  1732. for _, v := range lfsObjects {
  1733. count, err := sess.Count(&LFSMetaObject{Oid: v.Oid})
  1734. if err != nil {
  1735. return err
  1736. }
  1737. if count > 1 {
  1738. continue
  1739. }
  1740. oidPath := filepath.Join(setting.LFS.ContentPath, v.Oid[0:2], v.Oid[2:4], v.Oid[4:len(v.Oid)])
  1741. removeAllWithNotice(sess, "Delete orphaned LFS file", oidPath)
  1742. }
  1743. if _, err := sess.Delete(&LFSMetaObject{RepositoryID: repoID}); err != nil {
  1744. return err
  1745. }
  1746. if repo.NumForks > 0 {
  1747. if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1748. log.Error("reset 'fork_id' and 'is_fork': %v", err)
  1749. }
  1750. }
  1751. if err = sess.Commit(); err != nil {
  1752. if len(deployKeys) > 0 {
  1753. // We need to rewrite the public keys because the commit failed
  1754. if err2 := RewriteAllPublicKeys(); err2 != nil {
  1755. return fmt.Errorf("Commit: %v SSH Keys: %v", err, err2)
  1756. }
  1757. }
  1758. return fmt.Errorf("Commit: %v", err)
  1759. }
  1760. if len(repo.Avatar) > 0 {
  1761. avatarPath := repo.CustomAvatarPath()
  1762. if com.IsExist(avatarPath) {
  1763. if err := os.Remove(avatarPath); err != nil {
  1764. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1765. }
  1766. }
  1767. }
  1768. return nil
  1769. }
  1770. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
  1771. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
  1772. return getRepositoryByOwnerAndName(x, ownerName, repoName)
  1773. }
  1774. func getRepositoryByOwnerAndName(e Engine, ownerName, repoName string) (*Repository, error) {
  1775. var repo Repository
  1776. has, err := e.Table("repository").Select("repository.*").
  1777. Join("INNER", "`user`", "`user`.id = repository.owner_id").
  1778. Where("repository.lower_name = ?", strings.ToLower(repoName)).
  1779. And("`user`.lower_name = ?", strings.ToLower(ownerName)).
  1780. Get(&repo)
  1781. if err != nil {
  1782. return nil, err
  1783. } else if !has {
  1784. return nil, ErrRepoNotExist{0, 0, ownerName, repoName}
  1785. }
  1786. return &repo, nil
  1787. }
  1788. // GetRepositoryByName returns the repository by given name under user if exists.
  1789. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1790. repo := &Repository{
  1791. OwnerID: ownerID,
  1792. LowerName: strings.ToLower(name),
  1793. }
  1794. has, err := x.Get(repo)
  1795. if err != nil {
  1796. return nil, err
  1797. } else if !has {
  1798. return nil, ErrRepoNotExist{0, ownerID, "", name}
  1799. }
  1800. return repo, err
  1801. }
  1802. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1803. repo := new(Repository)
  1804. has, err := e.ID(id).Get(repo)
  1805. if err != nil {
  1806. return nil, err
  1807. } else if !has {
  1808. return nil, ErrRepoNotExist{id, 0, "", ""}
  1809. }
  1810. return repo, nil
  1811. }
  1812. // GetRepositoryByID returns the repository by given id if exists.
  1813. func GetRepositoryByID(id int64) (*Repository, error) {
  1814. return getRepositoryByID(x, id)
  1815. }
  1816. // GetRepositoriesMapByIDs returns the repositories by given id slice.
  1817. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
  1818. var repos = make(map[int64]*Repository, len(ids))
  1819. return repos, x.In("id", ids).Find(&repos)
  1820. }
  1821. // GetUserRepositories returns a list of repositories of given user.
  1822. func GetUserRepositories(userID int64, private bool, page, pageSize int, orderBy string) ([]*Repository, error) {
  1823. if len(orderBy) == 0 {
  1824. orderBy = "updated_unix DESC"
  1825. }
  1826. sess := x.
  1827. Where("owner_id = ?", userID).
  1828. OrderBy(orderBy)
  1829. if !private {
  1830. sess.And("is_private=?", false)
  1831. }
  1832. if page <= 0 {
  1833. page = 1
  1834. }
  1835. sess.Limit(pageSize, (page-1)*pageSize)
  1836. repos := make([]*Repository, 0, pageSize)
  1837. return repos, sess.Find(&repos)
  1838. }
  1839. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
  1840. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1841. repos := make([]*Repository, 0, 10)
  1842. return repos, x.
  1843. Where("owner_id = ?", userID).
  1844. And("is_mirror = ?", true).
  1845. Find(&repos)
  1846. }
  1847. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1848. return e.Count(&Repository{OwnerID: u.ID})
  1849. }
  1850. func getPublicRepositoryCount(e Engine, u *User) (int64, error) {
  1851. return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
  1852. }
  1853. func getPrivateRepositoryCount(e Engine, u *User) (int64, error) {
  1854. return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
  1855. }
  1856. // GetRepositoryCount returns the total number of repositories of user.
  1857. func GetRepositoryCount(u *User) (int64, error) {
  1858. return getRepositoryCount(x, u)
  1859. }
  1860. // GetPublicRepositoryCount returns the total number of public repositories of user.
  1861. func GetPublicRepositoryCount(u *User) (int64, error) {
  1862. return getPublicRepositoryCount(x, u)
  1863. }
  1864. // GetPrivateRepositoryCount returns the total number of private repositories of user.
  1865. func GetPrivateRepositoryCount(u *User) (int64, error) {
  1866. return getPrivateRepositoryCount(x, u)
  1867. }
  1868. // DeleteRepositoryArchives deletes all repositories' archives.
  1869. func DeleteRepositoryArchives() error {
  1870. return x.
  1871. Where("id > 0").
  1872. Iterate(new(Repository),
  1873. func(idx int, bean interface{}) error {
  1874. repo := bean.(*Repository)
  1875. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1876. })
  1877. }
  1878. // DeleteOldRepositoryArchives deletes old repository archives.
  1879. func DeleteOldRepositoryArchives() {
  1880. log.Trace("Doing: ArchiveCleanup")
  1881. if err := x.Where("id > 0").Iterate(new(Repository), deleteOldRepositoryArchives); err != nil {
  1882. log.Error("ArchiveClean: %v", err)
  1883. }
  1884. }
  1885. func deleteOldRepositoryArchives(idx int, bean interface{}) error {
  1886. repo := bean.(*Repository)
  1887. basePath := filepath.Join(repo.RepoPath(), "archives")
  1888. for _, ty := range []string{"zip", "targz"} {
  1889. path := filepath.Join(basePath, ty)
  1890. file, err := os.Open(path)
  1891. if err != nil {
  1892. if !os.IsNotExist(err) {
  1893. log.Warn("Unable to open directory %s: %v", path, err)
  1894. return err
  1895. }
  1896. // If the directory doesn't exist, that's okay.
  1897. continue
  1898. }
  1899. files, err := file.Readdir(0)
  1900. file.Close()
  1901. if err != nil {
  1902. log.Warn("Unable to read directory %s: %v", path, err)
  1903. return err
  1904. }
  1905. minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
  1906. for _, info := range files {
  1907. if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
  1908. toDelete := filepath.Join(path, info.Name())
  1909. // This is a best-effort purge, so we do not check error codes to confirm removal.
  1910. if err = os.Remove(toDelete); err != nil {
  1911. log.Trace("Unable to delete %s, but proceeding: %v", toDelete, err)
  1912. }
  1913. }
  1914. }
  1915. }
  1916. return nil
  1917. }
  1918. func gatherMissingRepoRecords() ([]*Repository, error) {
  1919. repos := make([]*Repository, 0, 10)
  1920. if err := x.
  1921. Where("id > 0").
  1922. Iterate(new(Repository),
  1923. func(idx int, bean interface{}) error {
  1924. repo := bean.(*Repository)
  1925. if !com.IsDir(repo.RepoPath()) {
  1926. repos = append(repos, repo)
  1927. }
  1928. return nil
  1929. }); err != nil {
  1930. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1931. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1932. }
  1933. }
  1934. return repos, nil
  1935. }
  1936. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1937. func DeleteMissingRepositories(doer *User) error {
  1938. repos, err := gatherMissingRepoRecords()
  1939. if err != nil {
  1940. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1941. }
  1942. if len(repos) == 0 {
  1943. return nil
  1944. }
  1945. for _, repo := range repos {
  1946. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1947. if err := DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  1948. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1949. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1950. }
  1951. }
  1952. }
  1953. return nil
  1954. }
  1955. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1956. func ReinitMissingRepositories() error {
  1957. repos, err := gatherMissingRepoRecords()
  1958. if err != nil {
  1959. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1960. }
  1961. if len(repos) == 0 {
  1962. return nil
  1963. }
  1964. for _, repo := range repos {
  1965. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1966. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1967. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1968. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1969. }
  1970. }
  1971. }
  1972. return nil
  1973. }
  1974. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1975. // to make sure the binary and custom conf path are up-to-date.
  1976. func SyncRepositoryHooks() error {
  1977. return x.Cols("owner_id", "name").Where("id > 0").Iterate(new(Repository),
  1978. func(idx int, bean interface{}) error {
  1979. if err := createDelegateHooks(bean.(*Repository).RepoPath()); err != nil {
  1980. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1981. }
  1982. if bean.(*Repository).HasWiki() {
  1983. if err := createDelegateHooks(bean.(*Repository).WikiPath()); err != nil {
  1984. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1985. }
  1986. }
  1987. return nil
  1988. })
  1989. }
  1990. // GitFsck calls 'git fsck' to check repository health.
  1991. func GitFsck() {
  1992. log.Trace("Doing: GitFsck")
  1993. if err := x.
  1994. Where("id>0 AND is_fsck_enabled=?", true).BufferSize(setting.Database.IterateBufferSize).
  1995. Iterate(new(Repository),
  1996. func(idx int, bean interface{}) error {
  1997. repo := bean.(*Repository)
  1998. repoPath := repo.RepoPath()
  1999. log.Trace("Running health check on repository %s", repoPath)
  2000. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  2001. desc := fmt.Sprintf("Failed to health check repository (%s): %v", repoPath, err)
  2002. log.Warn(desc)
  2003. if err = CreateRepositoryNotice(desc); err != nil {
  2004. log.Error("CreateRepositoryNotice: %v", err)
  2005. }
  2006. }
  2007. return nil
  2008. }); err != nil {
  2009. log.Error("GitFsck: %v", err)
  2010. }
  2011. log.Trace("Finished: GitFsck")
  2012. }
  2013. // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
  2014. func GitGcRepos() error {
  2015. args := append([]string{"gc"}, setting.Git.GCArgs...)
  2016. return x.
  2017. Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
  2018. Iterate(new(Repository),
  2019. func(idx int, bean interface{}) error {
  2020. repo := bean.(*Repository)
  2021. if err := repo.GetOwner(); err != nil {
  2022. return err
  2023. }
  2024. _, stderr, err := process.GetManager().ExecDir(
  2025. time.Duration(setting.Git.Timeout.GC)*time.Second,
  2026. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  2027. git.GitExecutable, args...)
  2028. if err != nil {
  2029. return fmt.Errorf("%v: %v", err, stderr)
  2030. }
  2031. return nil
  2032. })
  2033. }
  2034. type repoChecker struct {
  2035. querySQL, correctSQL string
  2036. desc string
  2037. }
  2038. func repoStatsCheck(checker *repoChecker) {
  2039. results, err := x.Query(checker.querySQL)
  2040. if err != nil {
  2041. log.Error("Select %s: %v", checker.desc, err)
  2042. return
  2043. }
  2044. for _, result := range results {
  2045. id := com.StrTo(result["id"]).MustInt64()
  2046. log.Trace("Updating %s: %d", checker.desc, id)
  2047. _, err = x.Exec(checker.correctSQL, id, id)
  2048. if err != nil {
  2049. log.Error("Update %s[%d]: %v", checker.desc, id, err)
  2050. }
  2051. }
  2052. }
  2053. // CheckRepoStats checks the repository stats
  2054. func CheckRepoStats() {
  2055. log.Trace("Doing: CheckRepoStats")
  2056. checkers := []*repoChecker{
  2057. // Repository.NumWatches
  2058. {
  2059. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  2060. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  2061. "repository count 'num_watches'",
  2062. },
  2063. // Repository.NumStars
  2064. {
  2065. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  2066. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  2067. "repository count 'num_stars'",
  2068. },
  2069. // Label.NumIssues
  2070. {
  2071. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  2072. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  2073. "label count 'num_issues'",
  2074. },
  2075. // User.NumRepos
  2076. {
  2077. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  2078. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  2079. "user count 'num_repos'",
  2080. },
  2081. // Issue.NumComments
  2082. {
  2083. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  2084. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  2085. "issue count 'num_comments'",
  2086. },
  2087. }
  2088. for i := range checkers {
  2089. repoStatsCheck(checkers[i])
  2090. }
  2091. // ***** START: Repository.NumClosedIssues *****
  2092. desc := "repository count 'num_closed_issues'"
  2093. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false)
  2094. if err != nil {
  2095. log.Error("Select %s: %v", desc, err)
  2096. } else {
  2097. for _, result := range results {
  2098. id := com.StrTo(result["id"]).MustInt64()
  2099. log.Trace("Updating %s: %d", desc, id)
  2100. _, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id)
  2101. if err != nil {
  2102. log.Error("Update %s[%d]: %v", desc, id, err)
  2103. }
  2104. }
  2105. }
  2106. // ***** END: Repository.NumClosedIssues *****
  2107. // ***** START: Repository.NumClosedPulls *****
  2108. desc = "repository count 'num_closed_pulls'"
  2109. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, true)
  2110. if err != nil {
  2111. log.Error("Select %s: %v", desc, err)
  2112. } else {
  2113. for _, result := range results {
  2114. id := com.StrTo(result["id"]).MustInt64()
  2115. log.Trace("Updating %s: %d", desc, id)
  2116. _, err = x.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, true, id)
  2117. if err != nil {
  2118. log.Error("Update %s[%d]: %v", desc, id, err)
  2119. }
  2120. }
  2121. }
  2122. // ***** END: Repository.NumClosedPulls *****
  2123. // FIXME: use checker when stop supporting old fork repo format.
  2124. // ***** START: Repository.NumForks *****
  2125. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  2126. if err != nil {
  2127. log.Error("Select repository count 'num_forks': %v", err)
  2128. } else {
  2129. for _, result := range results {
  2130. id := com.StrTo(result["id"]).MustInt64()
  2131. log.Trace("Updating repository count 'num_forks': %d", id)
  2132. repo, err := GetRepositoryByID(id)
  2133. if err != nil {
  2134. log.Error("GetRepositoryByID[%d]: %v", id, err)
  2135. continue
  2136. }
  2137. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  2138. if err != nil {
  2139. log.Error("Select count of forks[%d]: %v", repo.ID, err)
  2140. continue
  2141. }
  2142. repo.NumForks = int(parseCountResult(rawResult))
  2143. if err = UpdateRepository(repo, false); err != nil {
  2144. log.Error("UpdateRepository[%d]: %v", id, err)
  2145. continue
  2146. }
  2147. }
  2148. }
  2149. // ***** END: Repository.NumForks *****
  2150. }
  2151. // SetArchiveRepoState sets if a repo is archived
  2152. func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) {
  2153. repo.IsArchived = isArchived
  2154. _, err = x.Where("id = ?", repo.ID).Cols("is_archived").Update(repo)
  2155. return
  2156. }
  2157. // ___________ __
  2158. // \_ _____/__________| | __
  2159. // | __)/ _ \_ __ \ |/ /
  2160. // | \( <_> ) | \/ <
  2161. // \___ / \____/|__| |__|_ \
  2162. // \/ \/
  2163. // HasForkedRepo checks if given user has already forked a repository with given ID.
  2164. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  2165. repo := new(Repository)
  2166. has, _ := x.
  2167. Where("owner_id=? AND fork_id=?", ownerID, repoID).
  2168. Get(repo)
  2169. return repo, has
  2170. }
  2171. // ForkRepository forks a repository
  2172. func ForkRepository(doer, owner *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  2173. forkedRepo, err := oldRepo.GetUserFork(owner.ID)
  2174. if err != nil {
  2175. return nil, err
  2176. }
  2177. if forkedRepo != nil {
  2178. return nil, ErrForkAlreadyExist{
  2179. Uname: owner.Name,
  2180. RepoName: oldRepo.FullName(),
  2181. ForkName: forkedRepo.FullName(),
  2182. }
  2183. }
  2184. repo := &Repository{
  2185. OwnerID: owner.ID,
  2186. Owner: owner,
  2187. Name: name,
  2188. LowerName: strings.ToLower(name),
  2189. Description: desc,
  2190. DefaultBranch: oldRepo.DefaultBranch,
  2191. IsPrivate: oldRepo.IsPrivate,
  2192. IsEmpty: oldRepo.IsEmpty,
  2193. IsFork: true,
  2194. ForkID: oldRepo.ID,
  2195. }
  2196. sess := x.NewSession()
  2197. defer sess.Close()
  2198. if err = sess.Begin(); err != nil {
  2199. return nil, err
  2200. }
  2201. if err = createRepository(sess, doer, owner, repo); err != nil {
  2202. return nil, err
  2203. }
  2204. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  2205. return nil, err
  2206. }
  2207. repoPath := RepoPath(owner.Name, repo.Name)
  2208. _, stderr, err := process.GetManager().ExecTimeout(10*time.Minute,
  2209. fmt.Sprintf("ForkRepository(git clone): %s/%s", owner.Name, repo.Name),
  2210. git.GitExecutable, "clone", "--bare", oldRepo.repoPath(sess), repoPath)
  2211. if err != nil {
  2212. return nil, fmt.Errorf("git clone: %v", stderr)
  2213. }
  2214. _, stderr, err = process.GetManager().ExecDir(-1,
  2215. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  2216. git.GitExecutable, "update-server-info")
  2217. if err != nil {
  2218. return nil, fmt.Errorf("git update-server-info: %v", stderr)
  2219. }
  2220. if err = createDelegateHooks(repoPath); err != nil {
  2221. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2222. }
  2223. //Commit repo to get Fork ID
  2224. err = sess.Commit()
  2225. if err != nil {
  2226. return nil, err
  2227. }
  2228. if err = repo.UpdateSize(); err != nil {
  2229. log.Error("Failed to update size for repository: %v", err)
  2230. }
  2231. // Copy LFS meta objects in new session
  2232. sess2 := x.NewSession()
  2233. defer sess2.Close()
  2234. if err = sess2.Begin(); err != nil {
  2235. return repo, err
  2236. }
  2237. var lfsObjects []*LFSMetaObject
  2238. if err = sess2.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
  2239. return repo, err
  2240. }
  2241. for _, v := range lfsObjects {
  2242. v.ID = 0
  2243. v.RepositoryID = repo.ID
  2244. if _, err = sess2.Insert(v); err != nil {
  2245. return repo, err
  2246. }
  2247. }
  2248. return repo, sess2.Commit()
  2249. }
  2250. // GetForks returns all the forks of the repository
  2251. func (repo *Repository) GetForks() ([]*Repository, error) {
  2252. forks := make([]*Repository, 0, repo.NumForks)
  2253. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2254. }
  2255. // GetUserFork return user forked repository from this repository, if not forked return nil
  2256. func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
  2257. var forkedRepo Repository
  2258. has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
  2259. if err != nil {
  2260. return nil, err
  2261. }
  2262. if !has {
  2263. return nil, nil
  2264. }
  2265. return &forkedRepo, nil
  2266. }
  2267. // CustomAvatarPath returns repository custom avatar file path.
  2268. func (repo *Repository) CustomAvatarPath() string {
  2269. // Avatar empty by default
  2270. if len(repo.Avatar) == 0 {
  2271. return ""
  2272. }
  2273. return filepath.Join(setting.RepositoryAvatarUploadPath, repo.Avatar)
  2274. }
  2275. // generateRandomAvatar generates a random avatar for repository.
  2276. func (repo *Repository) generateRandomAvatar(e Engine) error {
  2277. idToString := fmt.Sprintf("%d", repo.ID)
  2278. seed := idToString
  2279. img, err := avatar.RandomImage([]byte(seed))
  2280. if err != nil {
  2281. return fmt.Errorf("RandomImage: %v", err)
  2282. }
  2283. repo.Avatar = idToString
  2284. if err = os.MkdirAll(filepath.Dir(repo.CustomAvatarPath()), os.ModePerm); err != nil {
  2285. return fmt.Errorf("MkdirAll: %v", err)
  2286. }
  2287. fw, err := os.Create(repo.CustomAvatarPath())
  2288. if err != nil {
  2289. return fmt.Errorf("Create: %v", err)
  2290. }
  2291. defer fw.Close()
  2292. if err = png.Encode(fw, img); err != nil {
  2293. return fmt.Errorf("Encode: %v", err)
  2294. }
  2295. log.Info("New random avatar created for repository: %d", repo.ID)
  2296. if _, err := e.ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil {
  2297. return err
  2298. }
  2299. return nil
  2300. }
  2301. // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories
  2302. func RemoveRandomAvatars() error {
  2303. return x.
  2304. Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
  2305. Iterate(new(Repository),
  2306. func(idx int, bean interface{}) error {
  2307. repository := bean.(*Repository)
  2308. stringifiedID := strconv.FormatInt(repository.ID, 10)
  2309. if repository.Avatar == stringifiedID {
  2310. return repository.DeleteAvatar()
  2311. }
  2312. return nil
  2313. })
  2314. }
  2315. // RelAvatarLink returns a relative link to the repository's avatar.
  2316. func (repo *Repository) RelAvatarLink() string {
  2317. return repo.relAvatarLink(x)
  2318. }
  2319. func (repo *Repository) relAvatarLink(e Engine) string {
  2320. // If no avatar - path is empty
  2321. avatarPath := repo.CustomAvatarPath()
  2322. if len(avatarPath) == 0 || !com.IsFile(avatarPath) {
  2323. switch mode := setting.RepositoryAvatarFallback; mode {
  2324. case "image":
  2325. return setting.RepositoryAvatarFallbackImage
  2326. case "random":
  2327. if err := repo.generateRandomAvatar(e); err != nil {
  2328. log.Error("generateRandomAvatar: %v", err)
  2329. }
  2330. default:
  2331. // default behaviour: do not display avatar
  2332. return ""
  2333. }
  2334. }
  2335. return setting.AppSubURL + "/repo-avatars/" + repo.Avatar
  2336. }
  2337. // avatarLink returns user avatar absolute link.
  2338. func (repo *Repository) avatarLink(e Engine) string {
  2339. link := repo.relAvatarLink(e)
  2340. // link may be empty!
  2341. if len(link) > 0 {
  2342. if link[0] == '/' && link[1] != '/' {
  2343. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  2344. }
  2345. }
  2346. return link
  2347. }
  2348. // UploadAvatar saves custom avatar for repository.
  2349. // FIXME: split uploads to different subdirs in case we have massive number of repos.
  2350. func (repo *Repository) UploadAvatar(data []byte) error {
  2351. m, err := avatar.Prepare(data)
  2352. if err != nil {
  2353. return err
  2354. }
  2355. sess := x.NewSession()
  2356. defer sess.Close()
  2357. if err = sess.Begin(); err != nil {
  2358. return err
  2359. }
  2360. oldAvatarPath := repo.CustomAvatarPath()
  2361. // Users can upload the same image to other repo - prefix it with ID
  2362. // Then repo will be removed - only it avatar file will be removed
  2363. repo.Avatar = fmt.Sprintf("%d-%x", repo.ID, md5.Sum(data))
  2364. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2365. return fmt.Errorf("UploadAvatar: Update repository avatar: %v", err)
  2366. }
  2367. if err := os.MkdirAll(setting.RepositoryAvatarUploadPath, os.ModePerm); err != nil {
  2368. return fmt.Errorf("UploadAvatar: Failed to create dir %s: %v", setting.RepositoryAvatarUploadPath, err)
  2369. }
  2370. fw, err := os.Create(repo.CustomAvatarPath())
  2371. if err != nil {
  2372. return fmt.Errorf("UploadAvatar: Create file: %v", err)
  2373. }
  2374. defer fw.Close()
  2375. if err = png.Encode(fw, *m); err != nil {
  2376. return fmt.Errorf("UploadAvatar: Encode png: %v", err)
  2377. }
  2378. if len(oldAvatarPath) > 0 && oldAvatarPath != repo.CustomAvatarPath() {
  2379. if err := os.Remove(oldAvatarPath); err != nil {
  2380. return fmt.Errorf("UploadAvatar: Failed to remove old repo avatar %s: %v", oldAvatarPath, err)
  2381. }
  2382. }
  2383. return sess.Commit()
  2384. }
  2385. // DeleteAvatar deletes the repos's custom avatar.
  2386. func (repo *Repository) DeleteAvatar() error {
  2387. // Avatar not exists
  2388. if len(repo.Avatar) == 0 {
  2389. return nil
  2390. }
  2391. avatarPath := repo.CustomAvatarPath()
  2392. log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath)
  2393. sess := x.NewSession()
  2394. defer sess.Close()
  2395. if err := sess.Begin(); err != nil {
  2396. return err
  2397. }
  2398. repo.Avatar = ""
  2399. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2400. return fmt.Errorf("DeleteAvatar: Update repository avatar: %v", err)
  2401. }
  2402. if _, err := os.Stat(avatarPath); err == nil {
  2403. if err := os.Remove(avatarPath); err != nil {
  2404. return fmt.Errorf("DeleteAvatar: Failed to remove %s: %v", avatarPath, err)
  2405. }
  2406. } else {
  2407. // // Schrodinger: file may or may not exist. See err for details.
  2408. log.Trace("DeleteAvatar[%d]: %v", err)
  2409. }
  2410. return sess.Commit()
  2411. }
  2412. // GetOriginalURLHostname returns the hostname of a URL or the URL
  2413. func (repo *Repository) GetOriginalURLHostname() string {
  2414. u, err := url.Parse(repo.OriginalURL)
  2415. if err != nil {
  2416. return repo.OriginalURL
  2417. }
  2418. return u.Host
  2419. }
上海开阖软件有限公司 沪ICP备12045867号-1