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

repo.go 31 kB

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