repo.go 17 KB

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