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

repo.go 71KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444
  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. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
  1614. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
  1615. var repo Repository
  1616. has, err := x.Select("repository.*").
  1617. Join("INNER", "user", "`user`.id = repository.owner_id").
  1618. Where("repository.lower_name = ?", strings.ToLower(repoName)).
  1619. And("`user`.lower_name = ?", strings.ToLower(ownerName)).
  1620. Get(&repo)
  1621. if err != nil {
  1622. return nil, err
  1623. } else if !has {
  1624. return nil, ErrRepoNotExist{0, 0, ownerName, repoName}
  1625. }
  1626. return &repo, nil
  1627. }
  1628. // GetRepositoryByName returns the repository by given name under user if exists.
  1629. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1630. repo := &Repository{
  1631. OwnerID: ownerID,
  1632. LowerName: strings.ToLower(name),
  1633. }
  1634. has, err := x.Get(repo)
  1635. if err != nil {
  1636. return nil, err
  1637. } else if !has {
  1638. return nil, ErrRepoNotExist{0, ownerID, "", name}
  1639. }
  1640. return repo, err
  1641. }
  1642. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1643. repo := new(Repository)
  1644. has, err := e.ID(id).Get(repo)
  1645. if err != nil {
  1646. return nil, err
  1647. } else if !has {
  1648. return nil, ErrRepoNotExist{id, 0, "", ""}
  1649. }
  1650. return repo, nil
  1651. }
  1652. // GetRepositoryByID returns the repository by given id if exists.
  1653. func GetRepositoryByID(id int64) (*Repository, error) {
  1654. return getRepositoryByID(x, id)
  1655. }
  1656. // GetUserRepositories returns a list of repositories of given user.
  1657. func GetUserRepositories(userID int64, private bool, page, pageSize int, orderBy string) ([]*Repository, error) {
  1658. if len(orderBy) == 0 {
  1659. orderBy = "updated_unix DESC"
  1660. }
  1661. sess := x.
  1662. Where("owner_id = ?", userID).
  1663. OrderBy(orderBy)
  1664. if !private {
  1665. sess.And("is_private=?", false)
  1666. }
  1667. if page <= 0 {
  1668. page = 1
  1669. }
  1670. sess.Limit(pageSize, (page-1)*pageSize)
  1671. repos := make([]*Repository, 0, pageSize)
  1672. return repos, sess.Find(&repos)
  1673. }
  1674. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
  1675. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1676. repos := make([]*Repository, 0, 10)
  1677. return repos, x.
  1678. Where("owner_id = ?", userID).
  1679. And("is_mirror = ?", true).
  1680. Find(&repos)
  1681. }
  1682. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1683. return e.Count(&Repository{OwnerID: u.ID})
  1684. }
  1685. func getPublicRepositoryCount(e Engine, u *User) (int64, error) {
  1686. return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
  1687. }
  1688. func getPrivateRepositoryCount(e Engine, u *User) (int64, error) {
  1689. return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
  1690. }
  1691. // GetRepositoryCount returns the total number of repositories of user.
  1692. func GetRepositoryCount(u *User) (int64, error) {
  1693. return getRepositoryCount(x, u)
  1694. }
  1695. // GetPublicRepositoryCount returns the total number of public repositories of user.
  1696. func GetPublicRepositoryCount(u *User) (int64, error) {
  1697. return getPublicRepositoryCount(x, u)
  1698. }
  1699. // GetPrivateRepositoryCount returns the total number of private repositories of user.
  1700. func GetPrivateRepositoryCount(u *User) (int64, error) {
  1701. return getPrivateRepositoryCount(x, u)
  1702. }
  1703. // DeleteRepositoryArchives deletes all repositories' archives.
  1704. func DeleteRepositoryArchives() error {
  1705. return x.
  1706. Where("id > 0").
  1707. Iterate(new(Repository),
  1708. func(idx int, bean interface{}) error {
  1709. repo := bean.(*Repository)
  1710. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1711. })
  1712. }
  1713. // DeleteOldRepositoryArchives deletes old repository archives.
  1714. func DeleteOldRepositoryArchives() {
  1715. if !taskStatusTable.StartIfNotRunning(archiveCleanup) {
  1716. return
  1717. }
  1718. defer taskStatusTable.Stop(archiveCleanup)
  1719. log.Trace("Doing: ArchiveCleanup")
  1720. if err := x.Where("id > 0").Iterate(new(Repository), deleteOldRepositoryArchives); err != nil {
  1721. log.Error(4, "ArchiveClean: %v", err)
  1722. }
  1723. }
  1724. func deleteOldRepositoryArchives(idx int, bean interface{}) error {
  1725. repo := bean.(*Repository)
  1726. basePath := filepath.Join(repo.RepoPath(), "archives")
  1727. for _, ty := range []string{"zip", "targz"} {
  1728. path := filepath.Join(basePath, ty)
  1729. file, err := os.Open(path)
  1730. if err != nil {
  1731. if !os.IsNotExist(err) {
  1732. log.Warn("Unable to open directory %s: %v", path, err)
  1733. return err
  1734. }
  1735. // If the directory doesn't exist, that's okay.
  1736. continue
  1737. }
  1738. files, err := file.Readdir(0)
  1739. file.Close()
  1740. if err != nil {
  1741. log.Warn("Unable to read directory %s: %v", path, err)
  1742. return err
  1743. }
  1744. minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
  1745. for _, info := range files {
  1746. if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
  1747. toDelete := filepath.Join(path, info.Name())
  1748. // This is a best-effort purge, so we do not check error codes to confirm removal.
  1749. if err = os.Remove(toDelete); err != nil {
  1750. log.Trace("Unable to delete %s, but proceeding: %v", toDelete, err)
  1751. }
  1752. }
  1753. }
  1754. }
  1755. return nil
  1756. }
  1757. func gatherMissingRepoRecords() ([]*Repository, error) {
  1758. repos := make([]*Repository, 0, 10)
  1759. if err := x.
  1760. Where("id > 0").
  1761. Iterate(new(Repository),
  1762. func(idx int, bean interface{}) error {
  1763. repo := bean.(*Repository)
  1764. if !com.IsDir(repo.RepoPath()) {
  1765. repos = append(repos, repo)
  1766. }
  1767. return nil
  1768. }); err != nil {
  1769. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1770. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1771. }
  1772. }
  1773. return repos, nil
  1774. }
  1775. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1776. func DeleteMissingRepositories(doer *User) error {
  1777. repos, err := gatherMissingRepoRecords()
  1778. if err != nil {
  1779. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1780. }
  1781. if len(repos) == 0 {
  1782. return nil
  1783. }
  1784. for _, repo := range repos {
  1785. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1786. if err := DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  1787. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1788. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1789. }
  1790. }
  1791. }
  1792. return nil
  1793. }
  1794. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1795. func ReinitMissingRepositories() error {
  1796. repos, err := gatherMissingRepoRecords()
  1797. if err != nil {
  1798. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1799. }
  1800. if len(repos) == 0 {
  1801. return nil
  1802. }
  1803. for _, repo := range repos {
  1804. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1805. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1806. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1807. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1808. }
  1809. }
  1810. }
  1811. return nil
  1812. }
  1813. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1814. // to make sure the binary and custom conf path are up-to-date.
  1815. func SyncRepositoryHooks() error {
  1816. return x.Where("id > 0").Iterate(new(Repository),
  1817. func(idx int, bean interface{}) error {
  1818. if err := createDelegateHooks(bean.(*Repository).RepoPath()); err != nil {
  1819. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1820. }
  1821. if bean.(*Repository).HasWiki() {
  1822. if err := createDelegateHooks(bean.(*Repository).WikiPath()); err != nil {
  1823. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1824. }
  1825. }
  1826. return nil
  1827. })
  1828. }
  1829. // Prevent duplicate running tasks.
  1830. var taskStatusTable = sync.NewStatusTable()
  1831. const (
  1832. mirrorUpdate = "mirror_update"
  1833. gitFsck = "git_fsck"
  1834. checkRepos = "check_repos"
  1835. archiveCleanup = "archive_cleanup"
  1836. )
  1837. // GitFsck calls 'git fsck' to check repository health.
  1838. func GitFsck() {
  1839. if !taskStatusTable.StartIfNotRunning(gitFsck) {
  1840. return
  1841. }
  1842. defer taskStatusTable.Stop(gitFsck)
  1843. log.Trace("Doing: GitFsck")
  1844. if err := x.
  1845. Where("id>0").BufferSize(setting.IterateBufferSize).
  1846. Iterate(new(Repository),
  1847. func(idx int, bean interface{}) error {
  1848. repo := bean.(*Repository)
  1849. repoPath := repo.RepoPath()
  1850. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1851. desc := fmt.Sprintf("Failed to health check repository (%s): %v", repoPath, err)
  1852. log.Warn(desc)
  1853. if err = CreateRepositoryNotice(desc); err != nil {
  1854. log.Error(4, "CreateRepositoryNotice: %v", err)
  1855. }
  1856. }
  1857. return nil
  1858. }); err != nil {
  1859. log.Error(4, "GitFsck: %v", err)
  1860. }
  1861. }
  1862. // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
  1863. func GitGcRepos() error {
  1864. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1865. return x.
  1866. Where("id > 0").BufferSize(setting.IterateBufferSize).
  1867. Iterate(new(Repository),
  1868. func(idx int, bean interface{}) error {
  1869. repo := bean.(*Repository)
  1870. if err := repo.GetOwner(); err != nil {
  1871. return err
  1872. }
  1873. _, stderr, err := process.GetManager().ExecDir(
  1874. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1875. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1876. "git", args...)
  1877. if err != nil {
  1878. return fmt.Errorf("%v: %v", err, stderr)
  1879. }
  1880. return nil
  1881. })
  1882. }
  1883. type repoChecker struct {
  1884. querySQL, correctSQL string
  1885. desc string
  1886. }
  1887. func repoStatsCheck(checker *repoChecker) {
  1888. results, err := x.Query(checker.querySQL)
  1889. if err != nil {
  1890. log.Error(4, "Select %s: %v", checker.desc, err)
  1891. return
  1892. }
  1893. for _, result := range results {
  1894. id := com.StrTo(result["id"]).MustInt64()
  1895. log.Trace("Updating %s: %d", checker.desc, id)
  1896. _, err = x.Exec(checker.correctSQL, id, id)
  1897. if err != nil {
  1898. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1899. }
  1900. }
  1901. }
  1902. // CheckRepoStats checks the repository stats
  1903. func CheckRepoStats() {
  1904. if !taskStatusTable.StartIfNotRunning(checkRepos) {
  1905. return
  1906. }
  1907. defer taskStatusTable.Stop(checkRepos)
  1908. log.Trace("Doing: CheckRepoStats")
  1909. checkers := []*repoChecker{
  1910. // Repository.NumWatches
  1911. {
  1912. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1913. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1914. "repository count 'num_watches'",
  1915. },
  1916. // Repository.NumStars
  1917. {
  1918. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1919. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1920. "repository count 'num_stars'",
  1921. },
  1922. // Label.NumIssues
  1923. {
  1924. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1925. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1926. "label count 'num_issues'",
  1927. },
  1928. // User.NumRepos
  1929. {
  1930. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1931. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1932. "user count 'num_repos'",
  1933. },
  1934. // Issue.NumComments
  1935. {
  1936. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1937. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1938. "issue count 'num_comments'",
  1939. },
  1940. }
  1941. for i := range checkers {
  1942. repoStatsCheck(checkers[i])
  1943. }
  1944. // ***** START: Repository.NumClosedIssues *****
  1945. desc := "repository count 'num_closed_issues'"
  1946. 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)
  1947. if err != nil {
  1948. log.Error(4, "Select %s: %v", desc, err)
  1949. } else {
  1950. for _, result := range results {
  1951. id := com.StrTo(result["id"]).MustInt64()
  1952. log.Trace("Updating %s: %d", desc, id)
  1953. _, 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)
  1954. if err != nil {
  1955. log.Error(4, "Update %s[%d]: %v", desc, id, err)
  1956. }
  1957. }
  1958. }
  1959. // ***** END: Repository.NumClosedIssues *****
  1960. // FIXME: use checker when stop supporting old fork repo format.
  1961. // ***** START: Repository.NumForks *****
  1962. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1963. if err != nil {
  1964. log.Error(4, "Select repository count 'num_forks': %v", err)
  1965. } else {
  1966. for _, result := range results {
  1967. id := com.StrTo(result["id"]).MustInt64()
  1968. log.Trace("Updating repository count 'num_forks': %d", id)
  1969. repo, err := GetRepositoryByID(id)
  1970. if err != nil {
  1971. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1972. continue
  1973. }
  1974. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1975. if err != nil {
  1976. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1977. continue
  1978. }
  1979. repo.NumForks = int(parseCountResult(rawResult))
  1980. if err = UpdateRepository(repo, false); err != nil {
  1981. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1982. continue
  1983. }
  1984. }
  1985. }
  1986. // ***** END: Repository.NumForks *****
  1987. }
  1988. // ___________ __
  1989. // \_ _____/__________| | __
  1990. // | __)/ _ \_ __ \ |/ /
  1991. // | \( <_> ) | \/ <
  1992. // \___ / \____/|__| |__|_ \
  1993. // \/ \/
  1994. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1995. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1996. repo := new(Repository)
  1997. has, _ := x.
  1998. Where("owner_id=? AND fork_id=?", ownerID, repoID).
  1999. Get(repo)
  2000. return repo, has
  2001. }
  2002. // ForkRepository forks a repository
  2003. func ForkRepository(doer, u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  2004. forkedRepo, err := oldRepo.GetUserFork(u.ID)
  2005. if err != nil {
  2006. return nil, err
  2007. }
  2008. if forkedRepo != nil {
  2009. return nil, ErrRepoAlreadyExist{
  2010. Uname: u.Name,
  2011. Name: forkedRepo.Name,
  2012. }
  2013. }
  2014. repo := &Repository{
  2015. OwnerID: u.ID,
  2016. Owner: u,
  2017. Name: name,
  2018. LowerName: strings.ToLower(name),
  2019. Description: desc,
  2020. DefaultBranch: oldRepo.DefaultBranch,
  2021. IsPrivate: oldRepo.IsPrivate,
  2022. IsFork: true,
  2023. ForkID: oldRepo.ID,
  2024. }
  2025. sess := x.NewSession()
  2026. defer sess.Close()
  2027. if err = sess.Begin(); err != nil {
  2028. return nil, err
  2029. }
  2030. if err = createRepository(sess, doer, u, repo); err != nil {
  2031. return nil, err
  2032. }
  2033. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  2034. return nil, err
  2035. }
  2036. repoPath := RepoPath(u.Name, repo.Name)
  2037. _, stderr, err := process.GetManager().ExecTimeout(10*time.Minute,
  2038. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  2039. "git", "clone", "--bare", oldRepo.RepoPath(), repoPath)
  2040. if err != nil {
  2041. return nil, fmt.Errorf("git clone: %v", stderr)
  2042. }
  2043. _, stderr, err = process.GetManager().ExecDir(-1,
  2044. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  2045. "git", "update-server-info")
  2046. if err != nil {
  2047. return nil, fmt.Errorf("git update-server-info: %v", stderr)
  2048. }
  2049. if err = createDelegateHooks(repoPath); err != nil {
  2050. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2051. }
  2052. //Commit repo to get Fork ID
  2053. err = sess.Commit()
  2054. if err != nil {
  2055. return nil, err
  2056. }
  2057. if err = repo.UpdateSize(); err != nil {
  2058. log.Error(4, "Failed to update size for repository: %v", err)
  2059. }
  2060. // Copy LFS meta objects in new session
  2061. sess2 := x.NewSession()
  2062. defer sess2.Close()
  2063. if err = sess2.Begin(); err != nil {
  2064. return nil, err
  2065. }
  2066. var lfsObjects []*LFSMetaObject
  2067. if err = sess2.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
  2068. return nil, err
  2069. }
  2070. for _, v := range lfsObjects {
  2071. v.ID = 0
  2072. v.RepositoryID = repo.ID
  2073. if _, err = sess2.Insert(v); err != nil {
  2074. return nil, err
  2075. }
  2076. }
  2077. return repo, sess2.Commit()
  2078. }
  2079. // GetForks returns all the forks of the repository
  2080. func (repo *Repository) GetForks() ([]*Repository, error) {
  2081. forks := make([]*Repository, 0, repo.NumForks)
  2082. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2083. }
  2084. // GetUserFork return user forked repository from this repository, if not forked return nil
  2085. func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
  2086. var forkedRepo Repository
  2087. has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
  2088. if err != nil {
  2089. return nil, err
  2090. }
  2091. if !has {
  2092. return nil, nil
  2093. }
  2094. return &forkedRepo, nil
  2095. }