repo.go 39 KB

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