1
0

repo.go 82 KB

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