repo.go 63 KB

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