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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil {
  377. return err
  378. }
  379. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  380. _, err = orm.Exec(rawSql, repoId)
  381. } else {
  382. if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil {
  383. return err
  384. }
  385. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  386. _, err = orm.Exec(rawSql, repoId)
  387. }
  388. return err
  389. }
  390. // GetWatches returns all watches of given repository.
  391. func GetWatches(repoId int64) ([]Watch, error) {
  392. watches := make([]Watch, 0, 10)
  393. err := orm.Find(&watches, &Watch{RepoId: repoId})
  394. return watches, err
  395. }
  396. // IsWatching checks if user has watched given repository.
  397. func IsWatching(userId, repoId int64) bool {
  398. has, _ := orm.Get(&Watch{0, repoId, userId})
  399. return has
  400. }
  401. func StarReposiory(user *User, repoName string) error {
  402. return nil
  403. }
  404. func UnStarRepository() {
  405. }
  406. func WatchRepository() {
  407. }
  408. func UnWatchRepository() {
  409. }
  410. func ForkRepository(reposName string, userId int64) {
  411. }
  412. // RepoFile represents a file object in git repository.
  413. type RepoFile struct {
  414. *git.TreeEntry
  415. Path string
  416. Size int64
  417. Repo *git.Repository
  418. Commit *git.Commit
  419. }
  420. // LookupBlob returns the content of an object.
  421. func (file *RepoFile) LookupBlob() (*git.Blob, error) {
  422. if file.Repo == nil {
  423. return nil, ErrRepoFileNotLoaded
  424. }
  425. return file.Repo.LookupBlob(file.Id)
  426. }
  427. // GetBranches returns all branches of given repository.
  428. func GetBranches(userName, reposName string) ([]string, error) {
  429. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  430. if err != nil {
  431. return nil, err
  432. }
  433. refs, err := repo.AllReferences()
  434. if err != nil {
  435. return nil, err
  436. }
  437. brs := make([]string, len(refs))
  438. for i, ref := range refs {
  439. brs[i] = ref.Name
  440. }
  441. return brs, nil
  442. }
  443. func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
  444. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  445. if err != nil {
  446. return nil, err
  447. }
  448. commit, err := repo.GetCommit(branchName, commitId)
  449. if err != nil {
  450. return nil, err
  451. }
  452. parts := strings.Split(path.Clean(rpath), "/")
  453. var entry *git.TreeEntry
  454. tree := commit.Tree
  455. for i, part := range parts {
  456. if i == len(parts)-1 {
  457. entry = tree.EntryByName(part)
  458. if entry == nil {
  459. return nil, ErrRepoFileNotExist
  460. }
  461. } else {
  462. tree, err = repo.SubTree(tree, part)
  463. if err != nil {
  464. return nil, err
  465. }
  466. }
  467. }
  468. size, err := repo.ObjectSize(entry.Id)
  469. if err != nil {
  470. return nil, err
  471. }
  472. repoFile := &RepoFile{
  473. entry,
  474. rpath,
  475. size,
  476. repo,
  477. commit,
  478. }
  479. return repoFile, nil
  480. }
  481. // GetReposFiles returns a list of file object in given directory of repository.
  482. func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
  483. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  484. if err != nil {
  485. return nil, err
  486. }
  487. commit, err := repo.GetCommit(branchName, commitId)
  488. if err != nil {
  489. return nil, err
  490. }
  491. var repodirs []*RepoFile
  492. var repofiles []*RepoFile
  493. commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
  494. if dirname == rpath {
  495. // TODO: size get method shoule be improved
  496. size, err := repo.ObjectSize(entry.Id)
  497. if err != nil {
  498. return 0
  499. }
  500. var cm = commit
  501. var i int
  502. for {
  503. i = i + 1
  504. //fmt.Println(".....", i, cm.Id(), cm.ParentCount())
  505. if cm.ParentCount() == 0 {
  506. break
  507. } else if cm.ParentCount() == 1 {
  508. pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
  509. if pt == nil {
  510. break
  511. }
  512. pEntry := pt.EntryByName(entry.Name)
  513. if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
  514. break
  515. } else {
  516. cm = cm.Parent(0)
  517. }
  518. } else {
  519. var emptyCnt = 0
  520. var sameIdcnt = 0
  521. var lastSameCm *git.Commit
  522. //fmt.Println(".....", cm.ParentCount())
  523. for i := 0; i < cm.ParentCount(); i++ {
  524. //fmt.Println("parent", i, cm.Parent(i).Id())
  525. p := cm.Parent(i)
  526. pt, _ := repo.SubTree(p.Tree, dirname)
  527. var pEntry *git.TreeEntry
  528. if pt != nil {
  529. pEntry = pt.EntryByName(entry.Name)
  530. }
  531. //fmt.Println("pEntry", pEntry)
  532. if pEntry == nil {
  533. emptyCnt = emptyCnt + 1
  534. if emptyCnt+sameIdcnt == cm.ParentCount() {
  535. if lastSameCm == nil {
  536. goto loop
  537. } else {
  538. cm = lastSameCm
  539. break
  540. }
  541. }
  542. } else {
  543. //fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
  544. if !pEntry.Id.Equal(entry.Id) {
  545. goto loop
  546. } else {
  547. lastSameCm = cm.Parent(i)
  548. sameIdcnt = sameIdcnt + 1
  549. if emptyCnt+sameIdcnt == cm.ParentCount() {
  550. // TODO: now follow the first parent commit?
  551. cm = lastSameCm
  552. //fmt.Println("sameId...")
  553. break
  554. }
  555. }
  556. }
  557. }
  558. }
  559. }
  560. loop:
  561. rp := &RepoFile{
  562. entry,
  563. path.Join(dirname, entry.Name),
  564. size,
  565. repo,
  566. cm,
  567. }
  568. if entry.IsFile() {
  569. repofiles = append(repofiles, rp)
  570. } else if entry.IsDir() {
  571. repodirs = append(repodirs, rp)
  572. }
  573. }
  574. return 0
  575. })
  576. return append(repodirs, repofiles...), nil
  577. }
  578. func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
  579. repo, err := git.OpenRepository(RepoPath(userName, repoName))
  580. if err != nil {
  581. return nil, err
  582. }
  583. return repo.GetCommit(branchname, commitid)
  584. }
  585. // GetCommits returns all commits of given branch of repository.
  586. func GetCommits(userName, reposName, branchname string) (*list.List, error) {
  587. repo, err := git.OpenRepository(RepoPath(userName, reposName))
  588. if err != nil {
  589. return nil, err
  590. }
  591. r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
  592. if err != nil {
  593. return nil, err
  594. }
  595. return r.AllCommits()
  596. }