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