repo.go 37 KB

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