Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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