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

repo.go 68KB

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