repo.go 78 KB

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