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

repo.go 69KB

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