repo.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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. if u.IsOrganization() {
  255. t, err := u.GetOwnerTeam()
  256. if err != nil {
  257. return nil, err
  258. }
  259. repo.NumWatches = t.NumMembers
  260. } else {
  261. repo.NumWatches = 1
  262. }
  263. repo.IsBare = false
  264. if mirror {
  265. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  266. return repo, err
  267. }
  268. repo.IsMirror = true
  269. return repo, UpdateRepository(repo)
  270. } else {
  271. os.RemoveAll(repoPath)
  272. }
  273. // this command could for both migrate and mirror
  274. _, stderr, err := process.ExecTimeout(10*time.Minute,
  275. fmt.Sprintf("MigrateRepository: %s", repoPath),
  276. "git", "clone", "--mirror", "--bare", url, repoPath)
  277. if err != nil {
  278. return repo, errors.New("git clone: " + stderr)
  279. }
  280. return repo, UpdateRepository(repo)
  281. }
  282. // extractGitBareZip extracts git-bare.zip to repository path.
  283. func extractGitBareZip(repoPath string) error {
  284. z, err := zip.Open(path.Join(setting.ConfRootPath, "content/git-bare.zip"))
  285. if err != nil {
  286. return err
  287. }
  288. defer z.Close()
  289. return z.ExtractTo(repoPath)
  290. }
  291. // initRepoCommit temporarily changes with work directory.
  292. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  293. var stderr string
  294. if _, stderr, err = process.ExecDir(-1,
  295. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  296. "git", "add", "--all"); err != nil {
  297. return errors.New("git add: " + stderr)
  298. }
  299. if _, stderr, err = process.ExecDir(-1,
  300. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  301. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  302. "-m", "Init commit"); err != nil {
  303. return errors.New("git commit: " + stderr)
  304. }
  305. if _, stderr, err = process.ExecDir(-1,
  306. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  307. "git", "push", "origin", "master"); err != nil {
  308. return errors.New("git push: " + stderr)
  309. }
  310. return nil
  311. }
  312. func createHookUpdate(hookPath, content string) error {
  313. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  314. if err != nil {
  315. return err
  316. }
  317. defer pu.Close()
  318. _, err = pu.WriteString(content)
  319. return err
  320. }
  321. // InitRepository initializes README and .gitignore if needed.
  322. func initRepository(f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error {
  323. repoPath := RepoPath(u.Name, repo.Name)
  324. // Create bare new repository.
  325. if err := extractGitBareZip(repoPath); err != nil {
  326. return err
  327. }
  328. // hook/post-update
  329. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  330. fmt.Sprintf(TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"")); err != nil {
  331. return err
  332. }
  333. // Initialize repository according to user's choice.
  334. fileName := map[string]string{}
  335. if initReadme {
  336. fileName["readme"] = "README.md"
  337. }
  338. if repoLang != "" {
  339. fileName["gitign"] = ".gitignore"
  340. }
  341. if license != "" {
  342. fileName["license"] = "LICENSE"
  343. }
  344. // Clone to temprory path and do the init commit.
  345. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  346. os.MkdirAll(tmpDir, os.ModePerm)
  347. _, stderr, err := process.Exec(
  348. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  349. "git", "clone", repoPath, tmpDir)
  350. if err != nil {
  351. return errors.New("initRepository(git clone): " + stderr)
  352. }
  353. // README
  354. if initReadme {
  355. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  356. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  357. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  358. []byte(defaultReadme), 0644); err != nil {
  359. return err
  360. }
  361. }
  362. // .gitignore
  363. filePath := "conf/gitignore/" + repoLang
  364. if com.IsFile(filePath) {
  365. targetPath := path.Join(tmpDir, fileName["gitign"])
  366. if com.IsFile(filePath) {
  367. if err = com.Copy(filePath, targetPath); err != nil {
  368. return err
  369. }
  370. } else {
  371. // Check custom files.
  372. filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  373. if com.IsFile(filePath) {
  374. if err := com.Copy(filePath, targetPath); err != nil {
  375. return err
  376. }
  377. }
  378. }
  379. } else {
  380. delete(fileName, "gitign")
  381. }
  382. // LICENSE
  383. filePath = "conf/license/" + license
  384. if com.IsFile(filePath) {
  385. targetPath := path.Join(tmpDir, fileName["license"])
  386. if com.IsFile(filePath) {
  387. if err = com.Copy(filePath, targetPath); err != nil {
  388. return err
  389. }
  390. } else {
  391. // Check custom files.
  392. filePath = path.Join(setting.CustomPath, "conf/license", license)
  393. if com.IsFile(filePath) {
  394. if err := com.Copy(filePath, targetPath); err != nil {
  395. return err
  396. }
  397. }
  398. }
  399. } else {
  400. delete(fileName, "license")
  401. }
  402. if len(fileName) == 0 {
  403. repo.IsBare = true
  404. repo.DefaultBranch = "master"
  405. return UpdateRepository(repo)
  406. }
  407. // Apply changes and commit.
  408. return initRepoCommit(tmpDir, u.NewGitSig())
  409. }
  410. // CreateRepository creates a repository for given user or organization.
  411. func CreateRepository(u *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
  412. if !IsLegalName(name) {
  413. return nil, ErrRepoNameIllegal
  414. }
  415. isExist, err := IsRepositoryExist(u, name)
  416. if err != nil {
  417. return nil, err
  418. } else if isExist {
  419. return nil, ErrRepoAlreadyExist
  420. }
  421. sess := x.NewSession()
  422. defer sess.Close()
  423. if err = sess.Begin(); err != nil {
  424. return nil, err
  425. }
  426. repo := &Repository{
  427. OwnerId: u.Id,
  428. Owner: u,
  429. Name: name,
  430. LowerName: strings.ToLower(name),
  431. Description: desc,
  432. IsPrivate: private,
  433. }
  434. if _, err = sess.Insert(repo); err != nil {
  435. sess.Rollback()
  436. return nil, err
  437. }
  438. var t *Team // Owner team.
  439. mode := WRITABLE
  440. if mirror {
  441. mode = READABLE
  442. }
  443. access := &Access{
  444. UserName: u.LowerName,
  445. RepoName: path.Join(u.LowerName, repo.LowerName),
  446. Mode: mode,
  447. }
  448. // Give access to all members in owner team.
  449. if u.IsOrganization() {
  450. t, err = u.GetOwnerTeam()
  451. if err != nil {
  452. sess.Rollback()
  453. return nil, err
  454. }
  455. if err = t.GetMembers(); err != nil {
  456. sess.Rollback()
  457. return nil, err
  458. }
  459. for _, u := range t.Members {
  460. access.Id = 0
  461. access.UserName = u.LowerName
  462. if _, err = sess.Insert(access); err != nil {
  463. sess.Rollback()
  464. return nil, err
  465. }
  466. }
  467. } else {
  468. if _, err = sess.Insert(access); err != nil {
  469. sess.Rollback()
  470. return nil, err
  471. }
  472. }
  473. if _, err = sess.Exec(
  474. "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  475. sess.Rollback()
  476. return nil, err
  477. }
  478. // Update owner team info and count.
  479. if u.IsOrganization() {
  480. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  481. t.NumRepos++
  482. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  483. sess.Rollback()
  484. return nil, err
  485. }
  486. }
  487. if err = sess.Commit(); err != nil {
  488. return nil, err
  489. }
  490. if u.IsOrganization() {
  491. t, err := u.GetOwnerTeam()
  492. if err != nil {
  493. log.Error(4, "GetOwnerTeam: %v", err)
  494. } else {
  495. if err = t.GetMembers(); err != nil {
  496. log.Error(4, "GetMembers: %v", err)
  497. } else {
  498. for _, u := range t.Members {
  499. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  500. log.Error(4, "WatchRepo2: %v", err)
  501. }
  502. }
  503. }
  504. }
  505. } else {
  506. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  507. log.Error(4, "WatchRepo3: %v", err)
  508. }
  509. }
  510. if err = NewRepoAction(u, repo); err != nil {
  511. log.Error(4, "NewRepoAction: %v", err)
  512. }
  513. // No need for init mirror.
  514. if mirror {
  515. return repo, nil
  516. }
  517. repoPath := RepoPath(u.Name, repo.Name)
  518. if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil {
  519. if err2 := os.RemoveAll(repoPath); err2 != nil {
  520. log.Error(4, "initRepository: %v", err)
  521. return nil, fmt.Errorf(
  522. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  523. }
  524. return nil, fmt.Errorf("initRepository: %v", err)
  525. }
  526. _, stderr, err := process.ExecDir(-1,
  527. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  528. "git", "update-server-info")
  529. if err != nil {
  530. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  531. }
  532. return repo, nil
  533. }
  534. // CountRepositories returns number of repositories.
  535. func CountRepositories() int64 {
  536. count, _ := x.Count(new(Repository))
  537. return count
  538. }
  539. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  540. // It also auto-gets corresponding users.
  541. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  542. repos := make([]*Repository, 0, num)
  543. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  544. return nil, err
  545. }
  546. for _, repo := range repos {
  547. repo.Owner = &User{Id: repo.OwnerId}
  548. has, err := x.Get(repo.Owner)
  549. if err != nil {
  550. return nil, err
  551. } else if !has {
  552. return nil, ErrUserNotExist
  553. }
  554. }
  555. return repos, nil
  556. }
  557. // RepoPath returns repository path by given user and repository name.
  558. func RepoPath(userName, repoName string) string {
  559. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  560. }
  561. // TransferOwnership transfers all corresponding setting from old user to new one.
  562. func TransferOwnership(u *User, newOwner string, repo *Repository) (err error) {
  563. newUser, err := GetUserByName(newOwner)
  564. if err != nil {
  565. return err
  566. }
  567. sess := x.NewSession()
  568. defer sess.Close()
  569. if err = sess.Begin(); err != nil {
  570. return err
  571. }
  572. if _, err = sess.Where("repo_name = ?", u.LowerName+"/"+repo.LowerName).
  573. And("user_name = ?", u.LowerName).Update(&Access{UserName: newUser.LowerName}); err != nil {
  574. sess.Rollback()
  575. return err
  576. }
  577. if _, err = sess.Where("repo_name = ?", u.LowerName+"/"+repo.LowerName).Update(&Access{
  578. RepoName: newUser.LowerName + "/" + repo.LowerName,
  579. }); err != nil {
  580. sess.Rollback()
  581. return err
  582. }
  583. // Update repository.
  584. repo.OwnerId = newUser.Id
  585. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  586. sess.Rollback()
  587. return err
  588. }
  589. // Update user repository number.
  590. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newUser.Id); err != nil {
  591. sess.Rollback()
  592. return err
  593. }
  594. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", u.Id); err != nil {
  595. sess.Rollback()
  596. return err
  597. }
  598. // New owner is organization.
  599. if newUser.IsOrganization() {
  600. mode := WRITABLE
  601. if repo.IsMirror {
  602. mode = READABLE
  603. }
  604. access := &Access{
  605. RepoName: path.Join(newUser.LowerName, repo.LowerName),
  606. Mode: mode,
  607. }
  608. // Give access to all members in owner team.
  609. t, err := newUser.GetOwnerTeam()
  610. if err != nil {
  611. sess.Rollback()
  612. return err
  613. }
  614. if err = t.GetMembers(); err != nil {
  615. sess.Rollback()
  616. return err
  617. }
  618. for _, u := range t.Members {
  619. access.Id = 0
  620. access.UserName = u.LowerName
  621. if _, err = sess.Insert(access); err != nil {
  622. sess.Rollback()
  623. return err
  624. }
  625. }
  626. if _, err = sess.Exec(
  627. "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  628. sess.Rollback()
  629. return err
  630. }
  631. // Update owner team info and count.
  632. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  633. t.NumRepos++
  634. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  635. sess.Rollback()
  636. return err
  637. }
  638. }
  639. // Change repository directory name.
  640. if err = os.Rename(RepoPath(u.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  641. sess.Rollback()
  642. return err
  643. }
  644. if err = sess.Commit(); err != nil {
  645. return err
  646. }
  647. // Add watch of new owner to repository.
  648. if !newUser.IsOrganization() {
  649. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  650. log.Error(4, "WatchRepo", err)
  651. }
  652. }
  653. if err = WatchRepo(u.Id, repo.Id, false); err != nil {
  654. log.Error(4, "WatchRepo2", err)
  655. }
  656. if err = TransferRepoAction(u, newUser, repo); err != nil {
  657. return err
  658. }
  659. return nil
  660. }
  661. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  662. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  663. if !IsLegalName(newRepoName) {
  664. return ErrRepoNameIllegal
  665. }
  666. // Update accesses.
  667. accesses := make([]Access, 0, 10)
  668. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  669. return err
  670. }
  671. sess := x.NewSession()
  672. defer sess.Close()
  673. if err = sess.Begin(); err != nil {
  674. return err
  675. }
  676. for i := range accesses {
  677. accesses[i].RepoName = userName + "/" + newRepoName
  678. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  679. return err
  680. }
  681. }
  682. // Change repository directory name.
  683. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  684. sess.Rollback()
  685. return err
  686. }
  687. return sess.Commit()
  688. }
  689. func UpdateRepository(repo *Repository) error {
  690. repo.LowerName = strings.ToLower(repo.Name)
  691. if len(repo.Description) > 255 {
  692. repo.Description = repo.Description[:255]
  693. }
  694. if len(repo.Website) > 255 {
  695. repo.Website = repo.Website[:255]
  696. }
  697. _, err := x.Id(repo.Id).AllCols().Update(repo)
  698. return err
  699. }
  700. // DeleteRepository deletes a repository for a user or orgnaztion.
  701. func DeleteRepository(uid, repoId int64, userName string) error {
  702. repo := &Repository{Id: repoId, OwnerId: uid}
  703. has, err := x.Get(repo)
  704. if err != nil {
  705. return err
  706. } else if !has {
  707. return ErrRepoNotExist
  708. }
  709. // In case is a organization.
  710. org, err := GetUserById(uid)
  711. if err != nil {
  712. return err
  713. }
  714. if org.IsOrganization() {
  715. if err = org.GetTeams(); err != nil {
  716. return err
  717. }
  718. }
  719. sess := x.NewSession()
  720. defer sess.Close()
  721. if err = sess.Begin(); err != nil {
  722. return err
  723. }
  724. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  725. sess.Rollback()
  726. return err
  727. }
  728. // Delete all access.
  729. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  730. sess.Rollback()
  731. return err
  732. }
  733. if org.IsOrganization() {
  734. idStr := "$" + com.ToStr(repoId) + "|"
  735. for _, t := range org.Teams {
  736. if !strings.Contains(t.RepoIds, idStr) {
  737. continue
  738. }
  739. t.NumRepos--
  740. t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
  741. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  742. sess.Rollback()
  743. return err
  744. }
  745. }
  746. }
  747. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  748. sess.Rollback()
  749. return err
  750. }
  751. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  752. sess.Rollback()
  753. return err
  754. }
  755. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  756. sess.Rollback()
  757. return err
  758. }
  759. if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  760. sess.Rollback()
  761. return err
  762. }
  763. if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  764. sess.Rollback()
  765. return err
  766. }
  767. if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  768. sess.Rollback()
  769. return err
  770. }
  771. // Delete comments.
  772. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  773. issue := bean.(*Issue)
  774. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  775. sess.Rollback()
  776. return err
  777. }
  778. return nil
  779. }); err != nil {
  780. sess.Rollback()
  781. return err
  782. }
  783. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  784. sess.Rollback()
  785. return err
  786. }
  787. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", uid); err != nil {
  788. sess.Rollback()
  789. return err
  790. }
  791. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  792. sess.Rollback()
  793. return err
  794. }
  795. return sess.Commit()
  796. }
  797. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  798. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  799. func GetRepositoryByRef(ref string) (*Repository, error) {
  800. n := strings.IndexByte(ref, byte('/'))
  801. if n < 2 {
  802. return nil, ErrInvalidReference
  803. }
  804. userName, repoName := ref[:n], ref[n+1:]
  805. user, err := GetUserByName(userName)
  806. if err != nil {
  807. return nil, err
  808. }
  809. return GetRepositoryByName(user.Id, repoName)
  810. }
  811. // GetRepositoryByName returns the repository by given name under user if exists.
  812. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  813. repo := &Repository{
  814. OwnerId: userId,
  815. LowerName: strings.ToLower(repoName),
  816. }
  817. has, err := x.Get(repo)
  818. if err != nil {
  819. return nil, err
  820. } else if !has {
  821. return nil, ErrRepoNotExist
  822. }
  823. return repo, err
  824. }
  825. // GetRepositoryById returns the repository by given id if exists.
  826. func GetRepositoryById(id int64) (*Repository, error) {
  827. repo := &Repository{}
  828. has, err := x.Id(id).Get(repo)
  829. if err != nil {
  830. return nil, err
  831. } else if !has {
  832. return nil, ErrRepoNotExist
  833. }
  834. return repo, nil
  835. }
  836. // GetRepositories returns a list of repositories of given user.
  837. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  838. repos := make([]*Repository, 0, 10)
  839. sess := x.Desc("updated")
  840. if !private {
  841. sess.Where("is_private=?", false)
  842. }
  843. err := sess.Find(&repos, &Repository{OwnerId: uid})
  844. return repos, err
  845. }
  846. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  847. func GetRecentUpdatedRepositories() (repos []*Repository, err error) {
  848. err = x.Where("is_private=?", false).Limit(5).Desc("updated").Find(&repos)
  849. return repos, err
  850. }
  851. // GetRepositoryCount returns the total number of repositories of user.
  852. func GetRepositoryCount(user *User) (int64, error) {
  853. return x.Count(&Repository{OwnerId: user.Id})
  854. }
  855. // GetCollaboratorNames returns a list of user name of repository's collaborators.
  856. func GetCollaboratorNames(repoName string) ([]string, error) {
  857. accesses := make([]*Access, 0, 10)
  858. if err := x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  859. return nil, err
  860. }
  861. names := make([]string, len(accesses))
  862. for i := range accesses {
  863. names[i] = accesses[i].UserName
  864. }
  865. return names, nil
  866. }
  867. // GetCollaborativeRepos returns a list of repositories that user is collaborator.
  868. func GetCollaborativeRepos(uname string) ([]*Repository, error) {
  869. uname = strings.ToLower(uname)
  870. accesses := make([]*Access, 0, 10)
  871. if err := x.Find(&accesses, &Access{UserName: uname}); err != nil {
  872. return nil, err
  873. }
  874. repos := make([]*Repository, 0, 10)
  875. for _, access := range accesses {
  876. infos := strings.Split(access.RepoName, "/")
  877. if infos[0] == uname {
  878. continue
  879. }
  880. u, err := GetUserByName(infos[0])
  881. if err != nil {
  882. return nil, err
  883. }
  884. repo, err := GetRepositoryByName(u.Id, infos[1])
  885. if err != nil {
  886. return nil, err
  887. }
  888. repo.Owner = u
  889. repos = append(repos, repo)
  890. }
  891. return repos, nil
  892. }
  893. // GetCollaborators returns a list of users of repository's collaborators.
  894. func GetCollaborators(repoName string) (us []*User, err error) {
  895. accesses := make([]*Access, 0, 10)
  896. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  897. return nil, err
  898. }
  899. us = make([]*User, len(accesses))
  900. for i := range accesses {
  901. us[i], err = GetUserByName(accesses[i].UserName)
  902. if err != nil {
  903. return nil, err
  904. }
  905. }
  906. return us, nil
  907. }
  908. type SearchOption struct {
  909. Keyword string
  910. Uid int64
  911. Limit int
  912. }
  913. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  914. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  915. // Prevent SQL inject.
  916. opt.Keyword = strings.TrimSpace(opt.Keyword)
  917. if len(opt.Keyword) == 0 {
  918. return repos, nil
  919. }
  920. opt.Keyword = strings.Split(opt.Keyword, " ")[0]
  921. if len(opt.Keyword) == 0 {
  922. return repos, nil
  923. }
  924. opt.Keyword = strings.ToLower(opt.Keyword)
  925. repos = make([]*Repository, 0, opt.Limit)
  926. // Append conditions.
  927. sess := x.Limit(opt.Limit)
  928. if opt.Uid > 0 {
  929. sess.Where("owner_id=?", opt.Uid)
  930. }
  931. sess.And("lower_name like '%" + opt.Keyword + "%'").Find(&repos)
  932. return repos, err
  933. }
  934. // Watch is connection request for receiving repository notifycation.
  935. type Watch struct {
  936. Id int64
  937. UserId int64 `xorm:"UNIQUE(watch)"`
  938. RepoId int64 `xorm:"UNIQUE(watch)"`
  939. }
  940. // Watch or unwatch repository.
  941. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  942. if watch {
  943. if IsWatching(uid, repoId) {
  944. return nil
  945. }
  946. if _, err = x.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
  947. return err
  948. }
  949. _, err = x.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  950. } else {
  951. if !IsWatching(uid, repoId) {
  952. return nil
  953. }
  954. if _, err = x.Delete(&Watch{0, uid, repoId}); err != nil {
  955. return err
  956. }
  957. _, err = x.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
  958. }
  959. return err
  960. }
  961. // IsWatching checks if user has watched given repository.
  962. func IsWatching(uid, rid int64) bool {
  963. has, _ := x.Get(&Watch{0, uid, rid})
  964. return has
  965. }
  966. // GetWatchers returns all watchers of given repository.
  967. func GetWatchers(rid int64) ([]*Watch, error) {
  968. watches := make([]*Watch, 0, 10)
  969. err := x.Find(&watches, &Watch{RepoId: rid})
  970. return watches, err
  971. }
  972. // NotifyWatchers creates batch of actions for every watcher.
  973. func NotifyWatchers(act *Action) error {
  974. // Add feeds for user self and all watchers.
  975. watches, err := GetWatchers(act.RepoId)
  976. if err != nil {
  977. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  978. }
  979. // Add feed for actioner.
  980. act.UserId = act.ActUserId
  981. if _, err = x.InsertOne(act); err != nil {
  982. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  983. }
  984. for i := range watches {
  985. if act.ActUserId == watches[i].UserId {
  986. continue
  987. }
  988. act.Id = 0
  989. act.UserId = watches[i].UserId
  990. if _, err = x.InsertOne(act); err != nil {
  991. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  992. }
  993. }
  994. return nil
  995. }
  996. type Star struct {
  997. Id int64
  998. Uid int64 `xorm:"UNIQUE(s)"`
  999. RepoId int64 `xorm:"UNIQUE(s)"`
  1000. }
  1001. // Star or unstar repository.
  1002. func StarRepo(uid, repoId int64, star bool) (err error) {
  1003. if star {
  1004. if IsStaring(uid, repoId) {
  1005. return nil
  1006. }
  1007. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1008. return err
  1009. }
  1010. _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId)
  1011. } else {
  1012. if !IsStaring(uid, repoId) {
  1013. return nil
  1014. }
  1015. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1016. return err
  1017. }
  1018. _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId)
  1019. }
  1020. return err
  1021. }
  1022. // IsStaring checks if user has starred given repository.
  1023. func IsStaring(uid, repoId int64) bool {
  1024. has, _ := x.Get(&Star{0, uid, repoId})
  1025. return has
  1026. }
  1027. func ForkRepository(repoName string, uid int64) {
  1028. }