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

repo.go 70KB

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