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 27 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
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  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 errors.New("UnpackRefs: " + err.Error())
  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(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  224. repo, err := CreateRepository(u, 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(u.Name, name)
  232. repo.IsBare = false
  233. if mirror {
  234. if err = MirrorRepository(repo.Id, u.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(filepath.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 organization.
  399. func CreateRepository(u *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(u, name)
  404. if err != nil {
  405. return nil, err
  406. } else if isExist {
  407. return nil, ErrRepoAlreadyExist
  408. }
  409. sess := x.NewSession()
  410. defer sess.Close()
  411. if err = sess.Begin(); err != nil {
  412. return nil, err
  413. }
  414. repo := &Repository{
  415. OwnerId: u.Id,
  416. Owner: u,
  417. Name: name,
  418. LowerName: strings.ToLower(name),
  419. Description: desc,
  420. IsPrivate: private,
  421. IsBare: lang == "" && license == "" && !initReadme,
  422. }
  423. if !repo.IsBare {
  424. repo.DefaultBranch = "master"
  425. }
  426. if _, err = sess.Insert(repo); err != nil {
  427. sess.Rollback()
  428. return nil, err
  429. }
  430. var t *Team // Owner team.
  431. mode := WRITABLE
  432. if mirror {
  433. mode = READABLE
  434. }
  435. access := &Access{
  436. UserName: u.LowerName,
  437. RepoName: strings.ToLower(path.Join(u.Name, repo.Name)),
  438. Mode: mode,
  439. }
  440. // Give access to all members in owner team.
  441. if u.IsOrganization() {
  442. t, err = u.GetOwnerTeam()
  443. if err != nil {
  444. sess.Rollback()
  445. return nil, err
  446. }
  447. us, err := GetTeamMembers(u.Id, t.Id)
  448. if err != nil {
  449. sess.Rollback()
  450. return nil, err
  451. }
  452. for _, u := range us {
  453. access.UserName = u.LowerName
  454. if _, err = sess.Insert(access); err != nil {
  455. sess.Rollback()
  456. return nil, err
  457. }
  458. }
  459. } else {
  460. if _, err = sess.Insert(access); err != nil {
  461. sess.Rollback()
  462. return nil, err
  463. }
  464. }
  465. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  466. if _, err = sess.Exec(rawSql, u.Id); err != nil {
  467. sess.Rollback()
  468. return nil, err
  469. }
  470. // Update owner team info and count.
  471. if u.IsOrganization() {
  472. t.RepoIds += "$" + base.ToStr(repo.Id) + "|"
  473. t.NumRepos++
  474. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  475. sess.Rollback()
  476. return nil, err
  477. }
  478. }
  479. if err = sess.Commit(); err != nil {
  480. return nil, err
  481. }
  482. if u.IsOrganization() {
  483. ous, err := GetOrgUsersByOrgId(u.Id)
  484. if err != nil {
  485. log.Error("repo.CreateRepository(GetOrgUsersByOrgId): %v", err)
  486. } else {
  487. for _, ou := range ous {
  488. if err = WatchRepo(ou.Uid, repo.Id, true); err != nil {
  489. log.Error("repo.CreateRepository(WatchRepo): %v", err)
  490. }
  491. }
  492. }
  493. }
  494. if err = WatchRepo(u.Id, repo.Id, true); err != nil {
  495. log.Error("repo.CreateRepository(WatchRepo2): %v", err)
  496. }
  497. if err = NewRepoAction(u, repo); err != nil {
  498. log.Error("repo.CreateRepository(NewRepoAction): %v", err)
  499. }
  500. // No need for init for mirror.
  501. if mirror {
  502. return repo, nil
  503. }
  504. repoPath := RepoPath(u.Name, repo.Name)
  505. if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil {
  506. if err2 := os.RemoveAll(repoPath); err2 != nil {
  507. log.Error("repo.CreateRepository(initRepository): %v", err)
  508. return nil, errors.New(fmt.Sprintf(
  509. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2))
  510. }
  511. return nil, err
  512. }
  513. _, stderr, err := process.ExecDir(
  514. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  515. "git", "update-server-info")
  516. if err != nil {
  517. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  518. }
  519. return repo, nil
  520. }
  521. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  522. // It also auto-gets corresponding users.
  523. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  524. repos := make([]*Repository, 0, num)
  525. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  526. return nil, err
  527. }
  528. for _, repo := range repos {
  529. repo.Owner = &User{Id: repo.OwnerId}
  530. has, err := x.Get(repo.Owner)
  531. if err != nil {
  532. return nil, err
  533. } else if !has {
  534. return nil, ErrUserNotExist
  535. }
  536. }
  537. return repos, nil
  538. }
  539. // RepoPath returns repository path by given user and repository name.
  540. func RepoPath(userName, repoName string) string {
  541. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  542. }
  543. // TransferOwnership transfers all corresponding setting from old user to new one.
  544. func TransferOwnership(u *User, newOwner string, repo *Repository) (err error) {
  545. newUser, err := GetUserByName(newOwner)
  546. if err != nil {
  547. return err
  548. }
  549. // Update accesses.
  550. /*accesses := make([]Access, 0, 10)
  551. if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repo.LowerName}); err != nil {
  552. return err
  553. }*/
  554. sess := x.NewSession()
  555. defer sess.Close()
  556. if err = sess.Begin(); err != nil {
  557. return err
  558. }
  559. access := &Access{
  560. RepoName: newUser.LowerName + "/" + repo.LowerName,
  561. }
  562. sess.Where("repo_name = ?", u.LowerName+"/"+repo.LowerName)
  563. _, err = sess.And("user_name = ?", u.LowerName).Update(&Access{UserName: newUser.LowerName})
  564. if err != nil {
  565. sess.Rollback()
  566. return err
  567. }
  568. _, err = sess.Where("repo_name = ?", u.LowerName+"/"+repo.LowerName).Update(access)
  569. if err != nil {
  570. sess.Rollback()
  571. return err
  572. }
  573. /*
  574. for i := range accesses {
  575. accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
  576. if accesses[i].UserName == u.LowerName {
  577. accesses[i].UserName = newUser.LowerName
  578. }
  579. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  580. return err
  581. }
  582. }*/
  583. // Update repository.
  584. repo.OwnerId = newUser.Id
  585. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  586. sess.Rollback()
  587. return err
  588. }
  589. // Update user repository number.
  590. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
  591. if _, err = sess.Exec(rawSql, newUser.Id); err != nil {
  592. sess.Rollback()
  593. return err
  594. }
  595. rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  596. if _, err = sess.Exec(rawSql, u.Id); err != nil {
  597. sess.Rollback()
  598. return err
  599. }
  600. // Add watch of new owner to repository.
  601. if !IsWatching(newUser.Id, repo.Id) {
  602. if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
  603. sess.Rollback()
  604. return err
  605. }
  606. }
  607. if err = TransferRepoAction(u, newUser, repo); err != nil {
  608. sess.Rollback()
  609. return err
  610. }
  611. // Change repository directory name.
  612. if err = os.Rename(RepoPath(u.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  613. sess.Rollback()
  614. return err
  615. }
  616. return sess.Commit()
  617. }
  618. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  619. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  620. // Update accesses.
  621. accesses := make([]Access, 0, 10)
  622. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
  623. return err
  624. }
  625. sess := x.NewSession()
  626. defer sess.Close()
  627. if err = sess.Begin(); err != nil {
  628. return err
  629. }
  630. for i := range accesses {
  631. accesses[i].RepoName = userName + "/" + newRepoName
  632. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  633. return err
  634. }
  635. }
  636. // Change repository directory name.
  637. if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil {
  638. sess.Rollback()
  639. return err
  640. }
  641. return sess.Commit()
  642. }
  643. func UpdateRepository(repo *Repository) error {
  644. repo.LowerName = strings.ToLower(repo.Name)
  645. if len(repo.Description) > 255 {
  646. repo.Description = repo.Description[:255]
  647. }
  648. if len(repo.Website) > 255 {
  649. repo.Website = repo.Website[:255]
  650. }
  651. _, err := x.Id(repo.Id).AllCols().Update(repo)
  652. return err
  653. }
  654. // DeleteRepository deletes a repository for a user or orgnaztion.
  655. func DeleteRepository(userId, repoId int64, userName string) error {
  656. repo := &Repository{Id: repoId, OwnerId: userId}
  657. has, err := x.Get(repo)
  658. if err != nil {
  659. return err
  660. } else if !has {
  661. return ErrRepoNotExist
  662. }
  663. sess := x.NewSession()
  664. defer sess.Close()
  665. if err = sess.Begin(); err != nil {
  666. return err
  667. }
  668. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  669. sess.Rollback()
  670. return err
  671. }
  672. if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
  673. sess.Rollback()
  674. return err
  675. }
  676. if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  677. sess.Rollback()
  678. return err
  679. }
  680. if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  681. sess.Rollback()
  682. return err
  683. }
  684. if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  685. sess.Rollback()
  686. return err
  687. }
  688. if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  689. sess.Rollback()
  690. return err
  691. }
  692. if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  693. sess.Rollback()
  694. return err
  695. }
  696. if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  697. sess.Rollback()
  698. return err
  699. }
  700. // Delete comments.
  701. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  702. issue := bean.(*Issue)
  703. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  704. sess.Rollback()
  705. return err
  706. }
  707. return nil
  708. }); err != nil {
  709. sess.Rollback()
  710. return err
  711. }
  712. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  713. sess.Rollback()
  714. return err
  715. }
  716. rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
  717. if _, err = sess.Exec(rawSql, userId); err != nil {
  718. sess.Rollback()
  719. return err
  720. }
  721. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  722. sess.Rollback()
  723. return err
  724. }
  725. return sess.Commit()
  726. }
  727. // GetRepositoryByName returns the repository by given name under user if exists.
  728. func GetRepositoryByName(userId int64, repoName string) (*Repository, error) {
  729. repo := &Repository{
  730. OwnerId: userId,
  731. LowerName: strings.ToLower(repoName),
  732. }
  733. has, err := x.Get(repo)
  734. if err != nil {
  735. return nil, err
  736. } else if !has {
  737. return nil, ErrRepoNotExist
  738. }
  739. return repo, err
  740. }
  741. // GetRepositoryById returns the repository by given id if exists.
  742. func GetRepositoryById(id int64) (*Repository, error) {
  743. repo := &Repository{}
  744. has, err := x.Id(id).Get(repo)
  745. if err != nil {
  746. return nil, err
  747. } else if !has {
  748. return nil, ErrRepoNotExist
  749. }
  750. return repo, nil
  751. }
  752. // GetRepositories returns a list of repositories of given user.
  753. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  754. repos := make([]*Repository, 0, 10)
  755. sess := x.Desc("updated")
  756. if !private {
  757. sess.Where("is_private=?", false)
  758. }
  759. err := sess.Find(&repos, &Repository{OwnerId: uid})
  760. return repos, err
  761. }
  762. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  763. func GetRecentUpdatedRepositories() (repos []*Repository, err error) {
  764. err = x.Where("is_private=?", false).Limit(5).Desc("updated").Find(&repos)
  765. return repos, err
  766. }
  767. // GetRepositoryCount returns the total number of repositories of user.
  768. func GetRepositoryCount(user *User) (int64, error) {
  769. return x.Count(&Repository{OwnerId: user.Id})
  770. }
  771. // GetCollaboratorNames returns a list of user name of repository's collaborators.
  772. func GetCollaboratorNames(repoName string) ([]string, error) {
  773. accesses := make([]*Access, 0, 10)
  774. if err := x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  775. return nil, err
  776. }
  777. names := make([]string, len(accesses))
  778. for i := range accesses {
  779. names[i] = accesses[i].UserName
  780. }
  781. return names, nil
  782. }
  783. // GetCollaborativeRepos returns a list of repositories that user is collaborator.
  784. func GetCollaborativeRepos(uname string) ([]*Repository, error) {
  785. uname = strings.ToLower(uname)
  786. accesses := make([]*Access, 0, 10)
  787. if err := x.Find(&accesses, &Access{UserName: uname}); err != nil {
  788. return nil, err
  789. }
  790. repos := make([]*Repository, 0, 10)
  791. for _, access := range accesses {
  792. infos := strings.Split(access.RepoName, "/")
  793. if infos[0] == uname {
  794. continue
  795. }
  796. u, err := GetUserByName(infos[0])
  797. if err != nil {
  798. return nil, err
  799. }
  800. repo, err := GetRepositoryByName(u.Id, infos[1])
  801. if err != nil {
  802. return nil, err
  803. }
  804. repo.Owner = u
  805. repos = append(repos, repo)
  806. }
  807. return repos, nil
  808. }
  809. // GetCollaborators returns a list of users of repository's collaborators.
  810. func GetCollaborators(repoName string) (us []*User, err error) {
  811. accesses := make([]*Access, 0, 10)
  812. if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil {
  813. return nil, err
  814. }
  815. us = make([]*User, len(accesses))
  816. for i := range accesses {
  817. us[i], err = GetUserByName(accesses[i].UserName)
  818. if err != nil {
  819. return nil, err
  820. }
  821. }
  822. return us, nil
  823. }
  824. // Watch is connection request for receiving repository notifycation.
  825. type Watch struct {
  826. Id int64
  827. UserId int64 `xorm:"UNIQUE(watch)"`
  828. RepoId int64 `xorm:"UNIQUE(watch)"`
  829. }
  830. // Watch or unwatch repository.
  831. func WatchRepo(uid, rid int64, watch bool) (err error) {
  832. if watch {
  833. if _, err = x.Insert(&Watch{RepoId: rid, UserId: uid}); err != nil {
  834. return err
  835. }
  836. rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?"
  837. _, err = x.Exec(rawSql, rid)
  838. } else {
  839. if _, err = x.Delete(&Watch{0, uid, rid}); err != nil {
  840. return err
  841. }
  842. rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?"
  843. _, err = x.Exec(rawSql, rid)
  844. }
  845. return err
  846. }
  847. // GetWatchers returns all watchers of given repository.
  848. func GetWatchers(rid int64) ([]*Watch, error) {
  849. watches := make([]*Watch, 0, 10)
  850. err := x.Find(&watches, &Watch{RepoId: rid})
  851. return watches, err
  852. }
  853. // NotifyWatchers creates batch of actions for every watcher.
  854. func NotifyWatchers(act *Action) error {
  855. // Add feeds for user self and all watchers.
  856. watches, err := GetWatchers(act.RepoId)
  857. if err != nil {
  858. return errors.New("repo.NotifyWatchers(get watches): " + err.Error())
  859. }
  860. // Add feed for actioner.
  861. act.UserId = act.ActUserId
  862. if _, err = x.InsertOne(act); err != nil {
  863. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  864. }
  865. for i := range watches {
  866. if act.ActUserId == watches[i].UserId {
  867. continue
  868. }
  869. act.Id = 0
  870. act.UserId = watches[i].UserId
  871. if _, err = x.InsertOne(act); err != nil {
  872. return errors.New("repo.NotifyWatchers(create action): " + err.Error())
  873. }
  874. }
  875. return nil
  876. }
  877. // IsWatching checks if user has watched given repository.
  878. func IsWatching(uid, rid int64) bool {
  879. has, _ := x.Get(&Watch{0, uid, rid})
  880. return has
  881. }
  882. func ForkRepository(repoName string, uid int64) {
  883. }