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

repo.go 71KB

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