repo.go 73 KB

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