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 37KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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": "gogitservice@gmail.com"} {
  93. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  94. // ExitError indicates this config is not set
  95. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  96. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  97. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  98. }
  99. log.Info("Git config %s set to %s", configKey, defaultValue)
  100. } else {
  101. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  102. }
  103. }
  104. }
  105. // Set git some configurations.
  106. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  107. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  108. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  109. }
  110. }
  111. // Repository represents a git repository.
  112. type Repository struct {
  113. Id int64
  114. OwnerId int64 `xorm:"UNIQUE(s)"`
  115. Owner *User `xorm:"-"`
  116. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  117. Name string `xorm:"INDEX NOT NULL"`
  118. Description string
  119. Website string
  120. DefaultBranch string
  121. NumWatches int
  122. NumStars int
  123. NumForks int
  124. NumIssues int
  125. NumClosedIssues int
  126. NumOpenIssues int `xorm:"-"`
  127. NumPulls int
  128. NumClosedPulls int
  129. NumOpenPulls int `xorm:"-"`
  130. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  132. NumOpenMilestones int `xorm:"-"`
  133. NumTags int `xorm:"-"`
  134. IsPrivate bool
  135. IsBare bool
  136. 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, isPrivate, isMirror, 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: isPrivate,
  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("getOwnerTeam: %v", err)
  485. } else if err = t.addRepository(sess, repo); err != nil {
  486. return nil, fmt.Errorf("addRepository: %v", err)
  487. }
  488. } else {
  489. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  490. return nil, fmt.Errorf("watchRepo: %v", err)
  491. }
  492. }
  493. if err = newRepoAction(sess, u, repo); err != nil {
  494. return nil, fmt.Errorf("newRepoAction: %v", err)
  495. }
  496. // No need for init mirror.
  497. if !isMirror {
  498. repoPath := RepoPath(u.Name, repo.Name)
  499. if err = initRepository(sess, repoPath, u, repo, initReadme, lang, license); err != nil {
  500. if err2 := os.RemoveAll(repoPath); err2 != nil {
  501. log.Error(4, "initRepository: %v", err)
  502. return nil, fmt.Errorf(
  503. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  504. }
  505. return nil, fmt.Errorf("initRepository: %v", err)
  506. }
  507. _, stderr, err := process.ExecDir(-1,
  508. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  509. "git", "update-server-info")
  510. if err != nil {
  511. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  512. }
  513. }
  514. return repo, sess.Commit()
  515. }
  516. // CountRepositories returns number of repositories.
  517. func CountRepositories() int64 {
  518. count, _ := x.Count(new(Repository))
  519. return count
  520. }
  521. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  522. // It also auto-gets corresponding users.
  523. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  524. repos := make([]*Repository, 0, num)
  525. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  526. return nil, err
  527. }
  528. for _, repo := range repos {
  529. repo.Owner = &User{Id: repo.OwnerId}
  530. has, err := x.Get(repo.Owner)
  531. if err != nil {
  532. return nil, err
  533. } else if !has {
  534. return nil, ErrUserNotExist
  535. }
  536. }
  537. return repos, nil
  538. }
  539. // RepoPath returns repository path by given user and repository name.
  540. func RepoPath(userName, repoName string) string {
  541. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  542. }
  543. // TransferOwnership transfers all corresponding setting from old user to new one.
  544. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  545. newOwner, err := GetUserByName(newOwnerName)
  546. if err != nil {
  547. return fmt.Errorf("get new owner(%s): %v", newOwnerName, err)
  548. }
  549. // Check if new owner has repository with same name.
  550. has, err := IsRepositoryExist(newOwner, repo.Name)
  551. if err != nil {
  552. return err
  553. } else if has {
  554. return ErrRepoAlreadyExist
  555. }
  556. sess := x.NewSession()
  557. defer sessionRelease(sess)
  558. if err = sess.Begin(); err != nil {
  559. return err
  560. }
  561. owner := repo.Owner
  562. // Update repository.
  563. repo.OwnerId = newOwner.Id
  564. repo.Owner = newOwner
  565. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  566. return err
  567. }
  568. // Remove redundant collaborators
  569. collaborators, err := repo.GetCollaborators()
  570. if err != nil {
  571. return err
  572. }
  573. for _, c := range collaborators {
  574. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  575. if _, err = sess.Delete(&Collaboration{RepoID: repo.Id, UserID: c.Id}); err != nil {
  576. return err
  577. }
  578. }
  579. }
  580. if newOwner.IsOrganization() {
  581. // Update owner team info and count.
  582. t, err := newOwner.GetOwnerTeam()
  583. if err != nil {
  584. return err
  585. } else if err = t.addRepository(sess, repo); err != nil {
  586. return err
  587. }
  588. }
  589. // Update user repository number.
  590. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newOwner.Id); err != nil {
  591. return err
  592. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", owner.Id); err != nil {
  593. return err
  594. } else if err = repo.recalculateAccesses(sess); err != nil {
  595. return err
  596. } else if err = watchRepo(sess, newOwner.Id, repo.Id, true); err != nil {
  597. return err
  598. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  599. return err
  600. }
  601. // Change repository directory name.
  602. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  603. return err
  604. }
  605. return sess.Commit()
  606. }
  607. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  608. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  609. userName = strings.ToLower(userName)
  610. oldRepoName = strings.ToLower(oldRepoName)
  611. newRepoName = strings.ToLower(newRepoName)
  612. if !IsLegalName(newRepoName) {
  613. return ErrRepoNameIllegal
  614. }
  615. // Change repository directory name.
  616. return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName))
  617. }
  618. func updateRepository(e Engine, repo *Repository) error {
  619. repo.LowerName = strings.ToLower(repo.Name)
  620. if len(repo.Description) > 255 {
  621. repo.Description = repo.Description[:255]
  622. }
  623. if len(repo.Website) > 255 {
  624. repo.Website = repo.Website[:255]
  625. }
  626. _, err := e.Id(repo.Id).AllCols().Update(repo)
  627. return err
  628. }
  629. func UpdateRepository(repo *Repository) error {
  630. return updateRepository(x, repo)
  631. }
  632. // DeleteRepository deletes a repository for a user or organization.
  633. func DeleteRepository(uid, repoID int64, userName string) error {
  634. repo := &Repository{Id: repoID, OwnerId: uid}
  635. has, err := x.Get(repo)
  636. if err != nil {
  637. return err
  638. } else if !has {
  639. return ErrRepoNotExist
  640. }
  641. // In case is a organization.
  642. org, err := GetUserById(uid)
  643. if err != nil {
  644. return err
  645. }
  646. if org.IsOrganization() {
  647. if err = org.GetTeams(); err != nil {
  648. return err
  649. }
  650. }
  651. sess := x.NewSession()
  652. defer sessionRelease(sess)
  653. if err = sess.Begin(); err != nil {
  654. return err
  655. }
  656. if org.IsOrganization() {
  657. for _, t := range org.Teams {
  658. if !t.hasRepository(sess, repoID) {
  659. continue
  660. } else if err = t.removeRepository(sess, repo); err != nil {
  661. return err
  662. }
  663. }
  664. }
  665. if _, err = sess.Delete(&Repository{Id: repoID}); err != nil {
  666. return err
  667. } else if _, err := sess.Delete(&Access{RepoID: repo.Id}); err != nil {
  668. return err
  669. } else if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  670. return err
  671. } else if _, err = sess.Delete(&Watch{RepoId: repoID}); err != nil {
  672. return err
  673. } else if _, err = sess.Delete(&Mirror{RepoId: repoID}); err != nil {
  674. return err
  675. } else if _, err = sess.Delete(&IssueUser{RepoId: repoID}); err != nil {
  676. return err
  677. } else if _, err = sess.Delete(&Milestone{RepoId: repoID}); err != nil {
  678. return err
  679. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  680. return err
  681. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  682. return err
  683. }
  684. // Delete comments.
  685. issues := make([]*Issue, 0, 25)
  686. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  687. return err
  688. }
  689. for i := range issues {
  690. if _, err = sess.Delete(&Comment{IssueId: issues[i].Id}); err != nil {
  691. return err
  692. }
  693. }
  694. if _, err = sess.Delete(&Issue{RepoId: repoID}); err != nil {
  695. return err
  696. }
  697. if repo.IsFork {
  698. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkId); err != nil {
  699. return err
  700. }
  701. }
  702. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  703. return err
  704. }
  705. // Remove repository files.
  706. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  707. desc := fmt.Sprintf("delete repository files(%s/%s): %v", userName, repo.Name, err)
  708. log.Warn(desc)
  709. if err = CreateRepositoryNotice(desc); err != nil {
  710. log.Error(4, "add notice: %v", err)
  711. }
  712. }
  713. return sess.Commit()
  714. }
  715. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  716. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  717. func GetRepositoryByRef(ref string) (*Repository, error) {
  718. n := strings.IndexByte(ref, byte('/'))
  719. if n < 2 {
  720. return nil, ErrInvalidReference
  721. }
  722. userName, repoName := ref[:n], ref[n+1:]
  723. user, err := GetUserByName(userName)
  724. if err != nil {
  725. return nil, err
  726. }
  727. return GetRepositoryByName(user.Id, repoName)
  728. }
  729. // GetRepositoryByName returns the repository by given name under user if exists.
  730. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  731. repo := &Repository{
  732. OwnerId: uid,
  733. LowerName: strings.ToLower(repoName),
  734. }
  735. has, err := x.Get(repo)
  736. if err != nil {
  737. return nil, err
  738. } else if !has {
  739. return nil, ErrRepoNotExist
  740. }
  741. return repo, err
  742. }
  743. func getRepositoryById(e Engine, id int64) (*Repository, error) {
  744. repo := &Repository{}
  745. has, err := e.Id(id).Get(repo)
  746. if err != nil {
  747. return nil, err
  748. } else if !has {
  749. return nil, ErrRepoNotExist
  750. }
  751. return repo, nil
  752. }
  753. // GetRepositoryById returns the repository by given id if exists.
  754. func GetRepositoryById(id int64) (*Repository, error) {
  755. return getRepositoryById(x, id)
  756. }
  757. // GetRepositories returns a list of repositories of given user.
  758. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  759. repos := make([]*Repository, 0, 10)
  760. sess := x.Desc("updated")
  761. if !private {
  762. sess.Where("is_private=?", false)
  763. }
  764. err := sess.Find(&repos, &Repository{OwnerId: uid})
  765. return repos, err
  766. }
  767. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  768. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  769. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  770. return repos, err
  771. }
  772. // GetRepositoryCount returns the total number of repositories of user.
  773. func GetRepositoryCount(user *User) (int64, error) {
  774. return x.Count(&Repository{OwnerId: user.Id})
  775. }
  776. type SearchOption struct {
  777. Keyword string
  778. Uid int64
  779. Limit int
  780. Private bool
  781. }
  782. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  783. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  784. if len(opt.Keyword) == 0 {
  785. return repos, nil
  786. }
  787. opt.Keyword = strings.ToLower(opt.Keyword)
  788. repos = make([]*Repository, 0, opt.Limit)
  789. // Append conditions.
  790. sess := x.Limit(opt.Limit)
  791. if opt.Uid > 0 {
  792. sess.Where("owner_id=?", opt.Uid)
  793. }
  794. if !opt.Private {
  795. sess.And("is_private=false")
  796. }
  797. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  798. return repos, err
  799. }
  800. // DeleteRepositoryArchives deletes all repositories' archives.
  801. func DeleteRepositoryArchives() error {
  802. return x.Where("id > 0").Iterate(new(Repository),
  803. func(idx int, bean interface{}) error {
  804. repo := bean.(*Repository)
  805. if err := repo.GetOwner(); err != nil {
  806. return err
  807. }
  808. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  809. })
  810. }
  811. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  812. func RewriteRepositoryUpdateHook() error {
  813. return x.Where("id > 0").Iterate(new(Repository),
  814. func(idx int, bean interface{}) error {
  815. repo := bean.(*Repository)
  816. if err := repo.GetOwner(); err != nil {
  817. return err
  818. }
  819. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  820. })
  821. }
  822. var (
  823. // Prevent duplicate tasks.
  824. isMirrorUpdating = false
  825. isGitFscking = false
  826. )
  827. // MirrorUpdate checks and updates mirror repositories.
  828. func MirrorUpdate() {
  829. if isMirrorUpdating {
  830. return
  831. }
  832. isMirrorUpdating = true
  833. defer func() { isMirrorUpdating = false }()
  834. mirrors := make([]*Mirror, 0, 10)
  835. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  836. m := bean.(*Mirror)
  837. if m.NextUpdate.After(time.Now()) {
  838. return nil
  839. }
  840. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  841. if _, stderr, err := process.ExecDir(10*time.Minute,
  842. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  843. "git", "remote", "update"); err != nil {
  844. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  845. log.Error(4, desc)
  846. if err = CreateRepositoryNotice(desc); err != nil {
  847. log.Error(4, "Fail to add notice: %v", err)
  848. }
  849. return nil
  850. }
  851. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  852. mirrors = append(mirrors, m)
  853. return nil
  854. }); err != nil {
  855. log.Error(4, "MirrorUpdate: %v", err)
  856. }
  857. for i := range mirrors {
  858. if err := UpdateMirror(mirrors[i]); err != nil {
  859. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  860. }
  861. }
  862. }
  863. // GitFsck calls 'git fsck' to check repository health.
  864. func GitFsck() {
  865. if isGitFscking {
  866. return
  867. }
  868. isGitFscking = true
  869. defer func() { isGitFscking = false }()
  870. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  871. if err := x.Where("id > 0").Iterate(new(Repository),
  872. func(idx int, bean interface{}) error {
  873. repo := bean.(*Repository)
  874. if err := repo.GetOwner(); err != nil {
  875. return err
  876. }
  877. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  878. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  879. if err != nil {
  880. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  881. log.Warn(desc)
  882. if err = CreateRepositoryNotice(desc); err != nil {
  883. log.Error(4, "Fail to add notice: %v", err)
  884. }
  885. }
  886. return nil
  887. }); err != nil {
  888. log.Error(4, "repo.Fsck: %v", err)
  889. }
  890. }
  891. func GitGcRepos() error {
  892. args := append([]string{"gc"}, setting.Git.GcArgs...)
  893. return x.Where("id > 0").Iterate(new(Repository),
  894. func(idx int, bean interface{}) error {
  895. repo := bean.(*Repository)
  896. if err := repo.GetOwner(); err != nil {
  897. return err
  898. }
  899. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  900. if err != nil {
  901. return fmt.Errorf("%v: %v", err, stderr)
  902. }
  903. return nil
  904. })
  905. }
  906. // _________ .__ .__ ___. __ .__
  907. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  908. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  909. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  910. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  911. // \/ \/ \/ \/ \/
  912. // A Collaboration is a relation between an individual and a repository
  913. type Collaboration struct {
  914. ID int64 `xorm:"pk autoincr"`
  915. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  916. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  917. Created time.Time `xorm:"CREATED"`
  918. }
  919. // Add collaborator and accompanying access
  920. func (repo *Repository) AddCollaborator(u *User) error {
  921. collaboration := &Collaboration{
  922. RepoID: repo.Id,
  923. UserID: u.Id,
  924. }
  925. has, err := x.Get(collaboration)
  926. if err != nil {
  927. return err
  928. } else if has {
  929. return nil
  930. }
  931. sess := x.NewSession()
  932. defer sessionRelease(sess)
  933. if err = sess.Begin(); err != nil {
  934. return err
  935. }
  936. if _, err = sess.InsertOne(collaboration); err != nil {
  937. return err
  938. } else if err = repo.recalculateAccesses(sess); err != nil {
  939. return err
  940. }
  941. return sess.Commit()
  942. }
  943. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  944. collaborations := make([]*Collaboration, 0)
  945. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil {
  946. return nil, err
  947. }
  948. users := make([]*User, len(collaborations))
  949. for i, c := range collaborations {
  950. user, err := getUserById(e, c.UserID)
  951. if err != nil {
  952. return nil, err
  953. }
  954. users[i] = user
  955. }
  956. return users, nil
  957. }
  958. // GetCollaborators returns the collaborators for a repository
  959. func (repo *Repository) GetCollaborators() ([]*User, error) {
  960. return repo.getCollaborators(x)
  961. }
  962. // Delete collaborator and accompanying access
  963. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  964. collaboration := &Collaboration{
  965. RepoID: repo.Id,
  966. UserID: u.Id,
  967. }
  968. sess := x.NewSession()
  969. defer sessionRelease(sess)
  970. if err = sess.Begin(); err != nil {
  971. return err
  972. }
  973. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  974. return err
  975. } else if err = repo.recalculateAccesses(sess); err != nil {
  976. return err
  977. }
  978. return sess.Commit()
  979. }
  980. // __ __ __ .__
  981. // / \ / \_____ _/ |_ ____ | |__
  982. // \ \/\/ /\__ \\ __\/ ___\| | \
  983. // \ / / __ \| | \ \___| Y \
  984. // \__/\ / (____ /__| \___ >___| /
  985. // \/ \/ \/ \/
  986. // Watch is connection request for receiving repository notification.
  987. type Watch struct {
  988. Id int64
  989. UserId int64 `xorm:"UNIQUE(watch)"`
  990. RepoId int64 `xorm:"UNIQUE(watch)"`
  991. }
  992. // IsWatching checks if user has watched given repository.
  993. func IsWatching(uid, repoId int64) bool {
  994. has, _ := x.Get(&Watch{0, uid, repoId})
  995. return has
  996. }
  997. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  998. if watch {
  999. if IsWatching(uid, repoId) {
  1000. return nil
  1001. }
  1002. if _, err = e.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
  1003. return err
  1004. }
  1005. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1006. } else {
  1007. if !IsWatching(uid, repoId) {
  1008. return nil
  1009. }
  1010. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1011. return err
  1012. }
  1013. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
  1014. }
  1015. return err
  1016. }
  1017. // Watch or unwatch repository.
  1018. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1019. return watchRepo(x, uid, repoId, watch)
  1020. }
  1021. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1022. watches := make([]*Watch, 0, 10)
  1023. err := e.Find(&watches, &Watch{RepoId: rid})
  1024. return watches, err
  1025. }
  1026. // GetWatchers returns all watchers of given repository.
  1027. func GetWatchers(rid int64) ([]*Watch, error) {
  1028. return getWatchers(x, rid)
  1029. }
  1030. func notifyWatchers(e Engine, act *Action) error {
  1031. // Add feeds for user self and all watchers.
  1032. watches, err := getWatchers(e, act.RepoId)
  1033. if err != nil {
  1034. return fmt.Errorf("get watchers: %v", err)
  1035. }
  1036. // Add feed for actioner.
  1037. act.UserId = act.ActUserId
  1038. if _, err = e.InsertOne(act); err != nil {
  1039. return fmt.Errorf("insert new actioner: %v", err)
  1040. }
  1041. for i := range watches {
  1042. if act.ActUserId == watches[i].UserId {
  1043. continue
  1044. }
  1045. act.Id = 0
  1046. act.UserId = watches[i].UserId
  1047. if _, err = e.InsertOne(act); err != nil {
  1048. return fmt.Errorf("insert new action: %v", err)
  1049. }
  1050. }
  1051. return nil
  1052. }
  1053. // NotifyWatchers creates batch of actions for every watcher.
  1054. func NotifyWatchers(act *Action) error {
  1055. return notifyWatchers(x, act)
  1056. }
  1057. // _________ __
  1058. // / _____// |______ _______
  1059. // \_____ \\ __\__ \\_ __ \
  1060. // / \| | / __ \| | \/
  1061. // /_______ /|__| (____ /__|
  1062. // \/ \/
  1063. type Star struct {
  1064. Id int64
  1065. Uid int64 `xorm:"UNIQUE(s)"`
  1066. RepoId int64 `xorm:"UNIQUE(s)"`
  1067. }
  1068. // Star or unstar repository.
  1069. func StarRepo(uid, repoId int64, star bool) (err error) {
  1070. if star {
  1071. if IsStaring(uid, repoId) {
  1072. return nil
  1073. }
  1074. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1075. return err
  1076. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1077. return err
  1078. }
  1079. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1080. } else {
  1081. if !IsStaring(uid, repoId) {
  1082. return nil
  1083. }
  1084. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1085. return err
  1086. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1087. return err
  1088. }
  1089. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1090. }
  1091. return err
  1092. }
  1093. // IsStaring checks if user has starred given repository.
  1094. func IsStaring(uid, repoId int64) bool {
  1095. has, _ := x.Get(&Star{0, uid, repoId})
  1096. return has
  1097. }
  1098. // ___________ __
  1099. // \_ _____/__________| | __
  1100. // | __)/ _ \_ __ \ |/ /
  1101. // | \( <_> ) | \/ <
  1102. // \___ / \____/|__| |__|_ \
  1103. // \/ \/
  1104. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repository, error) {
  1105. isExist, err := IsRepositoryExist(u, name)
  1106. if err != nil {
  1107. return nil, err
  1108. } else if isExist {
  1109. return nil, ErrRepoAlreadyExist
  1110. }
  1111. // In case the old repository is a fork.
  1112. if oldRepo.IsFork {
  1113. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1114. if err != nil {
  1115. return nil, err
  1116. }
  1117. }
  1118. repo := &Repository{
  1119. OwnerId: u.Id,
  1120. Owner: u,
  1121. Name: name,
  1122. LowerName: strings.ToLower(name),
  1123. Description: desc,
  1124. IsPrivate: oldRepo.IsPrivate,
  1125. IsFork: true,
  1126. ForkId: oldRepo.Id,
  1127. }
  1128. sess := x.NewSession()
  1129. defer sessionRelease(sess)
  1130. if err = sess.Begin(); err != nil {
  1131. return nil, err
  1132. }
  1133. if _, err = sess.Insert(repo); err != nil {
  1134. return nil, err
  1135. }
  1136. if err = repo.recalculateAccesses(sess); err != nil {
  1137. return nil, err
  1138. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1139. return nil, err
  1140. }
  1141. if u.IsOrganization() {
  1142. // Update owner team info and count.
  1143. t, err := u.getOwnerTeam(sess)
  1144. if err != nil {
  1145. return nil, fmt.Errorf("getOwnerTeam: %v", err)
  1146. } else if err = t.addRepository(sess, repo); err != nil {
  1147. return nil, fmt.Errorf("addRepository: %v", err)
  1148. }
  1149. } else {
  1150. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1151. return nil, fmt.Errorf("watchRepo: %v", err)
  1152. }
  1153. }
  1154. if err = newRepoAction(sess, u, repo); err != nil {
  1155. return nil, fmt.Errorf("newRepoAction: %v", err)
  1156. }
  1157. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.Id); err != nil {
  1158. return nil, err
  1159. }
  1160. oldRepoPath, err := oldRepo.RepoPath()
  1161. if err != nil {
  1162. return nil, fmt.Errorf("get old repository path: %v", err)
  1163. }
  1164. repoPath := RepoPath(u.Name, repo.Name)
  1165. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1166. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1167. "git", "clone", "--bare", oldRepoPath, repoPath)
  1168. if err != nil {
  1169. return nil, fmt.Errorf("git clone: %v", stderr)
  1170. }
  1171. _, stderr, err = process.ExecDir(-1,
  1172. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1173. "git", "update-server-info")
  1174. if err != nil {
  1175. return nil, fmt.Errorf("git update-server-info: %v", err)
  1176. }
  1177. return repo, sess.Commit()
  1178. }