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

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