repo.go 36 KB

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