repo.go 28 KB

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