You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 60 kB

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