You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. "io/ioutil"
  9. "html"
  10. "html/template"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "runtime"
  16. "sort"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/Unknwon/cae/zip"
  21. "github.com/Unknwon/com"
  22. "github.com/gogits/git"
  23. "github.com/gogits/gogs/modules/base"
  24. "github.com/gogits/gogs/modules/bin"
  25. "github.com/gogits/gogs/modules/log"
  26. "github.com/gogits/gogs/modules/process"
  27. "github.com/gogits/gogs/modules/setting"
  28. )
  29. const (
  30. TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3\n"
  31. )
  32. var (
  33. ErrRepoAlreadyExist = errors.New("Repository already exist")
  34. ErrRepoNotExist = errors.New("Repository does not exist")
  35. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  36. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  37. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  38. ErrMirrorNotExist = errors.New("Mirror does not exist")
  39. )
  40. var (
  41. LanguageIgns, Licenses []string
  42. )
  43. var (
  44. DescriptionPattern = regexp.MustCompile(`https?://\S+`)
  45. )
  46. // getAssetList returns corresponding asset list in 'conf'.
  47. func getAssetList(prefix string) []string {
  48. assets := make([]string, 0, 15)
  49. for _, name := range bin.AssetNames() {
  50. if strings.HasPrefix(name, prefix) {
  51. assets = append(assets, strings.TrimPrefix(name, prefix+"/"))
  52. }
  53. }
  54. return assets
  55. }
  56. func LoadRepoConfig() {
  57. // Load .gitignore and license files.
  58. types := []string{"gitignore", "license"}
  59. typeFiles := make([][]string, 2)
  60. for i, t := range types {
  61. files := getAssetList(path.Join("conf", t))
  62. customPath := path.Join(setting.CustomPath, "conf", t)
  63. if com.IsDir(customPath) {
  64. customFiles, err := com.StatDir(customPath)
  65. if err != nil {
  66. log.Fatal("Fail to get custom %s files: %v", t, err)
  67. }
  68. for _, f := range customFiles {
  69. if !com.IsSliceContainsStr(files, f) {
  70. files = append(files, f)
  71. }
  72. }
  73. }
  74. typeFiles[i] = files
  75. }
  76. LanguageIgns = typeFiles[0]
  77. Licenses = typeFiles[1]
  78. sort.Strings(LanguageIgns)
  79. sort.Strings(Licenses)
  80. }
  81. func NewRepoContext() {
  82. zip.Verbose = false
  83. // Check if server has basic git setting.
  84. stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", "user.name")
  85. if err != nil {
  86. log.Fatal("repo.NewRepoContext(fail to get git user.name): %s", stderr)
  87. } else if err != nil || len(strings.TrimSpace(stdout)) == 0 {
  88. if _, stderr, err = process.Exec("NewRepoContext(set email)", "git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil {
  89. log.Fatal("repo.NewRepoContext(fail to set git user.email): %s", stderr)
  90. } else if _, stderr, err = process.Exec("NewRepoContext(set name)", "git", "config", "--global", "user.name", "Gogs"); err != nil {
  91. log.Fatal("repo.NewRepoContext(fail to set git user.name): %s", stderr)
  92. }
  93. }
  94. barePath := path.Join(setting.RepoRootPath, "git-bare.zip")
  95. if !com.IsExist(barePath) {
  96. data, err := bin.Asset("conf/content/git-bare.zip")
  97. if err != nil {
  98. log.Fatal("Fail to get asset 'git-bare.zip': %v", err)
  99. } else if err := ioutil.WriteFile(barePath, data, os.ModePerm); err != nil {
  100. log.Fatal("Fail to write asset 'git-bare.zip': %v", err)
  101. }
  102. }
  103. }
  104. // Repository represents a git repository.
  105. type Repository struct {
  106. Id int64
  107. OwnerId int64 `xorm:"UNIQUE(s)"`
  108. Owner *User `xorm:"-"`
  109. ForkId int64
  110. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  111. Name string `xorm:"INDEX NOT NULL"`
  112. Description string
  113. Website string
  114. NumWatches int
  115. NumStars int
  116. NumForks int
  117. NumIssues int
  118. NumClosedIssues int
  119. NumOpenIssues int `xorm:"-"`
  120. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  121. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  122. NumOpenMilestones int `xorm:"-"`
  123. NumTags int `xorm:"-"`
  124. IsPrivate bool
  125. IsMirror bool
  126. IsBare bool
  127. IsGoget bool
  128. DefaultBranch string
  129. Created time.Time `xorm:"CREATED"`
  130. Updated time.Time `xorm:"UPDATED"`
  131. }
  132. func (repo *Repository) GetOwner() (err error) {
  133. repo.Owner, err = GetUserById(repo.OwnerId)
  134. return err
  135. }
  136. func (repo *Repository) DescriptionHtml() template.HTML {
  137. sanitize := func(s string) string {
  138. // TODO(nuss-justin): Improve sanitization. Strip all tags?
  139. ss := html.EscapeString(s)
  140. return fmt.Sprintf(`<a href="%s" target="_blank">%s</a>`, ss, ss)
  141. }
  142. return template.HTML(DescriptionPattern.ReplaceAllStringFunc(repo.Description, sanitize))
  143. }
  144. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  145. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  146. repo := Repository{OwnerId: u.Id}
  147. has, err := x.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  148. if err != nil {
  149. return has, err
  150. } else if !has {
  151. return false, nil
  152. }
  153. return com.IsDir(RepoPath(u.Name, repoName)), nil
  154. }
  155. var (
  156. illegalEquals = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  157. illegalSuffixs = []string{".git"}
  158. )
  159. // IsLegalName returns false if name contains illegal characters.
  160. func IsLegalName(repoName string) bool {
  161. repoName = strings.ToLower(repoName)
  162. for _, char := range illegalEquals {
  163. if repoName == char {
  164. return false
  165. }
  166. }
  167. for _, char := range illegalSuffixs {
  168. if strings.HasSuffix(repoName, char) {
  169. return false
  170. }
  171. }
  172. return true
  173. }
  174. // Mirror represents a mirror information of repository.
  175. type Mirror struct {
  176. Id int64
  177. RepoId int64
  178. RepoName string // <user name>/<repo name>
  179. Interval int // Hour.
  180. Updated time.Time `xorm:"UPDATED"`
  181. NextUpdate time.Time
  182. }
  183. // MirrorRepository creates a mirror repository from source.
  184. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  185. _, stderr, err := process.ExecTimeout(10*time.Minute,
  186. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  187. "git", "clone", "--mirror", url, repoPath)
  188. if err != nil {
  189. return errors.New("git clone --mirror: " + stderr)
  190. }
  191. if _, err = x.InsertOne(&Mirror{
  192. RepoId: repoId,
  193. RepoName: strings.ToLower(userName + "/" + repoName),
  194. Interval: 24,
  195. NextUpdate: time.Now().Add(24 * time.Hour),
  196. }); err != nil {
  197. return err
  198. }
  199. return git.UnpackRefs(repoPath)
  200. }
  201. func GetMirror(repoId int64) (*Mirror, error) {
  202. m := &Mirror{RepoId: repoId}
  203. has, err := x.Get(m)
  204. if err != nil {
  205. return nil, err
  206. } else if !has {
  207. return nil, ErrMirrorNotExist
  208. }
  209. return m, nil
  210. }
  211. func UpdateMirror(m *Mirror) error {
  212. _, err := x.Id(m.Id).Update(m)
  213. return err
  214. }
  215. // MirrorUpdate checks and updates mirror repositories.
  216. func MirrorUpdate() {
  217. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  218. m := bean.(*Mirror)
  219. if m.NextUpdate.After(time.Now()) {
  220. return nil
  221. }
  222. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  223. if _, stderr, err := process.ExecDir(10*time.Minute,
  224. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  225. "git", "remote", "update"); err != nil {
  226. return errors.New("git remote update: " + stderr)
  227. } else if err = git.UnpackRefs(repoPath); err != nil {
  228. return errors.New("UnpackRefs: " + err.Error())
  229. }
  230. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  231. return UpdateMirror(m)
  232. }); err != nil {
  233. log.Error("repo.MirrorUpdate: %v", err)
  234. }
  235. }
  236. // MigrateRepository migrates a existing repository from other project hosting.
  237. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  238. repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
  239. if err != nil {
  240. return nil, err
  241. }
  242. // Clone to temprory path and do the init commit.
  243. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  244. os.MkdirAll(tmpDir, os.ModePerm)
  245. repoPath := RepoPath(u.Name, name)
  246. repo.IsBare = false
  247. if mirror {
  248. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  249. return repo, err
  250. }
  251. repo.IsMirror = true
  252. return repo, UpdateRepository(repo)
  253. }
  254. // Clone from local repository.
  255. _, stderr, err := process.ExecTimeout(10*time.Minute,
  256. fmt.Sprintf("MigrateRepository(git clone): %s", repoPath),
  257. "git", "clone", repoPath, tmpDir)
  258. if err != nil {
  259. return repo, errors.New("git clone: " + stderr)
  260. }
  261. // Pull data from source.
  262. if _, stderr, err = process.ExecDir(3*time.Minute,
  263. tmpDir, fmt.Sprintf("MigrateRepository(git pull): %s", repoPath),
  264. "git", "pull", url); err != nil {
  265. return repo, errors.New("git pull: " + stderr)
  266. }
  267. // Push data to local repository.
  268. if _, stderr, err = process.ExecDir(3*time.Minute,
  269. tmpDir, fmt.Sprintf("MigrateRepository(git push): %s", repoPath),
  270. "git", "push", "origin", "master"); err != nil {
  271. return repo, errors.New("git push: " + stderr)
  272. }
  273. return repo, UpdateRepository(repo)
  274. }
  275. // extractGitBareZip extracts git-bare.zip to repository path.
  276. func extractGitBareZip(repoPath string) error {
  277. z, err := zip.Open(filepath.Join(setting.RepoRootPath, "git-bare.zip"))
  278. if err != nil {
  279. return err
  280. }
  281. defer z.Close()
  282. return z.ExtractTo(repoPath)
  283. }
  284. // initRepoCommit temporarily changes with work directory.
  285. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  286. var stderr string
  287. if _, stderr, err = process.ExecDir(-1,
  288. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  289. "git", "add", "--all"); err != nil {
  290. return errors.New("git add: " + stderr)
  291. }
  292. if _, stderr, err = process.ExecDir(-1,
  293. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  294. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  295. "-m", "Init commit"); err != nil {
  296. return errors.New("git commit: " + stderr)
  297. }
  298. if _, stderr, err = process.ExecDir(-1,
  299. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  300. "git", "push", "origin", "master"); err != nil {
  301. return errors.New("git push: " + stderr)
  302. }
  303. return nil
  304. }
  305. func createHookUpdate(hookPath, content string) error {
  306. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  307. if err != nil {
  308. return err
  309. }
  310. defer pu.Close()
  311. _, err = pu.WriteString(content)
  312. return err
  313. }
  314. // SetRepoEnvs sets environment variables for command update.
  315. func SetRepoEnvs(userId int64, userName, repoName, repoUserName string) {
  316. os.Setenv("userId", base.ToStr(userId))
  317. os.Setenv("userName", userName)
  318. os.Setenv("repoName", repoName)
  319. os.Setenv("repoUserName", repoUserName)
  320. }
  321. // InitRepository initializes README and .gitignore if needed.
  322. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  323. repoPath := RepoPath(user.Name, repo.Name)
  324. // Create bare new repository.
  325. if err := extractGitBareZip(repoPath); err != nil {
  326. return err
  327. }
  328. if runtime.GOOS == "windows" {
  329. rp := strings.NewReplacer("\\", "/")
  330. appPath = "\"" + rp.Replace(appPath) + "\""
  331. } else {
  332. rp := strings.NewReplacer("\\", "/", " ", "\\ ")
  333. appPath = rp.Replace(appPath)
  334. }
  335. // hook/post-update
  336. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  337. fmt.Sprintf(TPL_UPDATE_HOOK, setting.ScriptType, appPath)); err != nil {
  338. return err
  339. }
  340. // Initialize repository according to user's choice.
  341. fileName := map[string]string{}
  342. if initReadme {
  343. fileName["readme"] = "README.md"
  344. }
  345. if repoLang != "" {
  346. fileName["gitign"] = ".gitignore"
  347. }
  348. if license != "" {
  349. fileName["license"] = "LICENSE"
  350. }
  351. // Clone to temprory path and do the init commit.
  352. tmpDir := filepath.Join(os.TempDir(), base.ToStr(time.Now().Nanosecond()))
  353. os.MkdirAll(tmpDir, os.ModePerm)
  354. _, stderr, err := process.Exec(
  355. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  356. "git", "clone", repoPath, tmpDir)
  357. if err != nil {
  358. return errors.New("initRepository(git clone): " + stderr)
  359. }
  360. // README
  361. if initReadme {
  362. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  363. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  364. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  365. []byte(defaultReadme), 0644); err != nil {
  366. return err
  367. }
  368. }
  369. // .gitignore
  370. if repoLang != "" {
  371. filePath := "conf/gitignore/" + repoLang
  372. targetPath := path.Join(tmpDir, fileName["gitign"])
  373. data, err := bin.Asset(filePath)
  374. if err == nil {
  375. if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil {
  376. return err
  377. }
  378. } else {
  379. // Check custom files.
  380. filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  381. if com.IsFile(filePath) {
  382. if err := com.Copy(filePath, targetPath); err != nil {
  383. return err
  384. }
  385. }
  386. }
  387. }
  388. // LICENSE
  389. if license != "" {
  390. filePath := "conf/license/" + license
  391. targetPath := path.Join(tmpDir, fileName["license"])
  392. data, err := bin.Asset(filePath)
  393. if err == nil {
  394. if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil {
  395. return err
  396. }
  397. } else {
  398. // Check custom files.
  399. filePath = path.Join(setting.CustomPath, "conf/license", license)
  400. if com.IsFile(filePath) {
  401. if err := com.Copy(filePath, targetPath); err != nil {
  402. return err
  403. }
  404. }
  405. }
  406. }
  407. if len(fileName) == 0 {
  408. return nil
  409. }
  410. SetRepoEnvs(user.Id, user.Name, repo.Name, user.Name)
  411. // Apply changes and commit.
  412. return initRepoCommit(tmpDir, user.NewGitSig())
  413. }
  414. // CreateRepository creates a repository for given user or organization.
  415. func CreateRepository(u *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
  416. if !IsLegalName(name) {
  417. return nil, ErrRepoNameIllegal
  418. }
  419. isExist, err := IsRepositoryExist(u, name)
  420. if err != nil {
  421. return nil, err
  422. } else if isExist {
  423. return nil, ErrRepoAlreadyExist
  424. }
  425. sess := x.NewSession()
  426. defer sess.Close()
  427. if err = sess.Begin(); err != nil {
  428. return nil, err
  429. }
  430. repo := &Repository{
  431. OwnerId: u.Id,
  432. Owner: u,
  433. Name: name,
  434. LowerName: strings.ToLower(name),
  435. Description: desc,
  436. IsPrivate: private,
  437. IsBare: lang == "" && license == "" && !initReadme,
  438. }
  439. if !repo.IsBare {
  440. repo.DefaultBranch = "master"
  441. }
  442. if _, err = sess.Insert(repo); err != nil {
  443. sess.Rollback()
  444. return nil, err
  445. }
  446. var t *Team // Owner team.
  447. mode := WRITABLE
  448. if mirror {
  449. mode = READABLE
  450. }
  451. access := &Access{
  452. UserName: u.LowerName,
  453. RepoName: strings.ToLower(path.Join(u.Name, repo.Name)),
  454. Mode: mode,
  455. }
  456. // Give access to all members in owner team.
  457. if u.IsOrganization() {
  458. t, err = u.GetOwnerTeam()
  459. if err != nil {
  460. sess.Rollback()
  461. return nil, err
  462. }
  463. us, err := GetTeamMembers(u.Id, t.Id)
  464. if err != nil {
  465. sess.Rollback()
  466. return nil, err
  467. }
  468. for _, u := range us {
  469. access.UserName = u.LowerName
  470. if _, err = sess.Insert(access); err != nil {
  471. sess.Rollback()
  472. return nil, err
  473. }
  474. }
  475. } else {
  476. if _, err = sess.Insert(access); err != nil {
  477. sess.Rollback()
  478. return nil, err
  479. }
  480. }
  481. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  482. if _, err = sess.Exec(rawSql, u.Id); err != nil {
  483. sess.Rollback()
  484. return nil, err
  485. }
  486. // Update owner team info and count.
  487. if u.IsOrganization() {
  488. t.RepoIds += "$" + base.ToStr(repo.Id) + "|"
  489. t.NumRepos++
  490. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  491. sess.Rollback()
  492. return nil, err
  493. }
  494. }
  495. if err = sess.Commit(); err != nil {
  496. return nil, err
  497. }
  498. if u.IsOrganization() {
  499. ous, err := GetOrgUsersByOrgId(u.Id)
  500. if err != nil {
  501. log.Error("repo.CreateRepository(GetOrgUsersByOrgId): %v", err)
  502. } else {
  503. for _, ou := range ous {
  504. if err = WatchRepo(ou.Uid, repo.Id, true); err != nil {
  505. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  506. }
  507. }
  508. }
  509. }
  510. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  511. log.Error("repo.CreateRepository(WatchRepo2): %v", err)
  512. }
  513. if err = NewRepoAction(u, repo); err != nil {
  514. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  515. }
  516. // No need for init for mirror.
  517. if mirror {
  518. return repo, nil
  519. }
  520. repoPath := RepoPath(u.Name, repo.Name)
  521. if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil {
  522. if err2 := os.RemoveAll(repoPath); err2 != nil {
  523. log.Error("repo.CreateRepository(initRepository): %v", err)
  524. return nil, errors.New(fmt.Sprintf(
  525. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2))
  526. }
  527. return nil, err
  528. }
  529. _, stderr, err := process.ExecDir(-1,
  530. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  531. "git", "update-server-info")
  532. if err != nil {
  533. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  534. }
  535. return repo, nil
  536. }
  537. // CountRepositories returns number of repositories.
  538. func CountRepositories() int64 {
  539. count, _ := x.Count(new(Repository))
  540. return count
  541. }
  542. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  543. // It also auto-gets corresponding users.
  544. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  545. repos := make([]*Repository, 0, num)
  546. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  547. return nil, err
  548. }
  549. for _, repo := range repos {
  550. repo.Owner = &User{Id: repo.OwnerId}
  551. has, err := x.Get(repo.Owner)
  552. if err != nil {
  553. return nil, err
  554. } else if !has {
  555. return nil, ErrUserNotExist
  556. }
  557. }
  558. return repos, nil
  559. }
  560. // RepoPath returns repository path by given user and repository name.
  561. func RepoPath(userName, repoName string) string {
  562. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  563. }
  564. // TransferOwnership transfers all corresponding setting from old user to new one.
  565. func TransferOwnership(u *User, newOwner string, repo *Repository) (err error) {
  566. newUser, err := GetUserByName(newOwner)
  567. if err != nil {
  568. return err
  569. }
  570. sess := x.NewSession()
  571. defer sess.Close()
  572. if err = sess.Begin(); err != nil {
  573. return err
  574. }
  575. if _, err = sess.Where("repo_name = ?", u.LowerName+"/"+repo.LowerName).
  576. And("user_name = ?", u.LowerName).Update(&Access{UserName: newUser.LowerName}); err != nil {
  577. sess.Rollback()
  578. return err
  579. }
  580. if _, err = sess.Where("repo_name = ?", u.LowerName+"/"+repo.LowerName).Update(&Access{
  581. RepoName: newUser.LowerName + "/" + repo.LowerName,
  582. }); err != nil {
  583. sess.Rollback()
  584. return err
  585. }
  586. // Update repository.
  587. repo.OwnerId = newUser.Id
  588. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  589. sess.Rollback()
  590. return err
  591. }
  592. // Update user repository number.
  593. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  594. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  595. sess.Rollback()
  596. return err
  597. }
  598. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  599. if _, err = sess.Exec(rawSql, u.Id); err != nil {
  600. sess.Rollback()
  601. return err
  602. }
  603. // Change repository directory name.
  604. if err = os.Rename(RepoPath(u.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  605. sess.Rollback()
  606. return err
  607. }
  608. if err = sess.Commit(); err != nil {
  609. return err
  610. }
  611. // Add watch of new owner to repository.
  612. if !IsWatching(newUser.Id, repo.Id) {
  613. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  614. return err
  615. }
  616. }
  617. if err = TransferRepoAction(u, newUser, repo); err != nil {
  618. return err
  619. }
  620. return nil
  621. }
  622. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  623. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  624. // Update accesses.
  625. accesses := make([]Access, 0, 10)
  626. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  627. return err
  628. }
  629. sess := x.NewSession()
  630. defer sess.Close()
  631. if err = sess.Begin(); err != nil {
  632. return err
  633. }
  634. for i := range accesses {
  635. accesses[i].RepoName = userName + "/" + newRepoName
  636. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  637. return err
  638. }
  639. }
  640. // Change repository directory name.
  641. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  642. sess.Rollback()
  643. return err
  644. }
  645. return sess.Commit()
  646. }
  647. func UpdateRepository(repo *Repository) error {
  648. repo.LowerName = strings.ToLower(repo.Name)
  649. if len(repo.Description) > 255 {
  650. repo.Description = repo.Description[:255]
  651. }
  652. if len(repo.Website) > 255 {
  653. repo.Website = repo.Website[:255]
  654. }
  655. _, err := x.Id(repo.Id).AllCols().Update(repo)
  656. return err
  657. }
  658. // DeleteRepository deletes a repository for a user or orgnaztion.
  659. func DeleteRepository(userId, repoId int64, userName string) error {
  660. repo := &Repository{Id: repoId, OwnerId: userId}
  661. has, err := x.Get(repo)
  662. if err != nil {
  663. return err
  664. } else if !has {
  665. return ErrRepoNotExist
  666. }
  667. sess := x.NewSession()
  668. defer sess.Close()
  669. if err = sess.Begin(); err != nil {
  670. return err
  671. }
  672. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  673. sess.Rollback()
  674. return err
  675. }
  676. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  677. sess.Rollback()
  678. return err
  679. }
  680. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  681. sess.Rollback()
  682. return err
  683. }
  684. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  685. sess.Rollback()
  686. return err
  687. }
  688. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  689. sess.Rollback()
  690. return err
  691. }
  692. if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  693. sess.Rollback()
  694. return err
  695. }
  696. if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  697. sess.Rollback()
  698. return err
  699. }
  700. if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  701. sess.Rollback()
  702. return err
  703. }
  704. // Delete comments.
  705. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  706. issue := bean.(*Issue)
  707. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  708. sess.Rollback()
  709. return err
  710. }
  711. return nil
  712. }); err != nil {
  713. sess.Rollback()
  714. return err
  715. }
  716. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  717. sess.Rollback()
  718. return err
  719. }
  720. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  721. if _, err = sess.Exec(rawSql, userId); err != nil {
  722. sess.Rollback()
  723. return err
  724. }
  725. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  726. sess.Rollback()
  727. return err
  728. }
  729. return sess.Commit()
  730. }
  731. // GetRepositoryByName returns the repository by given name under user if exists.
  732. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  733. repo := &Repository{
  734. OwnerId: userId,
  735. LowerName: strings.ToLower(repoName),
  736. }
  737. has, err := x.Get(repo)
  738. if err != nil {
  739. return nil, err
  740. } else if !has {
  741. return nil, ErrRepoNotExist
  742. }
  743. return repo, err
  744. }
  745. // GetRepositoryById returns the repository by given id if exists.
  746. func GetRepositoryById(id int64) (*Repository, error) {
  747. repo := &Repository{}
  748. has, err := x.Id(id).Get(repo)
  749. if err != nil {
  750. return nil, err
  751. } else if !has {
  752. return nil, ErrRepoNotExist
  753. }
  754. return repo, nil
  755. }
  756. // GetRepositories returns a list of repositories of given user.
  757. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  758. repos := make([]*Repository, 0, 10)
  759. sess := x.Desc("updated")
  760. if !private {
  761. sess.Where("is_private=?", false)
  762. }
  763. err := sess.Find(&repos, &Repository{OwnerId: uid})
  764. return repos, err
  765. }
  766. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  767. func GetRecentUpdatedRepositories() (repos []*Repository, err error) {
  768. err = x.Where("is_private=?", false).Limit(5).Desc("updated").Find(&repos)
  769. return repos, err
  770. }
  771. // GetRepositoryCount returns the total number of repositories of user.
  772. func GetRepositoryCount(user *User) (int64, error) {
  773. return x.Count(&Repository{OwnerId: user.Id})
  774. }
  775. // GetCollaboratorNames returns a list of user name of repository's collaborators.
  776. func GetCollaboratorNames(repoName string) ([]string, error) {
  777. accesses := make([]*Access, 0, 10)
  778. if err := x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  779. return nil, err
  780. }
  781. names := make([]string, len(accesses))
  782. for i := range accesses {
  783. names[i] = accesses[i].UserName
  784. }
  785. return names, nil
  786. }
  787. // GetCollaborativeRepos returns a list of repositories that user is collaborator.
  788. func GetCollaborativeRepos(uname string) ([]*Repository, error) {
  789. uname = strings.ToLower(uname)
  790. accesses := make([]*Access, 0, 10)
  791. if err := x.Find(&accesses, &Access{UserName: uname}); err != nil {
  792. return nil, err
  793. }
  794. repos := make([]*Repository, 0, 10)
  795. for _, access := range accesses {
  796. infos := strings.Split(access.RepoName, "/")
  797. if infos[0] == uname {
  798. continue
  799. }
  800. u, err := GetUserByName(infos[0])
  801. if err != nil {
  802. return nil, err
  803. }
  804. repo, err := GetRepositoryByName(u.Id, infos[1])
  805. if err != nil {
  806. return nil, err
  807. }
  808. repo.Owner = u
  809. repos = append(repos, repo)
  810. }
  811. return repos, nil
  812. }
  813. // GetCollaborators returns a list of users of repository's collaborators.
  814. func GetCollaborators(repoName string) (us []*User, err error) {
  815. accesses := make([]*Access, 0, 10)
  816. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  817. return nil, err
  818. }
  819. us = make([]*User, len(accesses))
  820. for i := range accesses {
  821. us[i], err = GetUserByName(accesses[i].UserName)
  822. if err != nil {
  823. return nil, err
  824. }
  825. }
  826. return us, nil
  827. }
  828. // Watch is connection request for receiving repository notifycation.
  829. type Watch struct {
  830. Id int64
  831. UserId int64 `xorm:"UNIQUE(watch)"`
  832. RepoId int64 `xorm:"UNIQUE(watch)"`
  833. }
  834. // Watch or unwatch repository.
  835. func WatchRepo(uid, rid int64, watch bool) (err error) {
  836. if watch {
  837. if _, err = x.Insert(&Watch{RepoId: rid, UserId: uid}); err != nil {
  838. return err
  839. }
  840. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  841. _, err = x.Exec(rawSql, rid)
  842. } else {
  843. if _, err = x.Delete(&Watch{0, uid, rid}); err != nil {
  844. return err
  845. }
  846. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  847. _, err = x.Exec(rawSql, rid)
  848. }
  849. return err
  850. }
  851. // GetWatchers returns all watchers of given repository.
  852. func GetWatchers(rid int64) ([]*Watch, error) {
  853. watches := make([]*Watch, 0, 10)
  854. err := x.Find(&watches, &Watch{RepoId: rid})
  855. return watches, err
  856. }
  857. // NotifyWatchers creates batch of actions for every watcher.
  858. func NotifyWatchers(act *Action) error {
  859. // Add feeds for user self and all watchers.
  860. watches, err := GetWatchers(act.RepoId)
  861. if err != nil {
  862. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  863. }
  864. // Add feed for actioner.
  865. act.UserId = act.ActUserId
  866. if _, err = x.InsertOne(act); err != nil {
  867. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  868. }
  869. for i := range watches {
  870. if act.ActUserId == watches[i].UserId {
  871. continue
  872. }
  873. act.Id = 0
  874. act.UserId = watches[i].UserId
  875. if _, err = x.InsertOne(act); err != nil {
  876. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  877. }
  878. }
  879. return nil
  880. }
  881. // IsWatching checks if user has watched given repository.
  882. func IsWatching(uid, rid int64) bool {
  883. has, _ := x.Get(&Watch{0, uid, rid})
  884. return has
  885. }
  886. func ForkRepository(repoName string, uid int64) {
  887. }