repo.go 39 KB

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