repo.go 74 KB

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