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 14KB

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