repo.go 65 KB

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