repo.go 37 KB

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