repo.go 72 KB

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