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

repo.go 40KB

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