repo.go 37 KB

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