repo.go 67 KB

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