repo.go 65 KB

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