repo.go 59 KB

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