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