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