repo.go 72 KB

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