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

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