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

repo.go 67KB

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