You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 38KB

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