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

repo.go 40KB

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