repo.go 61 KB

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