repo.go 37 KB

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