repo.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. "container/list"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "sync"
  16. "time"
  17. "unicode/utf8"
  18. "github.com/Unknwon/cae/zip"
  19. "github.com/Unknwon/com"
  20. "github.com/gogits/git"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/log"
  23. )
  24. var (
  25. ErrRepoAlreadyExist = errors.New("Repository already exist")
  26. ErrRepoNotExist = errors.New("Repository does not exist")
  27. ErrRepoFileNotExist = errors.New("Target Repo file does not exist")
  28. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  29. ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded")
  30. )
  31. var gitInitLocker = sync.Mutex{}
  32. var (
  33. LanguageIgns, Licenses []string
  34. )
  35. func init() {
  36. LanguageIgns = strings.Split(base.Cfg.MustValue("repository", "LANG_IGNS"), "|")
  37. Licenses = strings.Split(base.Cfg.MustValue("repository", "LICENSES"), "|")
  38. zip.Verbose = false
  39. // Check if server has basic git setting.
  40. stdout, _, err := com.ExecCmd("git", "config", "--get", "user.name")
  41. if err != nil {
  42. fmt.Printf("repo.init(fail to get git user.name): %v", err)
  43. os.Exit(2)
  44. } else if len(stdout) == 0 {
  45. if _, _, err = com.ExecCmd("git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil {
  46. fmt.Printf("repo.init(fail to set git user.email): %v", err)
  47. os.Exit(2)
  48. } else if _, _, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
  49. fmt.Printf("repo.init(fail to set git user.name): %v", err)
  50. os.Exit(2)
  51. }
  52. }
  53. // Initialize illegal patterns.
  54. for i := range illegalPatterns[1:] {
  55. pattern := ""
  56. for j := range illegalPatterns[i+1] {
  57. pattern += "[" + string(illegalPatterns[i+1][j]-32) + string(illegalPatterns[i+1][j]) + "]"
  58. }
  59. illegalPatterns[i+1] = pattern
  60. }
  61. }
  62. // Repository represents a git repository.
  63. type Repository struct {
  64. Id int64
  65. OwnerId int64 `xorm:"unique(s)"`
  66. ForkId int64
  67. LowerName string `xorm:"unique(s) index not null"`
  68. Name string `xorm:"index not null"`
  69. Description string
  70. Website string
  71. Private bool
  72. NumWatches int
  73. NumStars int
  74. NumForks int
  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]", "user", "help", "stars", "issues", "pulls", "commits", "admin", "repo", "template"}
  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. Private: private,
  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.Name,
  141. RepoName: 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. return repo, NewRepoAction(user, repo)
  173. }
  174. // extractGitBareZip extracts git-bare.zip to repository path.
  175. func extractGitBareZip(repoPath string) error {
  176. z, err := zip.Open("conf/content/git-bare.zip")
  177. if err != nil {
  178. fmt.Println("shi?")
  179. return err
  180. }
  181. defer z.Close()
  182. return z.ExtractTo(repoPath)
  183. }
  184. // initRepoCommit temporarily changes with work directory.
  185. func initRepoCommit(tmpPath string, sig *git.Signature) error {
  186. gitInitLocker.Lock()
  187. defer gitInitLocker.Unlock()
  188. // Change work directory.
  189. curPath, err := os.Getwd()
  190. if err != nil {
  191. return err
  192. } else if err = os.Chdir(tmpPath); err != nil {
  193. return err
  194. }
  195. defer os.Chdir(curPath)
  196. var stderr string
  197. if _, stderr, err = com.ExecCmd("git", "add", "--all"); err != nil {
  198. return err
  199. }
  200. log.Info("stderr(1): %s", stderr)
  201. if _, stderr, err = com.ExecCmd("git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  202. "-m", "Init commit"); err != nil {
  203. return err
  204. }
  205. log.Info("stderr(2): %s", stderr)
  206. if _, stderr, err = com.ExecCmd("git", "push", "origin", "master"); err != nil {
  207. return err
  208. }
  209. log.Info("stderr(3): %s", stderr)
  210. return nil
  211. }
  212. // InitRepository initializes README and .gitignore if needed.
  213. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  214. repoPath := RepoPath(user.Name, repo.Name)
  215. // Create bare new repository.
  216. if err := extractGitBareZip(repoPath); err != nil {
  217. return err
  218. }
  219. // hook/post-update
  220. pu, err := os.OpenFile(filepath.Join(repoPath, "hooks", "post-update"), os.O_CREATE|os.O_WRONLY, 0777)
  221. if err != nil {
  222. return err
  223. }
  224. defer pu.Close()
  225. // TODO: Windows .bat
  226. if _, err = pu.WriteString(fmt.Sprintf("#!/usr/bin/env bash\n%s update\n", appPath)); err != nil {
  227. return err
  228. }
  229. // Initialize repository according to user's choice.
  230. fileName := map[string]string{}
  231. if initReadme {
  232. fileName["readme"] = "README.md"
  233. }
  234. if repoLang != "" {
  235. fileName["gitign"] = ".gitignore"
  236. }
  237. if license != "" {
  238. fileName["license"] = "LICENSE"
  239. }
  240. // Clone to temprory path and do the init commit.
  241. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  242. os.MkdirAll(tmpDir, os.ModePerm)
  243. if _, _, err := com.ExecCmd("git", "clone", repoPath, tmpDir); err != nil {
  244. return err
  245. }
  246. // README
  247. if initReadme {
  248. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  249. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  250. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  251. []byte(defaultReadme), 0644); err != nil {
  252. return err
  253. }
  254. }
  255. // .gitignore
  256. if repoLang != "" {
  257. filePath := "conf/gitignore/" + repoLang
  258. if com.IsFile(filePath) {
  259. if _, err := com.Copy(filePath,
  260. filepath.Join(tmpDir, fileName["gitign"])); err != nil {
  261. return err
  262. }
  263. }
  264. }
  265. // LICENSE
  266. if license != "" {
  267. filePath := "conf/license/" + license
  268. if com.IsFile(filePath) {
  269. if _, err := com.Copy(filePath,
  270. filepath.Join(tmpDir, fileName["license"])); err != nil {
  271. return err
  272. }
  273. }
  274. }
  275. if len(fileName) == 0 {
  276. return nil
  277. }
  278. // Apply changes and commit.
  279. if err := initRepoCommit(tmpDir, user.NewGitSig()); err != nil {
  280. return err
  281. }
  282. return nil
  283. }
  284. // GetRepos returns given number of repository objects with offset.
  285. func GetRepos(num, offset int) ([]Repository, error) {
  286. repos := make([]Repository, 0, num)
  287. err := orm.Limit(num, offset).Asc("id").Find(&repos)
  288. return repos, err
  289. }
  290. func RepoPath(userName, repoName string) string {
  291. return filepath.Join(UserPath(userName), repoName+".git")
  292. }
  293. // DeleteRepository deletes a repository for a user or orgnaztion.
  294. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  295. repo := &Repository{Id: repoId, OwnerId: userId}
  296. has, err := orm.Get(repo)
  297. if err != nil {
  298. return err
  299. } else if !has {
  300. return ErrRepoNotExist
  301. }
  302. session := orm.NewSession()
  303. if err = session.Begin(); err != nil {
  304. return err
  305. }
  306. if _, err = session.Delete(&Repository{Id: repoId}); err != nil {
  307. session.Rollback()
  308. return err
  309. }
  310. if _, err := session.Delete(&Access{UserName: userName, RepoName: repo.Name}); err != nil {
  311. session.Rollback()
  312. return err
  313. }
  314. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  315. if _, err = session.Exec(rawSql, userId); err != nil {
  316. session.Rollback()
  317. return err
  318. }
  319. if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil {
  320. session.Rollback()
  321. return err
  322. }
  323. if err = session.Commit(); err != nil {
  324. session.Rollback()
  325. return err
  326. }
  327. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  328. // TODO: log and delete manully
  329. log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
  330. return err
  331. }
  332. return nil
  333. }
  334. // GetRepositoryByName returns the repository by given name under user if exists.
  335. func GetRepositoryByName(user *User, repoName string) (*Repository, error) {
  336. repo := &Repository{
  337. OwnerId: user.Id,
  338. LowerName: strings.ToLower(repoName),
  339. }
  340. has, err := orm.Get(repo)
  341. if err != nil {
  342. return nil, err
  343. } else if !has {
  344. return nil, ErrRepoNotExist
  345. }
  346. return repo, err
  347. }
  348. // GetRepositoryById returns the repository by given id if exists.
  349. func GetRepositoryById(id int64) (repo *Repository, err error) {
  350. has, err := orm.Id(id).Get(repo)
  351. if err != nil {
  352. return nil, err
  353. } else if !has {
  354. return nil, ErrRepoNotExist
  355. }
  356. return repo, err
  357. }
  358. // GetRepositories returns the list of repositories of given user.
  359. func GetRepositories(user *User) ([]Repository, error) {
  360. repos := make([]Repository, 0, 10)
  361. err := orm.Desc("updated").Find(&repos, &Repository{OwnerId: user.Id})
  362. return repos, err
  363. }
  364. func GetRepositoryCount(user *User) (int64, error) {
  365. return orm.Count(&Repository{OwnerId: user.Id})
  366. }
  367. // Watch is connection request for receiving repository notifycation.
  368. type Watch struct {
  369. Id int64
  370. RepoId int64 `xorm:"UNIQUE(watch)"`
  371. UserId int64 `xorm:"UNIQUE(watch)"`
  372. }
  373. // Watch or unwatch repository.
  374. func WatchRepo(userId, repoId int64, watch bool) (err error) {
  375. if watch {
  376. _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId})
  377. } else {
  378. _, err = orm.Delete(&Watch{0, repoId, userId})
  379. }
  380. return err
  381. }
  382. // GetWatches returns all watches of given repository.
  383. func GetWatches(repoId int64) ([]Watch, error) {
  384. watches := make([]Watch, 0, 10)
  385. err := orm.Find(&watches, &Watch{RepoId: repoId})
  386. return watches, err
  387. }
  388. // IsWatching checks if user has watched given repository.
  389. func IsWatching(userId, repoId int64) bool {
  390. has, _ := orm.Get(&Watch{0, repoId, userId})
  391. return has
  392. }
  393. func StarReposiory(user *User, repoName string) error {
  394. return nil
  395. }
  396. func UnStarRepository() {
  397. }
  398. func WatchRepository() {
  399. }
  400. func UnWatchRepository() {
  401. }
  402. func ForkRepository(reposName string, userId int64) {
  403. }
  404. // RepoFile represents a file object in git repository.
  405. type RepoFile struct {
  406. *git.TreeEntry
  407. Path string
  408. Size int64
  409. Repo *git.Repository
  410. Commit *git.Commit
  411. }
  412. // LookupBlob returns the content of an object.
  413. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  414. if file.Repo == nil {
  415. return nil, ErrRepoFileNotLoaded
  416. }
  417. return file.Repo.LookupBlob(file.Id)
  418. }
  419. // GetBranches returns all branches of given repository.
  420. func GetBranches(userName, reposName string) ([]string, error) {
  421. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  422. if err != nil {
  423. return nil, err
  424. }
  425. refs, err := repo.AllReferences()
  426. if err != nil {
  427. return nil, err
  428. }
  429. brs := make([]string, len(refs))
  430. for i, ref := range refs {
  431. brs[i] = ref.Name
  432. }
  433. return brs, nil
  434. }
  435. func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
  436. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  437. if err != nil {
  438. return nil, err
  439. }
  440. commit, err := repo.GetCommit(branchName, commitId)
  441. if err != nil {
  442. return nil, err
  443. }
  444. parts := strings.Split(path.Clean(rpath), "/")
  445. var entry *git.TreeEntry
  446. tree := commit.Tree
  447. for i, part := range parts {
  448. if i == len(parts)-1 {
  449. entry = tree.EntryByName(part)
  450. if entry == nil {
  451. return nil, ErrRepoFileNotExist
  452. }
  453. } else {
  454. tree, err = repo.SubTree(tree, part)
  455. if err != nil {
  456. return nil, err
  457. }
  458. }
  459. }
  460. size, err := repo.ObjectSize(entry.Id)
  461. if err != nil {
  462. return nil, err
  463. }
  464. repoFile := &RepoFile{
  465. entry,
  466. rpath,
  467. size,
  468. repo,
  469. commit,
  470. }
  471. return repoFile, nil
  472. }
  473. // GetReposFiles returns a list of file object in given directory of repository.
  474. func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
  475. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  476. if err != nil {
  477. return nil, err
  478. }
  479. commit, err := repo.GetCommit(branchName, commitId)
  480. if err != nil {
  481. return nil, err
  482. }
  483. var repodirs []*RepoFile
  484. var repofiles []*RepoFile
  485. commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  486. if dirname == rpath {
  487. // TODO: size get method shoule be improved
  488. size, err := repo.ObjectSize(entry.Id)
  489. if err != nil {
  490. return 0
  491. }
  492. var cm = commit
  493. var i int
  494. for {
  495. i = i + 1
  496. //fmt.Println(".....", i, cm.Id(), cm.ParentCount())
  497. if cm.ParentCount() == 0 {
  498. break
  499. } else if cm.ParentCount() == 1 {
  500. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  501. if pt == nil {
  502. break
  503. }
  504. pEntry := pt.EntryByName(entry.Name)
  505. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  506. break
  507. } else {
  508. cm = cm.Parent(0)
  509. }
  510. } else {
  511. var emptyCnt = 0
  512. var sameIdcnt = 0
  513. var lastSameCm *git.Commit
  514. //fmt.Println(".....", cm.ParentCount())
  515. for i := 0; i < cm.ParentCount(); i++ {
  516. //fmt.Println("parent", i, cm.Parent(i).Id())
  517. p := cm.Parent(i)
  518. pt, _ := repo.SubTree(p.Tree, dirname)
  519. var pEntry *git.TreeEntry
  520. if pt != nil {
  521. pEntry = pt.EntryByName(entry.Name)
  522. }
  523. //fmt.Println("pEntry", pEntry)
  524. if pEntry == nil {
  525. emptyCnt = emptyCnt + 1
  526. if emptyCnt+sameIdcnt == cm.ParentCount() {
  527. if lastSameCm == nil {
  528. goto loop
  529. } else {
  530. cm = lastSameCm
  531. break
  532. }
  533. }
  534. } else {
  535. //fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
  536. if !pEntry.Id.Equal(entry.Id) {
  537. goto loop
  538. } else {
  539. lastSameCm = cm.Parent(i)
  540. sameIdcnt = sameIdcnt + 1
  541. if emptyCnt+sameIdcnt == cm.ParentCount() {
  542. // TODO: now follow the first parent commit?
  543. cm = lastSameCm
  544. //fmt.Println("sameId...")
  545. break
  546. }
  547. }
  548. }
  549. }
  550. }
  551. }
  552. loop:
  553. rp := &RepoFile{
  554. entry,
  555. path.Join(dirname, entry.Name),
  556. size,
  557. repo,
  558. cm,
  559. }
  560. if entry.IsFile() {
  561. repofiles = append(repofiles, rp)
  562. } else if entry.IsDir() {
  563. repodirs = append(repodirs, rp)
  564. }
  565. }
  566. return 0
  567. })
  568. return append(repodirs, repofiles...), nil
  569. }
  570. func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
  571. repo, err := git.OpenRepository(RepoPath(userName, repoName))
  572. if err != nil {
  573. return nil, err
  574. }
  575. return repo.GetCommit(branchname, commitid)
  576. }
  577. // GetCommits returns all commits of given branch of repository.
  578. func GetCommits(userName, reposName, branchname string) (*list.List, error) {
  579. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  580. if err != nil {
  581. return nil, err
  582. }
  583. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  584. if err != nil {
  585. return nil, err
  586. }
  587. return r.AllCommits()
  588. }