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 38 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
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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. "html/template"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/Unknwon/cae/zip"
  20. "github.com/Unknwon/com"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/git"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/process"
  25. "github.com/gogits/gogs/modules/setting"
  26. )
  27. const (
  28. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  29. )
  30. var (
  31. ErrRepoAlreadyExist = errors.New("Repository already exist")
  32. ErrRepoNotExist = errors.New("Repository does not exist")
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoNameIllegal = errors.New("Repository name contains illegal characters")
  35. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  36. ErrMirrorNotExist = errors.New("Mirror does not exist")
  37. ErrInvalidReference = errors.New("Invalid reference specified")
  38. )
  39. var (
  40. Gitignores, Licenses []string
  41. )
  42. var (
  43. DescPattern = regexp.MustCompile(`https?://\S+`)
  44. )
  45. func LoadRepoConfig() {
  46. // Load .gitignore and license files.
  47. types := []string{"gitignore", "license"}
  48. typeFiles := make([][]string, 2)
  49. for i, t := range types {
  50. files, err := com.StatDir(path.Join("conf", t))
  51. if err != nil {
  52. log.Fatal(4, "Fail to get %s files: %v", t, err)
  53. }
  54. customPath := path.Join(setting.CustomPath, "conf", t)
  55. if com.IsDir(customPath) {
  56. customFiles, err := com.StatDir(customPath)
  57. if err != nil {
  58. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  59. }
  60. for _, f := range customFiles {
  61. if !com.IsSliceContainsStr(files, f) {
  62. files = append(files, f)
  63. }
  64. }
  65. }
  66. typeFiles[i] = files
  67. }
  68. Gitignores = typeFiles[0]
  69. Licenses = typeFiles[1]
  70. sort.Strings(Gitignores)
  71. sort.Strings(Licenses)
  72. }
  73. func NewRepoContext() {
  74. zip.Verbose = false
  75. // Check Git installation.
  76. if _, err := exec.LookPath("git"); err != nil {
  77. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  78. }
  79. // Check Git version.
  80. ver, err := git.GetVersion()
  81. if err != nil {
  82. log.Fatal(4, "Fail to get Git version: %v", err)
  83. }
  84. reqVer, err := git.ParseVersion("1.7.1")
  85. if err != nil {
  86. log.Fatal(4, "Fail to parse required Git version: %v", err)
  87. }
  88. if ver.LessThan(reqVer) {
  89. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  90. }
  91. // Check if server has user.email and user.name set correctly and set if they're not.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogitservice@gmail.com"} {
  93. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  94. // ExitError indicates this config is not set
  95. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  96. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  97. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  98. }
  99. log.Info("Git config %s set to %s", configKey, defaultValue)
  100. } else {
  101. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  102. }
  103. }
  104. }
  105. // Set git some configurations.
  106. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  107. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  108. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  109. }
  110. }
  111. // Repository represents a git repository.
  112. type Repository struct {
  113. Id int64
  114. OwnerId int64 `xorm:"UNIQUE(s)"`
  115. Owner *User `xorm:"-"`
  116. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  117. Name string `xorm:"INDEX NOT NULL"`
  118. Description string
  119. Website string
  120. DefaultBranch string
  121. NumWatches int
  122. NumStars int
  123. NumForks int
  124. NumIssues int
  125. NumClosedIssues int
  126. NumOpenIssues int `xorm:"-"`
  127. NumPulls int
  128. NumClosedPulls int
  129. NumOpenPulls int `xorm:"-"`
  130. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  132. NumOpenMilestones int `xorm:"-"`
  133. NumTags int `xorm:"-"`
  134. IsPrivate bool
  135. IsBare bool
  136. IsMirror bool
  137. *Mirror `xorm:"-"`
  138. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  139. ForkId int64
  140. ForkRepo *Repository `xorm:"-"`
  141. Created time.Time `xorm:"CREATED"`
  142. Updated time.Time `xorm:"UPDATED"`
  143. }
  144. func (repo *Repository) getOwner(e Engine) (err error) {
  145. if repo.Owner == nil {
  146. repo.Owner, err = getUserById(e, repo.OwnerId)
  147. }
  148. return err
  149. }
  150. func (repo *Repository) GetOwner() (err error) {
  151. return repo.getOwner(x)
  152. }
  153. func (repo *Repository) GetMirror() (err error) {
  154. repo.Mirror, err = GetMirror(repo.Id)
  155. return err
  156. }
  157. func (repo *Repository) GetForkRepo() (err error) {
  158. if !repo.IsFork {
  159. return nil
  160. }
  161. repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
  162. return err
  163. }
  164. func (repo *Repository) RepoPath() (string, error) {
  165. if err := repo.GetOwner(); err != nil {
  166. return "", err
  167. }
  168. return RepoPath(repo.Owner.Name, repo.Name), nil
  169. }
  170. func (repo *Repository) RepoLink() (string, error) {
  171. if err := repo.GetOwner(); err != nil {
  172. return "", err
  173. }
  174. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  175. }
  176. func (repo *Repository) HasAccess(u *User) bool {
  177. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  178. return has
  179. }
  180. func (repo *Repository) IsOwnedBy(u *User) bool {
  181. return repo.OwnerId == u.Id
  182. }
  183. // DescriptionHtml does special handles to description and return HTML string.
  184. func (repo *Repository) DescriptionHtml() template.HTML {
  185. sanitize := func(s string) string {
  186. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  187. }
  188. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  189. }
  190. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  191. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  192. repo := Repository{OwnerId: u.Id}
  193. has, err := x.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
  194. if err != nil {
  195. return has, err
  196. } else if !has {
  197. return false, nil
  198. }
  199. return com.IsDir(RepoPath(u.Name, repoName)), nil
  200. }
  201. // CloneLink represents different types of clone URLs of repository.
  202. type CloneLink struct {
  203. SSH string
  204. HTTPS string
  205. Git string
  206. }
  207. // CloneLink returns clone URLs of repository.
  208. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  209. if err = repo.GetOwner(); err != nil {
  210. return cl, err
  211. }
  212. if setting.SSHPort != 22 {
  213. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.Domain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  214. } else {
  215. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, repo.Owner.LowerName, repo.LowerName)
  216. }
  217. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  218. return cl, nil
  219. }
  220. var (
  221. illegalEquals = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  222. illegalSuffixs = []string{".git", ".keys"}
  223. )
  224. // IsLegalName returns false if name contains illegal characters.
  225. func IsLegalName(repoName string) bool {
  226. repoName = strings.ToLower(repoName)
  227. for _, char := range illegalEquals {
  228. if repoName == char {
  229. return false
  230. }
  231. }
  232. for _, char := range illegalSuffixs {
  233. if strings.HasSuffix(repoName, char) {
  234. return false
  235. }
  236. }
  237. return true
  238. }
  239. // Mirror represents a mirror information of repository.
  240. type Mirror struct {
  241. Id int64
  242. RepoId int64
  243. RepoName string // <user name>/<repo name>
  244. Interval int // Hour.
  245. Updated time.Time `xorm:"UPDATED"`
  246. NextUpdate time.Time
  247. }
  248. func GetMirror(repoId int64) (*Mirror, error) {
  249. m := &Mirror{RepoId: repoId}
  250. has, err := x.Get(m)
  251. if err != nil {
  252. return nil, err
  253. } else if !has {
  254. return nil, ErrMirrorNotExist
  255. }
  256. return m, nil
  257. }
  258. func UpdateMirror(m *Mirror) error {
  259. _, err := x.Id(m.Id).Update(m)
  260. return err
  261. }
  262. // MirrorRepository creates a mirror repository from source.
  263. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  264. _, stderr, err := process.ExecTimeout(10*time.Minute,
  265. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  266. "git", "clone", "--mirror", url, repoPath)
  267. if err != nil {
  268. return errors.New("git clone --mirror: " + stderr)
  269. }
  270. if _, err = x.InsertOne(&Mirror{
  271. RepoId: repoId,
  272. RepoName: strings.ToLower(userName + "/" + repoName),
  273. Interval: 24,
  274. NextUpdate: time.Now().Add(24 * time.Hour),
  275. }); err != nil {
  276. return err
  277. }
  278. return nil
  279. }
  280. // MigrateRepository migrates a existing repository from other project hosting.
  281. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  282. repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
  283. if err != nil {
  284. return nil, err
  285. }
  286. // Clone to temprory path and do the init commit.
  287. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  288. os.MkdirAll(tmpDir, os.ModePerm)
  289. repoPath := RepoPath(u.Name, name)
  290. if u.IsOrganization() {
  291. t, err := u.GetOwnerTeam()
  292. if err != nil {
  293. return nil, err
  294. }
  295. repo.NumWatches = t.NumMembers
  296. } else {
  297. repo.NumWatches = 1
  298. }
  299. repo.IsBare = false
  300. if mirror {
  301. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  302. return repo, err
  303. }
  304. repo.IsMirror = true
  305. return repo, UpdateRepository(repo)
  306. } else {
  307. os.RemoveAll(repoPath)
  308. }
  309. // FIXME: this command could for both migrate and mirror
  310. _, stderr, err := process.ExecTimeout(10*time.Minute,
  311. fmt.Sprintf("MigrateRepository: %s", repoPath),
  312. "git", "clone", "--mirror", "--bare", url, repoPath)
  313. if err != nil {
  314. return repo, fmt.Errorf("git clone --mirror --bare: %v", stderr)
  315. } else if err = createUpdateHook(repoPath); err != nil {
  316. return repo, fmt.Errorf("create update hook: %v", err)
  317. }
  318. return repo, UpdateRepository(repo)
  319. }
  320. // extractGitBareZip extracts git-bare.zip to repository path.
  321. func extractGitBareZip(repoPath string) error {
  322. z, err := zip.Open(path.Join(setting.ConfRootPath, "content/git-bare.zip"))
  323. if err != nil {
  324. return err
  325. }
  326. defer z.Close()
  327. return z.ExtractTo(repoPath)
  328. }
  329. // initRepoCommit temporarily changes with work directory.
  330. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  331. var stderr string
  332. if _, stderr, err = process.ExecDir(-1,
  333. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  334. "git", "add", "--all"); err != nil {
  335. return errors.New("git add: " + stderr)
  336. }
  337. if _, stderr, err = process.ExecDir(-1,
  338. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  339. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  340. "-m", "Init commit"); err != nil {
  341. return errors.New("git commit: " + stderr)
  342. }
  343. if _, stderr, err = process.ExecDir(-1,
  344. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  345. "git", "push", "origin", "master"); err != nil {
  346. return errors.New("git push: " + stderr)
  347. }
  348. return nil
  349. }
  350. func createUpdateHook(repoPath string) error {
  351. return ioutil.WriteFile(path.Join(repoPath, "hooks/update"),
  352. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  353. }
  354. // InitRepository initializes README and .gitignore if needed.
  355. func initRepository(e Engine, f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error {
  356. repoPath := RepoPath(u.Name, repo.Name)
  357. // Create bare new repository.
  358. if err := extractGitBareZip(repoPath); err != nil {
  359. return err
  360. }
  361. if err := createUpdateHook(repoPath); err != nil {
  362. return err
  363. }
  364. // Initialize repository according to user's choice.
  365. fileName := map[string]string{}
  366. if initReadme {
  367. fileName["readme"] = "README.md"
  368. }
  369. if repoLang != "" {
  370. fileName["gitign"] = ".gitignore"
  371. }
  372. if license != "" {
  373. fileName["license"] = "LICENSE"
  374. }
  375. // Clone to temprory path and do the init commit.
  376. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  377. os.MkdirAll(tmpDir, os.ModePerm)
  378. _, stderr, err := process.Exec(
  379. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  380. "git", "clone", repoPath, tmpDir)
  381. if err != nil {
  382. return errors.New("initRepository(git clone): " + stderr)
  383. }
  384. // README
  385. if initReadme {
  386. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  387. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  388. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  389. []byte(defaultReadme), 0644); err != nil {
  390. return err
  391. }
  392. }
  393. // .gitignore
  394. filePath := "conf/gitignore/" + repoLang
  395. if com.IsFile(filePath) {
  396. targetPath := path.Join(tmpDir, fileName["gitign"])
  397. if com.IsFile(filePath) {
  398. if err = com.Copy(filePath, targetPath); err != nil {
  399. return err
  400. }
  401. } else {
  402. // Check custom files.
  403. filePath = path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  404. if com.IsFile(filePath) {
  405. if err := com.Copy(filePath, targetPath); err != nil {
  406. return err
  407. }
  408. }
  409. }
  410. } else {
  411. delete(fileName, "gitign")
  412. }
  413. // LICENSE
  414. filePath = "conf/license/" + license
  415. if com.IsFile(filePath) {
  416. targetPath := path.Join(tmpDir, fileName["license"])
  417. if com.IsFile(filePath) {
  418. if err = com.Copy(filePath, targetPath); err != nil {
  419. return err
  420. }
  421. } else {
  422. // Check custom files.
  423. filePath = path.Join(setting.CustomPath, "conf/license", license)
  424. if com.IsFile(filePath) {
  425. if err := com.Copy(filePath, targetPath); err != nil {
  426. return err
  427. }
  428. }
  429. }
  430. } else {
  431. delete(fileName, "license")
  432. }
  433. if len(fileName) == 0 {
  434. // Re-fetch the repository from database before updating it (else it would
  435. // override changes that were done earlier with sql)
  436. if repo, err = getRepositoryById(e, repo.Id); err != nil {
  437. return err
  438. }
  439. repo.IsBare = true
  440. repo.DefaultBranch = "master"
  441. return updateRepository(e, repo)
  442. }
  443. // Apply changes and commit.
  444. return initRepoCommit(tmpDir, u.NewGitSig())
  445. }
  446. // CreateRepository creates a repository for given user or organization.
  447. func CreateRepository(u *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) {
  448. if !IsLegalName(name) {
  449. return nil, ErrRepoNameIllegal
  450. }
  451. isExist, err := IsRepositoryExist(u, name)
  452. if err != nil {
  453. return nil, err
  454. } else if isExist {
  455. return nil, ErrRepoAlreadyExist
  456. }
  457. repo := &Repository{
  458. OwnerId: u.Id,
  459. Owner: u,
  460. Name: name,
  461. LowerName: strings.ToLower(name),
  462. Description: desc,
  463. IsPrivate: private,
  464. }
  465. sess := x.NewSession()
  466. defer sessionRelease(sess)
  467. if err = sess.Begin(); err != nil {
  468. return nil, err
  469. }
  470. if _, err = sess.Insert(repo); err != nil {
  471. return nil, err
  472. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  473. return nil, err
  474. }
  475. // TODO fix code for mirrors?
  476. // Give access to all members in owner team.
  477. if u.IsOrganization() {
  478. if err = repo.recalculateAccesses(sess); err != nil {
  479. return nil, err
  480. }
  481. // Update owner team info and count.
  482. t, err := u.getOwnerTeam(sess)
  483. if err != nil {
  484. return nil, fmt.Errorf("get owner team: %v", err)
  485. } else if err = t.getMembers(sess); err != nil {
  486. return nil, fmt.Errorf("get team members: %v", err)
  487. }
  488. for _, u := range t.Members {
  489. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  490. return nil, fmt.Errorf("watch repository: %v", err)
  491. }
  492. }
  493. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  494. t.NumRepos++
  495. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  496. return nil, err
  497. }
  498. } else {
  499. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  500. return nil, fmt.Errorf("watch repository 2: %v", err)
  501. }
  502. }
  503. if err = newRepoAction(sess, u, repo); err != nil {
  504. return nil, fmt.Errorf("new repository action: %v", err)
  505. }
  506. // No need for init mirror.
  507. if !mirror {
  508. repoPath := RepoPath(u.Name, repo.Name)
  509. if err = initRepository(sess, repoPath, u, repo, initReadme, lang, license); err != nil {
  510. if err2 := os.RemoveAll(repoPath); err2 != nil {
  511. log.Error(4, "initRepository: %v", err)
  512. return nil, fmt.Errorf(
  513. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  514. }
  515. return nil, fmt.Errorf("initRepository: %v", err)
  516. }
  517. _, stderr, err := process.ExecDir(-1,
  518. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  519. "git", "update-server-info")
  520. if err != nil {
  521. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  522. }
  523. }
  524. return repo, sess.Commit()
  525. }
  526. // CountRepositories returns number of repositories.
  527. func CountRepositories() int64 {
  528. count, _ := x.Count(new(Repository))
  529. return count
  530. }
  531. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  532. // It also auto-gets corresponding users.
  533. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  534. repos := make([]*Repository, 0, num)
  535. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  536. return nil, err
  537. }
  538. for _, repo := range repos {
  539. repo.Owner = &User{Id: repo.OwnerId}
  540. has, err := x.Get(repo.Owner)
  541. if err != nil {
  542. return nil, err
  543. } else if !has {
  544. return nil, ErrUserNotExist
  545. }
  546. }
  547. return repos, nil
  548. }
  549. // RepoPath returns repository path by given user and repository name.
  550. func RepoPath(userName, repoName string) string {
  551. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  552. }
  553. // TransferOwnership transfers all corresponding setting from old user to new one.
  554. func TransferOwnership(u *User, newOwner string, repo *Repository) error {
  555. newUser, err := GetUserByName(newOwner)
  556. if err != nil {
  557. return fmt.Errorf("fail to get new owner(%s): %v", newOwner, err)
  558. }
  559. // Check if new owner has repository with same name.
  560. has, err := IsRepositoryExist(newUser, repo.Name)
  561. if err != nil {
  562. return err
  563. } else if has {
  564. return ErrRepoAlreadyExist
  565. }
  566. sess := x.NewSession()
  567. defer sessionRelease(sess)
  568. if err = sess.Begin(); err != nil {
  569. return err
  570. }
  571. owner := repo.Owner
  572. // Update repository.
  573. repo.OwnerId = newUser.Id
  574. repo.Owner = newUser
  575. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  576. return err
  577. }
  578. // Update user repository number.
  579. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newUser.Id); err != nil {
  580. return err
  581. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", owner.Id); err != nil {
  582. return err
  583. } else if err = repo.recalculateAccesses(sess); err != nil {
  584. return err
  585. } else if err = watchRepo(sess, newUser.Id, repo.Id, true); err != nil {
  586. return err
  587. } else if err = transferRepoAction(sess, u, newUser, repo); err != nil {
  588. return err
  589. }
  590. // Change repository directory name.
  591. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil {
  592. return err
  593. }
  594. return sess.Commit()
  595. }
  596. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  597. func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
  598. userName = strings.ToLower(userName)
  599. oldRepoName = strings.ToLower(oldRepoName)
  600. newRepoName = strings.ToLower(newRepoName)
  601. if !IsLegalName(newRepoName) {
  602. return ErrRepoNameIllegal
  603. }
  604. // Change repository directory name.
  605. return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName))
  606. }
  607. func updateRepository(e Engine, repo *Repository) error {
  608. repo.LowerName = strings.ToLower(repo.Name)
  609. if len(repo.Description) > 255 {
  610. repo.Description = repo.Description[:255]
  611. }
  612. if len(repo.Website) > 255 {
  613. repo.Website = repo.Website[:255]
  614. }
  615. _, err := e.Id(repo.Id).AllCols().Update(repo)
  616. return err
  617. }
  618. func UpdateRepository(repo *Repository) error {
  619. return updateRepository(x, repo)
  620. }
  621. // DeleteRepository deletes a repository for a user or organization.
  622. func DeleteRepository(uid, repoId int64, userName string) error {
  623. repo := &Repository{Id: repoId, OwnerId: uid}
  624. has, err := x.Get(repo)
  625. if err != nil {
  626. return err
  627. } else if !has {
  628. return ErrRepoNotExist
  629. }
  630. // In case is a organization.
  631. org, err := GetUserById(uid)
  632. if err != nil {
  633. return err
  634. }
  635. if org.IsOrganization() {
  636. if err = org.GetTeams(); err != nil {
  637. return err
  638. }
  639. }
  640. sess := x.NewSession()
  641. defer sessionRelease(sess)
  642. if err = sess.Begin(); err != nil {
  643. return err
  644. }
  645. if org.IsOrganization() {
  646. idStr := "$" + com.ToStr(repoId) + "|"
  647. for _, t := range org.Teams {
  648. if !strings.Contains(t.RepoIds, idStr) {
  649. continue
  650. }
  651. t.NumRepos--
  652. t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
  653. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  654. return err
  655. }
  656. }
  657. }
  658. if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
  659. return err
  660. } else if _, err := sess.Delete(&Access{RepoID: repo.Id}); err != nil {
  661. return err
  662. } else if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil {
  663. return err
  664. } else if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
  665. return err
  666. } else if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil {
  667. return err
  668. } else if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil {
  669. return err
  670. } else if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil {
  671. return err
  672. } else if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil {
  673. return err
  674. }
  675. // Delete comments.
  676. if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error {
  677. issue := bean.(*Issue)
  678. if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil {
  679. return err
  680. }
  681. return nil
  682. }); err != nil {
  683. return err
  684. }
  685. if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil {
  686. return err
  687. }
  688. if repo.IsFork {
  689. if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks - 1 WHERE id = ?", repo.ForkId); err != nil {
  690. return err
  691. }
  692. }
  693. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", uid); err != nil {
  694. return err
  695. }
  696. // Remove repository files.
  697. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  698. desc := fmt.Sprintf("Fail to delete repository files(%s/%s): %v", userName, repo.Name, err)
  699. log.Warn(desc)
  700. if err = CreateRepositoryNotice(desc); err != nil {
  701. log.Error(4, "Fail to add notice: %v", err)
  702. }
  703. }
  704. return sess.Commit()
  705. }
  706. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  707. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  708. func GetRepositoryByRef(ref string) (*Repository, error) {
  709. n := strings.IndexByte(ref, byte('/'))
  710. if n < 2 {
  711. return nil, ErrInvalidReference
  712. }
  713. userName, repoName := ref[:n], ref[n+1:]
  714. user, err := GetUserByName(userName)
  715. if err != nil {
  716. return nil, err
  717. }
  718. return GetRepositoryByName(user.Id, repoName)
  719. }
  720. // GetRepositoryByName returns the repository by given name under user if exists.
  721. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  722. repo := &Repository{
  723. OwnerId: uid,
  724. LowerName: strings.ToLower(repoName),
  725. }
  726. has, err := x.Get(repo)
  727. if err != nil {
  728. return nil, err
  729. } else if !has {
  730. return nil, ErrRepoNotExist
  731. }
  732. return repo, err
  733. }
  734. func getRepositoryById(e Engine, id int64) (*Repository, error) {
  735. repo := &Repository{}
  736. has, err := e.Id(id).Get(repo)
  737. if err != nil {
  738. return nil, err
  739. } else if !has {
  740. return nil, ErrRepoNotExist
  741. }
  742. return repo, nil
  743. }
  744. // GetRepositoryById returns the repository by given id if exists.
  745. func GetRepositoryById(id int64) (*Repository, error) {
  746. return getRepositoryById(x, id)
  747. }
  748. // GetRepositories returns a list of repositories of given user.
  749. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  750. repos := make([]*Repository, 0, 10)
  751. sess := x.Desc("updated")
  752. if !private {
  753. sess.Where("is_private=?", false)
  754. }
  755. err := sess.Find(&repos, &Repository{OwnerId: uid})
  756. return repos, err
  757. }
  758. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  759. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  760. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  761. return repos, err
  762. }
  763. // GetRepositoryCount returns the total number of repositories of user.
  764. func GetRepositoryCount(user *User) (int64, error) {
  765. return x.Count(&Repository{OwnerId: user.Id})
  766. }
  767. type SearchOption struct {
  768. Keyword string
  769. Uid int64
  770. Limit int
  771. Private bool
  772. }
  773. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  774. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  775. if len(opt.Keyword) == 0 {
  776. return repos, nil
  777. }
  778. opt.Keyword = strings.ToLower(opt.Keyword)
  779. repos = make([]*Repository, 0, opt.Limit)
  780. // Append conditions.
  781. sess := x.Limit(opt.Limit)
  782. if opt.Uid > 0 {
  783. sess.Where("owner_id=?", opt.Uid)
  784. }
  785. if !opt.Private {
  786. sess.And("is_private=false")
  787. }
  788. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  789. return repos, err
  790. }
  791. // DeleteRepositoryArchives deletes all repositories' archives.
  792. func DeleteRepositoryArchives() error {
  793. return x.Where("id > 0").Iterate(new(Repository),
  794. func(idx int, bean interface{}) error {
  795. repo := bean.(*Repository)
  796. if err := repo.GetOwner(); err != nil {
  797. return err
  798. }
  799. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  800. })
  801. }
  802. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  803. func RewriteRepositoryUpdateHook() error {
  804. return x.Where("id > 0").Iterate(new(Repository),
  805. func(idx int, bean interface{}) error {
  806. repo := bean.(*Repository)
  807. if err := repo.GetOwner(); err != nil {
  808. return err
  809. }
  810. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  811. })
  812. }
  813. var (
  814. // Prevent duplicate tasks.
  815. isMirrorUpdating = false
  816. isGitFscking = false
  817. )
  818. // MirrorUpdate checks and updates mirror repositories.
  819. func MirrorUpdate() {
  820. if isMirrorUpdating {
  821. return
  822. }
  823. isMirrorUpdating = true
  824. defer func() { isMirrorUpdating = false }()
  825. mirrors := make([]*Mirror, 0, 10)
  826. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  827. m := bean.(*Mirror)
  828. if m.NextUpdate.After(time.Now()) {
  829. return nil
  830. }
  831. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  832. if _, stderr, err := process.ExecDir(10*time.Minute,
  833. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  834. "git", "remote", "update"); err != nil {
  835. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  836. log.Error(4, desc)
  837. if err = CreateRepositoryNotice(desc); err != nil {
  838. log.Error(4, "Fail to add notice: %v", err)
  839. }
  840. return nil
  841. }
  842. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  843. mirrors = append(mirrors, m)
  844. return nil
  845. }); err != nil {
  846. log.Error(4, "MirrorUpdate: %v", err)
  847. }
  848. for i := range mirrors {
  849. if err := UpdateMirror(mirrors[i]); err != nil {
  850. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  851. }
  852. }
  853. }
  854. // GitFsck calls 'git fsck' to check repository health.
  855. func GitFsck() {
  856. if isGitFscking {
  857. return
  858. }
  859. isGitFscking = true
  860. defer func() { isGitFscking = false }()
  861. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  862. if err := x.Where("id > 0").Iterate(new(Repository),
  863. func(idx int, bean interface{}) error {
  864. repo := bean.(*Repository)
  865. if err := repo.GetOwner(); err != nil {
  866. return err
  867. }
  868. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  869. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  870. if err != nil {
  871. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  872. log.Warn(desc)
  873. if err = CreateRepositoryNotice(desc); err != nil {
  874. log.Error(4, "Fail to add notice: %v", err)
  875. }
  876. }
  877. return nil
  878. }); err != nil {
  879. log.Error(4, "repo.Fsck: %v", err)
  880. }
  881. }
  882. func GitGcRepos() error {
  883. args := append([]string{"gc"}, setting.Git.GcArgs...)
  884. return x.Where("id > 0").Iterate(new(Repository),
  885. func(idx int, bean interface{}) error {
  886. repo := bean.(*Repository)
  887. if err := repo.GetOwner(); err != nil {
  888. return err
  889. }
  890. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  891. if err != nil {
  892. return fmt.Errorf("%v: %v", err, stderr)
  893. }
  894. return nil
  895. })
  896. }
  897. // _________ .__ .__ ___. __ .__
  898. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  899. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  900. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  901. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  902. // \/ \/ \/ \/ \/
  903. // A Collaboration is a relation between an individual and a repository
  904. type Collaboration struct {
  905. ID int64 `xorm:"pk autoincr"`
  906. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  907. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  908. Created time.Time `xorm:"CREATED"`
  909. }
  910. // Add collaborator and accompanying access
  911. func (repo *Repository) AddCollaborator(u *User) error {
  912. collaboration := &Collaboration{
  913. RepoID: repo.Id,
  914. UserID: u.Id,
  915. }
  916. has, err := x.Get(collaboration)
  917. if err != nil {
  918. return err
  919. } else if has {
  920. return nil
  921. }
  922. sess := x.NewSession()
  923. defer sessionRelease(sess)
  924. if err = sess.Begin(); err != nil {
  925. return err
  926. }
  927. if _, err = sess.InsertOne(collaboration); err != nil {
  928. return err
  929. } else if err = repo.recalculateAccesses(sess); err != nil {
  930. return err
  931. }
  932. return sess.Commit()
  933. }
  934. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  935. collaborations := make([]*Collaboration, 0)
  936. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil {
  937. return nil, err
  938. }
  939. users := make([]*User, len(collaborations))
  940. for i, c := range collaborations {
  941. user, err := getUserById(e, c.UserID)
  942. if err != nil {
  943. return nil, err
  944. }
  945. users[i] = user
  946. }
  947. return users, nil
  948. }
  949. // GetCollaborators returns the collaborators for a repository
  950. func (repo *Repository) GetCollaborators() ([]*User, error) {
  951. return repo.getCollaborators(x)
  952. }
  953. // Delete collaborator and accompanying access
  954. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  955. collaboration := &Collaboration{
  956. RepoID: repo.Id,
  957. UserID: u.Id,
  958. }
  959. sess := x.NewSession()
  960. defer sessionRelease(sess)
  961. if err = sess.Begin(); err != nil {
  962. return err
  963. }
  964. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  965. return err
  966. } else if err = repo.recalculateAccesses(sess); err != nil {
  967. return err
  968. }
  969. return sess.Commit()
  970. }
  971. // __ __ __ .__
  972. // / \ / \_____ _/ |_ ____ | |__
  973. // \ \/\/ /\__ \\ __\/ ___\| | \
  974. // \ / / __ \| | \ \___| Y \
  975. // \__/\ / (____ /__| \___ >___| /
  976. // \/ \/ \/ \/
  977. // Watch is connection request for receiving repository notification.
  978. type Watch struct {
  979. Id int64
  980. UserId int64 `xorm:"UNIQUE(watch)"`
  981. RepoId int64 `xorm:"UNIQUE(watch)"`
  982. }
  983. // IsWatching checks if user has watched given repository.
  984. func IsWatching(uid, repoId int64) bool {
  985. has, _ := x.Get(&Watch{0, uid, repoId})
  986. return has
  987. }
  988. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  989. if watch {
  990. if IsWatching(uid, repoId) {
  991. return nil
  992. }
  993. if _, err = e.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
  994. return err
  995. }
  996. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  997. } else {
  998. if !IsWatching(uid, repoId) {
  999. return nil
  1000. }
  1001. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1002. return err
  1003. }
  1004. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
  1005. }
  1006. return err
  1007. }
  1008. // Watch or unwatch repository.
  1009. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1010. return watchRepo(x, uid, repoId, watch)
  1011. }
  1012. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1013. watches := make([]*Watch, 0, 10)
  1014. err := e.Find(&watches, &Watch{RepoId: rid})
  1015. return watches, err
  1016. }
  1017. // GetWatchers returns all watchers of given repository.
  1018. func GetWatchers(rid int64) ([]*Watch, error) {
  1019. return getWatchers(x, rid)
  1020. }
  1021. func notifyWatchers(e Engine, act *Action) error {
  1022. // Add feeds for user self and all watchers.
  1023. watches, err := getWatchers(e, act.RepoId)
  1024. if err != nil {
  1025. return fmt.Errorf("get watchers: %v", err)
  1026. }
  1027. // Add feed for actioner.
  1028. act.UserId = act.ActUserId
  1029. if _, err = e.InsertOne(act); err != nil {
  1030. return fmt.Errorf("insert new actioner: %v", err)
  1031. }
  1032. for i := range watches {
  1033. if act.ActUserId == watches[i].UserId {
  1034. continue
  1035. }
  1036. act.Id = 0
  1037. act.UserId = watches[i].UserId
  1038. if _, err = e.InsertOne(act); err != nil {
  1039. return fmt.Errorf("insert new action: %v", err)
  1040. }
  1041. }
  1042. return nil
  1043. }
  1044. // NotifyWatchers creates batch of actions for every watcher.
  1045. func NotifyWatchers(act *Action) error {
  1046. return notifyWatchers(x, act)
  1047. }
  1048. // _________ __
  1049. // / _____// |______ _______
  1050. // \_____ \\ __\__ \\_ __ \
  1051. // / \| | / __ \| | \/
  1052. // /_______ /|__| (____ /__|
  1053. // \/ \/
  1054. type Star struct {
  1055. Id int64
  1056. Uid int64 `xorm:"UNIQUE(s)"`
  1057. RepoId int64 `xorm:"UNIQUE(s)"`
  1058. }
  1059. // Star or unstar repository.
  1060. func StarRepo(uid, repoId int64, star bool) (err error) {
  1061. if star {
  1062. if IsStaring(uid, repoId) {
  1063. return nil
  1064. }
  1065. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1066. return err
  1067. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1068. return err
  1069. }
  1070. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1071. } else {
  1072. if !IsStaring(uid, repoId) {
  1073. return nil
  1074. }
  1075. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1076. return err
  1077. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1078. return err
  1079. }
  1080. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1081. }
  1082. return err
  1083. }
  1084. // IsStaring checks if user has starred given repository.
  1085. func IsStaring(uid, repoId int64) bool {
  1086. has, _ := x.Get(&Star{0, uid, repoId})
  1087. return has
  1088. }
  1089. // ___________ __
  1090. // \_ _____/__________| | __
  1091. // | __)/ _ \_ __ \ |/ /
  1092. // | \( <_> ) | \/ <
  1093. // \___ / \____/|__| |__|_ \
  1094. // \/ \/
  1095. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repository, error) {
  1096. isExist, err := IsRepositoryExist(u, name)
  1097. if err != nil {
  1098. return nil, err
  1099. } else if isExist {
  1100. return nil, ErrRepoAlreadyExist
  1101. }
  1102. // In case the old repository is a fork.
  1103. if oldRepo.IsFork {
  1104. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1105. if err != nil {
  1106. return nil, err
  1107. }
  1108. }
  1109. repo := &Repository{
  1110. OwnerId: u.Id,
  1111. Owner: u,
  1112. Name: name,
  1113. LowerName: strings.ToLower(name),
  1114. Description: desc,
  1115. IsPrivate: oldRepo.IsPrivate,
  1116. IsFork: true,
  1117. ForkId: oldRepo.Id,
  1118. }
  1119. sess := x.NewSession()
  1120. defer sessionRelease(sess)
  1121. if err = sess.Begin(); err != nil {
  1122. return nil, err
  1123. }
  1124. if _, err = sess.Insert(repo); err != nil {
  1125. return nil, err
  1126. }
  1127. if err = repo.recalculateAccesses(sess); err != nil {
  1128. return nil, err
  1129. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1130. return nil, err
  1131. }
  1132. if u.IsOrganization() {
  1133. // Update owner team info and count.
  1134. t, err := u.getOwnerTeam(sess)
  1135. if err != nil {
  1136. return nil, fmt.Errorf("get owner team: %v", err)
  1137. } else if err = t.getMembers(sess); err != nil {
  1138. return nil, fmt.Errorf("get team members: %v", err)
  1139. }
  1140. for _, u := range t.Members {
  1141. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1142. return nil, fmt.Errorf("watch repository: %v", err)
  1143. }
  1144. }
  1145. t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
  1146. t.NumRepos++
  1147. if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
  1148. return nil, err
  1149. }
  1150. } else {
  1151. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1152. return nil, fmt.Errorf("watch repository 2: %v", err)
  1153. }
  1154. }
  1155. if err = newRepoAction(sess, u, repo); err != nil {
  1156. return nil, fmt.Errorf("new repository action: %v", err)
  1157. }
  1158. if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil {
  1159. return nil, err
  1160. }
  1161. oldRepoPath, err := oldRepo.RepoPath()
  1162. if err != nil {
  1163. return nil, fmt.Errorf("get old repository path: %v", err)
  1164. }
  1165. repoPath := RepoPath(u.Name, repo.Name)
  1166. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1167. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1168. "git", "clone", "--bare", oldRepoPath, repoPath)
  1169. if err != nil {
  1170. return nil, fmt.Errorf("git clone: %v", stderr)
  1171. }
  1172. _, stderr, err = process.ExecDir(-1,
  1173. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1174. "git", "update-server-info")
  1175. if err != nil {
  1176. return nil, fmt.Errorf("git update-server-info: %v", err)
  1177. }
  1178. return repo, sess.Commit()
  1179. }