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

repo.go 71KB

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