Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

repo.go 37KB

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