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