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

repo.go 67KB

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