repo.go 40 KB

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