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 41 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
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
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
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
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
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
11 years ago
11 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
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
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
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
11 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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. "errors"
  7. "fmt"
  8. "html/template"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/Unknwon/cae/zip"
  20. "github.com/Unknwon/com"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/git"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/process"
  25. "github.com/gogits/gogs/modules/setting"
  26. )
  27. const (
  28. TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3\n"
  29. )
  30. var (
  31. ErrRepoAlreadyExist = errors.New("Repository already exist")
  32. ErrRepoNotExist = errors.New("Repository does not exist")
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  35. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  36. ErrMirrorNotExist = errors.New("Mirror does not exist")
  37. ErrInvalidReference = errors.New("Invalid reference specified")
  38. )
  39. var (
  40. Gitignores, Licenses []string
  41. )
  42. var (
  43. DescPattern = regexp.MustCompile(`https?://\S+`)
  44. )
  45. func LoadRepoConfig() {
  46. // Load .gitignore and license files.
  47. types := []string{"gitignore", "license"}
  48. typeFiles := make([][]string, 2)
  49. for i, t := range types {
  50. files, err := com.StatDir(path.Join("conf", t))
  51. if err != nil {
  52. log.Fatal(4, "Fail to get %s files: %v", t, err)
  53. }
  54. customPath := path.Join(setting.CustomPath, "conf", t)
  55. if com.IsDir(customPath) {
  56. customFiles, err := com.StatDir(customPath)
  57. if err != nil {
  58. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  59. }
  60. for _, f := range customFiles {
  61. if !com.IsSliceContainsStr(files, f) {
  62. files = append(files, f)
  63. }
  64. }
  65. }
  66. typeFiles[i] = files
  67. }
  68. Gitignores = typeFiles[0]
  69. Licenses = typeFiles[1]
  70. sort.Strings(Gitignores)
  71. sort.Strings(Licenses)
  72. }
  73. func NewRepoContext() {
  74. zip.Verbose = false
  75. // Check Git installation.
  76. if _, err := exec.LookPath("git"); err != nil {
  77. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  78. }
  79. // Check Git version.
  80. ver, err := git.GetVersion()
  81. if err != nil {
  82. log.Fatal(4, "Fail to get Git version: %v", err)
  83. }
  84. reqVer, err := git.ParseVersion("1.7.1")
  85. if err != nil {
  86. log.Fatal(4, "Fail to parse required Git version: %v", err)
  87. }
  88. if ver.LessThan(reqVer) {
  89. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  90. }
  91. // Check if server has user.email and user.name set correctly and set if they're not.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogitservice@gmail.com"} {
  93. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  94. // ExitError indicates this config is not set
  95. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  96. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  97. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  98. }
  99. log.Info("Git config %s set to %s", configKey, defaultValue)
  100. } else {
  101. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  102. }
  103. }
  104. }
  105. // Set git some configurations.
  106. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  107. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  108. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  109. }
  110. }
  111. // Repository represents a git repository.
  112. type Repository struct {
  113. Id int64
  114. OwnerId int64 `xorm:"UNIQUE(s)"`
  115. Owner *User `xorm:"-"`
  116. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  117. Name string `xorm:"INDEX NOT NULL"`
  118. Description string
  119. Website string
  120. DefaultBranch string
  121. NumWatches int
  122. NumStars int
  123. NumForks int
  124. NumIssues int
  125. NumClosedIssues int
  126. NumOpenIssues int `xorm:"-"`
  127. NumPulls int
  128. NumClosedPulls int
  129. NumOpenPulls int `xorm:"-"`
  130. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  132. NumOpenMilestones int `xorm:"-"`
  133. NumTags int `xorm:"-"`
  134. IsPrivate bool
  135. IsBare bool
  136. IsGoget bool
  137. IsMirror bool
  138. *Mirror `xorm:"-"`
  139. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  140. ForkId int64
  141. ForkRepo *Repository `xorm:"-"`
  142. Created time.Time `xorm:"CREATED"`
  143. Updated time.Time `xorm:"UPDATED"`
  144. }
  145. func (repo *Repository) GetOwner() (err error) {
  146. if repo.Owner == nil {
  147. repo.Owner, err = GetUserById(repo.OwnerId)
  148. }
  149. return err
  150. }
  151. func (repo *Repository) GetMirror() (err error) {
  152. repo.Mirror, err = GetMirror(repo.Id)
  153. return err
  154. }
  155. func (repo *Repository) GetForkRepo() (err error) {
  156. if !repo.IsFork {
  157. return nil
  158. }
  159. repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
  160. return err
  161. }
  162. func (repo *Repository) RepoPath() (string, error) {
  163. if err := repo.GetOwner(); err != nil {
  164. return "", err
  165. }
  166. return RepoPath(repo.Owner.Name, repo.Name), nil
  167. }
  168. func (repo *Repository) RepoLink() (string, error) {
  169. if err := repo.GetOwner(); err != nil {
  170. return "", err
  171. }
  172. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  173. }
  174. func (repo *Repository) IsOwnedBy(u *User) bool {
  175. return repo.OwnerId == u.Id
  176. }
  177. func (repo *Repository) HasAccess(uname string) bool {
  178. if err := repo.GetOwner(); err != nil {
  179. return false
  180. }
  181. has, _ := HasAccess(uname, path.Join(repo.Owner.Name, repo.Name), READABLE)
  182. return has
  183. }
  184. // DescriptionHtml does special handles to description and return HTML string.
  185. func (repo *Repository) DescriptionHtml() template.HTML {
  186. sanitize := func(s string) string {
  187. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  188. }
  189. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  190. }
  191. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  192. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  193. repo := Repository{OwnerId: u.Id}
  194. has, err := x.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  195. if err != nil {
  196. return has, err
  197. } else if !has {
  198. return false, nil
  199. }
  200. return com.IsDir(RepoPath(u.Name, repoName)), nil
  201. }
  202. // CloneLink represents different types of clone URLs of repository.
  203. type CloneLink struct {
  204. SSH string
  205. HTTPS string
  206. Git string
  207. }
  208. // CloneLink returns clone URLs of repository.
  209. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  210. if err = repo.GetOwner(); err != nil {
  211. return cl, err
  212. }
  213. if setting.SshPort != 22 {
  214. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.Domain, setting.SshPort, repo.Owner.LowerName, repo.LowerName)
  215. } else {
  216. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, repo.Owner.LowerName, repo.LowerName)
  217. }
  218. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  219. return cl, nil
  220. }
  221. var (
  222. illegalEquals = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  223. illegalSuffixs = []string{".git", ".keys"}
  224. )
  225. // IsLegalName returns false if name contains illegal characters.
  226. func IsLegalName(repoName string) bool {
  227. repoName = strings.ToLower(repoName)
  228. for _, char := range illegalEquals {
  229. if repoName == char {
  230. return false
  231. }
  232. }
  233. for _, char := range illegalSuffixs {
  234. if strings.HasSuffix(repoName, char) {
  235. return false
  236. }
  237. }
  238. return true
  239. }
  240. // Mirror represents a mirror information of repository.
  241. type Mirror struct {
  242. Id int64
  243. RepoId int64
  244. RepoName string // <user name>/<repo name>
  245. Interval int // Hour.
  246. Updated time.Time `xorm:"UPDATED"`
  247. NextUpdate time.Time
  248. }
  249. func GetMirror(repoId int64) (*Mirror, error) {
  250. m := &Mirror{RepoId: repoId}
  251. has, err := x.Get(m)
  252. if err != nil {
  253. return nil, err
  254. } else if !has {
  255. return nil, ErrMirrorNotExist
  256. }
  257. return m, nil
  258. }
  259. func UpdateMirror(m *Mirror) error {
  260. _, err := x.Id(m.Id).Update(m)
  261. return err
  262. }
  263. // MirrorRepository creates a mirror repository from source.
  264. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  265. _, stderr, err := process.ExecTimeout(10*time.Minute,
  266. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  267. "git", "clone", "--mirror", url, repoPath)
  268. if err != nil {
  269. return errors.New("git clone --mirror: " + stderr)
  270. }
  271. if _, err = x.InsertOne(&Mirror{
  272. RepoId: repoId,
  273. RepoName: strings.ToLower(userName + "/" + repoName),
  274. Interval: 24,
  275. NextUpdate: time.Now().Add(24 * time.Hour),
  276. }); err != nil {
  277. return err
  278. }
  279. return nil
  280. }
  281. // MigrateRepository migrates a existing repository from other project hosting.
  282. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  283. repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
  284. if err != nil {
  285. return nil, err
  286. }
  287. // Clone to temprory path and do the init commit.
  288. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  289. os.MkdirAll(tmpDir, os.ModePerm)
  290. repoPath := RepoPath(u.Name, name)
  291. if u.IsOrganization() {
  292. t, err := u.GetOwnerTeam()
  293. if err != nil {
  294. return nil, err
  295. }
  296. repo.NumWatches = t.NumMembers
  297. } else {
  298. repo.NumWatches = 1
  299. }
  300. repo.IsBare = false
  301. if mirror {
  302. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  303. return repo, err
  304. }
  305. repo.IsMirror = true
  306. return repo, UpdateRepository(repo)
  307. } else {
  308. os.RemoveAll(repoPath)
  309. }
  310. // this command could for both migrate and mirror
  311. _, stderr, err := process.ExecTimeout(10*time.Minute,
  312. fmt.Sprintf("MigrateRepository: %s", repoPath),
  313. "git", "clone", "--mirror", "--bare", url, repoPath)
  314. if err != nil {
  315. return repo, errors.New("git clone: " + stderr)
  316. }
  317. return repo, UpdateRepository(repo)
  318. }
  319. // extractGitBareZip extracts git-bare.zip to repository path.
  320. func extractGitBareZip(repoPath string) error {
  321. z, err := zip.Open(path.Join(setting.ConfRootPath, "content/git-bare.zip"))
  322. if err != nil {
  323. return err
  324. }
  325. defer z.Close()
  326. return z.ExtractTo(repoPath)
  327. }
  328. // initRepoCommit temporarily changes with work directory.
  329. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  330. var stderr string
  331. if _, stderr, err = process.ExecDir(-1,
  332. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  333. "git", "add", "--all"); err != nil {
  334. return errors.New("git add: " + stderr)
  335. }
  336. if _, stderr, err = process.ExecDir(-1,
  337. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  338. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  339. "-m", "Init commit"); err != nil {
  340. return errors.New("git commit: " + stderr)
  341. }
  342. if _, stderr, err = process.ExecDir(-1,
  343. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  344. "git", "push", "origin", "master"); err != nil {
  345. return errors.New("git push: " + stderr)
  346. }
  347. return nil
  348. }
  349. func createHookUpdate(hookPath, content string) error {
  350. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  351. if err != nil {
  352. return err
  353. }
  354. defer pu.Close()
  355. _, err = pu.WriteString(content)
  356. return err
  357. }
  358. // InitRepository initializes README and .gitignore if needed.
  359. func initRepository(f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error {
  360. repoPath := RepoPath(u.Name, repo.Name)
  361. // Create bare new repository.
  362. if err := extractGitBareZip(repoPath); err != nil {
  363. return err
  364. }
  365. // hook/post-update
  366. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  367. fmt.Sprintf(TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"")); err != nil {
  368. return err
  369. }
  370. // Initialize repository according to user's choice.
  371. fileName := map[string]string{}
  372. if initReadme {
  373. fileName["readme"] = "README.md"
  374. }
  375. if repoLang != "" {
  376. fileName["gitign"] = ".gitignore"
  377. }
  378. if license != "" {
  379. fileName["license"] = "LICENSE"
  380. }
  381. // Clone to temprory path and do the init commit.
  382. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  383. os.MkdirAll(tmpDir, os.ModePerm)
  384. _, stderr, err := process.Exec(
  385. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  386. "git", "clone", repoPath, tmpDir)
  387. if err != nil {
  388. return errors.New("initRepository(git clone): " + stderr)
  389. }
  390. // README
  391. if initReadme {
  392. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  393. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  394. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  395. []byte(defaultReadme), 0644); err != nil {
  396. return err
  397. }
  398. }
  399. // .gitignore
  400. filePath := "conf/gitignore/" + repoLang
  401. if com.IsFile(filePath) {
  402. targetPath := path.Join(tmpDir, fileName["gitign"])
  403. if com.IsFile(filePath) {
  404. if err = com.Copy(filePath, targetPath); err != nil {
  405. return err
  406. }
  407. } else {
  408. // Check custom files.
  409. filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  410. if com.IsFile(filePath) {
  411. if err := com.Copy(filePath, targetPath); err != nil {
  412. return err
  413. }
  414. }
  415. }
  416. } else {
  417. delete(fileName, "gitign")
  418. }
  419. // LICENSE
  420. filePath = "conf/license/" + license
  421. if com.IsFile(filePath) {
  422. targetPath := path.Join(tmpDir, fileName["license"])
  423. if com.IsFile(filePath) {
  424. if err = com.Copy(filePath, targetPath); err != nil {
  425. return err
  426. }
  427. } else {
  428. // Check custom files.
  429. filePath = path.Join(setting.CustomPath, "conf/license", license)
  430. if com.IsFile(filePath) {
  431. if err := com.Copy(filePath, targetPath); err != nil {
  432. return err
  433. }
  434. }
  435. }
  436. } else {
  437. delete(fileName, "license")
  438. }
  439. if len(fileName) == 0 {
  440. // Re-fetch the repository from database before updating it (else it would
  441. // override changes that were done earlier with sql)
  442. if repo, err = GetRepositoryById(repo.Id); err != nil {
  443. return err
  444. }
  445. repo.IsBare = true
  446. repo.DefaultBranch = "master"
  447. return UpdateRepository(repo)
  448. }
  449. // Apply changes and commit.
  450. return initRepoCommit(tmpDir, u.NewGitSig())
  451. }
  452. // CreateRepository creates a repository for given user or organization.
  453. func CreateRepository(u *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
  454. if !IsLegalName(name) {
  455. return nil, ErrRepoNameIllegal
  456. }
  457. isExist, err := IsRepositoryExist(u, name)
  458. if err != nil {
  459. return nil, err
  460. } else if isExist {
  461. return nil, ErrRepoAlreadyExist
  462. }
  463. sess := x.NewSession()
  464. defer sess.Close()
  465. if err = sess.Begin(); err != nil {
  466. return nil, err
  467. }
  468. repo := &Repository{
  469. OwnerId: u.Id,
  470. Owner: u,
  471. Name: name,
  472. LowerName: strings.ToLower(name),
  473. Description: desc,
  474. IsPrivate: private,
  475. }
  476. if _, err = sess.Insert(repo); err != nil {
  477. sess.Rollback()
  478. return nil, err
  479. }
  480. var t *Team // Owner team.
  481. mode := WRITABLE
  482. if mirror {
  483. mode = READABLE
  484. }
  485. access := &Access{
  486. UserName: u.LowerName,
  487. RepoName: path.Join(u.LowerName, repo.LowerName),
  488. Mode: mode,
  489. }
  490. // Give access to all members in owner team.
  491. if u.IsOrganization() {
  492. t, err = u.GetOwnerTeam()
  493. if err != nil {
  494. sess.Rollback()
  495. return nil, err
  496. }
  497. if err = t.GetMembers(); err != nil {
  498. sess.Rollback()
  499. return nil, err
  500. }
  501. for _, u := range t.Members {
  502. access.Id = 0
  503. access.UserName = u.LowerName
  504. if _, err = sess.Insert(access); err != nil {
  505. sess.Rollback()
  506. return nil, err
  507. }
  508. }
  509. } else {
  510. if _, err = sess.Insert(access); err != nil {
  511. sess.Rollback()
  512. return nil, err
  513. }
  514. }
  515. if _, err = sess.Exec(
  516. "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  517. sess.Rollback()
  518. return nil, err
  519. }
  520. // Update owner team info and count.
  521. if u.IsOrganization() {
  522. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  523. t.NumRepos++
  524. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  525. sess.Rollback()
  526. return nil, err
  527. }
  528. }
  529. if err = sess.Commit(); err != nil {
  530. return nil, err
  531. }
  532. if u.IsOrganization() {
  533. t, err := u.GetOwnerTeam()
  534. if err != nil {
  535. log.Error(4, "GetOwnerTeam: %v", err)
  536. } else {
  537. if err = t.GetMembers(); err != nil {
  538. log.Error(4, "GetMembers: %v", err)
  539. } else {
  540. for _, u := range t.Members {
  541. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  542. log.Error(4, "WatchRepo2: %v", err)
  543. }
  544. }
  545. }
  546. }
  547. } else {
  548. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  549. log.Error(4, "WatchRepo3: %v", err)
  550. }
  551. }
  552. if err = NewRepoAction(u, repo); err != nil {
  553. log.Error(4, "NewRepoAction: %v", err)
  554. }
  555. // No need for init mirror.
  556. if mirror {
  557. return repo, nil
  558. }
  559. repoPath := RepoPath(u.Name, repo.Name)
  560. if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil {
  561. if err2 := os.RemoveAll(repoPath); err2 != nil {
  562. log.Error(4, "initRepository: %v", err)
  563. return nil, fmt.Errorf(
  564. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  565. }
  566. return nil, fmt.Errorf("initRepository: %v", err)
  567. }
  568. _, stderr, err := process.ExecDir(-1,
  569. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  570. "git", "update-server-info")
  571. if err != nil {
  572. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  573. }
  574. return repo, nil
  575. }
  576. // CountRepositories returns number of repositories.
  577. func CountRepositories() int64 {
  578. count, _ := x.Count(new(Repository))
  579. return count
  580. }
  581. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  582. // It also auto-gets corresponding users.
  583. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  584. repos := make([]*Repository, 0, num)
  585. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  586. return nil, err
  587. }
  588. for _, repo := range repos {
  589. repo.Owner = &User{Id: repo.OwnerId}
  590. has, err := x.Get(repo.Owner)
  591. if err != nil {
  592. return nil, err
  593. } else if !has {
  594. return nil, ErrUserNotExist
  595. }
  596. }
  597. return repos, nil
  598. }
  599. // RepoPath returns repository path by given user and repository name.
  600. func RepoPath(userName, repoName string) string {
  601. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  602. }
  603. // TransferOwnership transfers all corresponding setting from old user to new one.
  604. func TransferOwnership(u *User, newOwner string, repo *Repository) error {
  605. newUser, err := GetUserByName(newOwner)
  606. if err != nil {
  607. return fmt.Errorf("fail to get new owner(%s): %v", newOwner, err)
  608. }
  609. // Check if new owner has repository with same name.
  610. has, err := IsRepositoryExist(newUser, repo.Name)
  611. if err != nil {
  612. return err
  613. } else if has {
  614. return ErrRepoAlreadyExist
  615. }
  616. sess := x.NewSession()
  617. defer sess.Close()
  618. if err = sess.Begin(); err != nil {
  619. return err
  620. }
  621. owner := repo.Owner
  622. oldRepoLink := path.Join(owner.LowerName, repo.LowerName)
  623. // Delete all access first if current owner is an organization.
  624. if owner.IsOrganization() {
  625. if _, err = sess.Where("repo_name=?", oldRepoLink).Delete(new(Access)); err != nil {
  626. sess.Rollback()
  627. return fmt.Errorf("fail to delete current accesses: %v", err)
  628. }
  629. } else {
  630. // Delete current owner access.
  631. if _, err = sess.Where("repo_name=?", oldRepoLink).And("user_name=?", owner.LowerName).
  632. Delete(new(Access)); err != nil {
  633. sess.Rollback()
  634. return fmt.Errorf("fail to delete access(owner): %v", err)
  635. }
  636. // In case new owner has access.
  637. if _, err = sess.Where("repo_name=?", oldRepoLink).And("user_name=?", newUser.LowerName).
  638. Delete(new(Access)); err != nil {
  639. sess.Rollback()
  640. return fmt.Errorf("fail to delete access(new user): %v", err)
  641. }
  642. }
  643. // Change accesses to new repository path.
  644. if _, err = sess.Where("repo_name=?", oldRepoLink).
  645. Update(&Access{RepoName: path.Join(newUser.LowerName, repo.LowerName)}); err != nil {
  646. sess.Rollback()
  647. return fmt.Errorf("fail to update access(change reponame): %v", err)
  648. }
  649. // Update repository.
  650. repo.OwnerId = newUser.Id
  651. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  652. sess.Rollback()
  653. return err
  654. }
  655. // Update user repository number.
  656. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newUser.Id); err != nil {
  657. sess.Rollback()
  658. return err
  659. }
  660. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", owner.Id); err != nil {
  661. sess.Rollback()
  662. return err
  663. }
  664. mode := WRITABLE
  665. if repo.IsMirror {
  666. mode = READABLE
  667. }
  668. // New owner is organization.
  669. if newUser.IsOrganization() {
  670. access := &Access{
  671. RepoName: path.Join(newUser.LowerName, repo.LowerName),
  672. Mode: mode,
  673. }
  674. // Give access to all members in owner team.
  675. t, err := newUser.GetOwnerTeam()
  676. if err != nil {
  677. sess.Rollback()
  678. return err
  679. }
  680. if err = t.GetMembers(); err != nil {
  681. sess.Rollback()
  682. return err
  683. }
  684. for _, u := range t.Members {
  685. access.Id = 0
  686. access.UserName = u.LowerName
  687. if _, err = sess.Insert(access); err != nil {
  688. sess.Rollback()
  689. return err
  690. }
  691. }
  692. // Update owner team info and count.
  693. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  694. t.NumRepos++
  695. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  696. sess.Rollback()
  697. return err
  698. }
  699. } else {
  700. access := &Access{
  701. RepoName: path.Join(newUser.LowerName, repo.LowerName),
  702. UserName: newUser.LowerName,
  703. Mode: mode,
  704. }
  705. if _, err = sess.Insert(access); err != nil {
  706. sess.Rollback()
  707. return fmt.Errorf("fail to insert access: %v", err)
  708. }
  709. }
  710. // Change repository directory name.
  711. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  712. sess.Rollback()
  713. return err
  714. }
  715. if err = sess.Commit(); err != nil {
  716. return err
  717. }
  718. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  719. log.Error(4, "WatchRepo", err)
  720. }
  721. if err = TransferRepoAction(u, newUser, repo); err != nil {
  722. return err
  723. }
  724. return nil
  725. }
  726. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  727. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  728. userName = strings.ToLower(userName)
  729. oldRepoName = strings.ToLower(oldRepoName)
  730. newRepoName = strings.ToLower(newRepoName)
  731. if !IsLegalName(newRepoName) {
  732. return ErrRepoNameIllegal
  733. }
  734. // Update accesses.
  735. accesses := make([]Access, 0, 10)
  736. if err = x.Find(&accesses, &Access{RepoName: userName + "/" + oldRepoName}); err != nil {
  737. return err
  738. }
  739. sess := x.NewSession()
  740. defer sess.Close()
  741. if err = sess.Begin(); err != nil {
  742. return err
  743. }
  744. for i := range accesses {
  745. accesses[i].RepoName = userName + "/" + newRepoName
  746. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  747. return err
  748. }
  749. }
  750. // Change repository directory name.
  751. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  752. sess.Rollback()
  753. return err
  754. }
  755. return sess.Commit()
  756. }
  757. func UpdateRepository(repo *Repository) error {
  758. repo.LowerName = strings.ToLower(repo.Name)
  759. if len(repo.Description) > 255 {
  760. repo.Description = repo.Description[:255]
  761. }
  762. if len(repo.Website) > 255 {
  763. repo.Website = repo.Website[:255]
  764. }
  765. _, err := x.Id(repo.Id).AllCols().Update(repo)
  766. return err
  767. }
  768. // DeleteRepository deletes a repository for a user or organization.
  769. func DeleteRepository(uid, repoId int64, userName string) error {
  770. repo := &Repository{Id: repoId, OwnerId: uid}
  771. has, err := x.Get(repo)
  772. if err != nil {
  773. return err
  774. } else if !has {
  775. return ErrRepoNotExist
  776. }
  777. // In case is a organization.
  778. org, err := GetUserById(uid)
  779. if err != nil {
  780. return err
  781. }
  782. if org.IsOrganization() {
  783. if err = org.GetTeams(); err != nil {
  784. return err
  785. }
  786. }
  787. sess := x.NewSession()
  788. defer sess.Close()
  789. if err = sess.Begin(); err != nil {
  790. return err
  791. }
  792. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  793. sess.Rollback()
  794. return err
  795. }
  796. // Delete all access.
  797. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  798. sess.Rollback()
  799. return err
  800. }
  801. if org.IsOrganization() {
  802. idStr := "$" + com.ToStr(repoId) + "|"
  803. for _, t := range org.Teams {
  804. if !strings.Contains(t.RepoIds, idStr) {
  805. continue
  806. }
  807. t.NumRepos--
  808. t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
  809. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  810. sess.Rollback()
  811. return err
  812. }
  813. }
  814. }
  815. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  816. sess.Rollback()
  817. return err
  818. }
  819. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  820. sess.Rollback()
  821. return err
  822. }
  823. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  824. sess.Rollback()
  825. return err
  826. }
  827. if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  828. sess.Rollback()
  829. return err
  830. }
  831. if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  832. sess.Rollback()
  833. return err
  834. }
  835. if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  836. sess.Rollback()
  837. return err
  838. }
  839. // Delete comments.
  840. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  841. issue := bean.(*Issue)
  842. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  843. sess.Rollback()
  844. return err
  845. }
  846. return nil
  847. }); err != nil {
  848. sess.Rollback()
  849. return err
  850. }
  851. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  852. sess.Rollback()
  853. return err
  854. }
  855. if repo.IsFork {
  856. if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks - 1 WHERE id = ?", repo.ForkId); err != nil {
  857. sess.Rollback()
  858. return err
  859. }
  860. }
  861. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", uid); err != nil {
  862. sess.Rollback()
  863. return err
  864. }
  865. // Remove repository files.
  866. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  867. desc := fmt.Sprintf("Fail to delete repository files(%s/%s): %v", userName, repo.Name, err)
  868. log.Warn(desc)
  869. if err = CreateRepositoryNotice(desc); err != nil {
  870. log.Error(4, "Fail to add notice: %v", err)
  871. }
  872. }
  873. return sess.Commit()
  874. }
  875. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  876. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  877. func GetRepositoryByRef(ref string) (*Repository, error) {
  878. n := strings.IndexByte(ref, byte('/'))
  879. if n < 2 {
  880. return nil, ErrInvalidReference
  881. }
  882. userName, repoName := ref[:n], ref[n+1:]
  883. user, err := GetUserByName(userName)
  884. if err != nil {
  885. return nil, err
  886. }
  887. return GetRepositoryByName(user.Id, repoName)
  888. }
  889. // GetRepositoryByName returns the repository by given name under user if exists.
  890. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  891. repo := &Repository{
  892. OwnerId: uid,
  893. LowerName: strings.ToLower(repoName),
  894. }
  895. has, err := x.Get(repo)
  896. if err != nil {
  897. return nil, err
  898. } else if !has {
  899. return nil, ErrRepoNotExist
  900. }
  901. return repo, err
  902. }
  903. // GetRepositoryById returns the repository by given id if exists.
  904. func GetRepositoryById(id int64) (*Repository, error) {
  905. repo := &Repository{}
  906. has, err := x.Id(id).Get(repo)
  907. if err != nil {
  908. return nil, err
  909. } else if !has {
  910. return nil, ErrRepoNotExist
  911. }
  912. return repo, nil
  913. }
  914. // GetRepositories returns a list of repositories of given user.
  915. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  916. repos := make([]*Repository, 0, 10)
  917. sess := x.Desc("updated")
  918. if !private {
  919. sess.Where("is_private=?", false)
  920. }
  921. err := sess.Find(&repos, &Repository{OwnerId: uid})
  922. return repos, err
  923. }
  924. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  925. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  926. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  927. return repos, err
  928. }
  929. // GetRepositoryCount returns the total number of repositories of user.
  930. func GetRepositoryCount(user *User) (int64, error) {
  931. return x.Count(&Repository{OwnerId: user.Id})
  932. }
  933. // GetCollaborators returns the collaborators for a repository
  934. func (r *Repository) GetCollaborators() ([]*User, error) {
  935. collaborations := make([]*Collaboration, 0)
  936. if err := x.Find(&collaborations, &Collaboration{RepoID: r.Id}); err != nil {
  937. return nil, err
  938. }
  939. users := make([]*User, len(collaborations))
  940. for i, c := range collaborations {
  941. user, err := GetUserById(c.UserID)
  942. if err != nil {
  943. return nil, err
  944. }
  945. users[i] = user
  946. }
  947. return users, nil
  948. }
  949. // Add collaborator and accompanying access
  950. func (r *Repository) AddCollaborator(u *User) error {
  951. collaboration := &Collaboration{RepoID: r.Id, UserID: u.Id}
  952. has, err := x.Get(collaboration)
  953. if err != nil {
  954. return err
  955. }
  956. if has {
  957. return nil
  958. }
  959. if _, err = x.InsertOne(collaboration); err != nil {
  960. return err
  961. }
  962. if err = r.GetOwner(); err != nil {
  963. return err
  964. }
  965. return AddAccess(&Access{UserName: u.LowerName, RepoName: path.Join(r.Owner.LowerName, r.LowerName), Mode: WRITABLE})
  966. }
  967. // Delete collaborator and accompanying access
  968. func (r *Repository) DeleteCollaborator(u *User) error {
  969. collaboration := &Collaboration{RepoID: r.Id, UserID: u.Id}
  970. if has, err := x.Delete(collaboration); err != nil || has == 0 {
  971. return err
  972. }
  973. if err := r.GetOwner(); err != nil {
  974. return err
  975. }
  976. needDelete := true
  977. if r.Owner.IsOrganization() {
  978. auth, err := GetHighestAuthorize(r.Owner.Id, u.Id, r.Id, 0)
  979. if err != nil {
  980. return err
  981. }
  982. if auth > 0 {
  983. needDelete = false
  984. }
  985. }
  986. if needDelete {
  987. return DeleteAccess(&Access{UserName: u.LowerName, RepoName: path.Join(r.Owner.LowerName, r.LowerName), Mode: WRITABLE})
  988. }
  989. return nil
  990. }
  991. type SearchOption struct {
  992. Keyword string
  993. Uid int64
  994. Limit int
  995. Private bool
  996. }
  997. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  998. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  999. if len(opt.Keyword) == 0 {
  1000. return repos, nil
  1001. }
  1002. opt.Keyword = strings.ToLower(opt.Keyword)
  1003. repos = make([]*Repository, 0, opt.Limit)
  1004. // Append conditions.
  1005. sess := x.Limit(opt.Limit)
  1006. if opt.Uid > 0 {
  1007. sess.Where("owner_id=?", opt.Uid)
  1008. }
  1009. if !opt.Private {
  1010. sess.And("is_private=false")
  1011. }
  1012. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  1013. return repos, err
  1014. }
  1015. // DeleteRepositoryArchives deletes all repositories' archives.
  1016. func DeleteRepositoryArchives() error {
  1017. return x.Where("id > 0").Iterate(new(Repository),
  1018. func(idx int, bean interface{}) error {
  1019. repo := bean.(*Repository)
  1020. if err := repo.GetOwner(); err != nil {
  1021. return err
  1022. }
  1023. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  1024. })
  1025. }
  1026. var (
  1027. // Prevent duplicate tasks.
  1028. isMirrorUpdating = false
  1029. isGitFscking = false
  1030. )
  1031. // MirrorUpdate checks and updates mirror repositories.
  1032. func MirrorUpdate() {
  1033. if isMirrorUpdating {
  1034. return
  1035. }
  1036. isMirrorUpdating = true
  1037. defer func() { isMirrorUpdating = false }()
  1038. mirrors := make([]*Mirror, 0, 10)
  1039. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1040. m := bean.(*Mirror)
  1041. if m.NextUpdate.After(time.Now()) {
  1042. return nil
  1043. }
  1044. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  1045. if _, stderr, err := process.ExecDir(10*time.Minute,
  1046. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1047. "git", "remote", "update"); err != nil {
  1048. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1049. log.Error(4, desc)
  1050. if err = CreateRepositoryNotice(desc); err != nil {
  1051. log.Error(4, "Fail to add notice: %v", err)
  1052. }
  1053. return nil
  1054. }
  1055. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1056. mirrors = append(mirrors, m)
  1057. return nil
  1058. }); err != nil {
  1059. log.Error(4, "MirrorUpdate: %v", err)
  1060. }
  1061. for i := range mirrors {
  1062. if err := UpdateMirror(mirrors[i]); err != nil {
  1063. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  1064. }
  1065. }
  1066. }
  1067. // GitFsck calls 'git fsck' to check repository health.
  1068. func GitFsck() {
  1069. if isGitFscking {
  1070. return
  1071. }
  1072. isGitFscking = true
  1073. defer func() { isGitFscking = false }()
  1074. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  1075. if err := x.Where("id > 0").Iterate(new(Repository),
  1076. func(idx int, bean interface{}) error {
  1077. repo := bean.(*Repository)
  1078. if err := repo.GetOwner(); err != nil {
  1079. return err
  1080. }
  1081. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  1082. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  1083. if err != nil {
  1084. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1085. log.Warn(desc)
  1086. if err = CreateRepositoryNotice(desc); err != nil {
  1087. log.Error(4, "Fail to add notice: %v", err)
  1088. }
  1089. }
  1090. return nil
  1091. }); err != nil {
  1092. log.Error(4, "repo.Fsck: %v", err)
  1093. }
  1094. }
  1095. func GitGcRepos() error {
  1096. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1097. return x.Where("id > 0").Iterate(new(Repository),
  1098. func(idx int, bean interface{}) error {
  1099. repo := bean.(*Repository)
  1100. if err := repo.GetOwner(); err != nil {
  1101. return err
  1102. }
  1103. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1104. if err != nil {
  1105. return fmt.Errorf("%v: %v", err, stderr)
  1106. }
  1107. return nil
  1108. })
  1109. }
  1110. // __ __ __ .__
  1111. // / \ / \_____ _/ |_ ____ | |__
  1112. // \ \/\/ /\__ \\ __\/ ___\| | \
  1113. // \ / / __ \| | \ \___| Y \
  1114. // \__/\ / (____ /__| \___ >___| /
  1115. // \/ \/ \/ \/
  1116. // Watch is connection request for receiving repository notification.
  1117. type Watch struct {
  1118. Id int64
  1119. UserId int64 `xorm:"UNIQUE(watch)"`
  1120. RepoId int64 `xorm:"UNIQUE(watch)"`
  1121. }
  1122. // IsWatching checks if user has watched given repository.
  1123. func IsWatching(uid, repoId int64) bool {
  1124. has, _ := x.Get(&Watch{0, uid, repoId})
  1125. return has
  1126. }
  1127. func watchRepoWithEngine(e Engine, uid, repoId int64, watch bool) (err error) {
  1128. if watch {
  1129. if IsWatching(uid, repoId) {
  1130. return nil
  1131. }
  1132. if _, err = e.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
  1133. return err
  1134. }
  1135. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1136. } else {
  1137. if !IsWatching(uid, repoId) {
  1138. return nil
  1139. }
  1140. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1141. return err
  1142. }
  1143. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
  1144. }
  1145. return err
  1146. }
  1147. // Watch or unwatch repository.
  1148. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1149. return watchRepoWithEngine(x, uid, repoId, watch)
  1150. }
  1151. // GetWatchers returns all watchers of given repository.
  1152. func GetWatchers(rid int64) ([]*Watch, error) {
  1153. watches := make([]*Watch, 0, 10)
  1154. err := x.Find(&watches, &Watch{RepoId: rid})
  1155. return watches, err
  1156. }
  1157. // NotifyWatchers creates batch of actions for every watcher.
  1158. func NotifyWatchers(act *Action) error {
  1159. // Add feeds for user self and all watchers.
  1160. watches, err := GetWatchers(act.RepoId)
  1161. if err != nil {
  1162. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  1163. }
  1164. // Add feed for actioner.
  1165. act.UserId = act.ActUserId
  1166. if _, err = x.InsertOne(act); err != nil {
  1167. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  1168. }
  1169. for i := range watches {
  1170. if act.ActUserId == watches[i].UserId {
  1171. continue
  1172. }
  1173. act.Id = 0
  1174. act.UserId = watches[i].UserId
  1175. if _, err = x.InsertOne(act); err != nil {
  1176. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  1177. }
  1178. }
  1179. return nil
  1180. }
  1181. // _________ __
  1182. // / _____// |______ _______
  1183. // \_____ \\ __\__ \\_ __ \
  1184. // / \| | / __ \| | \/
  1185. // /_______ /|__| (____ /__|
  1186. // \/ \/
  1187. type Star struct {
  1188. Id int64
  1189. Uid int64 `xorm:"UNIQUE(s)"`
  1190. RepoId int64 `xorm:"UNIQUE(s)"`
  1191. }
  1192. // Star or unstar repository.
  1193. func StarRepo(uid, repoId int64, star bool) (err error) {
  1194. if star {
  1195. if IsStaring(uid, repoId) {
  1196. return nil
  1197. }
  1198. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1199. return err
  1200. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1201. return err
  1202. }
  1203. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1204. } else {
  1205. if !IsStaring(uid, repoId) {
  1206. return nil
  1207. }
  1208. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1209. return err
  1210. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1211. return err
  1212. }
  1213. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1214. }
  1215. return err
  1216. }
  1217. // IsStaring checks if user has starred given repository.
  1218. func IsStaring(uid, repoId int64) bool {
  1219. has, _ := x.Get(&Star{0, uid, repoId})
  1220. return has
  1221. }
  1222. // ___________ __
  1223. // \_ _____/__________| | __
  1224. // | __)/ _ \_ __ \ |/ /
  1225. // | \( <_> ) | \/ <
  1226. // \___ / \____/|__| |__|_ \
  1227. // \/ \/
  1228. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repository, error) {
  1229. isExist, err := IsRepositoryExist(u, name)
  1230. if err != nil {
  1231. return nil, err
  1232. } else if isExist {
  1233. return nil, ErrRepoAlreadyExist
  1234. }
  1235. // In case the old repository is a fork.
  1236. if oldRepo.IsFork {
  1237. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1238. if err != nil {
  1239. return nil, err
  1240. }
  1241. }
  1242. sess := x.NewSession()
  1243. defer sess.Close()
  1244. if err = sess.Begin(); err != nil {
  1245. return nil, err
  1246. }
  1247. repo := &Repository{
  1248. OwnerId: u.Id,
  1249. Owner: u,
  1250. Name: name,
  1251. LowerName: strings.ToLower(name),
  1252. Description: desc,
  1253. IsPrivate: oldRepo.IsPrivate,
  1254. IsFork: true,
  1255. ForkId: oldRepo.Id,
  1256. }
  1257. if _, err = sess.Insert(repo); err != nil {
  1258. sess.Rollback()
  1259. return nil, err
  1260. }
  1261. var t *Team // Owner team.
  1262. mode := WRITABLE
  1263. access := &Access{
  1264. UserName: u.LowerName,
  1265. RepoName: path.Join(u.LowerName, repo.LowerName),
  1266. Mode: mode,
  1267. }
  1268. // Give access to all members in owner team.
  1269. if u.IsOrganization() {
  1270. t, err = u.GetOwnerTeam()
  1271. if err != nil {
  1272. sess.Rollback()
  1273. return nil, err
  1274. }
  1275. if err = t.GetMembers(); err != nil {
  1276. sess.Rollback()
  1277. return nil, err
  1278. }
  1279. for _, u := range t.Members {
  1280. access.Id = 0
  1281. access.UserName = u.LowerName
  1282. if _, err = sess.Insert(access); err != nil {
  1283. sess.Rollback()
  1284. return nil, err
  1285. }
  1286. }
  1287. } else {
  1288. if _, err = sess.Insert(access); err != nil {
  1289. sess.Rollback()
  1290. return nil, err
  1291. }
  1292. }
  1293. if _, err = sess.Exec(
  1294. "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1295. sess.Rollback()
  1296. return nil, err
  1297. }
  1298. // Update owner team info and count.
  1299. if u.IsOrganization() {
  1300. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  1301. t.NumRepos++
  1302. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  1303. sess.Rollback()
  1304. return nil, err
  1305. }
  1306. }
  1307. if u.IsOrganization() {
  1308. t, err := u.GetOwnerTeam()
  1309. if err != nil {
  1310. log.Error(4, "GetOwnerTeam: %v", err)
  1311. } else {
  1312. if err = t.GetMembers(); err != nil {
  1313. log.Error(4, "GetMembers: %v", err)
  1314. } else {
  1315. for _, u := range t.Members {
  1316. if err = watchRepoWithEngine(sess, u.Id, repo.Id, true); err != nil {
  1317. log.Error(4, "WatchRepo2: %v", err)
  1318. }
  1319. }
  1320. }
  1321. }
  1322. } else {
  1323. if err = watchRepoWithEngine(sess, u.Id, repo.Id, true); err != nil {
  1324. log.Error(4, "WatchRepo3: %v", err)
  1325. }
  1326. }
  1327. if err = NewRepoAction(u, repo); err != nil {
  1328. log.Error(4, "NewRepoAction: %v", err)
  1329. }
  1330. if _, err = sess.Exec(
  1331. "UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil {
  1332. sess.Rollback()
  1333. return nil, err
  1334. }
  1335. oldRepoPath, err := oldRepo.RepoPath()
  1336. if err != nil {
  1337. sess.Rollback()
  1338. return nil, fmt.Errorf("fail to get repo path(%s): %v", oldRepo.Name, err)
  1339. }
  1340. if err = sess.Commit(); err != nil {
  1341. return nil, err
  1342. }
  1343. repoPath := RepoPath(u.Name, repo.Name)
  1344. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1345. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1346. "git", "clone", "--bare", oldRepoPath, repoPath)
  1347. if err != nil {
  1348. return nil, errors.New("ForkRepository(git clone): " + stderr)
  1349. }
  1350. _, stderr, err = process.ExecDir(-1,
  1351. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1352. "git", "update-server-info")
  1353. if err != nil {
  1354. return nil, errors.New("ForkRepository(git update-server-info): " + stderr)
  1355. }
  1356. return repo, nil
  1357. }
  1358. // A Collaboration is a relation between an individual and a repository
  1359. type Collaboration struct {
  1360. ID int64 `xorm:"pk autoincr"`
  1361. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1362. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1363. Created time.Time `xorm:"CREATED"`
  1364. }