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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "github.com/Unknwon/cae/zip"
  17. "github.com/Unknwon/com"
  18. "github.com/gogits/git"
  19. "github.com/gogits/gogs/modules/base"
  20. "github.com/gogits/gogs/modules/log"
  21. )
  22. var (
  23. ErrRepoAlreadyExist = errors.New("Repository already exist")
  24. ErrRepoNotExist = errors.New("Repository does not exist")
  25. ErrRepoFileNotExist = errors.New("Target Repo file does not exist")
  26. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  27. ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded")
  28. )
  29. var (
  30. LanguageIgns, Licenses []string
  31. )
  32. func LoadRepoConfig() {
  33. LanguageIgns = strings.Split(base.Cfg.MustValue("repository", "LANG_IGNS"), "|")
  34. Licenses = strings.Split(base.Cfg.MustValue("repository", "LICENSES"), "|")
  35. }
  36. func NewRepoContext() {
  37. zip.Verbose = false
  38. // Check if server has basic git setting.
  39. stdout, _, err := com.ExecCmd("git", "config", "--get", "user.name")
  40. if err != nil {
  41. fmt.Printf("repo.init(fail to get git user.name): %v", err)
  42. os.Exit(2)
  43. } else if len(stdout) == 0 {
  44. if _, _, err = com.ExecCmd("git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil {
  45. fmt.Printf("repo.init(fail to set git user.email): %v", err)
  46. os.Exit(2)
  47. } else if _, _, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
  48. fmt.Printf("repo.init(fail to set git user.name): %v", err)
  49. os.Exit(2)
  50. }
  51. }
  52. }
  53. // Repository represents a git repository.
  54. type Repository struct {
  55. Id int64
  56. OwnerId int64 `xorm:"unique(s)"`
  57. ForkId int64
  58. LowerName string `xorm:"unique(s) index not null"`
  59. Name string `xorm:"index not null"`
  60. Description string
  61. Website string
  62. NumWatches int
  63. NumStars int
  64. NumForks int
  65. NumIssues int
  66. NumReleases int `xorm:"NOT NULL"`
  67. NumClosedIssues int
  68. NumOpenIssues int `xorm:"-"`
  69. IsPrivate bool
  70. IsBare bool
  71. IsGoget bool
  72. DefaultBranch string
  73. Created time.Time `xorm:"created"`
  74. Updated time.Time `xorm:"updated"`
  75. }
  76. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  77. func IsRepositoryExist(user *User, repoName string) (bool, error) {
  78. repo := Repository{OwnerId: user.Id}
  79. has, err := orm.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  80. if err != nil {
  81. return has, err
  82. } else if !has {
  83. return false, nil
  84. }
  85. return com.IsDir(RepoPath(user.Name, repoName)), nil
  86. }
  87. var (
  88. illegalEquals = []string{"raw", "install", "api", "avatar", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"}
  89. illegalSuffixs = []string{".git"}
  90. )
  91. // IsLegalName returns false if name contains illegal characters.
  92. func IsLegalName(repoName string) bool {
  93. repoName = strings.ToLower(repoName)
  94. for _, char := range illegalEquals {
  95. if repoName == char {
  96. return false
  97. }
  98. }
  99. for _, char := range illegalSuffixs {
  100. if strings.HasSuffix(repoName, char) {
  101. return false
  102. }
  103. }
  104. return true
  105. }
  106. // CreateRepository creates a repository for given user or orgnaziation.
  107. func CreateRepository(user *User, repoName, desc, repoLang, license string, private bool, initReadme bool) (*Repository, error) {
  108. if !IsLegalName(repoName) {
  109. return nil, ErrRepoNameIllegal
  110. }
  111. isExist, err := IsRepositoryExist(user, repoName)
  112. if err != nil {
  113. return nil, err
  114. } else if isExist {
  115. return nil, ErrRepoAlreadyExist
  116. }
  117. repo := &Repository{
  118. OwnerId: user.Id,
  119. Name: repoName,
  120. LowerName: strings.ToLower(repoName),
  121. Description: desc,
  122. IsPrivate: private,
  123. IsBare: repoLang == "" && license == "" && !initReadme,
  124. }
  125. repoPath := RepoPath(user.Name, repoName)
  126. sess := orm.NewSession()
  127. defer sess.Close()
  128. sess.Begin()
  129. if _, err = sess.Insert(repo); err != nil {
  130. if err2 := os.RemoveAll(repoPath); err2 != nil {
  131. log.Error("repo.CreateRepository(repo): %v", err)
  132. return nil, errors.New(fmt.Sprintf(
  133. "delete repo directory %s/%s failed(1): %v", user.Name, repoName, err2))
  134. }
  135. sess.Rollback()
  136. return nil, err
  137. }
  138. access := Access{
  139. UserName: user.LowerName,
  140. RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
  141. Mode: AU_WRITABLE,
  142. }
  143. if _, err = sess.Insert(&access); err != nil {
  144. sess.Rollback()
  145. if err2 := os.RemoveAll(repoPath); err2 != nil {
  146. log.Error("repo.CreateRepository(access): %v", err)
  147. return nil, errors.New(fmt.Sprintf(
  148. "delete repo directory %s/%s failed(2): %v", user.Name, repoName, err2))
  149. }
  150. return nil, err
  151. }
  152. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  153. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  154. sess.Rollback()
  155. if err2 := os.RemoveAll(repoPath); err2 != nil {
  156. log.Error("repo.CreateRepository(repo count): %v", err)
  157. return nil, errors.New(fmt.Sprintf(
  158. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  159. }
  160. return nil, err
  161. }
  162. if err = sess.Commit(); err != nil {
  163. sess.Rollback()
  164. if err2 := os.RemoveAll(repoPath); err2 != nil {
  165. log.Error("repo.CreateRepository(commit): %v", err)
  166. return nil, errors.New(fmt.Sprintf(
  167. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  168. }
  169. return nil, err
  170. }
  171. if !repo.IsPrivate {
  172. if err = NewRepoAction(user, repo); err != nil {
  173. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  174. }
  175. }
  176. if err = WatchRepo(user.Id, repo.Id, true); err != nil {
  177. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  178. }
  179. if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
  180. return nil, err
  181. }
  182. c := exec.Command("git", "update-server-info")
  183. c.Dir = repoPath
  184. if err = c.Run(); err != nil {
  185. log.Error("repo.CreateRepository(exec update-server-info): %v", err)
  186. }
  187. return repo, nil
  188. }
  189. // extractGitBareZip extracts git-bare.zip to repository path.
  190. func extractGitBareZip(repoPath string) error {
  191. z, err := zip.Open("conf/content/git-bare.zip")
  192. if err != nil {
  193. fmt.Println("shi?")
  194. return err
  195. }
  196. defer z.Close()
  197. return z.ExtractTo(repoPath)
  198. }
  199. // initRepoCommit temporarily changes with work directory.
  200. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  201. var stderr string
  202. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "add", "--all"); err != nil {
  203. return err
  204. }
  205. if len(stderr) > 0 {
  206. log.Trace("stderr(1): %s", stderr)
  207. }
  208. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  209. "-m", "Init commit"); err != nil {
  210. return err
  211. }
  212. if len(stderr) > 0 {
  213. log.Trace("stderr(2): %s", stderr)
  214. }
  215. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "push", "origin", "master"); err != nil {
  216. return err
  217. }
  218. if len(stderr) > 0 {
  219. log.Trace("stderr(3): %s", stderr)
  220. }
  221. return nil
  222. }
  223. func createHookUpdate(hookPath, content string) error {
  224. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  225. if err != nil {
  226. return err
  227. }
  228. defer pu.Close()
  229. _, err = pu.WriteString(content)
  230. return err
  231. }
  232. // SetRepoEnvs sets environment variables for command update.
  233. func SetRepoEnvs(userId int64, userName, repoName string) {
  234. os.Setenv("userId", base.ToStr(userId))
  235. os.Setenv("userName", userName)
  236. os.Setenv("repoName", repoName)
  237. }
  238. // InitRepository initializes README and .gitignore if needed.
  239. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  240. repoPath := RepoPath(user.Name, repo.Name)
  241. // Create bare new repository.
  242. if err := extractGitBareZip(repoPath); err != nil {
  243. return err
  244. }
  245. // hook/post-update
  246. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  247. fmt.Sprintf("#!/usr/bin/env bash\n%s update $1 $2 $3\n",
  248. strings.Replace(appPath, "\\", "/", -1))); err != nil {
  249. return err
  250. }
  251. // Initialize repository according to user's choice.
  252. fileName := map[string]string{}
  253. if initReadme {
  254. fileName["readme"] = "README.md"
  255. }
  256. if repoLang != "" {
  257. fileName["gitign"] = ".gitignore"
  258. }
  259. if license != "" {
  260. fileName["license"] = "LICENSE"
  261. }
  262. // Clone to temprory path and do the init commit.
  263. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  264. os.MkdirAll(tmpDir, os.ModePerm)
  265. if _, _, err := com.ExecCmd("git", "clone", repoPath, tmpDir); err != nil {
  266. return err
  267. }
  268. // README
  269. if initReadme {
  270. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  271. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  272. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  273. []byte(defaultReadme), 0644); err != nil {
  274. return err
  275. }
  276. }
  277. // .gitignore
  278. if repoLang != "" {
  279. filePath := "conf/gitignore/" + repoLang
  280. if com.IsFile(filePath) {
  281. if _, err := com.Copy(filePath,
  282. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  283. return err
  284. }
  285. }
  286. }
  287. // LICENSE
  288. if license != "" {
  289. filePath := "conf/license/" + license
  290. if com.IsFile(filePath) {
  291. if _, err := com.Copy(filePath,
  292. filepath.Join(tmpDir, fileName["license"])); err != nil {
  293. return err
  294. }
  295. }
  296. }
  297. if len(fileName) == 0 {
  298. return nil
  299. }
  300. SetRepoEnvs(user.Id, user.Name, repo.Name)
  301. // Apply changes and commit.
  302. return initRepoCommit(tmpDir, user.NewGitSig())
  303. }
  304. // UserRepo reporesents a repository with user name.
  305. type UserRepo struct {
  306. *Repository
  307. UserName string
  308. }
  309. // GetRepos returns given number of repository objects with offset.
  310. func GetRepos(num, offset int) ([]UserRepo, error) {
  311. repos := make([]Repository, 0, num)
  312. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  313. return nil, err
  314. }
  315. urepos := make([]UserRepo, len(repos))
  316. for i := range repos {
  317. urepos[i].Repository = &repos[i]
  318. u := new(User)
  319. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  320. if err != nil {
  321. return nil, err
  322. } else if !has {
  323. return nil, ErrUserNotExist
  324. }
  325. urepos[i].UserName = u.Name
  326. }
  327. return urepos, nil
  328. }
  329. func RepoPath(userName, repoName string) string {
  330. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  331. }
  332. // TransferOwnership transfers all corresponding setting from old user to new one.
  333. func TransferOwnership(user *User, newOwner string, repo *Repository) (err error) {
  334. newUser, err := GetUserByName(newOwner)
  335. if err != nil {
  336. return err
  337. }
  338. // Update accesses.
  339. accesses := make([]Access, 0, 10)
  340. if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil {
  341. return err
  342. }
  343. sess := orm.NewSession()
  344. defer sess.Close()
  345. if err = sess.Begin(); err != nil {
  346. return err
  347. }
  348. for i := range accesses {
  349. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  350. if accesses[i].UserName == user.LowerName {
  351. accesses[i].UserName = newUser.LowerName
  352. }
  353. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  354. return err
  355. }
  356. }
  357. // Update repository.
  358. repo.OwnerId = newUser.Id
  359. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  360. sess.Rollback()
  361. return err
  362. }
  363. // Update user repository number.
  364. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  365. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  366. sess.Rollback()
  367. return err
  368. }
  369. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  370. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  371. sess.Rollback()
  372. return err
  373. }
  374. // Add watch of new owner to repository.
  375. if !IsWatching(newUser.Id, repo.Id) {
  376. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  377. sess.Rollback()
  378. return err
  379. }
  380. }
  381. if err = TransferRepoAction(user, newUser, repo); err != nil {
  382. sess.Rollback()
  383. return err
  384. }
  385. // Change repository directory name.
  386. if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  387. sess.Rollback()
  388. return err
  389. }
  390. return sess.Commit()
  391. }
  392. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  393. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  394. // Update accesses.
  395. accesses := make([]Access, 0, 10)
  396. if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  397. return err
  398. }
  399. sess := orm.NewSession()
  400. defer sess.Close()
  401. if err = sess.Begin(); err != nil {
  402. return err
  403. }
  404. for i := range accesses {
  405. accesses[i].RepoName = userName + "/" + newRepoName
  406. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  407. return err
  408. }
  409. }
  410. // Change repository directory name.
  411. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  412. sess.Rollback()
  413. return err
  414. }
  415. return sess.Commit()
  416. }
  417. func UpdateRepository(repo *Repository) error {
  418. repo.LowerName = strings.ToLower(repo.Name)
  419. if len(repo.Description) > 255 {
  420. repo.Description = repo.Description[:255]
  421. }
  422. if len(repo.Website) > 255 {
  423. repo.Website = repo.Website[:255]
  424. }
  425. _, err := orm.Id(repo.Id).AllCols().Update(repo)
  426. return err
  427. }
  428. // DeleteRepository deletes a repository for a user or orgnaztion.
  429. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  430. repo := &Repository{Id: repoId, OwnerId: userId}
  431. has, err := orm.Get(repo)
  432. if err != nil {
  433. return err
  434. } else if !has {
  435. return ErrRepoNotExist
  436. }
  437. sess := orm.NewSession()
  438. defer sess.Close()
  439. if err = sess.Begin(); err != nil {
  440. return err
  441. }
  442. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  443. sess.Rollback()
  444. return err
  445. }
  446. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  447. sess.Rollback()
  448. return err
  449. }
  450. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  451. if _, err = sess.Exec(rawSql, userId); err != nil {
  452. sess.Rollback()
  453. return err
  454. }
  455. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  456. sess.Rollback()
  457. return err
  458. }
  459. if err = sess.Commit(); err != nil {
  460. sess.Rollback()
  461. return err
  462. }
  463. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  464. // TODO: log and delete manully
  465. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  466. return err
  467. }
  468. return nil
  469. }
  470. // GetRepositoryByName returns the repository by given name under user if exists.
  471. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  472. repo := &Repository{
  473. OwnerId: userId,
  474. LowerName: strings.ToLower(repoName),
  475. }
  476. has, err := orm.Get(repo)
  477. if err != nil {
  478. return nil, err
  479. } else if !has {
  480. return nil, ErrRepoNotExist
  481. }
  482. return repo, err
  483. }
  484. // GetRepositoryById returns the repository by given id if exists.
  485. func GetRepositoryById(id int64) (*Repository, error) {
  486. repo := &Repository{}
  487. has, err := orm.Id(id).Get(repo)
  488. if err != nil {
  489. return nil, err
  490. } else if !has {
  491. return nil, ErrRepoNotExist
  492. }
  493. return repo, err
  494. }
  495. // GetRepositories returns the list of repositories of given user.
  496. func GetRepositories(user *User) ([]Repository, error) {
  497. repos := make([]Repository, 0, 10)
  498. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  499. return repos, err
  500. }
  501. func GetRepositoryCount(user *User) (int64, error) {
  502. return orm.Count(&Repository{OwnerId: user.Id})
  503. }
  504. // Watch is connection request for receiving repository notifycation.
  505. type Watch struct {
  506. Id int64
  507. RepoId int64 `xorm:"UNIQUE(watch)"`
  508. UserId int64 `xorm:"UNIQUE(watch)"`
  509. }
  510. // Watch or unwatch repository.
  511. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  512. if watch {
  513. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  514. return err
  515. }
  516. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  517. _, err = orm.Exec(rawSql, repoId)
  518. } else {
  519. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  520. return err
  521. }
  522. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  523. _, err = orm.Exec(rawSql, repoId)
  524. }
  525. return err
  526. }
  527. // GetWatches returns all watches of given repository.
  528. func GetWatches(repoId int64) ([]Watch, error) {
  529. watches := make([]Watch, 0, 10)
  530. err := orm.Find(&watches, &Watch{RepoId: repoId})
  531. return watches, err
  532. }
  533. // NotifyWatchers creates batch of actions for every watcher.
  534. func NotifyWatchers(act *Action) error {
  535. // Add feeds for user self and all watchers.
  536. watches, err := GetWatches(act.RepoId)
  537. if err != nil {
  538. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  539. }
  540. // Add feed for actioner.
  541. act.UserId = act.ActUserId
  542. if _, err = orm.InsertOne(act); err != nil {
  543. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  544. }
  545. for i := range watches {
  546. if act.ActUserId == watches[i].UserId {
  547. continue
  548. }
  549. act.Id = 0
  550. act.UserId = watches[i].UserId
  551. if _, err = orm.InsertOne(act); err != nil {
  552. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  553. }
  554. }
  555. return nil
  556. }
  557. // IsWatching checks if user has watched given repository.
  558. func IsWatching(userId, repoId int64) bool {
  559. has, _ := orm.Get(&Watch{0, repoId, userId})
  560. return has
  561. }
  562. func ForkRepository(reposName string, userId int64) {
  563. }