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

repo.go 71KB

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