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

repo.go 64KB

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