repo.go 14 KB

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