repo.go 40 KB

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