repo.go 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  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. func (repo *Repository) cloneLink(isWiki bool) *CloneLink {
  422. repoName := repo.Name
  423. if isWiki {
  424. repoName += ".wiki"
  425. }
  426. repo.Owner = repo.MustOwner()
  427. cl := new(CloneLink)
  428. if setting.SSH.Port != 22 {
  429. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  430. } else {
  431. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  432. }
  433. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.Name, repoName)
  434. return cl
  435. }
  436. // CloneLink returns clone URLs of repository.
  437. func (repo *Repository) CloneLink() (cl *CloneLink) {
  438. return repo.cloneLink(false)
  439. }
  440. // Mirror represents a mirror information of repository.
  441. type Mirror struct {
  442. ID int64 `xorm:"pk autoincr"`
  443. RepoID int64
  444. Repo *Repository `xorm:"-"`
  445. Interval int // Hour.
  446. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  447. Updated time.Time `xorm:"-"`
  448. UpdatedUnix int64
  449. NextUpdate time.Time `xorm:"-"`
  450. NextUpdateUnix int64
  451. address string `xorm:"-"`
  452. }
  453. func (m *Mirror) BeforeInsert() {
  454. m.NextUpdateUnix = m.NextUpdate.Unix()
  455. }
  456. func (m *Mirror) BeforeUpdate() {
  457. m.UpdatedUnix = time.Now().Unix()
  458. m.NextUpdateUnix = m.NextUpdate.Unix()
  459. }
  460. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  461. var err error
  462. switch colName {
  463. case "repo_id":
  464. m.Repo, err = GetRepositoryByID(m.RepoID)
  465. if err != nil {
  466. log.Error(3, "GetRepositoryByID[%d]: %v", m.ID, err)
  467. }
  468. case "updated_unix":
  469. m.Updated = time.Unix(m.UpdatedUnix, 0).Local()
  470. case "next_updated_unix":
  471. m.NextUpdate = time.Unix(m.NextUpdateUnix, 0).Local()
  472. }
  473. }
  474. func (m *Mirror) readAddress() {
  475. if len(m.address) > 0 {
  476. return
  477. }
  478. cfg, err := ini.Load(m.Repo.GitConfigPath())
  479. if err != nil {
  480. log.Error(4, "Load: %v", err)
  481. return
  482. }
  483. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  484. }
  485. // HandleCloneUserCredentials replaces user credentials from HTTP/HTTPS URL
  486. // with placeholder <credentials>.
  487. // It will fail for any other forms of clone addresses.
  488. func HandleCloneUserCredentials(url string, mosaics bool) string {
  489. i := strings.Index(url, "@")
  490. if i == -1 {
  491. return url
  492. }
  493. start := strings.Index(url, "://")
  494. if start == -1 {
  495. return url
  496. }
  497. if mosaics {
  498. return url[:start+3] + "<credentials>" + url[i:]
  499. }
  500. return url[:start+3] + url[i+1:]
  501. }
  502. // Address returns mirror address from Git repository config without credentials.
  503. func (m *Mirror) Address() string {
  504. m.readAddress()
  505. return HandleCloneUserCredentials(m.address, false)
  506. }
  507. // FullAddress returns mirror address from Git repository config.
  508. func (m *Mirror) FullAddress() string {
  509. m.readAddress()
  510. return m.address
  511. }
  512. // SaveAddress writes new address to Git repository config.
  513. func (m *Mirror) SaveAddress(addr string) error {
  514. configPath := m.Repo.GitConfigPath()
  515. cfg, err := ini.Load(configPath)
  516. if err != nil {
  517. return fmt.Errorf("Load: %v", err)
  518. }
  519. cfg.Section("remote \"origin\"").Key("url").SetValue(addr)
  520. return cfg.SaveToIndent(configPath, "\t")
  521. }
  522. func getMirror(e Engine, repoId int64) (*Mirror, error) {
  523. m := &Mirror{RepoID: repoId}
  524. has, err := e.Get(m)
  525. if err != nil {
  526. return nil, err
  527. } else if !has {
  528. return nil, ErrMirrorNotExist
  529. }
  530. return m, nil
  531. }
  532. // GetMirror returns mirror object by given repository ID.
  533. func GetMirror(repoId int64) (*Mirror, error) {
  534. return getMirror(x, repoId)
  535. }
  536. func updateMirror(e Engine, m *Mirror) error {
  537. _, err := e.Id(m.ID).AllCols().Update(m)
  538. return err
  539. }
  540. func UpdateMirror(m *Mirror) error {
  541. return updateMirror(x, m)
  542. }
  543. func DeleteMirrorByRepoID(repoID int64) error {
  544. _, err := x.Delete(&Mirror{RepoID: repoID})
  545. return err
  546. }
  547. func createUpdateHook(repoPath string) error {
  548. return git.SetUpdateHook(repoPath,
  549. fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+setting.AppPath+"\"", setting.CustomConf))
  550. }
  551. type MigrateRepoOptions struct {
  552. Name string
  553. Description string
  554. IsPrivate bool
  555. IsMirror bool
  556. RemoteAddr string
  557. }
  558. // MigrateRepository migrates a existing repository from other project hosting.
  559. func MigrateRepository(u *User, opts MigrateRepoOptions) (*Repository, error) {
  560. repo, err := CreateRepository(u, CreateRepoOptions{
  561. Name: opts.Name,
  562. Description: opts.Description,
  563. IsPrivate: opts.IsPrivate,
  564. IsMirror: opts.IsMirror,
  565. })
  566. if err != nil {
  567. return nil, err
  568. }
  569. // Clone to temprory path and do the init commit.
  570. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  571. os.MkdirAll(tmpDir, os.ModePerm)
  572. repoPath := RepoPath(u.Name, opts.Name)
  573. if u.IsOrganization() {
  574. t, err := u.GetOwnerTeam()
  575. if err != nil {
  576. return nil, err
  577. }
  578. repo.NumWatches = t.NumMembers
  579. } else {
  580. repo.NumWatches = 1
  581. }
  582. os.RemoveAll(repoPath)
  583. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{
  584. Mirror: true,
  585. Quiet: true,
  586. Timeout: time.Duration(setting.Git.Timeout.Migrate) * time.Second,
  587. }); err != nil {
  588. return repo, fmt.Errorf("Clone: %v", err)
  589. }
  590. // Check if repository is empty.
  591. _, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
  592. if err != nil {
  593. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  594. repo.IsBare = true
  595. } else {
  596. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  597. }
  598. }
  599. if !repo.IsBare {
  600. // Try to get HEAD branch and set it as default branch.
  601. gitRepo, err := git.OpenRepository(repoPath)
  602. if err != nil {
  603. return repo, fmt.Errorf("OpenRepository: %v", err)
  604. }
  605. // BEGIN notabug patch
  606. if gitRepo.IsBranchExist("master") {
  607. repo.DefaultBranch = "master"
  608. } else {
  609. // END notabug patch
  610. headBranch, err := gitRepo.GetHEADBranch()
  611. if err != nil {
  612. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  613. }
  614. if headBranch != nil {
  615. repo.DefaultBranch = headBranch.Name
  616. }
  617. // BEGIN notabug patch
  618. }
  619. // END notabug patch
  620. }
  621. if opts.IsMirror {
  622. if _, err = x.InsertOne(&Mirror{
  623. RepoID: repo.ID,
  624. Interval: 24,
  625. EnablePrune: true,
  626. NextUpdate: time.Now().Add(24 * time.Hour),
  627. }); err != nil {
  628. return repo, fmt.Errorf("InsertOne: %v", err)
  629. }
  630. repo.IsMirror = true
  631. return repo, UpdateRepository(repo, false)
  632. }
  633. return CleanUpMigrateInfo(repo, repoPath)
  634. }
  635. // Finish migrating repository with things that don't need to be done for mirrors.
  636. func CleanUpMigrateInfo(repo *Repository, repoPath string) (*Repository, error) {
  637. if err := createUpdateHook(repoPath); err != nil {
  638. return repo, fmt.Errorf("createUpdateHook: %v", err)
  639. }
  640. // Clean up mirror info which prevents "push --all".
  641. // This also removes possible user credentials.
  642. configPath := repo.GitConfigPath()
  643. cfg, err := ini.Load(configPath)
  644. if err != nil {
  645. return repo, fmt.Errorf("open config file: %v", err)
  646. }
  647. cfg.DeleteSection("remote \"origin\"")
  648. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  649. return repo, fmt.Errorf("save config file: %v", err)
  650. }
  651. return repo, UpdateRepository(repo, false)
  652. }
  653. // initRepoCommit temporarily changes with work directory.
  654. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  655. var stderr string
  656. if _, stderr, err = process.ExecDir(-1,
  657. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  658. "git", "add", "--all"); err != nil {
  659. return fmt.Errorf("git add: %s", stderr)
  660. }
  661. if _, stderr, err = process.ExecDir(-1,
  662. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  663. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  664. "-m", "initial commit"); err != nil {
  665. return fmt.Errorf("git commit: %s", stderr)
  666. }
  667. if _, stderr, err = process.ExecDir(-1,
  668. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  669. "git", "push", "origin", "master"); err != nil {
  670. return fmt.Errorf("git push: %s", stderr)
  671. }
  672. return nil
  673. }
  674. type CreateRepoOptions struct {
  675. Name string
  676. Description string
  677. Gitignores string
  678. License string
  679. Readme string
  680. IsPrivate bool
  681. IsMirror bool
  682. AutoInit bool
  683. }
  684. func getRepoInitFile(tp, name string) ([]byte, error) {
  685. relPath := path.Join("conf", tp, name)
  686. // Use custom file when available.
  687. customPath := path.Join(setting.CustomPath, relPath)
  688. if com.IsFile(customPath) {
  689. return ioutil.ReadFile(customPath)
  690. }
  691. return bindata.Asset(relPath)
  692. }
  693. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  694. // Clone to temprory path and do the init commit.
  695. _, stderr, err := process.Exec(
  696. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  697. if err != nil {
  698. return fmt.Errorf("git clone: %v - %s", err, stderr)
  699. }
  700. // README
  701. data, err := getRepoInitFile("readme", opts.Readme)
  702. if err != nil {
  703. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  704. }
  705. cloneLink := repo.CloneLink()
  706. match := map[string]string{
  707. "Name": repo.Name,
  708. "Description": repo.Description,
  709. "CloneURL.SSH": cloneLink.SSH,
  710. "CloneURL.HTTPS": cloneLink.HTTPS,
  711. }
  712. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  713. []byte(com.Expand(string(data), match)), 0644); err != nil {
  714. return fmt.Errorf("write README.md: %v", err)
  715. }
  716. // .gitignore
  717. if len(opts.Gitignores) > 0 {
  718. var buf bytes.Buffer
  719. names := strings.Split(opts.Gitignores, ",")
  720. for _, name := range names {
  721. data, err = getRepoInitFile("gitignore", name)
  722. if err != nil {
  723. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  724. }
  725. buf.WriteString("# ---> " + name + "\n")
  726. buf.Write(data)
  727. buf.WriteString("\n")
  728. }
  729. if buf.Len() > 0 {
  730. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  731. return fmt.Errorf("write .gitignore: %v", err)
  732. }
  733. }
  734. }
  735. // LICENSE
  736. if len(opts.License) > 0 {
  737. data, err = getRepoInitFile("license", opts.License)
  738. if err != nil {
  739. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  740. }
  741. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  742. return fmt.Errorf("write LICENSE: %v", err)
  743. }
  744. }
  745. return nil
  746. }
  747. // InitRepository initializes README and .gitignore if needed.
  748. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  749. // Somehow the directory could exist.
  750. if com.IsExist(repoPath) {
  751. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  752. }
  753. // Init bare new repository.
  754. if err = git.InitRepository(repoPath, true); err != nil {
  755. return fmt.Errorf("InitRepository: %v", err)
  756. } else if err = createUpdateHook(repoPath); err != nil {
  757. return fmt.Errorf("createUpdateHook: %v", err)
  758. }
  759. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  760. // Initialize repository according to user's choice.
  761. if opts.AutoInit {
  762. os.MkdirAll(tmpDir, os.ModePerm)
  763. defer os.RemoveAll(tmpDir)
  764. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  765. return fmt.Errorf("prepareRepoCommit: %v", err)
  766. }
  767. // Apply changes and commit.
  768. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  769. return fmt.Errorf("initRepoCommit: %v", err)
  770. }
  771. }
  772. // Re-fetch the repository from database before updating it (else it would
  773. // override changes that were done earlier with sql)
  774. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  775. return fmt.Errorf("getRepositoryByID: %v", err)
  776. }
  777. if !opts.AutoInit {
  778. repo.IsBare = true
  779. }
  780. repo.DefaultBranch = "master"
  781. if err = updateRepository(e, repo, false); err != nil {
  782. return fmt.Errorf("updateRepository: %v", err)
  783. }
  784. return nil
  785. }
  786. var (
  787. reservedRepoNames = []string{".", ".."}
  788. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  789. )
  790. func IsUsableRepoName(name string) error {
  791. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  792. }
  793. func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
  794. if err = IsUsableRepoName(repo.Name); err != nil {
  795. return err
  796. }
  797. has, err := isRepositoryExist(e, u, repo.Name)
  798. if err != nil {
  799. return fmt.Errorf("IsRepositoryExist: %v", err)
  800. } else if has {
  801. return ErrRepoAlreadyExist{u.Name, repo.Name}
  802. }
  803. if _, err = e.Insert(repo); err != nil {
  804. return err
  805. }
  806. u.NumRepos++
  807. // Remember visibility preference.
  808. u.LastRepoVisibility = repo.IsPrivate
  809. if err = updateUser(e, u); err != nil {
  810. return fmt.Errorf("updateUser: %v", err)
  811. }
  812. // Give access to all members in owner team.
  813. if u.IsOrganization() {
  814. t, err := u.getOwnerTeam(e)
  815. if err != nil {
  816. return fmt.Errorf("getOwnerTeam: %v", err)
  817. } else if err = t.addRepository(e, repo); err != nil {
  818. return fmt.Errorf("addRepository: %v", err)
  819. }
  820. } else {
  821. // Organization automatically called this in addRepository method.
  822. if err = repo.recalculateAccesses(e); err != nil {
  823. return fmt.Errorf("recalculateAccesses: %v", err)
  824. }
  825. }
  826. if err = watchRepo(e, u.ID, repo.ID, true); err != nil {
  827. return fmt.Errorf("watchRepo: %v", err)
  828. } else if err = newRepoAction(e, u, repo); err != nil {
  829. return fmt.Errorf("newRepoAction: %v", err)
  830. }
  831. return nil
  832. }
  833. // CreateRepository creates a repository for given user or organization.
  834. func CreateRepository(u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  835. if !u.CanCreateRepo() {
  836. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  837. }
  838. repo := &Repository{
  839. OwnerID: u.ID,
  840. Owner: u,
  841. Name: opts.Name,
  842. LowerName: strings.ToLower(opts.Name),
  843. Description: opts.Description,
  844. IsPrivate: opts.IsPrivate,
  845. EnableWiki: true,
  846. EnableIssues: true,
  847. EnablePulls: true,
  848. }
  849. sess := x.NewSession()
  850. defer sessionRelease(sess)
  851. if err = sess.Begin(); err != nil {
  852. return nil, err
  853. }
  854. if err = createRepository(sess, u, repo); err != nil {
  855. return nil, err
  856. }
  857. // No need for init mirror.
  858. if !opts.IsMirror {
  859. repoPath := RepoPath(u.Name, repo.Name)
  860. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  861. if err2 := os.RemoveAll(repoPath); err2 != nil {
  862. log.Error(4, "initRepository: %v", err)
  863. return nil, fmt.Errorf(
  864. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  865. }
  866. return nil, fmt.Errorf("initRepository: %v", err)
  867. }
  868. _, stderr, err := process.ExecDir(-1,
  869. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  870. "git", "update-server-info")
  871. if err != nil {
  872. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  873. }
  874. }
  875. return repo, sess.Commit()
  876. }
  877. func countRepositories(userID int64, private bool) int64 {
  878. sess := x.Where("id > 0")
  879. if userID > 0 {
  880. sess.And("owner_id = ?", userID)
  881. }
  882. if !private {
  883. sess.And("is_private=?", false)
  884. }
  885. count, err := sess.Count(new(Repository))
  886. if err != nil {
  887. log.Error(4, "countRepositories: %v", err)
  888. }
  889. return count
  890. }
  891. // CountRepositories returns number of repositories.
  892. // Argument private only takes effect when it is false,
  893. // set it true to count all repositories.
  894. func CountRepositories(private bool) int64 {
  895. return countRepositories(-1, private)
  896. }
  897. // CountUserRepositories returns number of repositories user owns.
  898. // Argument private only takes effect when it is false,
  899. // set it true to count all repositories.
  900. func CountUserRepositories(userID int64, private bool) int64 {
  901. return countRepositories(userID, private)
  902. }
  903. func Repositories(page, pageSize int) (_ []*Repository, err error) {
  904. repos := make([]*Repository, 0, pageSize)
  905. return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos)
  906. }
  907. // RepositoriesWithUsers returns number of repos in given page.
  908. func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
  909. repos, err := Repositories(page, pageSize)
  910. if err != nil {
  911. return nil, fmt.Errorf("Repositories: %v", err)
  912. }
  913. for i := range repos {
  914. if err = repos[i].GetOwner(); err != nil {
  915. return nil, err
  916. }
  917. }
  918. return repos, nil
  919. }
  920. // RepoPath returns repository path by given user and repository name.
  921. func RepoPath(userName, repoName string) string {
  922. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  923. }
  924. // TransferOwnership transfers all corresponding setting from old user to new one.
  925. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  926. newOwner, err := GetUserByName(newOwnerName)
  927. if err != nil {
  928. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  929. }
  930. // Check if new owner has repository with same name.
  931. has, err := IsRepositoryExist(newOwner, repo.Name)
  932. if err != nil {
  933. return fmt.Errorf("IsRepositoryExist: %v", err)
  934. } else if has {
  935. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  936. }
  937. sess := x.NewSession()
  938. defer sessionRelease(sess)
  939. if err = sess.Begin(); err != nil {
  940. return fmt.Errorf("sess.Begin: %v", err)
  941. }
  942. owner := repo.Owner
  943. // Note: we have to set value here to make sure recalculate accesses is based on
  944. // new owner.
  945. repo.OwnerID = newOwner.ID
  946. repo.Owner = newOwner
  947. // Update repository.
  948. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  949. return fmt.Errorf("update owner: %v", err)
  950. }
  951. // Remove redundant collaborators.
  952. collaborators, err := repo.getCollaborators(sess)
  953. if err != nil {
  954. return fmt.Errorf("getCollaborators: %v", err)
  955. }
  956. // Dummy object.
  957. collaboration := &Collaboration{RepoID: repo.ID}
  958. for _, c := range collaborators {
  959. collaboration.UserID = c.ID
  960. if c.ID == newOwner.ID || newOwner.IsOrgMember(c.ID) {
  961. if _, err = sess.Delete(collaboration); err != nil {
  962. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  963. }
  964. }
  965. }
  966. // Remove old team-repository relations.
  967. if owner.IsOrganization() {
  968. if err = owner.getTeams(sess); err != nil {
  969. return fmt.Errorf("getTeams: %v", err)
  970. }
  971. for _, t := range owner.Teams {
  972. if !t.hasRepository(sess, repo.ID) {
  973. continue
  974. }
  975. t.NumRepos--
  976. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  977. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  978. }
  979. }
  980. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  981. return fmt.Errorf("removeOrgRepo: %v", err)
  982. }
  983. }
  984. if newOwner.IsOrganization() {
  985. t, err := newOwner.getOwnerTeam(sess)
  986. if err != nil {
  987. return fmt.Errorf("getOwnerTeam: %v", err)
  988. } else if err = t.addRepository(sess, repo); err != nil {
  989. return fmt.Errorf("add to owner team: %v", err)
  990. }
  991. } else {
  992. // Organization called this in addRepository method.
  993. if err = repo.recalculateAccesses(sess); err != nil {
  994. return fmt.Errorf("recalculateAccesses: %v", err)
  995. }
  996. }
  997. // Update repository count.
  998. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  999. return fmt.Errorf("increase new owner repository count: %v", err)
  1000. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1001. return fmt.Errorf("decrease old owner repository count: %v", err)
  1002. }
  1003. if err = watchRepo(sess, newOwner.ID, repo.ID, true); err != nil {
  1004. return fmt.Errorf("watchRepo: %v", err)
  1005. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  1006. return fmt.Errorf("transferRepoAction: %v", err)
  1007. }
  1008. // Rename remote repository to new path and delete local copy.
  1009. os.MkdirAll(UserPath(newOwner.Name), os.ModePerm)
  1010. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1011. return fmt.Errorf("rename repository directory: %v", err)
  1012. }
  1013. RemoveAllWithNotice("Delete repository local copy", repo.LocalCopyPath())
  1014. // Rename remote wiki repository to new path and delete local copy.
  1015. wikiPath := WikiPath(owner.Name, repo.Name)
  1016. if com.IsExist(wikiPath) {
  1017. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1018. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1019. return fmt.Errorf("rename repository wiki: %v", err)
  1020. }
  1021. }
  1022. return sess.Commit()
  1023. }
  1024. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1025. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1026. oldRepoName = strings.ToLower(oldRepoName)
  1027. newRepoName = strings.ToLower(newRepoName)
  1028. if err = IsUsableRepoName(newRepoName); err != nil {
  1029. return err
  1030. }
  1031. has, err := IsRepositoryExist(u, newRepoName)
  1032. if err != nil {
  1033. return fmt.Errorf("IsRepositoryExist: %v", err)
  1034. } else if has {
  1035. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1036. }
  1037. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1038. if err != nil {
  1039. return fmt.Errorf("GetRepositoryByName: %v", err)
  1040. }
  1041. // Change repository directory name.
  1042. if err = os.Rename(repo.RepoPath(), RepoPath(u.Name, newRepoName)); err != nil {
  1043. return fmt.Errorf("rename repository directory: %v", err)
  1044. }
  1045. wikiPath := repo.WikiPath()
  1046. if com.IsExist(wikiPath) {
  1047. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1048. return fmt.Errorf("rename repository wiki: %v", err)
  1049. }
  1050. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1051. }
  1052. return nil
  1053. }
  1054. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1055. repos := make([]*Repository, 0, 10)
  1056. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  1057. }
  1058. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1059. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1060. return getRepositoriesByForkID(x, forkID)
  1061. }
  1062. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1063. repo.LowerName = strings.ToLower(repo.Name)
  1064. if len(repo.Description) > 255 {
  1065. repo.Description = repo.Description[:255]
  1066. }
  1067. if len(repo.Website) > 255 {
  1068. repo.Website = repo.Website[:255]
  1069. }
  1070. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  1071. return fmt.Errorf("update: %v", err)
  1072. }
  1073. if visibilityChanged {
  1074. if err = repo.getOwner(e); err != nil {
  1075. return fmt.Errorf("getOwner: %v", err)
  1076. }
  1077. if repo.Owner.IsOrganization() {
  1078. // Organization repository need to recalculate access table when visivility is changed.
  1079. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1080. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1081. }
  1082. }
  1083. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1084. if err != nil {
  1085. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1086. }
  1087. for i := range forkRepos {
  1088. forkRepos[i].IsPrivate = repo.IsPrivate
  1089. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1090. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1091. }
  1092. }
  1093. }
  1094. return nil
  1095. }
  1096. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1097. sess := x.NewSession()
  1098. defer sessionRelease(sess)
  1099. if err = sess.Begin(); err != nil {
  1100. return err
  1101. }
  1102. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  1103. return fmt.Errorf("updateRepository: %v", err)
  1104. }
  1105. return sess.Commit()
  1106. }
  1107. // DeleteRepository deletes a repository for a user or organization.
  1108. func DeleteRepository(uid, repoID int64) error {
  1109. repo := &Repository{ID: repoID, OwnerID: uid}
  1110. has, err := x.Get(repo)
  1111. if err != nil {
  1112. return err
  1113. } else if !has {
  1114. return ErrRepoNotExist{repoID, uid, ""}
  1115. }
  1116. // In case is a organization.
  1117. org, err := GetUserByID(uid)
  1118. if err != nil {
  1119. return err
  1120. }
  1121. if org.IsOrganization() {
  1122. if err = org.GetTeams(); err != nil {
  1123. return err
  1124. }
  1125. }
  1126. sess := x.NewSession()
  1127. defer sessionRelease(sess)
  1128. if err = sess.Begin(); err != nil {
  1129. return err
  1130. }
  1131. if org.IsOrganization() {
  1132. for _, t := range org.Teams {
  1133. if !t.hasRepository(sess, repoID) {
  1134. continue
  1135. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1136. return err
  1137. }
  1138. }
  1139. }
  1140. if err = deleteBeans(sess,
  1141. &Repository{ID: repoID},
  1142. &Access{RepoID: repo.ID},
  1143. &Action{RepoID: repo.ID},
  1144. &Watch{RepoID: repoID},
  1145. &Star{RepoID: repoID},
  1146. &Mirror{RepoID: repoID},
  1147. &IssueUser{RepoID: repoID},
  1148. &Milestone{RepoID: repoID},
  1149. &Release{RepoID: repoID},
  1150. &Collaboration{RepoID: repoID},
  1151. &PullRequest{BaseRepoID: repoID},
  1152. ); err != nil {
  1153. return fmt.Errorf("deleteBeans: %v", err)
  1154. }
  1155. // Delete comments and attachments.
  1156. issues := make([]*Issue, 0, 25)
  1157. attachmentPaths := make([]string, 0, len(issues))
  1158. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  1159. return err
  1160. }
  1161. for i := range issues {
  1162. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  1163. return err
  1164. }
  1165. attachments := make([]*Attachment, 0, 5)
  1166. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  1167. return err
  1168. }
  1169. for j := range attachments {
  1170. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1171. }
  1172. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  1173. return err
  1174. }
  1175. }
  1176. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1177. return err
  1178. }
  1179. if repo.IsFork {
  1180. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1181. return fmt.Errorf("decrease fork count: %v", err)
  1182. }
  1183. }
  1184. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1185. return err
  1186. }
  1187. // Remove repository files.
  1188. repoPath := repo.repoPath(sess)
  1189. RemoveAllWithNotice("Delete repository files", repoPath)
  1190. repo.DeleteWiki()
  1191. // Remove attachment files.
  1192. for i := range attachmentPaths {
  1193. RemoveAllWithNotice("Delete attachment", attachmentPaths[i])
  1194. }
  1195. if err = sess.Commit(); err != nil {
  1196. return fmt.Errorf("Commit: %v", err)
  1197. }
  1198. if repo.NumForks > 0 {
  1199. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1200. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1201. }
  1202. }
  1203. return nil
  1204. }
  1205. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1206. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1207. func GetRepositoryByRef(ref string) (*Repository, error) {
  1208. n := strings.IndexByte(ref, byte('/'))
  1209. if n < 2 {
  1210. return nil, ErrInvalidReference
  1211. }
  1212. userName, repoName := ref[:n], ref[n+1:]
  1213. user, err := GetUserByName(userName)
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. return GetRepositoryByName(user.ID, repoName)
  1218. }
  1219. // GetRepositoryByName returns the repository by given name under user if exists.
  1220. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  1221. repo := &Repository{
  1222. OwnerID: uid,
  1223. LowerName: strings.ToLower(repoName),
  1224. }
  1225. has, err := x.Get(repo)
  1226. if err != nil {
  1227. return nil, err
  1228. } else if !has {
  1229. return nil, ErrRepoNotExist{0, uid, repoName}
  1230. }
  1231. return repo, err
  1232. }
  1233. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1234. repo := new(Repository)
  1235. has, err := e.Id(id).Get(repo)
  1236. if err != nil {
  1237. return nil, err
  1238. } else if !has {
  1239. return nil, ErrRepoNotExist{id, 0, ""}
  1240. }
  1241. return repo, nil
  1242. }
  1243. // GetRepositoryByID returns the repository by given id if exists.
  1244. func GetRepositoryByID(id int64) (*Repository, error) {
  1245. return getRepositoryByID(x, id)
  1246. }
  1247. // GetUserRepositories returns a list of repositories of given user.
  1248. func GetUserRepositories(userID int64, private bool, page, pageSize int) ([]*Repository, error) {
  1249. sess := x.Where("owner_id = ?", userID).Desc("updated_unix")
  1250. if !private {
  1251. sess.And("is_private=?", false)
  1252. }
  1253. if page <= 0 {
  1254. page = 1
  1255. }
  1256. sess.Limit(pageSize, (page-1)*pageSize)
  1257. repos := make([]*Repository, 0, pageSize)
  1258. return repos, sess.Find(&repos)
  1259. }
  1260. // GetUserRepositories returns a list of mirror repositories of given user.
  1261. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1262. repos := make([]*Repository, 0, 10)
  1263. return repos, x.Where("owner_id = ?", userID).And("is_mirror = ?", true).Find(&repos)
  1264. }
  1265. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1266. func GetRecentUpdatedRepositories(page, pageSize int) (repos []*Repository, err error) {
  1267. return repos, x.Limit(pageSize, (page-1)*pageSize).
  1268. Where("is_private=?", false).Limit(pageSize).Desc("updated_unix").Find(&repos)
  1269. }
  1270. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1271. return x.Count(&Repository{OwnerID: u.ID})
  1272. }
  1273. // GetRepositoryCount returns the total number of repositories of user.
  1274. func GetRepositoryCount(u *User) (int64, error) {
  1275. return getRepositoryCount(x, u)
  1276. }
  1277. type SearchRepoOptions struct {
  1278. Keyword string
  1279. OwnerID int64
  1280. OrderBy string
  1281. Private bool // Include private repositories in results
  1282. Page int
  1283. PageSize int // Can be smaller than or equal to setting.ExplorePagingNum
  1284. }
  1285. // SearchRepositoryByName takes keyword and part of repository name to search,
  1286. // it returns results in given range and number of total results.
  1287. func SearchRepositoryByName(opts *SearchRepoOptions) (repos []*Repository, _ int64, _ error) {
  1288. if len(opts.Keyword) == 0 {
  1289. return repos, 0, nil
  1290. }
  1291. opts.Keyword = strings.ToLower(opts.Keyword)
  1292. if opts.Page <= 0 {
  1293. opts.Page = 1
  1294. }
  1295. repos = make([]*Repository, 0, opts.PageSize)
  1296. // Append conditions
  1297. sess := x.Where("LOWER(lower_name) LIKE ?", "%"+opts.Keyword+"%")
  1298. if opts.OwnerID > 0 {
  1299. sess.And("owner_id = ?", opts.OwnerID)
  1300. }
  1301. if !opts.Private {
  1302. sess.And("is_private=?", false)
  1303. }
  1304. var countSess xorm.Session
  1305. countSess = *sess
  1306. count, err := countSess.Count(new(Repository))
  1307. if err != nil {
  1308. return nil, 0, fmt.Errorf("Count: %v", err)
  1309. }
  1310. if len(opts.OrderBy) > 0 {
  1311. sess.OrderBy(opts.OrderBy)
  1312. }
  1313. return repos, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&repos)
  1314. }
  1315. // DeleteRepositoryArchives deletes all repositories' archives.
  1316. func DeleteRepositoryArchives() error {
  1317. return x.Where("id > 0").Iterate(new(Repository),
  1318. func(idx int, bean interface{}) error {
  1319. repo := bean.(*Repository)
  1320. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1321. })
  1322. }
  1323. func gatherMissingRepoRecords() ([]*Repository, error) {
  1324. repos := make([]*Repository, 0, 10)
  1325. if err := x.Where("id > 0").Iterate(new(Repository),
  1326. func(idx int, bean interface{}) error {
  1327. repo := bean.(*Repository)
  1328. if !com.IsDir(repo.RepoPath()) {
  1329. repos = append(repos, repo)
  1330. }
  1331. return nil
  1332. }); err != nil {
  1333. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1334. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1335. }
  1336. }
  1337. return repos, nil
  1338. }
  1339. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1340. func DeleteMissingRepositories() error {
  1341. repos, err := gatherMissingRepoRecords()
  1342. if err != nil {
  1343. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1344. }
  1345. if len(repos) == 0 {
  1346. return nil
  1347. }
  1348. for _, repo := range repos {
  1349. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1350. if err := DeleteRepository(repo.OwnerID, repo.ID); err != nil {
  1351. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1352. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1353. }
  1354. }
  1355. }
  1356. return nil
  1357. }
  1358. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1359. func ReinitMissingRepositories() error {
  1360. repos, err := gatherMissingRepoRecords()
  1361. if err != nil {
  1362. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1363. }
  1364. if len(repos) == 0 {
  1365. return nil
  1366. }
  1367. for _, repo := range repos {
  1368. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1369. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1370. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1371. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1372. }
  1373. }
  1374. }
  1375. return nil
  1376. }
  1377. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1378. func RewriteRepositoryUpdateHook() error {
  1379. return x.Where("id > 0").Iterate(new(Repository),
  1380. func(idx int, bean interface{}) error {
  1381. repo := bean.(*Repository)
  1382. return createUpdateHook(repo.RepoPath())
  1383. })
  1384. }
  1385. // statusPool represents a pool of status with true/false.
  1386. type statusPool struct {
  1387. lock sync.RWMutex
  1388. pool map[string]bool
  1389. }
  1390. // Start sets value of given name to true in the pool.
  1391. func (p *statusPool) Start(name string) {
  1392. p.lock.Lock()
  1393. defer p.lock.Unlock()
  1394. p.pool[name] = true
  1395. }
  1396. // Stop sets value of given name to false in the pool.
  1397. func (p *statusPool) Stop(name string) {
  1398. p.lock.Lock()
  1399. defer p.lock.Unlock()
  1400. p.pool[name] = false
  1401. }
  1402. // IsRunning checks if value of given name is set to true in the pool.
  1403. func (p *statusPool) IsRunning(name string) bool {
  1404. p.lock.RLock()
  1405. defer p.lock.RUnlock()
  1406. return p.pool[name]
  1407. }
  1408. // Prevent duplicate running tasks.
  1409. var taskStatusPool = &statusPool{
  1410. pool: make(map[string]bool),
  1411. }
  1412. const (
  1413. _MIRROR_UPDATE = "mirror_update"
  1414. _GIT_FSCK = "git_fsck"
  1415. _CHECK_REPOs = "check_repos"
  1416. )
  1417. // MirrorUpdate checks and updates mirror repositories.
  1418. func MirrorUpdate() {
  1419. if taskStatusPool.IsRunning(_MIRROR_UPDATE) {
  1420. return
  1421. }
  1422. taskStatusPool.Start(_MIRROR_UPDATE)
  1423. defer taskStatusPool.Stop(_MIRROR_UPDATE)
  1424. log.Trace("Doing: MirrorUpdate")
  1425. mirrors := make([]*Mirror, 0, 10)
  1426. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1427. m := bean.(*Mirror)
  1428. if m.Repo == nil {
  1429. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1430. return nil
  1431. }
  1432. repoPath := m.Repo.RepoPath()
  1433. gitArgs := []string{"remote", "update"}
  1434. if m.EnablePrune {
  1435. gitArgs = append(gitArgs, "--prune")
  1436. }
  1437. if _, stderr, err := process.ExecDir(
  1438. time.Duration(setting.Git.Timeout.Mirror)*time.Second,
  1439. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1440. "git", gitArgs...); err != nil {
  1441. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1442. log.Error(4, desc)
  1443. if err = CreateRepositoryNotice(desc); err != nil {
  1444. log.Error(4, "CreateRepositoryNotice: %v", err)
  1445. }
  1446. return nil
  1447. }
  1448. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1449. mirrors = append(mirrors, m)
  1450. return nil
  1451. }); err != nil {
  1452. log.Error(4, "MirrorUpdate: %v", err)
  1453. }
  1454. for i := range mirrors {
  1455. if err := UpdateMirror(mirrors[i]); err != nil {
  1456. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1457. }
  1458. }
  1459. }
  1460. // GitFsck calls 'git fsck' to check repository health.
  1461. func GitFsck() {
  1462. if taskStatusPool.IsRunning(_GIT_FSCK) {
  1463. return
  1464. }
  1465. taskStatusPool.Start(_GIT_FSCK)
  1466. defer taskStatusPool.Stop(_GIT_FSCK)
  1467. log.Trace("Doing: GitFsck")
  1468. if err := x.Where("id>0").Iterate(new(Repository),
  1469. func(idx int, bean interface{}) error {
  1470. repo := bean.(*Repository)
  1471. repoPath := repo.RepoPath()
  1472. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1473. desc := fmt.Sprintf("Fail to health check repository (%s): %v", repoPath, err)
  1474. log.Warn(desc)
  1475. if err = CreateRepositoryNotice(desc); err != nil {
  1476. log.Error(4, "CreateRepositoryNotice: %v", err)
  1477. }
  1478. }
  1479. return nil
  1480. }); err != nil {
  1481. log.Error(4, "GitFsck: %v", err)
  1482. }
  1483. }
  1484. func GitGcRepos() error {
  1485. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1486. return x.Where("id > 0").Iterate(new(Repository),
  1487. func(idx int, bean interface{}) error {
  1488. repo := bean.(*Repository)
  1489. if err := repo.GetOwner(); err != nil {
  1490. return err
  1491. }
  1492. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1493. if err != nil {
  1494. return fmt.Errorf("%v: %v", err, stderr)
  1495. }
  1496. return nil
  1497. })
  1498. }
  1499. type repoChecker struct {
  1500. querySQL, correctSQL string
  1501. desc string
  1502. }
  1503. func repoStatsCheck(checker *repoChecker) {
  1504. results, err := x.Query(checker.querySQL)
  1505. if err != nil {
  1506. log.Error(4, "Select %s: %v", checker.desc, err)
  1507. return
  1508. }
  1509. for _, result := range results {
  1510. id := com.StrTo(result["id"]).MustInt64()
  1511. log.Trace("Updating %s: %d", checker.desc, id)
  1512. _, err = x.Exec(checker.correctSQL, id, id)
  1513. if err != nil {
  1514. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1515. }
  1516. }
  1517. }
  1518. func CheckRepoStats() {
  1519. if taskStatusPool.IsRunning(_CHECK_REPOs) {
  1520. return
  1521. }
  1522. taskStatusPool.Start(_CHECK_REPOs)
  1523. defer taskStatusPool.Stop(_CHECK_REPOs)
  1524. log.Trace("Doing: CheckRepoStats")
  1525. checkers := []*repoChecker{
  1526. // Repository.NumWatches
  1527. {
  1528. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1529. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1530. "repository count 'num_watches'",
  1531. },
  1532. // Repository.NumStars
  1533. {
  1534. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1535. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1536. "repository count 'num_stars'",
  1537. },
  1538. // Label.NumIssues
  1539. {
  1540. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1541. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1542. "label count 'num_issues'",
  1543. },
  1544. // User.NumRepos
  1545. {
  1546. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1547. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1548. "user count 'num_repos'",
  1549. },
  1550. // Issue.NumComments
  1551. {
  1552. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1553. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1554. "issue count 'num_comments'",
  1555. },
  1556. }
  1557. for i := range checkers {
  1558. repoStatsCheck(checkers[i])
  1559. }
  1560. // ***** START: Repository.NumClosedIssues *****
  1561. desc := "repository count 'num_closed_issues'"
  1562. 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)
  1563. if err != nil {
  1564. log.Error(4, "Select %s: %v", desc, err)
  1565. } else {
  1566. for _, result := range results {
  1567. id := com.StrTo(result["id"]).MustInt64()
  1568. log.Trace("Updating %s: %d", desc, id)
  1569. _, 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)
  1570. if err != nil {
  1571. log.Error(4, "Update %s[%d]: %v", desc, id, err)
  1572. }
  1573. }
  1574. }
  1575. // ***** END: Repository.NumClosedIssues *****
  1576. // FIXME: use checker when stop supporting old fork repo format.
  1577. // ***** START: Repository.NumForks *****
  1578. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1579. if err != nil {
  1580. log.Error(4, "Select repository count 'num_forks': %v", err)
  1581. } else {
  1582. for _, result := range results {
  1583. id := com.StrTo(result["id"]).MustInt64()
  1584. log.Trace("Updating repository count 'num_forks': %d", id)
  1585. repo, err := GetRepositoryByID(id)
  1586. if err != nil {
  1587. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1588. continue
  1589. }
  1590. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1591. if err != nil {
  1592. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1593. continue
  1594. }
  1595. repo.NumForks = int(parseCountResult(rawResult))
  1596. if err = UpdateRepository(repo, false); err != nil {
  1597. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1598. continue
  1599. }
  1600. }
  1601. }
  1602. // ***** END: Repository.NumForks *****
  1603. }
  1604. type RepositoryList []*Repository
  1605. func (repos RepositoryList) loadAttributes(e Engine) error {
  1606. if len(repos) == 0 {
  1607. return nil
  1608. }
  1609. // Load owners.
  1610. set := make(map[int64]*User)
  1611. for i := range repos {
  1612. set[repos[i].OwnerID] = nil
  1613. }
  1614. userIDs := make([]int64, 0, len(set))
  1615. for userID := range set {
  1616. userIDs = append(userIDs, userID)
  1617. }
  1618. users := make([]*User, 0, len(userIDs))
  1619. if err := e.Where("id > 0").In("id", userIDs).Find(&users); err != nil {
  1620. return fmt.Errorf("find users: %v", err)
  1621. }
  1622. for i := range users {
  1623. set[users[i].ID] = users[i]
  1624. }
  1625. for i := range repos {
  1626. repos[i].Owner = set[repos[i].OwnerID]
  1627. }
  1628. return nil
  1629. }
  1630. func (repos RepositoryList) LoadAttributes() error {
  1631. return repos.loadAttributes(x)
  1632. }
  1633. type MirrorRepositoryList []*Repository
  1634. func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
  1635. if len(repos) == 0 {
  1636. return nil
  1637. }
  1638. // Load mirrors.
  1639. repoIDs := make([]int64, 0, len(repos))
  1640. for i := range repos {
  1641. if !repos[i].IsMirror {
  1642. continue
  1643. }
  1644. repoIDs = append(repoIDs, repos[i].ID)
  1645. }
  1646. mirrors := make([]*Mirror, 0, len(repoIDs))
  1647. if err := e.Where("id > 0").In("repo_id", repoIDs).Find(&mirrors); err != nil {
  1648. return fmt.Errorf("find mirrors: %v", err)
  1649. }
  1650. set := make(map[int64]*Mirror)
  1651. for i := range mirrors {
  1652. set[mirrors[i].RepoID] = mirrors[i]
  1653. }
  1654. for i := range repos {
  1655. repos[i].Mirror = set[repos[i].ID]
  1656. }
  1657. return nil
  1658. }
  1659. func (repos MirrorRepositoryList) LoadAttributes() error {
  1660. return repos.loadAttributes(x)
  1661. }
  1662. // __ __ __ .__
  1663. // / \ / \_____ _/ |_ ____ | |__
  1664. // \ \/\/ /\__ \\ __\/ ___\| | \
  1665. // \ / / __ \| | \ \___| Y \
  1666. // \__/\ / (____ /__| \___ >___| /
  1667. // \/ \/ \/ \/
  1668. // Watch is connection request for receiving repository notification.
  1669. type Watch struct {
  1670. ID int64 `xorm:"pk autoincr"`
  1671. UserID int64 `xorm:"UNIQUE(watch)"`
  1672. RepoID int64 `xorm:"UNIQUE(watch)"`
  1673. }
  1674. func isWatching(e Engine, userID, repoID int64) bool {
  1675. has, _ := e.Get(&Watch{0, userID, repoID})
  1676. return has
  1677. }
  1678. // IsWatching checks if user has watched given repository.
  1679. func IsWatching(userID, repoID int64) bool {
  1680. return isWatching(x, userID, repoID)
  1681. }
  1682. func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) {
  1683. if watch {
  1684. if isWatching(e, userID, repoID) {
  1685. return nil
  1686. }
  1687. if _, err = e.Insert(&Watch{RepoID: repoID, UserID: userID}); err != nil {
  1688. return err
  1689. }
  1690. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoID)
  1691. } else {
  1692. if !isWatching(e, userID, repoID) {
  1693. return nil
  1694. }
  1695. if _, err = e.Delete(&Watch{0, userID, repoID}); err != nil {
  1696. return err
  1697. }
  1698. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoID)
  1699. }
  1700. return err
  1701. }
  1702. // Watch or unwatch repository.
  1703. func WatchRepo(userID, repoID int64, watch bool) (err error) {
  1704. return watchRepo(x, userID, repoID, watch)
  1705. }
  1706. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  1707. watches := make([]*Watch, 0, 10)
  1708. return watches, e.Find(&watches, &Watch{RepoID: repoID})
  1709. }
  1710. // GetWatchers returns all watchers of given repository.
  1711. func GetWatchers(repoID int64) ([]*Watch, error) {
  1712. return getWatchers(x, repoID)
  1713. }
  1714. // Repository.GetWatchers returns range of users watching given repository.
  1715. func (repo *Repository) GetWatchers(page int) ([]*User, error) {
  1716. users := make([]*User, 0, ItemsPerPage)
  1717. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", repo.ID)
  1718. if setting.UsePostgreSQL {
  1719. sess = sess.Join("LEFT", "watch", `"user".id=watch.user_id`)
  1720. } else {
  1721. sess = sess.Join("LEFT", "watch", "user.id=watch.user_id")
  1722. }
  1723. return users, sess.Find(&users)
  1724. }
  1725. func notifyWatchers(e Engine, act *Action) error {
  1726. // Add feeds for user self and all watchers.
  1727. watches, err := getWatchers(e, act.RepoID)
  1728. if err != nil {
  1729. return fmt.Errorf("get watchers: %v", err)
  1730. }
  1731. // Add feed for actioner.
  1732. act.UserID = act.ActUserID
  1733. if _, err = e.InsertOne(act); err != nil {
  1734. return fmt.Errorf("insert new actioner: %v", err)
  1735. }
  1736. for i := range watches {
  1737. if act.ActUserID == watches[i].UserID {
  1738. continue
  1739. }
  1740. act.ID = 0
  1741. act.UserID = watches[i].UserID
  1742. if _, err = e.InsertOne(act); err != nil {
  1743. return fmt.Errorf("insert new action: %v", err)
  1744. }
  1745. }
  1746. return nil
  1747. }
  1748. // NotifyWatchers creates batch of actions for every watcher.
  1749. func NotifyWatchers(act *Action) error {
  1750. return notifyWatchers(x, act)
  1751. }
  1752. // _________ __
  1753. // / _____// |______ _______
  1754. // \_____ \\ __\__ \\_ __ \
  1755. // / \| | / __ \| | \/
  1756. // /_______ /|__| (____ /__|
  1757. // \/ \/
  1758. type Star struct {
  1759. ID int64 `xorm:"pk autoincr"`
  1760. UID int64 `xorm:"UNIQUE(s)"`
  1761. RepoID int64 `xorm:"UNIQUE(s)"`
  1762. }
  1763. // Star or unstar repository.
  1764. func StarRepo(userID, repoID int64, star bool) (err error) {
  1765. if star {
  1766. if IsStaring(userID, repoID) {
  1767. return nil
  1768. }
  1769. if _, err = x.Insert(&Star{UID: userID, RepoID: repoID}); err != nil {
  1770. return err
  1771. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoID); err != nil {
  1772. return err
  1773. }
  1774. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", userID)
  1775. } else {
  1776. if !IsStaring(userID, repoID) {
  1777. return nil
  1778. }
  1779. if _, err = x.Delete(&Star{0, userID, repoID}); err != nil {
  1780. return err
  1781. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoID); err != nil {
  1782. return err
  1783. }
  1784. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", userID)
  1785. }
  1786. return err
  1787. }
  1788. // IsStaring checks if user has starred given repository.
  1789. func IsStaring(userID, repoID int64) bool {
  1790. has, _ := x.Get(&Star{0, userID, repoID})
  1791. return has
  1792. }
  1793. func (repo *Repository) GetStargazers(page int) ([]*User, error) {
  1794. users := make([]*User, 0, ItemsPerPage)
  1795. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", repo.ID)
  1796. if setting.UsePostgreSQL {
  1797. sess = sess.Join("LEFT", "star", `"user".id=star.uid`)
  1798. } else {
  1799. sess = sess.Join("LEFT", "star", "user.id=star.uid")
  1800. }
  1801. return users, sess.Find(&users)
  1802. }
  1803. // ___________ __
  1804. // \_ _____/__________| | __
  1805. // | __)/ _ \_ __ \ |/ /
  1806. // | \( <_> ) | \/ <
  1807. // \___ / \____/|__| |__|_ \
  1808. // \/ \/
  1809. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1810. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1811. repo := new(Repository)
  1812. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1813. return repo, has
  1814. }
  1815. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1816. repo := &Repository{
  1817. OwnerID: u.ID,
  1818. Owner: u,
  1819. Name: name,
  1820. LowerName: strings.ToLower(name),
  1821. Description: desc,
  1822. DefaultBranch: oldRepo.DefaultBranch,
  1823. IsPrivate: oldRepo.IsPrivate,
  1824. IsFork: true,
  1825. ForkID: oldRepo.ID,
  1826. }
  1827. sess := x.NewSession()
  1828. defer sessionRelease(sess)
  1829. if err = sess.Begin(); err != nil {
  1830. return nil, err
  1831. }
  1832. if err = createRepository(sess, u, repo); err != nil {
  1833. return nil, err
  1834. }
  1835. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1836. return nil, err
  1837. }
  1838. repoPath := RepoPath(u.Name, repo.Name)
  1839. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1840. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1841. "git", "clone", "--bare", oldRepo.RepoPath(), repoPath)
  1842. if err != nil {
  1843. return nil, fmt.Errorf("git clone: %v", stderr)
  1844. }
  1845. _, stderr, err = process.ExecDir(-1,
  1846. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1847. "git", "update-server-info")
  1848. if err != nil {
  1849. return nil, fmt.Errorf("git update-server-info: %v", err)
  1850. }
  1851. if err = createUpdateHook(repoPath); err != nil {
  1852. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1853. }
  1854. return repo, sess.Commit()
  1855. }
  1856. func (repo *Repository) GetForks() ([]*Repository, error) {
  1857. forks := make([]*Repository, 0, repo.NumForks)
  1858. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  1859. }