repo.go 38 KB

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