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

repo.go 15 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. Created time.Time `xorm:"created"`
  72. Updated time.Time `xorm:"updated"`
  73. }
  74. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  75. func IsRepositoryExist(user *User, repoName string) (bool, error) {
  76. repo := Repository{OwnerId: user.Id}
  77. has, err := orm.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  78. if err != nil {
  79. return has, err
  80. } else if !has {
  81. return false, nil
  82. }
  83. return com.IsDir(RepoPath(user.Name, repoName)), nil
  84. }
  85. var (
  86. illegalEquals = []string{"raw", "install", "api", "avatar", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"}
  87. illegalSuffixs = []string{".git"}
  88. )
  89. // IsLegalName returns false if name contains illegal characters.
  90. func IsLegalName(repoName string) bool {
  91. repoName = strings.ToLower(repoName)
  92. for _, char := range illegalEquals {
  93. if repoName == char {
  94. return false
  95. }
  96. }
  97. for _, char := range illegalSuffixs {
  98. if strings.HasSuffix(repoName, char) {
  99. return false
  100. }
  101. }
  102. return true
  103. }
  104. // CreateRepository creates a repository for given user or orgnaziation.
  105. func CreateRepository(user *User, repoName, desc, repoLang, license string, private bool, initReadme bool) (*Repository, error) {
  106. if !IsLegalName(repoName) {
  107. return nil, ErrRepoNameIllegal
  108. }
  109. isExist, err := IsRepositoryExist(user, repoName)
  110. if err != nil {
  111. return nil, err
  112. } else if isExist {
  113. return nil, ErrRepoAlreadyExist
  114. }
  115. repo := &Repository{
  116. OwnerId: user.Id,
  117. Name: repoName,
  118. LowerName: strings.ToLower(repoName),
  119. Description: desc,
  120. IsPrivate: private,
  121. IsBare: repoLang == "" && license == "" && !initReadme,
  122. }
  123. repoPath := RepoPath(user.Name, repoName)
  124. if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
  125. return nil, err
  126. }
  127. session := orm.NewSession()
  128. defer session.Close()
  129. session.Begin()
  130. if _, err = session.Insert(repo); err != nil {
  131. if err2 := os.RemoveAll(repoPath); err2 != nil {
  132. log.Error("repo.CreateRepository(repo): %v", err)
  133. return nil, errors.New(fmt.Sprintf(
  134. "delete repo directory %s/%s failed(1): %v", user.Name, repoName, err2))
  135. }
  136. session.Rollback()
  137. return nil, err
  138. }
  139. access := Access{
  140. UserName: user.LowerName,
  141. RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
  142. Mode: AU_WRITABLE,
  143. }
  144. if _, err = session.Insert(&access); err != nil {
  145. session.Rollback()
  146. if err2 := os.RemoveAll(repoPath); err2 != nil {
  147. log.Error("repo.CreateRepository(access): %v", err)
  148. return nil, errors.New(fmt.Sprintf(
  149. "delete repo directory %s/%s failed(2): %v", user.Name, repoName, err2))
  150. }
  151. return nil, err
  152. }
  153. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  154. if _, err = session.Exec(rawSql, user.Id); err != nil {
  155. session.Rollback()
  156. if err2 := os.RemoveAll(repoPath); err2 != nil {
  157. log.Error("repo.CreateRepository(repo count): %v", err)
  158. return nil, errors.New(fmt.Sprintf(
  159. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  160. }
  161. return nil, err
  162. }
  163. if err = session.Commit(); err != nil {
  164. session.Rollback()
  165. if err2 := os.RemoveAll(repoPath); err2 != nil {
  166. log.Error("repo.CreateRepository(commit): %v", err)
  167. return nil, errors.New(fmt.Sprintf(
  168. "delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
  169. }
  170. return nil, err
  171. }
  172. c := exec.Command("git", "update-server-info")
  173. c.Dir = repoPath
  174. if err = c.Run(); err != nil {
  175. log.Error("repo.CreateRepository(exec update-server-info): %v", err)
  176. }
  177. if err = NewRepoAction(user, repo); err != nil {
  178. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  179. }
  180. if err = WatchRepo(user.Id, repo.Id, true); err != nil {
  181. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  182. }
  183. return repo, nil
  184. }
  185. // extractGitBareZip extracts git-bare.zip to repository path.
  186. func extractGitBareZip(repoPath string) error {
  187. z, err := zip.Open("conf/content/git-bare.zip")
  188. if err != nil {
  189. fmt.Println("shi?")
  190. return err
  191. }
  192. defer z.Close()
  193. return z.ExtractTo(repoPath)
  194. }
  195. // initRepoCommit temporarily changes with work directory.
  196. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  197. var stderr string
  198. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "add", "--all"); err != nil {
  199. return err
  200. }
  201. if len(stderr) > 0 {
  202. log.Trace("stderr(1): %s", stderr)
  203. }
  204. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  205. "-m", "Init commit"); err != nil {
  206. return err
  207. }
  208. if len(stderr) > 0 {
  209. log.Trace("stderr(2): %s", stderr)
  210. }
  211. if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "push", "origin", "master"); err != nil {
  212. return err
  213. }
  214. if len(stderr) > 0 {
  215. log.Trace("stderr(3): %s", stderr)
  216. }
  217. return nil
  218. }
  219. func createHookUpdate(hookPath, content string) error {
  220. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  221. if err != nil {
  222. return err
  223. }
  224. defer pu.Close()
  225. _, err = pu.WriteString(content)
  226. return err
  227. }
  228. // InitRepository initializes README and .gitignore if needed.
  229. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  230. repoPath := RepoPath(user.Name, repo.Name)
  231. // Create bare new repository.
  232. if err := extractGitBareZip(repoPath); err != nil {
  233. return err
  234. }
  235. // hook/post-update
  236. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  237. fmt.Sprintf("#!/usr/bin/env bash\n%s update $1 $2 $3\n",
  238. strings.Replace(appPath, "\\", "/", -1))); err != nil {
  239. return err
  240. }
  241. // Initialize repository according to user's choice.
  242. fileName := map[string]string{}
  243. if initReadme {
  244. fileName["readme"] = "README.md"
  245. }
  246. if repoLang != "" {
  247. fileName["gitign"] = ".gitignore"
  248. }
  249. if license != "" {
  250. fileName["license"] = "LICENSE"
  251. }
  252. // Clone to temprory path and do the init commit.
  253. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  254. os.MkdirAll(tmpDir, os.ModePerm)
  255. if _, _, err := com.ExecCmd("git", "clone", repoPath, tmpDir); err != nil {
  256. return err
  257. }
  258. // README
  259. if initReadme {
  260. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  261. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  262. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  263. []byte(defaultReadme), 0644); err != nil {
  264. return err
  265. }
  266. }
  267. // .gitignore
  268. if repoLang != "" {
  269. filePath := "conf/gitignore/" + repoLang
  270. if com.IsFile(filePath) {
  271. if _, err := com.Copy(filePath,
  272. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  273. return err
  274. }
  275. }
  276. }
  277. // LICENSE
  278. if license != "" {
  279. filePath := "conf/license/" + license
  280. if com.IsFile(filePath) {
  281. if _, err := com.Copy(filePath,
  282. filepath.Join(tmpDir, fileName["license"])); err != nil {
  283. return err
  284. }
  285. }
  286. }
  287. if len(fileName) == 0 {
  288. return nil
  289. }
  290. // Apply changes and commit.
  291. return initRepoCommit(tmpDir, user.NewGitSig())
  292. }
  293. // UserRepo reporesents a repository with user name.
  294. type UserRepo struct {
  295. *Repository
  296. UserName string
  297. }
  298. // GetRepos returns given number of repository objects with offset.
  299. func GetRepos(num, offset int) ([]UserRepo, error) {
  300. repos := make([]Repository, 0, num)
  301. if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  302. return nil, err
  303. }
  304. urepos := make([]UserRepo, len(repos))
  305. for i := range repos {
  306. urepos[i].Repository = &repos[i]
  307. u := new(User)
  308. has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u)
  309. if err != nil {
  310. return nil, err
  311. } else if !has {
  312. return nil, ErrUserNotExist
  313. }
  314. urepos[i].UserName = u.Name
  315. }
  316. return urepos, nil
  317. }
  318. func RepoPath(userName, repoName string) string {
  319. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  320. }
  321. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  322. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  323. // Update accesses.
  324. accesses := make([]Access, 0, 10)
  325. if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  326. return err
  327. }
  328. for i := range accesses {
  329. accesses[i].RepoName = userName + "/" + newRepoName
  330. if err = UpdateAccess(&accesses[i]); err != nil {
  331. return err
  332. }
  333. }
  334. // Change repository directory name.
  335. return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName))
  336. }
  337. func UpdateRepository(repo *Repository) error {
  338. repo.LowerName = strings.ToLower(repo.Name)
  339. if len(repo.Description) > 255 {
  340. repo.Description = repo.Description[:255]
  341. }
  342. if len(repo.Website) > 255 {
  343. repo.Website = repo.Website[:255]
  344. }
  345. _, err := orm.Id(repo.Id).AllCols().Update(repo)
  346. return err
  347. }
  348. // DeleteRepository deletes a repository for a user or orgnaztion.
  349. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  350. repo := &Repository{Id: repoId, OwnerId: userId}
  351. has, err := orm.Get(repo)
  352. if err != nil {
  353. return err
  354. } else if !has {
  355. return ErrRepoNotExist
  356. }
  357. session := orm.NewSession()
  358. if err = session.Begin(); err != nil {
  359. return err
  360. }
  361. if _, err = session.Delete(&Repository{Id: repoId}); err != nil {
  362. session.Rollback()
  363. return err
  364. }
  365. if _, err := session.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  366. session.Rollback()
  367. return err
  368. }
  369. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  370. if _, err = session.Exec(rawSql, userId); err != nil {
  371. session.Rollback()
  372. return err
  373. }
  374. if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil {
  375. session.Rollback()
  376. return err
  377. }
  378. if err = session.Commit(); err != nil {
  379. session.Rollback()
  380. return err
  381. }
  382. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  383. // TODO: log and delete manully
  384. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  385. return err
  386. }
  387. return nil
  388. }
  389. // GetRepositoryByName returns the repository by given name under user if exists.
  390. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  391. repo := &Repository{
  392. OwnerId: userId,
  393. LowerName: strings.ToLower(repoName),
  394. }
  395. has, err := orm.Get(repo)
  396. if err != nil {
  397. return nil, err
  398. } else if !has {
  399. return nil, ErrRepoNotExist
  400. }
  401. return repo, err
  402. }
  403. // GetRepositoryById returns the repository by given id if exists.
  404. func GetRepositoryById(id int64) (*Repository, error) {
  405. repo := &Repository{}
  406. has, err := orm.Id(id).Get(repo)
  407. if err != nil {
  408. return nil, err
  409. } else if !has {
  410. return nil, ErrRepoNotExist
  411. }
  412. return repo, err
  413. }
  414. // GetRepositories returns the list of repositories of given user.
  415. func GetRepositories(user *User) ([]Repository, error) {
  416. repos := make([]Repository, 0, 10)
  417. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  418. return repos, err
  419. }
  420. func GetRepositoryCount(user *User) (int64, error) {
  421. return orm.Count(&Repository{OwnerId: user.Id})
  422. }
  423. // Watch is connection request for receiving repository notifycation.
  424. type Watch struct {
  425. Id int64
  426. RepoId int64 `xorm:"UNIQUE(watch)"`
  427. UserId int64 `xorm:"UNIQUE(watch)"`
  428. }
  429. // Watch or unwatch repository.
  430. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  431. if watch {
  432. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  433. return err
  434. }
  435. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  436. _, err = orm.Exec(rawSql, repoId)
  437. } else {
  438. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  439. return err
  440. }
  441. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  442. _, err = orm.Exec(rawSql, repoId)
  443. }
  444. return err
  445. }
  446. // GetWatches returns all watches of given repository.
  447. func GetWatches(repoId int64) ([]Watch, error) {
  448. watches := make([]Watch, 0, 10)
  449. err := orm.Find(&watches, &Watch{RepoId: repoId})
  450. return watches, err
  451. }
  452. // NotifyWatchers creates batch of actions for every watcher.
  453. func NotifyWatchers(act *Action) error {
  454. // Add feeds for user self and all watchers.
  455. watches, err := GetWatches(act.RepoId)
  456. if err != nil {
  457. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  458. }
  459. // Add feed for actioner.
  460. act.UserId = act.ActUserId
  461. if _, err = orm.InsertOne(act); err != nil {
  462. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  463. }
  464. for i := range watches {
  465. if act.ActUserId == watches[i].UserId {
  466. continue
  467. }
  468. act.Id = 0
  469. act.UserId = watches[i].UserId
  470. if _, err = orm.InsertOne(act); err != nil {
  471. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  472. }
  473. }
  474. return nil
  475. }
  476. // IsWatching checks if user has watched given repository.
  477. func IsWatching(userId, repoId int64) bool {
  478. has, _ := orm.Get(&Watch{0, repoId, userId})
  479. return has
  480. }
  481. func ForkRepository(reposName string, userId int64) {
  482. }