repo.go 66 KB

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