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

repo.go 70KB

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