You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 26 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. "path"
  11. "path/filepath"
  12. "sort"
  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/bin"
  21. "github.com/gogits/gogs/modules/log"
  22. "github.com/gogits/gogs/modules/process"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. const (
  26. TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3\n"
  27. )
  28. var (
  29. ErrRepoAlreadyExist = errors.New("Repository already exist")
  30. ErrRepoNotExist = errors.New("Repository does not exist")
  31. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  32. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  33. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  34. ErrMirrorNotExist = errors.New("Mirror does not exist")
  35. )
  36. var (
  37. LanguageIgns, Licenses []string
  38. )
  39. // getAssetList returns corresponding asset list in 'conf'.
  40. func getAssetList(prefix string) []string {
  41. assets := make([]string, 0, 15)
  42. for _, name := range bin.AssetNames() {
  43. if strings.HasPrefix(name, prefix) {
  44. assets = append(assets, strings.TrimPrefix(name, prefix+"/"))
  45. }
  46. }
  47. return assets
  48. }
  49. func LoadRepoConfig() {
  50. // Load .gitignore and license files.
  51. types := []string{"gitignore", "license"}
  52. typeFiles := make([][]string, 2)
  53. for i, t := range types {
  54. files := getAssetList(path.Join("conf", t))
  55. customPath := path.Join(setting.CustomPath, "conf", t)
  56. if com.IsDir(customPath) {
  57. customFiles, err := com.StatDir(customPath)
  58. if err != nil {
  59. log.Fatal("Fail to get custom %s files: %v", t, err)
  60. }
  61. for _, f := range customFiles {
  62. if !com.IsSliceContainsStr(files, f) {
  63. files = append(files, f)
  64. }
  65. }
  66. }
  67. typeFiles[i] = files
  68. }
  69. LanguageIgns = typeFiles[0]
  70. Licenses = typeFiles[1]
  71. sort.Strings(LanguageIgns)
  72. sort.Strings(Licenses)
  73. }
  74. func NewRepoContext() {
  75. zip.Verbose = false
  76. // Check if server has basic git setting.
  77. stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", "user.name")
  78. if strings.Contains(stderr, "fatal:") {
  79. log.Fatal("repo.NewRepoContext(fail to get git user.name): %s", stderr)
  80. } else if err != nil || len(strings.TrimSpace(stdout)) == 0 {
  81. if _, stderr, err = process.Exec("NewRepoContext(set email)", "git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil {
  82. log.Fatal("repo.NewRepoContext(fail to set git user.email): %s", stderr)
  83. } else if _, stderr, err = process.Exec("NewRepoContext(set name)", "git", "config", "--global", "user.name", "Gogs"); err != nil {
  84. log.Fatal("repo.NewRepoContext(fail to set git user.name): %s", stderr)
  85. }
  86. }
  87. barePath := path.Join(setting.RepoRootPath, "git-bare.zip")
  88. if !com.IsExist(barePath) {
  89. data, err := bin.Asset("conf/content/git-bare.zip")
  90. if err != nil {
  91. log.Fatal("Fail to get asset 'git-bare.zip': %v", err)
  92. } else if err := ioutil.WriteFile(barePath, data, os.ModePerm); err != nil {
  93. log.Fatal("Fail to write asset 'git-bare.zip': %v", err)
  94. }
  95. }
  96. }
  97. // Repository represents a git repository.
  98. type Repository struct {
  99. Id int64
  100. OwnerId int64 `xorm:"UNIQUE(s)"`
  101. Owner *User `xorm:"-"`
  102. ForkId int64
  103. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  104. Name string `xorm:"INDEX NOT NULL"`
  105. Description string
  106. Website string
  107. NumWatches int
  108. NumStars int
  109. NumForks int
  110. NumIssues int
  111. NumClosedIssues int
  112. NumOpenIssues int `xorm:"-"`
  113. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  114. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  115. NumOpenMilestones int `xorm:"-"`
  116. NumTags int `xorm:"-"`
  117. IsPrivate bool
  118. IsMirror bool
  119. IsBare bool
  120. IsGoget bool
  121. DefaultBranch string
  122. Created time.Time `xorm:"CREATED"`
  123. Updated time.Time `xorm:"UPDATED"`
  124. }
  125. func (repo *Repository) GetOwner() (err error) {
  126. repo.Owner, err = GetUserById(repo.OwnerId)
  127. return err
  128. }
  129. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  130. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  131. repo := Repository{OwnerId: u.Id}
  132. has, err := x.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  133. if err != nil {
  134. return has, err
  135. } else if !has {
  136. return false, nil
  137. }
  138. return com.IsDir(RepoPath(u.Name, repoName)), nil
  139. }
  140. var (
  141. illegalEquals = []string{"raw", "install", "api", "avatar", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"}
  142. illegalSuffixs = []string{".git"}
  143. )
  144. // IsLegalName returns false if name contains illegal characters.
  145. func IsLegalName(repoName string) bool {
  146. repoName = strings.ToLower(repoName)
  147. for _, char := range illegalEquals {
  148. if repoName == char {
  149. return false
  150. }
  151. }
  152. for _, char := range illegalSuffixs {
  153. if strings.HasSuffix(repoName, char) {
  154. return false
  155. }
  156. }
  157. return true
  158. }
  159. // Mirror represents a mirror information of repository.
  160. type Mirror struct {
  161. Id int64
  162. RepoId int64
  163. RepoName string // <user name>/<repo name>
  164. Interval int // Hour.
  165. Updated time.Time `xorm:"UPDATED"`
  166. NextUpdate time.Time
  167. }
  168. // MirrorRepository creates a mirror repository from source.
  169. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  170. // TODO: need timeout.
  171. _, stderr, err := process.Exec(fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  172. "git", "clone", "--mirror", url, repoPath)
  173. if err != nil {
  174. return errors.New("git clone --mirror: " + stderr)
  175. }
  176. if _, err = x.InsertOne(&Mirror{
  177. RepoId: repoId,
  178. RepoName: strings.ToLower(userName + "/" + repoName),
  179. Interval: 24,
  180. NextUpdate: time.Now().Add(24 * time.Hour),
  181. }); err != nil {
  182. return err
  183. }
  184. return git.UnpackRefs(repoPath)
  185. }
  186. func GetMirror(repoId int64) (*Mirror, error) {
  187. m := &Mirror{RepoId: repoId}
  188. has, err := x.Get(m)
  189. if err != nil {
  190. return nil, err
  191. } else if !has {
  192. return nil, ErrMirrorNotExist
  193. }
  194. return m, nil
  195. }
  196. func UpdateMirror(m *Mirror) error {
  197. _, err := x.Id(m.Id).Update(m)
  198. return err
  199. }
  200. // MirrorUpdate checks and updates mirror repositories.
  201. func MirrorUpdate() {
  202. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  203. m := bean.(*Mirror)
  204. if m.NextUpdate.After(time.Now()) {
  205. return nil
  206. }
  207. // TODO: need timeout.
  208. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  209. if _, stderr, err := process.ExecDir(
  210. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  211. "git", "remote", "update"); err != nil {
  212. return errors.New("git remote update: " + stderr)
  213. } else if err = git.UnpackRefs(repoPath); err != nil {
  214. return err
  215. }
  216. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  217. return UpdateMirror(m)
  218. }); err != nil {
  219. log.Error("repo.MirrorUpdate: %v", err)
  220. }
  221. }
  222. // MigrateRepository migrates a existing repository from other project hosting.
  223. func MigrateRepository(user *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  224. repo, err := CreateRepository(user, name, desc, "", "", private, mirror, false)
  225. if err != nil {
  226. return nil, err
  227. }
  228. // Clone to temprory path and do the init commit.
  229. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  230. os.MkdirAll(tmpDir, os.ModePerm)
  231. repoPath := RepoPath(user.Name, name)
  232. repo.IsBare = false
  233. if mirror {
  234. if err = MirrorRepository(repo.Id, user.Name, repo.Name, repoPath, url); err != nil {
  235. return repo, err
  236. }
  237. repo.IsMirror = true
  238. return repo, UpdateRepository(repo)
  239. }
  240. // TODO: need timeout.
  241. // Clone from local repository.
  242. _, stderr, err := process.Exec(
  243. fmt.Sprintf("MigrateRepository(git clone): %s", repoPath),
  244. "git", "clone", repoPath, tmpDir)
  245. if err != nil {
  246. return repo, errors.New("git clone: " + stderr)
  247. }
  248. // TODO: need timeout.
  249. // Pull data from source.
  250. if _, stderr, err = process.ExecDir(
  251. tmpDir, fmt.Sprintf("MigrateRepository(git pull): %s", repoPath),
  252. "git", "pull", url); err != nil {
  253. return repo, errors.New("git pull: " + stderr)
  254. }
  255. // TODO: need timeout.
  256. // Push data to local repository.
  257. if _, stderr, err = process.ExecDir(
  258. tmpDir, fmt.Sprintf("MigrateRepository(git push): %s", repoPath),
  259. "git", "push", "origin", "master"); err != nil {
  260. return repo, errors.New("git push: " + stderr)
  261. }
  262. return repo, UpdateRepository(repo)
  263. }
  264. // extractGitBareZip extracts git-bare.zip to repository path.
  265. func extractGitBareZip(repoPath string) error {
  266. z, err := zip.Open(path.Join(setting.RepoRootPath, "git-bare.zip"))
  267. if err != nil {
  268. return err
  269. }
  270. defer z.Close()
  271. return z.ExtractTo(repoPath)
  272. }
  273. // initRepoCommit temporarily changes with work directory.
  274. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  275. var stderr string
  276. if _, stderr, err = process.ExecDir(
  277. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  278. "git", "add", "--all"); err != nil {
  279. return errors.New("git add: " + stderr)
  280. }
  281. if _, stderr, err = process.ExecDir(
  282. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  283. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  284. "-m", "Init commit"); err != nil {
  285. return errors.New("git commit: " + stderr)
  286. }
  287. if _, stderr, err = process.ExecDir(
  288. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  289. "git", "push", "origin", "master"); err != nil {
  290. return errors.New("git push: " + stderr)
  291. }
  292. return nil
  293. }
  294. func createHookUpdate(hookPath, content string) error {
  295. pu, err := os.OpenFile(hookPath, os.O_CREATE|os.O_WRONLY, 0777)
  296. if err != nil {
  297. return err
  298. }
  299. defer pu.Close()
  300. _, err = pu.WriteString(content)
  301. return err
  302. }
  303. // SetRepoEnvs sets environment variables for command update.
  304. func SetRepoEnvs(userId int64, userName, repoName, repoUserName string) {
  305. os.Setenv("userId", base.ToStr(userId))
  306. os.Setenv("userName", userName)
  307. os.Setenv("repoName", repoName)
  308. os.Setenv("repoUserName", repoUserName)
  309. }
  310. // InitRepository initializes README and .gitignore if needed.
  311. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error {
  312. repoPath := RepoPath(user.Name, repo.Name)
  313. // Create bare new repository.
  314. if err := extractGitBareZip(repoPath); err != nil {
  315. return err
  316. }
  317. rp := strings.NewReplacer("\\", "/", " ", "\\ ")
  318. // hook/post-update
  319. if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"),
  320. fmt.Sprintf(TPL_UPDATE_HOOK, setting.ScriptType,
  321. rp.Replace(appPath))); err != nil {
  322. return err
  323. }
  324. // Initialize repository according to user's choice.
  325. fileName := map[string]string{}
  326. if initReadme {
  327. fileName["readme"] = "README.md"
  328. }
  329. if repoLang != "" {
  330. fileName["gitign"] = ".gitignore"
  331. }
  332. if license != "" {
  333. fileName["license"] = "LICENSE"
  334. }
  335. // Clone to temprory path and do the init commit.
  336. tmpDir := filepath.Join(os.TempDir(), base.ToStr(time.Now().Nanosecond()))
  337. os.MkdirAll(tmpDir, os.ModePerm)
  338. _, stderr, err := process.Exec(
  339. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  340. "git", "clone", repoPath, tmpDir)
  341. if err != nil {
  342. return errors.New("initRepository(git clone): " + stderr)
  343. }
  344. // README
  345. if initReadme {
  346. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  347. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  348. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  349. []byte(defaultReadme), 0644); err != nil {
  350. return err
  351. }
  352. }
  353. // .gitignore
  354. if repoLang != "" {
  355. filePath := "conf/gitignore/" + repoLang
  356. targetPath := path.Join(tmpDir, fileName["gitign"])
  357. data, err := bin.Asset(filePath)
  358. if err == nil {
  359. if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil {
  360. return err
  361. }
  362. } else {
  363. // Check custom files.
  364. filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  365. if com.IsFile(filePath) {
  366. if err := com.Copy(filePath, targetPath); err != nil {
  367. return err
  368. }
  369. }
  370. }
  371. }
  372. // LICENSE
  373. if license != "" {
  374. filePath := "conf/license/" + license
  375. targetPath := path.Join(tmpDir, fileName["license"])
  376. data, err := bin.Asset(filePath)
  377. if err == nil {
  378. if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil {
  379. return err
  380. }
  381. } else {
  382. // Check custom files.
  383. filePath = path.Join(setting.CustomPath, "conf/license", license)
  384. if com.IsFile(filePath) {
  385. if err := com.Copy(filePath, targetPath); err != nil {
  386. return err
  387. }
  388. }
  389. }
  390. }
  391. if len(fileName) == 0 {
  392. return nil
  393. }
  394. SetRepoEnvs(user.Id, user.Name, repo.Name, user.Name)
  395. // Apply changes and commit.
  396. return initRepoCommit(tmpDir, user.NewGitSig())
  397. }
  398. // CreateRepository creates a repository for given user or orgnaziation.
  399. func CreateRepository(user *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
  400. if !IsLegalName(name) {
  401. return nil, ErrRepoNameIllegal
  402. }
  403. isExist, err := IsRepositoryExist(user, name)
  404. if err != nil {
  405. return nil, err
  406. } else if isExist {
  407. return nil, ErrRepoAlreadyExist
  408. }
  409. repo := &Repository{
  410. OwnerId: user.Id,
  411. Name: name,
  412. LowerName: strings.ToLower(name),
  413. Description: desc,
  414. IsPrivate: private,
  415. IsBare: lang == "" && license == "" && !initReadme,
  416. }
  417. if !repo.IsBare {
  418. repo.DefaultBranch = "master"
  419. }
  420. repoPath := RepoPath(user.Name, repo.Name)
  421. sess := x.NewSession()
  422. defer sess.Close()
  423. sess.Begin()
  424. if _, err = sess.Insert(repo); err != nil {
  425. if err2 := os.RemoveAll(repoPath); err2 != nil {
  426. log.Error("repo.CreateRepository(repo): %v", err)
  427. return nil, errors.New(fmt.Sprintf(
  428. "delete repo directory %s/%s failed(1): %v", user.Name, repo.Name, err2))
  429. }
  430. sess.Rollback()
  431. return nil, err
  432. }
  433. mode := AU_WRITABLE
  434. if mirror {
  435. mode = AU_READABLE
  436. }
  437. access := Access{
  438. UserName: user.LowerName,
  439. RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
  440. Mode: mode,
  441. }
  442. if _, err = sess.Insert(&access); err != nil {
  443. sess.Rollback()
  444. if err2 := os.RemoveAll(repoPath); err2 != nil {
  445. log.Error("repo.CreateRepository(access): %v", err)
  446. return nil, errors.New(fmt.Sprintf(
  447. "delete repo directory %s/%s failed(2): %v", user.Name, repo.Name, err2))
  448. }
  449. return nil, err
  450. }
  451. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  452. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  453. sess.Rollback()
  454. if err2 := os.RemoveAll(repoPath); err2 != nil {
  455. log.Error("repo.CreateRepository(repo count): %v", err)
  456. return nil, errors.New(fmt.Sprintf(
  457. "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2))
  458. }
  459. return nil, err
  460. }
  461. if err = sess.Commit(); err != nil {
  462. sess.Rollback()
  463. if err2 := os.RemoveAll(repoPath); err2 != nil {
  464. log.Error("repo.CreateRepository(commit): %v", err)
  465. return nil, errors.New(fmt.Sprintf(
  466. "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2))
  467. }
  468. return nil, err
  469. }
  470. if err = WatchRepo(user.Id, repo.Id, true); err != nil {
  471. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  472. }
  473. if err = NewRepoAction(user, repo); err != nil {
  474. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  475. }
  476. // No need for init for mirror.
  477. if mirror {
  478. return repo, nil
  479. }
  480. if err = initRepository(repoPath, user, repo, initReadme, lang, license); err != nil {
  481. return nil, err
  482. }
  483. _, stderr, err := process.ExecDir(
  484. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  485. "git", "update-server-info")
  486. if err != nil {
  487. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  488. }
  489. return repo, nil
  490. }
  491. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  492. // It also auto-gets corresponding users.
  493. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  494. repos := make([]*Repository, 0, num)
  495. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  496. return nil, err
  497. }
  498. for _, repo := range repos {
  499. repo.Owner = &User{Id: repo.OwnerId}
  500. has, err := x.Get(repo.Owner)
  501. if err != nil {
  502. return nil, err
  503. } else if !has {
  504. return nil, ErrUserNotExist
  505. }
  506. }
  507. return repos, nil
  508. }
  509. // RepoPath returns repository path by given user and repository name.
  510. func RepoPath(userName, repoName string) string {
  511. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  512. }
  513. // TransferOwnership transfers all corresponding setting from old user to new one.
  514. func TransferOwnership(user *User, newOwner string, repo *Repository) (err error) {
  515. newUser, err := GetUserByName(newOwner)
  516. if err != nil {
  517. return err
  518. }
  519. // Update accesses.
  520. accesses := make([]Access, 0, 10)
  521. if err = x.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil {
  522. return err
  523. }
  524. sess := x.NewSession()
  525. defer sess.Close()
  526. if err = sess.Begin(); err != nil {
  527. return err
  528. }
  529. for i := range accesses {
  530. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  531. if accesses[i].UserName == user.LowerName {
  532. accesses[i].UserName = newUser.LowerName
  533. }
  534. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  535. return err
  536. }
  537. }
  538. // Update repository.
  539. repo.OwnerId = newUser.Id
  540. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  541. sess.Rollback()
  542. return err
  543. }
  544. // Update user repository number.
  545. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  546. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  547. sess.Rollback()
  548. return err
  549. }
  550. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  551. if _, err = sess.Exec(rawSql, user.Id); err != nil {
  552. sess.Rollback()
  553. return err
  554. }
  555. // Add watch of new owner to repository.
  556. if !IsWatching(newUser.Id, repo.Id) {
  557. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  558. sess.Rollback()
  559. return err
  560. }
  561. }
  562. if err = TransferRepoAction(user, newUser, repo); err != nil {
  563. sess.Rollback()
  564. return err
  565. }
  566. // Change repository directory name.
  567. if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  568. sess.Rollback()
  569. return err
  570. }
  571. return sess.Commit()
  572. }
  573. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  574. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  575. // Update accesses.
  576. accesses := make([]Access, 0, 10)
  577. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  578. return err
  579. }
  580. sess := x.NewSession()
  581. defer sess.Close()
  582. if err = sess.Begin(); err != nil {
  583. return err
  584. }
  585. for i := range accesses {
  586. accesses[i].RepoName = userName + "/" + newRepoName
  587. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  588. return err
  589. }
  590. }
  591. // Change repository directory name.
  592. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  593. sess.Rollback()
  594. return err
  595. }
  596. return sess.Commit()
  597. }
  598. func UpdateRepository(repo *Repository) error {
  599. repo.LowerName = strings.ToLower(repo.Name)
  600. if len(repo.Description) > 255 {
  601. repo.Description = repo.Description[:255]
  602. }
  603. if len(repo.Website) > 255 {
  604. repo.Website = repo.Website[:255]
  605. }
  606. _, err := x.Id(repo.Id).AllCols().Update(repo)
  607. return err
  608. }
  609. // DeleteRepository deletes a repository for a user or orgnaztion.
  610. func DeleteRepository(userId, repoId int64, userName string) (err error) {
  611. repo := &Repository{Id: repoId, OwnerId: userId}
  612. has, err := x.Get(repo)
  613. if err != nil {
  614. return err
  615. } else if !has {
  616. return ErrRepoNotExist
  617. }
  618. sess := x.NewSession()
  619. defer sess.Close()
  620. if err = sess.Begin(); err != nil {
  621. return err
  622. }
  623. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  624. sess.Rollback()
  625. return err
  626. }
  627. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  628. sess.Rollback()
  629. return err
  630. }
  631. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  632. sess.Rollback()
  633. return err
  634. }
  635. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  636. sess.Rollback()
  637. return err
  638. }
  639. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  640. sess.Rollback()
  641. return err
  642. }
  643. if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  644. sess.Rollback()
  645. return err
  646. }
  647. if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  648. sess.Rollback()
  649. return err
  650. }
  651. if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  652. sess.Rollback()
  653. return err
  654. }
  655. // Delete comments.
  656. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  657. issue := bean.(*Issue)
  658. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  659. sess.Rollback()
  660. return err
  661. }
  662. return nil
  663. }); err != nil {
  664. sess.Rollback()
  665. return err
  666. }
  667. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  668. sess.Rollback()
  669. return err
  670. }
  671. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  672. if _, err = sess.Exec(rawSql, userId); err != nil {
  673. sess.Rollback()
  674. return err
  675. }
  676. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  677. sess.Rollback()
  678. return err
  679. }
  680. return sess.Commit()
  681. }
  682. // GetRepositoryByName returns the repository by given name under user if exists.
  683. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  684. repo := &Repository{
  685. OwnerId: userId,
  686. LowerName: strings.ToLower(repoName),
  687. }
  688. has, err := x.Get(repo)
  689. if err != nil {
  690. return nil, err
  691. } else if !has {
  692. return nil, ErrRepoNotExist
  693. }
  694. return repo, err
  695. }
  696. // GetRepositoryById returns the repository by given id if exists.
  697. func GetRepositoryById(id int64) (*Repository, error) {
  698. repo := &Repository{}
  699. has, err := x.Id(id).Get(repo)
  700. if err != nil {
  701. return nil, err
  702. } else if !has {
  703. return nil, ErrRepoNotExist
  704. }
  705. return repo, nil
  706. }
  707. // GetRepositories returns a list of repositories of given user.
  708. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  709. repos := make([]*Repository, 0, 10)
  710. sess := x.Desc("updated")
  711. if !private {
  712. sess.Where("is_private=?", false)
  713. }
  714. err := sess.Find(&repos, &Repository{OwnerId: uid})
  715. return repos, err
  716. }
  717. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  718. func GetRecentUpdatedRepositories() (repos []*Repository, err error) {
  719. err = x.Where("is_private=?", false).Limit(5).Desc("updated").Find(&repos)
  720. return repos, err
  721. }
  722. // GetRepositoryCount returns the total number of repositories of user.
  723. func GetRepositoryCount(user *User) (int64, error) {
  724. return x.Count(&Repository{OwnerId: user.Id})
  725. }
  726. // GetCollaboratorNames returns a list of user name of repository's collaborators.
  727. func GetCollaboratorNames(repoName string) ([]string, error) {
  728. accesses := make([]*Access, 0, 10)
  729. if err := x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  730. return nil, err
  731. }
  732. names := make([]string, len(accesses))
  733. for i := range accesses {
  734. names[i] = accesses[i].UserName
  735. }
  736. return names, nil
  737. }
  738. // GetCollaborativeRepos returns a list of repositories that user is collaborator.
  739. func GetCollaborativeRepos(uname string) ([]*Repository, error) {
  740. uname = strings.ToLower(uname)
  741. accesses := make([]*Access, 0, 10)
  742. if err := x.Find(&accesses, &Access{UserName: uname}); err != nil {
  743. return nil, err
  744. }
  745. repos := make([]*Repository, 0, 10)
  746. for _, access := range accesses {
  747. infos := strings.Split(access.RepoName, "/")
  748. if infos[0] == uname {
  749. continue
  750. }
  751. u, err := GetUserByName(infos[0])
  752. if err != nil {
  753. return nil, err
  754. }
  755. repo, err := GetRepositoryByName(u.Id, infos[1])
  756. if err != nil {
  757. return nil, err
  758. }
  759. repo.Owner = u
  760. repos = append(repos, repo)
  761. }
  762. return repos, nil
  763. }
  764. // GetCollaborators returns a list of users of repository's collaborators.
  765. func GetCollaborators(repoName string) (us []*User, err error) {
  766. accesses := make([]*Access, 0, 10)
  767. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  768. return nil, err
  769. }
  770. us = make([]*User, len(accesses))
  771. for i := range accesses {
  772. us[i], err = GetUserByName(accesses[i].UserName)
  773. if err != nil {
  774. return nil, err
  775. }
  776. }
  777. return us, nil
  778. }
  779. // Watch is connection request for receiving repository notifycation.
  780. type Watch struct {
  781. Id int64
  782. UserId int64 `xorm:"UNIQUE(watch)"`
  783. RepoId int64 `xorm:"UNIQUE(watch)"`
  784. }
  785. // Watch or unwatch repository.
  786. func WatchRepo(uid, rid int64, watch bool) (err error) {
  787. if watch {
  788. if _, err = x.Insert(&Watch{RepoId: rid, UserId: uid}); err != nil {
  789. return err
  790. }
  791. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  792. _, err = x.Exec(rawSql, rid)
  793. } else {
  794. if _, err = x.Delete(&Watch{0, uid, rid}); err != nil {
  795. return err
  796. }
  797. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  798. _, err = x.Exec(rawSql, rid)
  799. }
  800. return err
  801. }
  802. // GetWatchers returns all watchers of given repository.
  803. func GetWatchers(rid int64) ([]*Watch, error) {
  804. watches := make([]*Watch, 0, 10)
  805. err := x.Find(&watches, &Watch{RepoId: rid})
  806. return watches, err
  807. }
  808. // NotifyWatchers creates batch of actions for every watcher.
  809. func NotifyWatchers(act *Action) error {
  810. // Add feeds for user self and all watchers.
  811. watches, err := GetWatchers(act.RepoId)
  812. if err != nil {
  813. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  814. }
  815. // Add feed for actioner.
  816. act.UserId = act.ActUserId
  817. if _, err = x.InsertOne(act); err != nil {
  818. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  819. }
  820. for i := range watches {
  821. if act.ActUserId == watches[i].UserId {
  822. continue
  823. }
  824. act.Id = 0
  825. act.UserId = watches[i].UserId
  826. if _, err = x.InsertOne(act); err != nil {
  827. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  828. }
  829. }
  830. return nil
  831. }
  832. // IsWatching checks if user has watched given repository.
  833. func IsWatching(uid, rid int64) bool {
  834. has, _ := x.Get(&Watch{0, uid, rid})
  835. return has
  836. }
  837. func ForkRepository(repoName string, uid int64) {
  838. }