You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 36KB

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