repo.go 40 KB

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