repo.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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 u.IsOrganization() {
  1150. t, err := u.GetOwnerTeam()
  1151. if err != nil {
  1152. log.Error(4, "GetOwnerTeam: %v", err)
  1153. } else {
  1154. if err = t.GetMembers(); err != nil {
  1155. log.Error(4, "GetMembers: %v", err)
  1156. } else {
  1157. for _, u := range t.Members {
  1158. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  1159. log.Error(4, "WatchRepo2: %v", err)
  1160. }
  1161. }
  1162. }
  1163. }
  1164. } else {
  1165. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  1166. log.Error(4, "WatchRepo3: %v", err)
  1167. }
  1168. }
  1169. if err = NewRepoAction(u, repo); err != nil {
  1170. log.Error(4, "NewRepoAction: %v", err)
  1171. }
  1172. if _, err = sess.Exec(
  1173. "UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil {
  1174. sess.Rollback()
  1175. return nil, err
  1176. }
  1177. if err = sess.Commit(); err != nil {
  1178. return nil, err
  1179. }
  1180. repoPath := RepoPath(u.Name, repo.Name)
  1181. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1182. fmt.Sprintf("ForkRepository: %s/%s", u.Name, repo.Name),
  1183. "git", "clone", oldRepo.GetPath(), repoPath)
  1184. _, stderr, err = process.ExecDir(-1,
  1185. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  1186. "git", "update-server-info")
  1187. if err != nil {
  1188. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  1189. }
  1190. return repo, nil
  1191. }