repo.go 37 KB

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