repo.go 36 KB

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