Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

repo.go 66KB

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