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