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

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