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 28KB

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