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