repo.go 66 KB

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