repo.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "errors"
  7. "fmt"
  8. "html/template"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/Unknwon/cae/zip"
  20. "github.com/Unknwon/com"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/git"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/process"
  25. "github.com/gogits/gogs/modules/setting"
  26. )
  27. const (
  28. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  29. )
  30. var (
  31. ErrRepoAlreadyExist = errors.New("Repository already exist")
  32. ErrRepoNotExist = errors.New("Repository does not exist")
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  35. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  36. ErrMirrorNotExist = errors.New("Mirror does not exist")
  37. ErrInvalidReference = errors.New("Invalid reference specified")
  38. )
  39. var (
  40. Gitignores, Licenses []string
  41. )
  42. var (
  43. DescPattern = regexp.MustCompile(`https?://\S+`)
  44. )
  45. func LoadRepoConfig() {
  46. // Load .gitignore and license files.
  47. types := []string{"gitignore", "license"}
  48. typeFiles := make([][]string, 2)
  49. for i, t := range types {
  50. files, err := com.StatDir(path.Join("conf", t))
  51. if err != nil {
  52. log.Fatal(4, "Fail to get %s files: %v", t, err)
  53. }
  54. customPath := path.Join(setting.CustomPath, "conf", t)
  55. if com.IsDir(customPath) {
  56. customFiles, err := com.StatDir(customPath)
  57. if err != nil {
  58. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  59. }
  60. for _, f := range customFiles {
  61. if !com.IsSliceContainsStr(files, f) {
  62. files = append(files, f)
  63. }
  64. }
  65. }
  66. typeFiles[i] = files
  67. }
  68. Gitignores = typeFiles[0]
  69. Licenses = typeFiles[1]
  70. sort.Strings(Gitignores)
  71. sort.Strings(Licenses)
  72. }
  73. func NewRepoContext() {
  74. zip.Verbose = false
  75. // Check Git installation.
  76. if _, err := exec.LookPath("git"); err != nil {
  77. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  78. }
  79. // Check Git version.
  80. ver, err := git.GetVersion()
  81. if err != nil {
  82. log.Fatal(4, "Fail to get Git version: %v", err)
  83. }
  84. reqVer, err := git.ParseVersion("1.7.1")
  85. if err != nil {
  86. log.Fatal(4, "Fail to parse required Git version: %v", err)
  87. }
  88. if ver.LessThan(reqVer) {
  89. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  90. }
  91. // Check if server has user.email and user.name set correctly and set if they're not.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "[email protected]"} {
  93. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  94. // ExitError indicates this config is not set
  95. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  96. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  97. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  98. }
  99. log.Info("Git config %s set to %s", configKey, defaultValue)
  100. } else {
  101. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  102. }
  103. }
  104. }
  105. // Set git some configurations.
  106. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  107. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  108. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  109. }
  110. }
  111. // Repository represents a git repository.
  112. type Repository struct {
  113. Id int64
  114. OwnerId int64 `xorm:"UNIQUE(s)"`
  115. Owner *User `xorm:"-"`
  116. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  117. Name string `xorm:"INDEX NOT NULL"`
  118. Description string
  119. Website string
  120. DefaultBranch string
  121. NumWatches int
  122. NumStars int
  123. NumForks int
  124. NumIssues int
  125. NumClosedIssues int
  126. NumOpenIssues int `xorm:"-"`
  127. NumPulls int
  128. NumClosedPulls int
  129. NumOpenPulls int `xorm:"-"`
  130. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  132. NumOpenMilestones int `xorm:"-"`
  133. NumTags int `xorm:"-"`
  134. IsPrivate bool
  135. IsBare bool
  136. 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. // Remove redundant collaborators
  580. collaborators, err := repo.GetCollaborators()
  581. if err != nil {
  582. return err
  583. }
  584. for _, c := range collaborators {
  585. if c.Id == newUser.Id || newUser.IsOrgMember(c.Id) {
  586. if _, err = sess.Delete(&Collaboration{RepoID: repo.Id, UserID: c.Id}); err != nil {
  587. return err
  588. }
  589. }
  590. }
  591. // Update user repository number.
  592. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newUser.Id); err != nil {
  593. return err
  594. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", owner.Id); err != nil {
  595. return err
  596. } else if err = repo.recalculateAccesses(sess); err != nil {
  597. return err
  598. } else if err = watchRepo(sess, newUser.Id, repo.Id, true); err != nil {
  599. return err
  600. } else if err = transferRepoAction(sess, u, newUser, repo); err != nil {
  601. return err
  602. }
  603. // Change repository directory name.
  604. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  605. return err
  606. }
  607. return sess.Commit()
  608. }
  609. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  610. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  611. userName = strings.ToLower(userName)
  612. oldRepoName = strings.ToLower(oldRepoName)
  613. newRepoName = strings.ToLower(newRepoName)
  614. if !IsLegalName(newRepoName) {
  615. return ErrRepoNameIllegal
  616. }
  617. // Change repository directory name.
  618. return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName))
  619. }
  620. func updateRepository(e Engine, repo *Repository) error {
  621. repo.LowerName = strings.ToLower(repo.Name)
  622. if len(repo.Description) > 255 {
  623. repo.Description = repo.Description[:255]
  624. }
  625. if len(repo.Website) > 255 {
  626. repo.Website = repo.Website[:255]
  627. }
  628. _, err := e.Id(repo.Id).AllCols().Update(repo)
  629. return err
  630. }
  631. func UpdateRepository(repo *Repository) error {
  632. return updateRepository(x, repo)
  633. }
  634. // DeleteRepository deletes a repository for a user or organization.
  635. func DeleteRepository(uid, repoId int64, userName string) error {
  636. repo := &Repository{Id: repoId, OwnerId: uid}
  637. has, err := x.Get(repo)
  638. if err != nil {
  639. return err
  640. } else if !has {
  641. return ErrRepoNotExist
  642. }
  643. // In case is a organization.
  644. org, err := GetUserById(uid)
  645. if err != nil {
  646. return err
  647. }
  648. if org.IsOrganization() {
  649. if err = org.GetTeams(); err != nil {
  650. return err
  651. }
  652. }
  653. sess := x.NewSession()
  654. defer sessionRelease(sess)
  655. if err = sess.Begin(); err != nil {
  656. return err
  657. }
  658. if org.IsOrganization() {
  659. idStr := "$" + com.ToStr(repoId) + "|"
  660. for _, t := range org.Teams {
  661. if !strings.Contains(t.RepoIds, idStr) {
  662. continue
  663. }
  664. t.NumRepos--
  665. t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
  666. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  667. return err
  668. }
  669. }
  670. }
  671. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  672. return err
  673. } else if _, err := sess.Delete(&Access{RepoID: repo.Id}); err != nil {
  674. return err
  675. } else if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  676. return err
  677. } else if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  678. return err
  679. } else if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  680. return err
  681. } else if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  682. return err
  683. } else if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  684. return err
  685. } else if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  686. return err
  687. } else if _, err = sess.Delete(&Collaboration{RepoID: repoId}); err != nil {
  688. return err
  689. }
  690. // Delete comments.
  691. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  692. issue := bean.(*Issue)
  693. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  694. return err
  695. }
  696. return nil
  697. }); err != nil {
  698. return err
  699. }
  700. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  701. return err
  702. }
  703. if repo.IsFork {
  704. if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks - 1 WHERE id = ?", repo.ForkId); err != nil {
  705. return err
  706. }
  707. }
  708. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", uid); err != nil {
  709. return err
  710. }
  711. // Remove repository files.
  712. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  713. desc := fmt.Sprintf("Fail to delete repository files(%s/%s): %v", userName, repo.Name, err)
  714. log.Warn(desc)
  715. if err = CreateRepositoryNotice(desc); err != nil {
  716. log.Error(4, "Fail to add notice: %v", err)
  717. }
  718. }
  719. return sess.Commit()
  720. }
  721. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  722. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  723. func GetRepositoryByRef(ref string) (*Repository, error) {
  724. n := strings.IndexByte(ref, byte('/'))
  725. if n < 2 {
  726. return nil, ErrInvalidReference
  727. }
  728. userName, repoName := ref[:n], ref[n+1:]
  729. user, err := GetUserByName(userName)
  730. if err != nil {
  731. return nil, err
  732. }
  733. return GetRepositoryByName(user.Id, repoName)
  734. }
  735. // GetRepositoryByName returns the repository by given name under user if exists.
  736. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  737. repo := &Repository{
  738. OwnerId: uid,
  739. LowerName: strings.ToLower(repoName),
  740. }
  741. has, err := x.Get(repo)
  742. if err != nil {
  743. return nil, err
  744. } else if !has {
  745. return nil, ErrRepoNotExist
  746. }
  747. return repo, err
  748. }
  749. func getRepositoryById(e Engine, id int64) (*Repository, error) {
  750. repo := &Repository{}
  751. has, err := e.Id(id).Get(repo)
  752. if err != nil {
  753. return nil, err
  754. } else if !has {
  755. return nil, ErrRepoNotExist
  756. }
  757. return repo, nil
  758. }
  759. // GetRepositoryById returns the repository by given id if exists.
  760. func GetRepositoryById(id int64) (*Repository, error) {
  761. return getRepositoryById(x, id)
  762. }
  763. // GetRepositories returns a list of repositories of given user.
  764. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  765. repos := make([]*Repository, 0, 10)
  766. sess := x.Desc("updated")
  767. if !private {
  768. sess.Where("is_private=?", false)
  769. }
  770. err := sess.Find(&repos, &Repository{OwnerId: uid})
  771. return repos, err
  772. }
  773. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  774. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  775. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  776. return repos, err
  777. }
  778. // GetRepositoryCount returns the total number of repositories of user.
  779. func GetRepositoryCount(user *User) (int64, error) {
  780. return x.Count(&Repository{OwnerId: user.Id})
  781. }
  782. type SearchOption struct {
  783. Keyword string
  784. Uid int64
  785. Limit int
  786. Private bool
  787. }
  788. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  789. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  790. if len(opt.Keyword) == 0 {
  791. return repos, nil
  792. }
  793. opt.Keyword = strings.ToLower(opt.Keyword)
  794. repos = make([]*Repository, 0, opt.Limit)
  795. // Append conditions.
  796. sess := x.Limit(opt.Limit)
  797. if opt.Uid > 0 {
  798. sess.Where("owner_id=?", opt.Uid)
  799. }
  800. if !opt.Private {
  801. sess.And("is_private=false")
  802. }
  803. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  804. return repos, err
  805. }
  806. // DeleteRepositoryArchives deletes all repositories' archives.
  807. func DeleteRepositoryArchives() error {
  808. return x.Where("id > 0").Iterate(new(Repository),
  809. func(idx int, bean interface{}) error {
  810. repo := bean.(*Repository)
  811. if err := repo.GetOwner(); err != nil {
  812. return err
  813. }
  814. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  815. })
  816. }
  817. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  818. func RewriteRepositoryUpdateHook() error {
  819. return x.Where("id > 0").Iterate(new(Repository),
  820. func(idx int, bean interface{}) error {
  821. repo := bean.(*Repository)
  822. if err := repo.GetOwner(); err != nil {
  823. return err
  824. }
  825. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  826. })
  827. }
  828. var (
  829. // Prevent duplicate tasks.
  830. isMirrorUpdating = false
  831. isGitFscking = false
  832. )
  833. // MirrorUpdate checks and updates mirror repositories.
  834. func MirrorUpdate() {
  835. if isMirrorUpdating {
  836. return
  837. }
  838. isMirrorUpdating = true
  839. defer func() { isMirrorUpdating = false }()
  840. mirrors := make([]*Mirror, 0, 10)
  841. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  842. m := bean.(*Mirror)
  843. if m.NextUpdate.After(time.Now()) {
  844. return nil
  845. }
  846. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  847. if _, stderr, err := process.ExecDir(10*time.Minute,
  848. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  849. "git", "remote", "update"); err != nil {
  850. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  851. log.Error(4, desc)
  852. if err = CreateRepositoryNotice(desc); err != nil {
  853. log.Error(4, "Fail to add notice: %v", err)
  854. }
  855. return nil
  856. }
  857. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  858. mirrors = append(mirrors, m)
  859. return nil
  860. }); err != nil {
  861. log.Error(4, "MirrorUpdate: %v", err)
  862. }
  863. for i := range mirrors {
  864. if err := UpdateMirror(mirrors[i]); err != nil {
  865. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  866. }
  867. }
  868. }
  869. // GitFsck calls 'git fsck' to check repository health.
  870. func GitFsck() {
  871. if isGitFscking {
  872. return
  873. }
  874. isGitFscking = true
  875. defer func() { isGitFscking = false }()
  876. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  877. if err := x.Where("id > 0").Iterate(new(Repository),
  878. func(idx int, bean interface{}) error {
  879. repo := bean.(*Repository)
  880. if err := repo.GetOwner(); err != nil {
  881. return err
  882. }
  883. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  884. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  885. if err != nil {
  886. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  887. log.Warn(desc)
  888. if err = CreateRepositoryNotice(desc); err != nil {
  889. log.Error(4, "Fail to add notice: %v", err)
  890. }
  891. }
  892. return nil
  893. }); err != nil {
  894. log.Error(4, "repo.Fsck: %v", err)
  895. }
  896. }
  897. func GitGcRepos() error {
  898. args := append([]string{"gc"}, setting.Git.GcArgs...)
  899. return x.Where("id > 0").Iterate(new(Repository),
  900. func(idx int, bean interface{}) error {
  901. repo := bean.(*Repository)
  902. if err := repo.GetOwner(); err != nil {
  903. return err
  904. }
  905. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  906. if err != nil {
  907. return fmt.Errorf("%v: %v", err, stderr)
  908. }
  909. return nil
  910. })
  911. }
  912. // _________ .__ .__ ___. __ .__
  913. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  914. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  915. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  916. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  917. // \/ \/ \/ \/ \/
  918. // A Collaboration is a relation between an individual and a repository
  919. type Collaboration struct {
  920. ID int64 `xorm:"pk autoincr"`
  921. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  922. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  923. Created time.Time `xorm:"CREATED"`
  924. }
  925. // Add collaborator and accompanying access
  926. func (repo *Repository) AddCollaborator(u *User) error {
  927. collaboration := &Collaboration{
  928. RepoID: repo.Id,
  929. UserID: u.Id,
  930. }
  931. has, err := x.Get(collaboration)
  932. if err != nil {
  933. return err
  934. } else if has {
  935. return nil
  936. }
  937. sess := x.NewSession()
  938. defer sessionRelease(sess)
  939. if err = sess.Begin(); err != nil {
  940. return err
  941. }
  942. if _, err = sess.InsertOne(collaboration); err != nil {
  943. return err
  944. } else if err = repo.recalculateAccesses(sess); err != nil {
  945. return err
  946. }
  947. return sess.Commit()
  948. }
  949. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  950. collaborations := make([]*Collaboration, 0)
  951. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil {
  952. return nil, err
  953. }
  954. users := make([]*User, len(collaborations))
  955. for i, c := range collaborations {
  956. user, err := getUserById(e, c.UserID)
  957. if err != nil {
  958. return nil, err
  959. }
  960. users[i] = user
  961. }
  962. return users, nil
  963. }
  964. // GetCollaborators returns the collaborators for a repository
  965. func (repo *Repository) GetCollaborators() ([]*User, error) {
  966. return repo.getCollaborators(x)
  967. }
  968. // Delete collaborator and accompanying access
  969. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  970. collaboration := &Collaboration{
  971. RepoID: repo.Id,
  972. UserID: u.Id,
  973. }
  974. sess := x.NewSession()
  975. defer sessionRelease(sess)
  976. if err = sess.Begin(); err != nil {
  977. return err
  978. }
  979. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  980. return err
  981. } else if err = repo.recalculateAccesses(sess); err != nil {
  982. return err
  983. }
  984. return sess.Commit()
  985. }
  986. // __ __ __ .__
  987. // / \ / \_____ _/ |_ ____ | |__
  988. // \ \/\/ /\__ \\ __\/ ___\| | \
  989. // \ / / __ \| | \ \___| Y \
  990. // \__/\ / (____ /__| \___ >___| /
  991. // \/ \/ \/ \/
  992. // Watch is connection request for receiving repository notification.
  993. type Watch struct {
  994. Id int64
  995. UserId int64 `xorm:"UNIQUE(watch)"`
  996. RepoId int64 `xorm:"UNIQUE(watch)"`
  997. }
  998. // IsWatching checks if user has watched given repository.
  999. func IsWatching(uid, repoId int64) bool {
  1000. has, _ := x.Get(&Watch{0, uid, repoId})
  1001. return has
  1002. }
  1003. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1004. if watch {
  1005. if IsWatching(uid, repoId) {
  1006. return nil
  1007. }
  1008. if _, err = e.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
  1009. return err
  1010. }
  1011. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1012. } else {
  1013. if !IsWatching(uid, repoId) {
  1014. return nil
  1015. }
  1016. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1017. return err
  1018. }
  1019. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
  1020. }
  1021. return err
  1022. }
  1023. // Watch or unwatch repository.
  1024. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1025. return watchRepo(x, uid, repoId, watch)
  1026. }
  1027. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1028. watches := make([]*Watch, 0, 10)
  1029. err := e.Find(&watches, &Watch{RepoId: rid})
  1030. return watches, err
  1031. }
  1032. // GetWatchers returns all watchers of given repository.
  1033. func GetWatchers(rid int64) ([]*Watch, error) {
  1034. return getWatchers(x, rid)
  1035. }
  1036. func notifyWatchers(e Engine, act *Action) error {
  1037. // Add feeds for user self and all watchers.
  1038. watches, err := getWatchers(e, act.RepoId)
  1039. if err != nil {
  1040. return fmt.Errorf("get watchers: %v", err)
  1041. }
  1042. // Add feed for actioner.
  1043. act.UserId = act.ActUserId
  1044. if _, err = e.InsertOne(act); err != nil {
  1045. return fmt.Errorf("insert new actioner: %v", err)
  1046. }
  1047. for i := range watches {
  1048. if act.ActUserId == watches[i].UserId {
  1049. continue
  1050. }
  1051. act.Id = 0
  1052. act.UserId = watches[i].UserId
  1053. if _, err = e.InsertOne(act); err != nil {
  1054. return fmt.Errorf("insert new action: %v", err)
  1055. }
  1056. }
  1057. return nil
  1058. }
  1059. // NotifyWatchers creates batch of actions for every watcher.
  1060. func NotifyWatchers(act *Action) error {
  1061. return notifyWatchers(x, act)
  1062. }
  1063. // _________ __
  1064. // / _____// |______ _______
  1065. // \_____ \\ __\__ \\_ __ \
  1066. // / \| | / __ \| | \/
  1067. // /_______ /|__| (____ /__|
  1068. // \/ \/
  1069. type Star struct {
  1070. Id int64
  1071. Uid int64 `xorm:"UNIQUE(s)"`
  1072. RepoId int64 `xorm:"UNIQUE(s)"`
  1073. }
  1074. // Star or unstar repository.
  1075. func StarRepo(uid, repoId int64, star bool) (err error) {
  1076. if star {
  1077. if IsStaring(uid, repoId) {
  1078. return nil
  1079. }
  1080. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1081. return err
  1082. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1083. return err
  1084. }
  1085. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1086. } else {
  1087. if !IsStaring(uid, repoId) {
  1088. return nil
  1089. }
  1090. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1091. return err
  1092. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1093. return err
  1094. }
  1095. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1096. }
  1097. return err
  1098. }
  1099. // IsStaring checks if user has starred given repository.
  1100. func IsStaring(uid, repoId int64) bool {
  1101. has, _ := x.Get(&Star{0, uid, repoId})
  1102. return has
  1103. }
  1104. // ___________ __
  1105. // \_ _____/__________| | __
  1106. // | __)/ _ \_ __ \ |/ /
  1107. // | \( <_> ) | \/ <
  1108. // \___ / \____/|__| |__|_ \
  1109. // \/ \/
  1110. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repository, error) {
  1111. isExist, err := IsRepositoryExist(u, name)
  1112. if err != nil {
  1113. return nil, err
  1114. } else if isExist {
  1115. return nil, ErrRepoAlreadyExist
  1116. }
  1117. // In case the old repository is a fork.
  1118. if oldRepo.IsFork {
  1119. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1120. if err != nil {
  1121. return nil, err
  1122. }
  1123. }
  1124. repo := &Repository{
  1125. OwnerId: u.Id,
  1126. Owner: u,
  1127. Name: name,
  1128. LowerName: strings.ToLower(name),
  1129. Description: desc,
  1130. IsPrivate: oldRepo.IsPrivate,
  1131. IsFork: true,
  1132. ForkId: oldRepo.Id,
  1133. }
  1134. sess := x.NewSession()
  1135. defer sessionRelease(sess)
  1136. if err = sess.Begin(); err != nil {
  1137. return nil, err
  1138. }
  1139. if _, err = sess.Insert(repo); err != nil {
  1140. return nil, err
  1141. }
  1142. if err = repo.recalculateAccesses(sess); err != nil {
  1143. return nil, err
  1144. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1145. return nil, err
  1146. }
  1147. if u.IsOrganization() {
  1148. // Update owner team info and count.
  1149. t, err := u.getOwnerTeam(sess)
  1150. if err != nil {
  1151. return nil, fmt.Errorf("get owner team: %v", err)
  1152. } else if err = t.getMembers(sess); err != nil {
  1153. return nil, fmt.Errorf("get team members: %v", err)
  1154. }
  1155. for _, u := range t.Members {
  1156. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1157. return nil, fmt.Errorf("watch repository: %v", err)
  1158. }
  1159. }
  1160. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  1161. t.NumRepos++
  1162. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  1163. return nil, err
  1164. }
  1165. } else {
  1166. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1167. return nil, fmt.Errorf("watch repository 2: %v", err)
  1168. }
  1169. }
  1170. if err = newRepoAction(sess, u, repo); err != nil {
  1171. return nil, fmt.Errorf("new repository action: %v", err)
  1172. }
  1173. if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil {
  1174. return nil, err
  1175. }
  1176. oldRepoPath, err := oldRepo.RepoPath()
  1177. if err != nil {
  1178. return nil, fmt.Errorf("get old repository path: %v", err)
  1179. }
  1180. repoPath := RepoPath(u.Name, repo.Name)
  1181. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1182. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1183. "git", "clone", "--bare", oldRepoPath, repoPath)
  1184. if err != nil {
  1185. return nil, fmt.Errorf("git clone: %v", stderr)
  1186. }
  1187. _, stderr, err = process.ExecDir(-1,
  1188. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1189. "git", "update-server-info")
  1190. if err != nil {
  1191. return nil, fmt.Errorf("git update-server-info: %v", err)
  1192. }
  1193. return repo, sess.Commit()
  1194. }