repo.go 36 KB

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