repo.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  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. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1080. if err != nil {
  1081. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1082. }
  1083. for i := range forkRepos {
  1084. forkRepos[i].IsPrivate = repo.IsPrivate
  1085. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1086. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1087. }
  1088. }
  1089. }
  1090. return nil
  1091. }
  1092. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1093. sess := x.NewSession()
  1094. defer sessionRelease(sess)
  1095. if err = sess.Begin(); err != nil {
  1096. return err
  1097. }
  1098. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  1099. return fmt.Errorf("updateRepository: %v", err)
  1100. }
  1101. return sess.Commit()
  1102. }
  1103. // DeleteRepository deletes a repository for a user or organization.
  1104. func DeleteRepository(uid, repoID int64) error {
  1105. repo := &Repository{ID: repoID, OwnerID: uid}
  1106. has, err := x.Get(repo)
  1107. if err != nil {
  1108. return err
  1109. } else if !has {
  1110. return ErrRepoNotExist{repoID, uid, ""}
  1111. }
  1112. // In case is a organization.
  1113. org, err := GetUserByID(uid)
  1114. if err != nil {
  1115. return err
  1116. }
  1117. if org.IsOrganization() {
  1118. if err = org.GetTeams(); err != nil {
  1119. return err
  1120. }
  1121. }
  1122. sess := x.NewSession()
  1123. defer sessionRelease(sess)
  1124. if err = sess.Begin(); err != nil {
  1125. return err
  1126. }
  1127. if org.IsOrganization() {
  1128. for _, t := range org.Teams {
  1129. if !t.hasRepository(sess, repoID) {
  1130. continue
  1131. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1132. return err
  1133. }
  1134. }
  1135. }
  1136. if err = deleteBeans(sess,
  1137. &Repository{ID: repoID},
  1138. &Access{RepoID: repo.ID},
  1139. &Action{RepoID: repo.ID},
  1140. &Watch{RepoID: repoID},
  1141. &Star{RepoID: repoID},
  1142. &Mirror{RepoID: repoID},
  1143. &IssueUser{RepoID: repoID},
  1144. &Milestone{RepoID: repoID},
  1145. &Release{RepoID: repoID},
  1146. &Collaboration{RepoID: repoID},
  1147. &PullRequest{BaseRepoID: repoID},
  1148. ); err != nil {
  1149. return fmt.Errorf("deleteBeans: %v", err)
  1150. }
  1151. // Delete comments and attachments.
  1152. issues := make([]*Issue, 0, 25)
  1153. attachmentPaths := make([]string, 0, len(issues))
  1154. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  1155. return err
  1156. }
  1157. for i := range issues {
  1158. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  1159. return err
  1160. }
  1161. attachments := make([]*Attachment, 0, 5)
  1162. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  1163. return err
  1164. }
  1165. for j := range attachments {
  1166. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1167. }
  1168. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  1169. return err
  1170. }
  1171. }
  1172. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1173. return err
  1174. }
  1175. if repo.IsFork {
  1176. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1177. return fmt.Errorf("decrease fork count: %v", err)
  1178. }
  1179. }
  1180. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1181. return err
  1182. }
  1183. // Remove repository files.
  1184. repoPath := repo.repoPath(sess)
  1185. RemoveAllWithNotice("Delete repository files", repoPath)
  1186. repo.DeleteWiki()
  1187. // Remove attachment files.
  1188. for i := range attachmentPaths {
  1189. RemoveAllWithNotice("Delete attachment", attachmentPaths[i])
  1190. }
  1191. if err = sess.Commit(); err != nil {
  1192. return fmt.Errorf("Commit: %v", err)
  1193. }
  1194. if repo.NumForks > 0 {
  1195. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1196. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  1197. }
  1198. }
  1199. return nil
  1200. }
  1201. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1202. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1203. func GetRepositoryByRef(ref string) (*Repository, error) {
  1204. n := strings.IndexByte(ref, byte('/'))
  1205. if n < 2 {
  1206. return nil, ErrInvalidReference
  1207. }
  1208. userName, repoName := ref[:n], ref[n+1:]
  1209. user, err := GetUserByName(userName)
  1210. if err != nil {
  1211. return nil, err
  1212. }
  1213. return GetRepositoryByName(user.ID, repoName)
  1214. }
  1215. // GetRepositoryByName returns the repository by given name under user if exists.
  1216. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  1217. repo := &Repository{
  1218. OwnerID: uid,
  1219. LowerName: strings.ToLower(repoName),
  1220. }
  1221. has, err := x.Get(repo)
  1222. if err != nil {
  1223. return nil, err
  1224. } else if !has {
  1225. return nil, ErrRepoNotExist{0, uid, repoName}
  1226. }
  1227. return repo, err
  1228. }
  1229. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1230. repo := new(Repository)
  1231. has, err := e.Id(id).Get(repo)
  1232. if err != nil {
  1233. return nil, err
  1234. } else if !has {
  1235. return nil, ErrRepoNotExist{id, 0, ""}
  1236. }
  1237. return repo, nil
  1238. }
  1239. // GetRepositoryByID returns the repository by given id if exists.
  1240. func GetRepositoryByID(id int64) (*Repository, error) {
  1241. return getRepositoryByID(x, id)
  1242. }
  1243. // GetUserRepositories returns a list of repositories of given user.
  1244. func GetUserRepositories(userID int64, private bool, page, pageSize int) ([]*Repository, error) {
  1245. sess := x.Where("owner_id = ?", userID).Desc("updated_unix")
  1246. if !private {
  1247. sess.And("is_private=?", false)
  1248. }
  1249. if page <= 0 {
  1250. page = 1
  1251. }
  1252. sess.Limit(pageSize, (page-1)*pageSize)
  1253. repos := make([]*Repository, 0, pageSize)
  1254. return repos, sess.Find(&repos)
  1255. }
  1256. // GetUserRepositories returns a list of mirror repositories of given user.
  1257. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1258. repos := make([]*Repository, 0, 10)
  1259. return repos, x.Where("owner_id = ?", userID).And("is_mirror = ?", true).Find(&repos)
  1260. }
  1261. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1262. func GetRecentUpdatedRepositories(page, pageSize int) (repos []*Repository, err error) {
  1263. return repos, x.Limit(pageSize, (page-1)*pageSize).
  1264. Where("is_private=?", false).Limit(pageSize).Desc("updated_unix").Find(&repos)
  1265. }
  1266. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1267. return x.Count(&Repository{OwnerID: u.ID})
  1268. }
  1269. // GetRepositoryCount returns the total number of repositories of user.
  1270. func GetRepositoryCount(u *User) (int64, error) {
  1271. return getRepositoryCount(x, u)
  1272. }
  1273. type SearchRepoOptions struct {
  1274. Keyword string
  1275. OwnerID int64
  1276. OrderBy string
  1277. Private bool // Include private repositories in results
  1278. Page int
  1279. PageSize int // Can be smaller than or equal to setting.ExplorePagingNum
  1280. }
  1281. // SearchRepositoryByName takes keyword and part of repository name to search,
  1282. // it returns results in given range and number of total results.
  1283. func SearchRepositoryByName(opts *SearchRepoOptions) (repos []*Repository, _ int64, _ error) {
  1284. if len(opts.Keyword) == 0 {
  1285. return repos, 0, nil
  1286. }
  1287. opts.Keyword = strings.ToLower(opts.Keyword)
  1288. if opts.Page <= 0 {
  1289. opts.Page = 1
  1290. }
  1291. repos = make([]*Repository, 0, opts.PageSize)
  1292. // Append conditions
  1293. sess := x.Where("LOWER(lower_name) LIKE ?", "%"+opts.Keyword+"%")
  1294. if opts.OwnerID > 0 {
  1295. sess.And("owner_id = ?", opts.OwnerID)
  1296. }
  1297. if !opts.Private {
  1298. sess.And("is_private=?", false)
  1299. }
  1300. var countSess xorm.Session
  1301. countSess = *sess
  1302. count, err := countSess.Count(new(Repository))
  1303. if err != nil {
  1304. return nil, 0, fmt.Errorf("Count: %v", err)
  1305. }
  1306. if len(opts.OrderBy) > 0 {
  1307. sess.OrderBy(opts.OrderBy)
  1308. }
  1309. return repos, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&repos)
  1310. }
  1311. // DeleteRepositoryArchives deletes all repositories' archives.
  1312. func DeleteRepositoryArchives() error {
  1313. return x.Where("id > 0").Iterate(new(Repository),
  1314. func(idx int, bean interface{}) error {
  1315. repo := bean.(*Repository)
  1316. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1317. })
  1318. }
  1319. func gatherMissingRepoRecords() ([]*Repository, error) {
  1320. repos := make([]*Repository, 0, 10)
  1321. if err := x.Where("id > 0").Iterate(new(Repository),
  1322. func(idx int, bean interface{}) error {
  1323. repo := bean.(*Repository)
  1324. if !com.IsDir(repo.RepoPath()) {
  1325. repos = append(repos, repo)
  1326. }
  1327. return nil
  1328. }); err != nil {
  1329. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1330. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1331. }
  1332. }
  1333. return repos, nil
  1334. }
  1335. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1336. func DeleteMissingRepositories() error {
  1337. repos, err := gatherMissingRepoRecords()
  1338. if err != nil {
  1339. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1340. }
  1341. if len(repos) == 0 {
  1342. return nil
  1343. }
  1344. for _, repo := range repos {
  1345. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1346. if err := DeleteRepository(repo.OwnerID, repo.ID); err != nil {
  1347. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1348. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1349. }
  1350. }
  1351. }
  1352. return nil
  1353. }
  1354. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1355. func ReinitMissingRepositories() error {
  1356. repos, err := gatherMissingRepoRecords()
  1357. if err != nil {
  1358. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1359. }
  1360. if len(repos) == 0 {
  1361. return nil
  1362. }
  1363. for _, repo := range repos {
  1364. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1365. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1366. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1367. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1368. }
  1369. }
  1370. }
  1371. return nil
  1372. }
  1373. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1374. func RewriteRepositoryUpdateHook() error {
  1375. return x.Where("id > 0").Iterate(new(Repository),
  1376. func(idx int, bean interface{}) error {
  1377. repo := bean.(*Repository)
  1378. return createUpdateHook(repo.RepoPath())
  1379. })
  1380. }
  1381. // statusPool represents a pool of status with true/false.
  1382. type statusPool struct {
  1383. lock sync.RWMutex
  1384. pool map[string]bool
  1385. }
  1386. // Start sets value of given name to true in the pool.
  1387. func (p *statusPool) Start(name string) {
  1388. p.lock.Lock()
  1389. defer p.lock.Unlock()
  1390. p.pool[name] = true
  1391. }
  1392. // Stop sets value of given name to false in the pool.
  1393. func (p *statusPool) Stop(name string) {
  1394. p.lock.Lock()
  1395. defer p.lock.Unlock()
  1396. p.pool[name] = false
  1397. }
  1398. // IsRunning checks if value of given name is set to true in the pool.
  1399. func (p *statusPool) IsRunning(name string) bool {
  1400. p.lock.RLock()
  1401. defer p.lock.RUnlock()
  1402. return p.pool[name]
  1403. }
  1404. // Prevent duplicate running tasks.
  1405. var taskStatusPool = &statusPool{
  1406. pool: make(map[string]bool),
  1407. }
  1408. const (
  1409. _MIRROR_UPDATE = "mirror_update"
  1410. _GIT_FSCK = "git_fsck"
  1411. _CHECK_REPOs = "check_repos"
  1412. )
  1413. // MirrorUpdate checks and updates mirror repositories.
  1414. func MirrorUpdate() {
  1415. if taskStatusPool.IsRunning(_MIRROR_UPDATE) {
  1416. return
  1417. }
  1418. taskStatusPool.Start(_MIRROR_UPDATE)
  1419. defer taskStatusPool.Stop(_MIRROR_UPDATE)
  1420. log.Trace("Doing: MirrorUpdate")
  1421. mirrors := make([]*Mirror, 0, 10)
  1422. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1423. m := bean.(*Mirror)
  1424. if m.Repo == nil {
  1425. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1426. return nil
  1427. }
  1428. repoPath := m.Repo.RepoPath()
  1429. gitArgs := []string{"remote", "update"}
  1430. if m.EnablePrune {
  1431. gitArgs = append(gitArgs, "--prune")
  1432. }
  1433. if _, stderr, err := process.ExecDir(
  1434. time.Duration(setting.Git.Timeout.Mirror)*time.Second,
  1435. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1436. "git", gitArgs...); err != nil {
  1437. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1438. log.Error(4, desc)
  1439. if err = CreateRepositoryNotice(desc); err != nil {
  1440. log.Error(4, "CreateRepositoryNotice: %v", err)
  1441. }
  1442. return nil
  1443. }
  1444. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1445. mirrors = append(mirrors, m)
  1446. return nil
  1447. }); err != nil {
  1448. log.Error(4, "MirrorUpdate: %v", err)
  1449. }
  1450. for i := range mirrors {
  1451. if err := UpdateMirror(mirrors[i]); err != nil {
  1452. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1453. }
  1454. }
  1455. }
  1456. // GitFsck calls 'git fsck' to check repository health.
  1457. func GitFsck() {
  1458. if taskStatusPool.IsRunning(_GIT_FSCK) {
  1459. return
  1460. }
  1461. taskStatusPool.Start(_GIT_FSCK)
  1462. defer taskStatusPool.Stop(_GIT_FSCK)
  1463. log.Trace("Doing: GitFsck")
  1464. if err := x.Where("id>0").Iterate(new(Repository),
  1465. func(idx int, bean interface{}) error {
  1466. repo := bean.(*Repository)
  1467. repoPath := repo.RepoPath()
  1468. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1469. desc := fmt.Sprintf("Fail to health check repository (%s): %v", repoPath, err)
  1470. log.Warn(desc)
  1471. if err = CreateRepositoryNotice(desc); err != nil {
  1472. log.Error(4, "CreateRepositoryNotice: %v", err)
  1473. }
  1474. }
  1475. return nil
  1476. }); err != nil {
  1477. log.Error(4, "GitFsck: %v", err)
  1478. }
  1479. }
  1480. func GitGcRepos() error {
  1481. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1482. return x.Where("id > 0").Iterate(new(Repository),
  1483. func(idx int, bean interface{}) error {
  1484. repo := bean.(*Repository)
  1485. if err := repo.GetOwner(); err != nil {
  1486. return err
  1487. }
  1488. _, stderr, err := process.ExecDir(
  1489. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1490. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1491. "git", args...)
  1492. if err != nil {
  1493. return fmt.Errorf("%v: %v", err, stderr)
  1494. }
  1495. return nil
  1496. })
  1497. }
  1498. type repoChecker struct {
  1499. querySQL, correctSQL string
  1500. desc string
  1501. }
  1502. func repoStatsCheck(checker *repoChecker) {
  1503. results, err := x.Query(checker.querySQL)
  1504. if err != nil {
  1505. log.Error(4, "Select %s: %v", checker.desc, err)
  1506. return
  1507. }
  1508. for _, result := range results {
  1509. id := com.StrTo(result["id"]).MustInt64()
  1510. log.Trace("Updating %s: %d", checker.desc, id)
  1511. _, err = x.Exec(checker.correctSQL, id, id)
  1512. if err != nil {
  1513. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1514. }
  1515. }
  1516. }
  1517. func CheckRepoStats() {
  1518. if taskStatusPool.IsRunning(_CHECK_REPOs) {
  1519. return
  1520. }
  1521. taskStatusPool.Start(_CHECK_REPOs)
  1522. defer taskStatusPool.Stop(_CHECK_REPOs)
  1523. log.Trace("Doing: CheckRepoStats")
  1524. checkers := []*repoChecker{
  1525. // Repository.NumWatches
  1526. {
  1527. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1528. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1529. "repository count 'num_watches'",
  1530. },
  1531. // Repository.NumStars
  1532. {
  1533. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1534. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1535. "repository count 'num_stars'",
  1536. },
  1537. // Label.NumIssues
  1538. {
  1539. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1540. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1541. "label count 'num_issues'",
  1542. },
  1543. // User.NumRepos
  1544. {
  1545. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1546. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1547. "user count 'num_repos'",
  1548. },
  1549. // Issue.NumComments
  1550. {
  1551. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1552. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1553. "issue count 'num_comments'",
  1554. },
  1555. }
  1556. for i := range checkers {
  1557. repoStatsCheck(checkers[i])
  1558. }
  1559. // ***** START: Repository.NumClosedIssues *****
  1560. desc := "repository count 'num_closed_issues'"
  1561. 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)
  1562. if err != nil {
  1563. log.Error(4, "Select %s: %v", desc, err)
  1564. } else {
  1565. for _, result := range results {
  1566. id := com.StrTo(result["id"]).MustInt64()
  1567. log.Trace("Updating %s: %d", desc, id)
  1568. _, 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)
  1569. if err != nil {
  1570. log.Error(4, "Update %s[%d]: %v", desc, id, err)
  1571. }
  1572. }
  1573. }
  1574. // ***** END: Repository.NumClosedIssues *****
  1575. // FIXME: use checker when stop supporting old fork repo format.
  1576. // ***** START: Repository.NumForks *****
  1577. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1578. if err != nil {
  1579. log.Error(4, "Select repository count 'num_forks': %v", err)
  1580. } else {
  1581. for _, result := range results {
  1582. id := com.StrTo(result["id"]).MustInt64()
  1583. log.Trace("Updating repository count 'num_forks': %d", id)
  1584. repo, err := GetRepositoryByID(id)
  1585. if err != nil {
  1586. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1587. continue
  1588. }
  1589. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1590. if err != nil {
  1591. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1592. continue
  1593. }
  1594. repo.NumForks = int(parseCountResult(rawResult))
  1595. if err = UpdateRepository(repo, false); err != nil {
  1596. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1597. continue
  1598. }
  1599. }
  1600. }
  1601. // ***** END: Repository.NumForks *****
  1602. }
  1603. type RepositoryList []*Repository
  1604. func (repos RepositoryList) loadAttributes(e Engine) error {
  1605. if len(repos) == 0 {
  1606. return nil
  1607. }
  1608. // Load owners.
  1609. set := make(map[int64]*User)
  1610. for i := range repos {
  1611. set[repos[i].OwnerID] = nil
  1612. }
  1613. userIDs := make([]int64, 0, len(set))
  1614. for userID := range set {
  1615. userIDs = append(userIDs, userID)
  1616. }
  1617. users := make([]*User, 0, len(userIDs))
  1618. if err := e.Where("id > 0").In("id", userIDs).Find(&users); err != nil {
  1619. return fmt.Errorf("find users: %v", err)
  1620. }
  1621. for i := range users {
  1622. set[users[i].ID] = users[i]
  1623. }
  1624. for i := range repos {
  1625. repos[i].Owner = set[repos[i].OwnerID]
  1626. }
  1627. return nil
  1628. }
  1629. func (repos RepositoryList) LoadAttributes() error {
  1630. return repos.loadAttributes(x)
  1631. }
  1632. type MirrorRepositoryList []*Repository
  1633. func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
  1634. if len(repos) == 0 {
  1635. return nil
  1636. }
  1637. // Load mirrors.
  1638. repoIDs := make([]int64, 0, len(repos))
  1639. for i := range repos {
  1640. if !repos[i].IsMirror {
  1641. continue
  1642. }
  1643. repoIDs = append(repoIDs, repos[i].ID)
  1644. }
  1645. mirrors := make([]*Mirror, 0, len(repoIDs))
  1646. if err := e.Where("id > 0").In("repo_id", repoIDs).Find(&mirrors); err != nil {
  1647. return fmt.Errorf("find mirrors: %v", err)
  1648. }
  1649. set := make(map[int64]*Mirror)
  1650. for i := range mirrors {
  1651. set[mirrors[i].RepoID] = mirrors[i]
  1652. }
  1653. for i := range repos {
  1654. repos[i].Mirror = set[repos[i].ID]
  1655. }
  1656. return nil
  1657. }
  1658. func (repos MirrorRepositoryList) LoadAttributes() error {
  1659. return repos.loadAttributes(x)
  1660. }
  1661. // __ __ __ .__
  1662. // / \ / \_____ _/ |_ ____ | |__
  1663. // \ \/\/ /\__ \\ __\/ ___\| | \
  1664. // \ / / __ \| | \ \___| Y \
  1665. // \__/\ / (____ /__| \___ >___| /
  1666. // \/ \/ \/ \/
  1667. // Watch is connection request for receiving repository notification.
  1668. type Watch struct {
  1669. ID int64 `xorm:"pk autoincr"`
  1670. UserID int64 `xorm:"UNIQUE(watch)"`
  1671. RepoID int64 `xorm:"UNIQUE(watch)"`
  1672. }
  1673. func isWatching(e Engine, userID, repoID int64) bool {
  1674. has, _ := e.Get(&Watch{0, userID, repoID})
  1675. return has
  1676. }
  1677. // IsWatching checks if user has watched given repository.
  1678. func IsWatching(userID, repoID int64) bool {
  1679. return isWatching(x, userID, repoID)
  1680. }
  1681. func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) {
  1682. if watch {
  1683. if isWatching(e, userID, repoID) {
  1684. return nil
  1685. }
  1686. if _, err = e.Insert(&Watch{RepoID: repoID, UserID: userID}); err != nil {
  1687. return err
  1688. }
  1689. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoID)
  1690. } else {
  1691. if !isWatching(e, userID, repoID) {
  1692. return nil
  1693. }
  1694. if _, err = e.Delete(&Watch{0, userID, repoID}); err != nil {
  1695. return err
  1696. }
  1697. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoID)
  1698. }
  1699. return err
  1700. }
  1701. // Watch or unwatch repository.
  1702. func WatchRepo(userID, repoID int64, watch bool) (err error) {
  1703. return watchRepo(x, userID, repoID, watch)
  1704. }
  1705. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  1706. watches := make([]*Watch, 0, 10)
  1707. return watches, e.Find(&watches, &Watch{RepoID: repoID})
  1708. }
  1709. // GetWatchers returns all watchers of given repository.
  1710. func GetWatchers(repoID int64) ([]*Watch, error) {
  1711. return getWatchers(x, repoID)
  1712. }
  1713. // Repository.GetWatchers returns range of users watching given repository.
  1714. func (repo *Repository) GetWatchers(page int) ([]*User, error) {
  1715. users := make([]*User, 0, ItemsPerPage)
  1716. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", repo.ID)
  1717. if setting.UsePostgreSQL {
  1718. sess = sess.Join("LEFT", "watch", `"user".id=watch.user_id`)
  1719. } else {
  1720. sess = sess.Join("LEFT", "watch", "user.id=watch.user_id")
  1721. }
  1722. return users, sess.Find(&users)
  1723. }
  1724. func notifyWatchers(e Engine, act *Action) error {
  1725. // Add feeds for user self and all watchers.
  1726. watches, err := getWatchers(e, act.RepoID)
  1727. if err != nil {
  1728. return fmt.Errorf("get watchers: %v", err)
  1729. }
  1730. // Add feed for actioner.
  1731. act.UserID = act.ActUserID
  1732. if _, err = e.InsertOne(act); err != nil {
  1733. return fmt.Errorf("insert new actioner: %v", err)
  1734. }
  1735. for i := range watches {
  1736. if act.ActUserID == watches[i].UserID {
  1737. continue
  1738. }
  1739. act.ID = 0
  1740. act.UserID = watches[i].UserID
  1741. if _, err = e.InsertOne(act); err != nil {
  1742. return fmt.Errorf("insert new action: %v", err)
  1743. }
  1744. }
  1745. return nil
  1746. }
  1747. // NotifyWatchers creates batch of actions for every watcher.
  1748. func NotifyWatchers(act *Action) error {
  1749. return notifyWatchers(x, act)
  1750. }
  1751. // _________ __
  1752. // / _____// |______ _______
  1753. // \_____ \\ __\__ \\_ __ \
  1754. // / \| | / __ \| | \/
  1755. // /_______ /|__| (____ /__|
  1756. // \/ \/
  1757. type Star struct {
  1758. ID int64 `xorm:"pk autoincr"`
  1759. UID int64 `xorm:"UNIQUE(s)"`
  1760. RepoID int64 `xorm:"UNIQUE(s)"`
  1761. }
  1762. // Star or unstar repository.
  1763. func StarRepo(userID, repoID int64, star bool) (err error) {
  1764. if star {
  1765. if IsStaring(userID, repoID) {
  1766. return nil
  1767. }
  1768. if _, err = x.Insert(&Star{UID: userID, RepoID: repoID}); err != nil {
  1769. return err
  1770. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoID); err != nil {
  1771. return err
  1772. }
  1773. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", userID)
  1774. } else {
  1775. if !IsStaring(userID, repoID) {
  1776. return nil
  1777. }
  1778. if _, err = x.Delete(&Star{0, userID, repoID}); err != nil {
  1779. return err
  1780. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoID); err != nil {
  1781. return err
  1782. }
  1783. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", userID)
  1784. }
  1785. return err
  1786. }
  1787. // IsStaring checks if user has starred given repository.
  1788. func IsStaring(userID, repoID int64) bool {
  1789. has, _ := x.Get(&Star{0, userID, repoID})
  1790. return has
  1791. }
  1792. func (repo *Repository) GetStargazers(page int) ([]*User, error) {
  1793. users := make([]*User, 0, ItemsPerPage)
  1794. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", repo.ID)
  1795. if setting.UsePostgreSQL {
  1796. sess = sess.Join("LEFT", "star", `"user".id=star.uid`)
  1797. } else {
  1798. sess = sess.Join("LEFT", "star", "user.id=star.uid")
  1799. }
  1800. return users, sess.Find(&users)
  1801. }
  1802. // ___________ __
  1803. // \_ _____/__________| | __
  1804. // | __)/ _ \_ __ \ |/ /
  1805. // | \( <_> ) | \/ <
  1806. // \___ / \____/|__| |__|_ \
  1807. // \/ \/
  1808. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1809. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1810. repo := new(Repository)
  1811. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1812. return repo, has
  1813. }
  1814. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1815. repo := &Repository{
  1816. OwnerID: u.ID,
  1817. Owner: u,
  1818. Name: name,
  1819. LowerName: strings.ToLower(name),
  1820. Description: desc,
  1821. DefaultBranch: oldRepo.DefaultBranch,
  1822. IsPrivate: oldRepo.IsPrivate,
  1823. IsFork: true,
  1824. ForkID: oldRepo.ID,
  1825. }
  1826. sess := x.NewSession()
  1827. defer sessionRelease(sess)
  1828. if err = sess.Begin(); err != nil {
  1829. return nil, err
  1830. }
  1831. if err = createRepository(sess, u, repo); err != nil {
  1832. return nil, err
  1833. }
  1834. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1835. return nil, err
  1836. }
  1837. repoPath := RepoPath(u.Name, repo.Name)
  1838. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1839. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1840. "git", "clone", "--bare", oldRepo.RepoPath(), repoPath)
  1841. if err != nil {
  1842. return nil, fmt.Errorf("git clone: %v", stderr)
  1843. }
  1844. _, stderr, err = process.ExecDir(-1,
  1845. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1846. "git", "update-server-info")
  1847. if err != nil {
  1848. return nil, fmt.Errorf("git update-server-info: %v", err)
  1849. }
  1850. if err = createUpdateHook(repoPath); err != nil {
  1851. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1852. }
  1853. return repo, sess.Commit()
  1854. }
  1855. func (repo *Repository) GetForks() ([]*Repository, error) {
  1856. forks := make([]*Repository, 0, repo.NumForks)
  1857. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  1858. }