repo.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  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/bindata"
  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 --config='%s'\n"
  30. )
  31. var (
  32. ErrRepoAlreadyExist = errors.New("Repository already exist")
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  35. ErrMirrorNotExist = errors.New("Mirror does not exist")
  36. ErrInvalidReference = errors.New("Invalid reference specified")
  37. ErrNameEmpty = errors.New("Name is empty")
  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 := bindata.AssetDir("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. // Git requires setting user.name and user.email in order to commit changes.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "[email protected]"} {
  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. IsMirror bool
  137. *Mirror `xorm:"-"`
  138. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  139. ForkId int64
  140. ForkRepo *Repository `xorm:"-"`
  141. Created time.Time `xorm:"CREATED"`
  142. Updated time.Time `xorm:"UPDATED"`
  143. }
  144. func (repo *Repository) getOwner(e Engine) (err error) {
  145. if repo.Owner == nil {
  146. repo.Owner, err = getUserById(e, repo.OwnerId)
  147. }
  148. return err
  149. }
  150. func (repo *Repository) GetOwner() (err error) {
  151. return repo.getOwner(x)
  152. }
  153. func (repo *Repository) GetMirror() (err error) {
  154. repo.Mirror, err = GetMirror(repo.Id)
  155. return err
  156. }
  157. func (repo *Repository) GetForkRepo() (err error) {
  158. if !repo.IsFork {
  159. return nil
  160. }
  161. repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
  162. return err
  163. }
  164. func (repo *Repository) RepoPath() (string, error) {
  165. if err := repo.GetOwner(); err != nil {
  166. return "", err
  167. }
  168. return RepoPath(repo.Owner.Name, repo.Name), nil
  169. }
  170. func (repo *Repository) RepoLink() (string, error) {
  171. if err := repo.GetOwner(); err != nil {
  172. return "", err
  173. }
  174. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  175. }
  176. func (repo *Repository) HasAccess(u *User) bool {
  177. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  178. return has
  179. }
  180. func (repo *Repository) IsOwnedBy(u *User) bool {
  181. return repo.OwnerId == u.Id
  182. }
  183. // DescriptionHtml does special handles to description and return HTML string.
  184. func (repo *Repository) DescriptionHtml() template.HTML {
  185. sanitize := func(s string) string {
  186. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  187. }
  188. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  189. }
  190. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  191. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  192. has, err := x.Get(&Repository{
  193. OwnerId: u.Id,
  194. LowerName: strings.ToLower(repoName),
  195. })
  196. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  197. }
  198. // CloneLink represents different types of clone URLs of repository.
  199. type CloneLink struct {
  200. SSH string
  201. HTTPS string
  202. Git string
  203. }
  204. // CloneLink returns clone URLs of repository.
  205. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  206. if err = repo.GetOwner(); err != nil {
  207. return cl, err
  208. }
  209. if setting.SSHPort != 22 {
  210. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSHDomain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  211. } else {
  212. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSHDomain, repo.Owner.LowerName, repo.LowerName)
  213. }
  214. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  215. return cl, nil
  216. }
  217. var (
  218. reservedNames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  219. reservedPatterns = []string{"*.git", "*.keys"}
  220. )
  221. // IsUsableName checks if name is reserved or pattern of name is not allowed.
  222. func IsUsableName(name string) error {
  223. name = strings.TrimSpace(strings.ToLower(name))
  224. if utf8.RuneCountInString(name) == 0 {
  225. return ErrNameEmpty
  226. }
  227. for i := range reservedNames {
  228. if name == reservedNames[i] {
  229. return ErrNameReserved{name}
  230. }
  231. }
  232. for _, pat := range reservedPatterns {
  233. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  234. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  235. return ErrNamePatternNotAllowed{pat}
  236. }
  237. }
  238. return nil
  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(e Engine, repoId int64) (*Mirror, error) {
  250. m := &Mirror{RepoId: repoId}
  251. has, err := e.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. // GetMirror returns mirror object by given repository ID.
  260. func GetMirror(repoId int64) (*Mirror, error) {
  261. return getMirror(x, repoId)
  262. }
  263. func updateMirror(e Engine, m *Mirror) error {
  264. _, err := e.Id(m.Id).Update(m)
  265. return err
  266. }
  267. func UpdateMirror(m *Mirror) error {
  268. return updateMirror(x, m)
  269. }
  270. // MirrorRepository creates a mirror repository from source.
  271. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  272. _, stderr, err := process.ExecTimeout(10*time.Minute,
  273. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  274. "git", "clone", "--mirror", url, repoPath)
  275. if err != nil {
  276. return errors.New("git clone --mirror: " + stderr)
  277. }
  278. if _, err = x.InsertOne(&Mirror{
  279. RepoId: repoId,
  280. RepoName: strings.ToLower(userName + "/" + repoName),
  281. Interval: 24,
  282. NextUpdate: time.Now().Add(24 * time.Hour),
  283. }); err != nil {
  284. return err
  285. }
  286. return nil
  287. }
  288. // MigrateRepository migrates a existing repository from other project hosting.
  289. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  290. repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
  291. if err != nil {
  292. return nil, err
  293. }
  294. // Clone to temprory path and do the init commit.
  295. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  296. os.MkdirAll(tmpDir, os.ModePerm)
  297. repoPath := RepoPath(u.Name, name)
  298. if u.IsOrganization() {
  299. t, err := u.GetOwnerTeam()
  300. if err != nil {
  301. return nil, err
  302. }
  303. repo.NumWatches = t.NumMembers
  304. } else {
  305. repo.NumWatches = 1
  306. }
  307. repo.IsBare = false
  308. if mirror {
  309. if err = MirrorRepository(repo.Id, u.Name, repo.Name, repoPath, url); err != nil {
  310. return repo, err
  311. }
  312. repo.IsMirror = true
  313. return repo, UpdateRepository(repo, false)
  314. } else {
  315. os.RemoveAll(repoPath)
  316. }
  317. // FIXME: this command could for both migrate and mirror
  318. _, stderr, err := process.ExecTimeout(10*time.Minute,
  319. fmt.Sprintf("MigrateRepository: %s", repoPath),
  320. "git", "clone", "--mirror", "--bare", url, repoPath)
  321. if err != nil {
  322. return repo, fmt.Errorf("git clone --mirror --bare: %v", stderr)
  323. } else if err = createUpdateHook(repoPath); err != nil {
  324. return repo, fmt.Errorf("create update hook: %v", err)
  325. }
  326. return repo, UpdateRepository(repo, false)
  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 createUpdateHook(repoPath string) error {
  350. return ioutil.WriteFile(path.Join(repoPath, "hooks/update"),
  351. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  352. }
  353. // InitRepository initializes README and .gitignore if needed.
  354. func initRepository(e Engine, repoPath string, u *User, repo *Repository, initReadme bool, repoLang, license string) error {
  355. // Init bare new repository.
  356. os.MkdirAll(repoPath, os.ModePerm)
  357. _, stderr, err := process.ExecDir(-1, repoPath,
  358. fmt.Sprintf("initRepository(git init --bare): %s", repoPath),
  359. "git", "init", "--bare")
  360. if err != nil {
  361. return errors.New("git init --bare: " + stderr)
  362. }
  363. if err := createUpdateHook(repoPath); err != nil {
  364. return err
  365. }
  366. // Initialize repository according to user's choice.
  367. fileName := map[string]string{}
  368. if initReadme {
  369. fileName["readme"] = "README.md"
  370. }
  371. if repoLang != "" {
  372. fileName["gitign"] = ".gitignore"
  373. }
  374. if license != "" {
  375. fileName["license"] = "LICENSE"
  376. }
  377. // Clone to temprory path and do the init commit.
  378. tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond()))
  379. os.MkdirAll(tmpDir, os.ModePerm)
  380. _, stderr, err = process.Exec(
  381. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  382. "git", "clone", repoPath, tmpDir)
  383. if err != nil {
  384. return errors.New("git clone: " + stderr)
  385. }
  386. // README
  387. if initReadme {
  388. defaultReadme := repo.Name + "\n" + strings.Repeat("=",
  389. utf8.RuneCountInString(repo.Name)) + "\n\n" + repo.Description
  390. if err := ioutil.WriteFile(filepath.Join(tmpDir, fileName["readme"]),
  391. []byte(defaultReadme), 0644); err != nil {
  392. return err
  393. }
  394. }
  395. // FIXME: following two can be merged.
  396. // .gitignore
  397. // Copy custom file when available.
  398. customPath := path.Join(setting.CustomPath, "conf/gitignore", repoLang)
  399. targetPath := path.Join(tmpDir, fileName["gitign"])
  400. if com.IsFile(customPath) {
  401. if err := com.Copy(customPath, targetPath); err != nil {
  402. return fmt.Errorf("copy gitignore: %v", err)
  403. }
  404. } else if com.IsSliceContainsStr(Gitignores, repoLang) {
  405. if err = ioutil.WriteFile(targetPath,
  406. bindata.MustAsset(path.Join("conf/gitignore", repoLang)), os.ModePerm); err != nil {
  407. return fmt.Errorf("generate gitignore: %v", err)
  408. }
  409. } else {
  410. delete(fileName, "gitign")
  411. }
  412. // LICENSE
  413. customPath = path.Join(setting.CustomPath, "conf/license", license)
  414. targetPath = path.Join(tmpDir, fileName["license"])
  415. if com.IsFile(customPath) {
  416. if err = com.Copy(customPath, targetPath); err != nil {
  417. return fmt.Errorf("copy license: %v", err)
  418. }
  419. } else if com.IsSliceContainsStr(Licenses, license) {
  420. if err = ioutil.WriteFile(targetPath,
  421. bindata.MustAsset(path.Join("conf/license", license)), os.ModePerm); err != nil {
  422. return fmt.Errorf("generate license: %v", err)
  423. }
  424. } else {
  425. delete(fileName, "license")
  426. }
  427. if len(fileName) == 0 {
  428. // Re-fetch the repository from database before updating it (else it would
  429. // override changes that were done earlier with sql)
  430. if repo, err = getRepositoryById(e, repo.Id); err != nil {
  431. return err
  432. }
  433. repo.IsBare = true
  434. repo.DefaultBranch = "master"
  435. return updateRepository(e, repo, false)
  436. }
  437. // Apply changes and commit.
  438. return initRepoCommit(tmpDir, u.NewGitSig())
  439. }
  440. // CreateRepository creates a repository for given user or organization.
  441. func CreateRepository(u *User, name, desc, lang, license string, isPrivate, isMirror, initReadme bool) (_ *Repository, err error) {
  442. if err = IsUsableName(name); err != nil {
  443. return nil, err
  444. }
  445. has, err := IsRepositoryExist(u, name)
  446. if err != nil {
  447. return nil, fmt.Errorf("IsRepositoryExist: %v", err)
  448. } else if has {
  449. return nil, ErrRepoAlreadyExist
  450. }
  451. repo := &Repository{
  452. OwnerId: u.Id,
  453. Owner: u,
  454. Name: name,
  455. LowerName: strings.ToLower(name),
  456. Description: desc,
  457. IsPrivate: isPrivate,
  458. }
  459. sess := x.NewSession()
  460. defer sessionRelease(sess)
  461. if err = sess.Begin(); err != nil {
  462. return nil, err
  463. }
  464. if _, err = sess.Insert(repo); err != nil {
  465. return nil, err
  466. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  467. return nil, err
  468. }
  469. // TODO fix code for mirrors?
  470. // Give access to all members in owner team.
  471. if u.IsOrganization() {
  472. t, err := u.getOwnerTeam(sess)
  473. if err != nil {
  474. return nil, fmt.Errorf("getOwnerTeam: %v", err)
  475. } else if err = t.addRepository(sess, repo); err != nil {
  476. return nil, fmt.Errorf("addRepository: %v", err)
  477. }
  478. } else {
  479. // Organization called this in addRepository method.
  480. if err = repo.recalculateAccesses(sess); err != nil {
  481. return nil, fmt.Errorf("recalculateAccesses: %v", err)
  482. }
  483. }
  484. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  485. return nil, fmt.Errorf("watchRepo: %v", err)
  486. } else if err = newRepoAction(sess, u, repo); err != nil {
  487. return nil, fmt.Errorf("newRepoAction: %v", err)
  488. }
  489. // No need for init mirror.
  490. if !isMirror {
  491. repoPath := RepoPath(u.Name, repo.Name)
  492. if err = initRepository(sess, repoPath, u, repo, initReadme, lang, license); err != nil {
  493. if err2 := os.RemoveAll(repoPath); err2 != nil {
  494. log.Error(4, "initRepository: %v", err)
  495. return nil, fmt.Errorf(
  496. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  497. }
  498. return nil, fmt.Errorf("initRepository: %v", err)
  499. }
  500. _, stderr, err := process.ExecDir(-1,
  501. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  502. "git", "update-server-info")
  503. if err != nil {
  504. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  505. }
  506. }
  507. return repo, sess.Commit()
  508. }
  509. // CountRepositories returns number of repositories.
  510. func CountRepositories() int64 {
  511. count, _ := x.Count(new(Repository))
  512. return count
  513. }
  514. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  515. // It also auto-gets corresponding users.
  516. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  517. repos := make([]*Repository, 0, num)
  518. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  519. return nil, err
  520. }
  521. for _, repo := range repos {
  522. repo.Owner = &User{Id: repo.OwnerId}
  523. has, err := x.Get(repo.Owner)
  524. if err != nil {
  525. return nil, err
  526. } else if !has {
  527. return nil, ErrUserNotExist
  528. }
  529. }
  530. return repos, nil
  531. }
  532. // RepoPath returns repository path by given user and repository name.
  533. func RepoPath(userName, repoName string) string {
  534. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  535. }
  536. // TransferOwnership transfers all corresponding setting from old user to new one.
  537. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  538. newOwner, err := GetUserByName(newOwnerName)
  539. if err != nil {
  540. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  541. }
  542. // Check if new owner has repository with same name.
  543. has, err := IsRepositoryExist(newOwner, repo.Name)
  544. if err != nil {
  545. return fmt.Errorf("IsRepositoryExist: %v", err)
  546. } else if has {
  547. return ErrRepoAlreadyExist
  548. }
  549. sess := x.NewSession()
  550. defer sessionRelease(sess)
  551. if err = sess.Begin(); err != nil {
  552. return fmt.Errorf("sess.Begin: %v", err)
  553. }
  554. owner := repo.Owner
  555. // Note: we have to set value here to make sure recalculate accesses is based on
  556. // new owner.
  557. repo.OwnerId = newOwner.Id
  558. repo.Owner = newOwner
  559. // Update repository.
  560. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  561. return fmt.Errorf("update owner: %v", err)
  562. }
  563. // Remove redundant collaborators.
  564. collaborators, err := repo.GetCollaborators()
  565. if err != nil {
  566. return fmt.Errorf("GetCollaborators: %v", err)
  567. }
  568. // Dummy object.
  569. collaboration := &Collaboration{RepoID: repo.Id}
  570. for _, c := range collaborators {
  571. collaboration.UserID = c.Id
  572. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  573. if _, err = sess.Delete(collaboration); err != nil {
  574. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  575. }
  576. }
  577. }
  578. // Remove old team-repository relations.
  579. if owner.IsOrganization() {
  580. if err = owner.getTeams(sess); err != nil {
  581. return fmt.Errorf("getTeams: %v", err)
  582. }
  583. for _, t := range owner.Teams {
  584. if !t.hasRepository(sess, repo.Id) {
  585. continue
  586. }
  587. t.NumRepos--
  588. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  589. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  590. }
  591. }
  592. if err = owner.removeOrgRepo(sess, repo.Id); err != nil {
  593. return fmt.Errorf("removeOrgRepo: %v", err)
  594. }
  595. }
  596. if newOwner.IsOrganization() {
  597. t, err := newOwner.GetOwnerTeam()
  598. if err != nil {
  599. return fmt.Errorf("GetOwnerTeam: %v", err)
  600. } else if err = t.addRepository(sess, repo); err != nil {
  601. return fmt.Errorf("add to owner team: %v", err)
  602. }
  603. } else {
  604. // Organization called this in addRepository method.
  605. if err = repo.recalculateAccesses(sess); err != nil {
  606. return fmt.Errorf("recalculateAccesses: %v", err)
  607. }
  608. }
  609. // Update repository count.
  610. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  611. return fmt.Errorf("increase new owner repository count: %v", err)
  612. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  613. return fmt.Errorf("decrease old owner repository count: %v", err)
  614. }
  615. if err = watchRepo(sess, newOwner.Id, repo.Id, true); err != nil {
  616. return fmt.Errorf("watchRepo: %v", err)
  617. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  618. return fmt.Errorf("transferRepoAction: %v", err)
  619. }
  620. // Update mirror information.
  621. if repo.IsMirror {
  622. mirror, err := getMirror(sess, repo.Id)
  623. if err != nil {
  624. return fmt.Errorf("getMirror: %v", err)
  625. }
  626. mirror.RepoName = newOwner.LowerName + "/" + repo.LowerName
  627. if err = updateMirror(sess, mirror); err != nil {
  628. return fmt.Errorf("updateMirror: %v", err)
  629. }
  630. }
  631. // Change repository directory name.
  632. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  633. return fmt.Errorf("rename directory: %v", err)
  634. }
  635. return sess.Commit()
  636. }
  637. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  638. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  639. oldRepoName = strings.ToLower(oldRepoName)
  640. newRepoName = strings.ToLower(newRepoName)
  641. if err = IsUsableName(newRepoName); err != nil {
  642. return err
  643. }
  644. has, err := IsRepositoryExist(u, newRepoName)
  645. if err != nil {
  646. return fmt.Errorf("IsRepositoryExist: %v", err)
  647. } else if has {
  648. return ErrRepoAlreadyExist
  649. }
  650. // Change repository directory name.
  651. return os.Rename(RepoPath(u.LowerName, oldRepoName), RepoPath(u.LowerName, newRepoName))
  652. }
  653. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  654. repo.LowerName = strings.ToLower(repo.Name)
  655. if len(repo.Description) > 255 {
  656. repo.Description = repo.Description[:255]
  657. }
  658. if len(repo.Website) > 255 {
  659. repo.Website = repo.Website[:255]
  660. }
  661. if _, err = e.Id(repo.Id).AllCols().Update(repo); err != nil {
  662. return fmt.Errorf("update: %v", err)
  663. }
  664. if visibilityChanged {
  665. if err = repo.getOwner(e); err != nil {
  666. return fmt.Errorf("getOwner: %v", err)
  667. }
  668. if !repo.Owner.IsOrganization() {
  669. return nil
  670. }
  671. // Organization repository need to recalculate access table when visivility is changed.
  672. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  673. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  674. }
  675. }
  676. return nil
  677. }
  678. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  679. sess := x.NewSession()
  680. defer sessionRelease(sess)
  681. if err = sess.Begin(); err != nil {
  682. return err
  683. }
  684. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  685. return fmt.Errorf("updateRepository: %v", err)
  686. }
  687. return sess.Commit()
  688. }
  689. // DeleteRepository deletes a repository for a user or organization.
  690. func DeleteRepository(uid, repoID int64, userName string) error {
  691. repo := &Repository{Id: repoID, OwnerId: uid}
  692. has, err := x.Get(repo)
  693. if err != nil {
  694. return err
  695. } else if !has {
  696. return ErrRepoNotExist{repoID, uid, ""}
  697. }
  698. // In case is a organization.
  699. org, err := GetUserById(uid)
  700. if err != nil {
  701. return err
  702. }
  703. if org.IsOrganization() {
  704. if err = org.GetTeams(); err != nil {
  705. return err
  706. }
  707. }
  708. sess := x.NewSession()
  709. defer sessionRelease(sess)
  710. if err = sess.Begin(); err != nil {
  711. return err
  712. }
  713. if org.IsOrganization() {
  714. for _, t := range org.Teams {
  715. if !t.hasRepository(sess, repoID) {
  716. continue
  717. } else if err = t.removeRepository(sess, repo, false); err != nil {
  718. return err
  719. }
  720. }
  721. }
  722. if _, err = sess.Delete(&Repository{Id: repoID}); err != nil {
  723. return err
  724. } else if _, err = sess.Delete(&Access{RepoID: repo.Id}); err != nil {
  725. return err
  726. } else if _, err = sess.Delete(&Action{RepoID: repo.Id}); err != nil {
  727. return err
  728. } else if _, err = sess.Delete(&Watch{RepoID: repoID}); err != nil {
  729. return err
  730. } else if _, err = sess.Delete(&Mirror{RepoId: repoID}); err != nil {
  731. return err
  732. } else if _, err = sess.Delete(&IssueUser{RepoId: repoID}); err != nil {
  733. return err
  734. } else if _, err = sess.Delete(&Milestone{RepoId: repoID}); err != nil {
  735. return err
  736. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  737. return err
  738. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  739. return err
  740. }
  741. // Delete comments.
  742. issues := make([]*Issue, 0, 25)
  743. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  744. return err
  745. }
  746. for i := range issues {
  747. if _, err = sess.Delete(&Comment{IssueId: issues[i].Id}); err != nil {
  748. return err
  749. }
  750. }
  751. if _, err = sess.Delete(&Issue{RepoId: repoID}); err != nil {
  752. return err
  753. }
  754. if repo.IsFork {
  755. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkId); err != nil {
  756. return err
  757. }
  758. }
  759. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  760. return err
  761. }
  762. // Remove repository files.
  763. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  764. desc := fmt.Sprintf("delete repository files(%s/%s): %v", userName, repo.Name, err)
  765. log.Warn(desc)
  766. if err = CreateRepositoryNotice(desc); err != nil {
  767. log.Error(4, "add notice: %v", err)
  768. }
  769. }
  770. return sess.Commit()
  771. }
  772. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  773. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  774. func GetRepositoryByRef(ref string) (*Repository, error) {
  775. n := strings.IndexByte(ref, byte('/'))
  776. if n < 2 {
  777. return nil, ErrInvalidReference
  778. }
  779. userName, repoName := ref[:n], ref[n+1:]
  780. user, err := GetUserByName(userName)
  781. if err != nil {
  782. return nil, err
  783. }
  784. return GetRepositoryByName(user.Id, repoName)
  785. }
  786. // GetRepositoryByName returns the repository by given name under user if exists.
  787. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  788. repo := &Repository{
  789. OwnerId: uid,
  790. LowerName: strings.ToLower(repoName),
  791. }
  792. has, err := x.Get(repo)
  793. if err != nil {
  794. return nil, err
  795. } else if !has {
  796. return nil, ErrRepoNotExist{0, uid, repoName}
  797. }
  798. return repo, err
  799. }
  800. func getRepositoryById(e Engine, id int64) (*Repository, error) {
  801. repo := new(Repository)
  802. has, err := e.Id(id).Get(repo)
  803. if err != nil {
  804. return nil, err
  805. } else if !has {
  806. return nil, ErrRepoNotExist{id, 0, ""}
  807. }
  808. return repo, nil
  809. }
  810. // GetRepositoryById returns the repository by given id if exists.
  811. func GetRepositoryById(id int64) (*Repository, error) {
  812. return getRepositoryById(x, id)
  813. }
  814. // GetRepositories returns a list of repositories of given user.
  815. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  816. repos := make([]*Repository, 0, 10)
  817. sess := x.Desc("updated")
  818. if !private {
  819. sess.Where("is_private=?", false)
  820. }
  821. err := sess.Find(&repos, &Repository{OwnerId: uid})
  822. return repos, err
  823. }
  824. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  825. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  826. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  827. return repos, err
  828. }
  829. // GetRepositoryCount returns the total number of repositories of user.
  830. func GetRepositoryCount(user *User) (int64, error) {
  831. return x.Count(&Repository{OwnerId: user.Id})
  832. }
  833. type SearchOption struct {
  834. Keyword string
  835. Uid int64
  836. Limit int
  837. Private bool
  838. }
  839. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  840. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  841. if len(opt.Keyword) == 0 {
  842. return repos, nil
  843. }
  844. opt.Keyword = strings.ToLower(opt.Keyword)
  845. repos = make([]*Repository, 0, opt.Limit)
  846. // Append conditions.
  847. sess := x.Limit(opt.Limit)
  848. if opt.Uid > 0 {
  849. sess.Where("owner_id=?", opt.Uid)
  850. }
  851. if !opt.Private {
  852. sess.And("is_private=false")
  853. }
  854. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  855. return repos, err
  856. }
  857. // DeleteRepositoryArchives deletes all repositories' archives.
  858. func DeleteRepositoryArchives() error {
  859. return x.Where("id > 0").Iterate(new(Repository),
  860. func(idx int, bean interface{}) error {
  861. repo := bean.(*Repository)
  862. if err := repo.GetOwner(); err != nil {
  863. return err
  864. }
  865. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  866. })
  867. }
  868. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  869. func RewriteRepositoryUpdateHook() error {
  870. return x.Where("id > 0").Iterate(new(Repository),
  871. func(idx int, bean interface{}) error {
  872. repo := bean.(*Repository)
  873. if err := repo.GetOwner(); err != nil {
  874. return err
  875. }
  876. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  877. })
  878. }
  879. var (
  880. // Prevent duplicate tasks.
  881. isMirrorUpdating = false
  882. isGitFscking = false
  883. )
  884. // MirrorUpdate checks and updates mirror repositories.
  885. func MirrorUpdate() {
  886. if isMirrorUpdating {
  887. return
  888. }
  889. isMirrorUpdating = true
  890. defer func() { isMirrorUpdating = false }()
  891. mirrors := make([]*Mirror, 0, 10)
  892. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  893. m := bean.(*Mirror)
  894. if m.NextUpdate.After(time.Now()) {
  895. return nil
  896. }
  897. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  898. if _, stderr, err := process.ExecDir(10*time.Minute,
  899. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  900. "git", "remote", "update"); err != nil {
  901. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  902. log.Error(4, desc)
  903. if err = CreateRepositoryNotice(desc); err != nil {
  904. log.Error(4, "Fail to add notice: %v", err)
  905. }
  906. return nil
  907. }
  908. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  909. mirrors = append(mirrors, m)
  910. return nil
  911. }); err != nil {
  912. log.Error(4, "MirrorUpdate: %v", err)
  913. }
  914. for i := range mirrors {
  915. if err := UpdateMirror(mirrors[i]); err != nil {
  916. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  917. }
  918. }
  919. }
  920. // GitFsck calls 'git fsck' to check repository health.
  921. func GitFsck() {
  922. if isGitFscking {
  923. return
  924. }
  925. isGitFscking = true
  926. defer func() { isGitFscking = false }()
  927. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  928. if err := x.Where("id > 0").Iterate(new(Repository),
  929. func(idx int, bean interface{}) error {
  930. repo := bean.(*Repository)
  931. if err := repo.GetOwner(); err != nil {
  932. return err
  933. }
  934. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  935. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  936. if err != nil {
  937. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  938. log.Warn(desc)
  939. if err = CreateRepositoryNotice(desc); err != nil {
  940. log.Error(4, "Fail to add notice: %v", err)
  941. }
  942. }
  943. return nil
  944. }); err != nil {
  945. log.Error(4, "repo.Fsck: %v", err)
  946. }
  947. }
  948. func GitGcRepos() error {
  949. args := append([]string{"gc"}, setting.Git.GcArgs...)
  950. return x.Where("id > 0").Iterate(new(Repository),
  951. func(idx int, bean interface{}) error {
  952. repo := bean.(*Repository)
  953. if err := repo.GetOwner(); err != nil {
  954. return err
  955. }
  956. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  957. if err != nil {
  958. return fmt.Errorf("%v: %v", err, stderr)
  959. }
  960. return nil
  961. })
  962. }
  963. // _________ .__ .__ ___. __ .__
  964. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  965. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  966. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  967. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  968. // \/ \/ \/ \/ \/
  969. // A Collaboration is a relation between an individual and a repository
  970. type Collaboration struct {
  971. ID int64 `xorm:"pk autoincr"`
  972. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  973. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  974. Created time.Time `xorm:"CREATED"`
  975. }
  976. // Add collaborator and accompanying access
  977. func (repo *Repository) AddCollaborator(u *User) error {
  978. collaboration := &Collaboration{
  979. RepoID: repo.Id,
  980. UserID: u.Id,
  981. }
  982. has, err := x.Get(collaboration)
  983. if err != nil {
  984. return err
  985. } else if has {
  986. return nil
  987. }
  988. if err = repo.GetOwner(); err != nil {
  989. return fmt.Errorf("GetOwner: %v", err)
  990. }
  991. sess := x.NewSession()
  992. defer sessionRelease(sess)
  993. if err = sess.Begin(); err != nil {
  994. return err
  995. }
  996. if _, err = sess.InsertOne(collaboration); err != nil {
  997. return err
  998. }
  999. if repo.Owner.IsOrganization() {
  1000. err = repo.recalculateTeamAccesses(sess, 0)
  1001. } else {
  1002. err = repo.recalculateAccesses(sess)
  1003. }
  1004. if err != nil {
  1005. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1006. }
  1007. return sess.Commit()
  1008. }
  1009. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1010. collaborations := make([]*Collaboration, 0)
  1011. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil {
  1012. return nil, err
  1013. }
  1014. users := make([]*User, len(collaborations))
  1015. for i, c := range collaborations {
  1016. user, err := getUserById(e, c.UserID)
  1017. if err != nil {
  1018. return nil, err
  1019. }
  1020. users[i] = user
  1021. }
  1022. return users, nil
  1023. }
  1024. // GetCollaborators returns the collaborators for a repository
  1025. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1026. return repo.getCollaborators(x)
  1027. }
  1028. // Delete collaborator and accompanying access
  1029. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1030. collaboration := &Collaboration{
  1031. RepoID: repo.Id,
  1032. UserID: u.Id,
  1033. }
  1034. sess := x.NewSession()
  1035. defer sessionRelease(sess)
  1036. if err = sess.Begin(); err != nil {
  1037. return err
  1038. }
  1039. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1040. return err
  1041. } else if err = repo.recalculateAccesses(sess); err != nil {
  1042. return err
  1043. }
  1044. return sess.Commit()
  1045. }
  1046. // __ __ __ .__
  1047. // / \ / \_____ _/ |_ ____ | |__
  1048. // \ \/\/ /\__ \\ __\/ ___\| | \
  1049. // \ / / __ \| | \ \___| Y \
  1050. // \__/\ / (____ /__| \___ >___| /
  1051. // \/ \/ \/ \/
  1052. // Watch is connection request for receiving repository notification.
  1053. type Watch struct {
  1054. ID int64 `xorm:"pk autoincr"`
  1055. UserID int64 `xorm:"UNIQUE(watch)"`
  1056. RepoID int64 `xorm:"UNIQUE(watch)"`
  1057. }
  1058. // IsWatching checks if user has watched given repository.
  1059. func IsWatching(uid, repoId int64) bool {
  1060. has, _ := x.Get(&Watch{0, uid, repoId})
  1061. return has
  1062. }
  1063. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1064. if watch {
  1065. if IsWatching(uid, repoId) {
  1066. return nil
  1067. }
  1068. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1069. return err
  1070. }
  1071. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1072. } else {
  1073. if !IsWatching(uid, repoId) {
  1074. return nil
  1075. }
  1076. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1077. return err
  1078. }
  1079. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1080. }
  1081. return err
  1082. }
  1083. // Watch or unwatch repository.
  1084. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1085. return watchRepo(x, uid, repoId, watch)
  1086. }
  1087. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1088. watches := make([]*Watch, 0, 10)
  1089. err := e.Find(&watches, &Watch{RepoID: rid})
  1090. return watches, err
  1091. }
  1092. // GetWatchers returns all watchers of given repository.
  1093. func GetWatchers(rid int64) ([]*Watch, error) {
  1094. return getWatchers(x, rid)
  1095. }
  1096. func notifyWatchers(e Engine, act *Action) error {
  1097. // Add feeds for user self and all watchers.
  1098. watches, err := getWatchers(e, act.RepoID)
  1099. if err != nil {
  1100. return fmt.Errorf("get watchers: %v", err)
  1101. }
  1102. // Add feed for actioner.
  1103. act.UserID = act.ActUserID
  1104. if _, err = e.InsertOne(act); err != nil {
  1105. return fmt.Errorf("insert new actioner: %v", err)
  1106. }
  1107. for i := range watches {
  1108. if act.ActUserID == watches[i].UserID {
  1109. continue
  1110. }
  1111. act.ID = 0
  1112. act.UserID = watches[i].UserID
  1113. if _, err = e.InsertOne(act); err != nil {
  1114. return fmt.Errorf("insert new action: %v", err)
  1115. }
  1116. }
  1117. return nil
  1118. }
  1119. // NotifyWatchers creates batch of actions for every watcher.
  1120. func NotifyWatchers(act *Action) error {
  1121. return notifyWatchers(x, act)
  1122. }
  1123. // _________ __
  1124. // / _____// |______ _______
  1125. // \_____ \\ __\__ \\_ __ \
  1126. // / \| | / __ \| | \/
  1127. // /_______ /|__| (____ /__|
  1128. // \/ \/
  1129. type Star struct {
  1130. Id int64
  1131. Uid int64 `xorm:"UNIQUE(s)"`
  1132. RepoId int64 `xorm:"UNIQUE(s)"`
  1133. }
  1134. // Star or unstar repository.
  1135. func StarRepo(uid, repoId int64, star bool) (err error) {
  1136. if star {
  1137. if IsStaring(uid, repoId) {
  1138. return nil
  1139. }
  1140. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1141. return err
  1142. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1143. return err
  1144. }
  1145. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1146. } else {
  1147. if !IsStaring(uid, repoId) {
  1148. return nil
  1149. }
  1150. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1151. return err
  1152. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1153. return err
  1154. }
  1155. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1156. }
  1157. return err
  1158. }
  1159. // IsStaring checks if user has starred given repository.
  1160. func IsStaring(uid, repoId int64) bool {
  1161. has, _ := x.Get(&Star{0, uid, repoId})
  1162. return has
  1163. }
  1164. // ___________ __
  1165. // \_ _____/__________| | __
  1166. // | __)/ _ \_ __ \ |/ /
  1167. // | \( <_> ) | \/ <
  1168. // \___ / \____/|__| |__|_ \
  1169. // \/ \/
  1170. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1171. has, err := IsRepositoryExist(u, name)
  1172. if err != nil {
  1173. return nil, fmt.Errorf("IsRepositoryExist: %v", err)
  1174. } else if has {
  1175. return nil, ErrRepoAlreadyExist
  1176. }
  1177. // In case the old repository is a fork.
  1178. if oldRepo.IsFork {
  1179. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1180. if err != nil {
  1181. return nil, err
  1182. }
  1183. }
  1184. repo := &Repository{
  1185. OwnerId: u.Id,
  1186. Owner: u,
  1187. Name: name,
  1188. LowerName: strings.ToLower(name),
  1189. Description: desc,
  1190. IsPrivate: oldRepo.IsPrivate,
  1191. IsFork: true,
  1192. ForkId: oldRepo.Id,
  1193. }
  1194. sess := x.NewSession()
  1195. defer sessionRelease(sess)
  1196. if err = sess.Begin(); err != nil {
  1197. return nil, err
  1198. }
  1199. if _, err = sess.Insert(repo); err != nil {
  1200. return nil, err
  1201. }
  1202. if err = repo.recalculateAccesses(sess); err != nil {
  1203. return nil, err
  1204. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1205. return nil, err
  1206. }
  1207. if u.IsOrganization() {
  1208. // Update owner team info and count.
  1209. t, err := u.getOwnerTeam(sess)
  1210. if err != nil {
  1211. return nil, fmt.Errorf("getOwnerTeam: %v", err)
  1212. } else if err = t.addRepository(sess, repo); err != nil {
  1213. return nil, fmt.Errorf("addRepository: %v", err)
  1214. }
  1215. } else {
  1216. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1217. return nil, fmt.Errorf("watchRepo: %v", err)
  1218. }
  1219. }
  1220. if err = newRepoAction(sess, u, repo); err != nil {
  1221. return nil, fmt.Errorf("newRepoAction: %v", err)
  1222. }
  1223. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.Id); err != nil {
  1224. return nil, err
  1225. }
  1226. oldRepoPath, err := oldRepo.RepoPath()
  1227. if err != nil {
  1228. return nil, fmt.Errorf("get old repository path: %v", err)
  1229. }
  1230. repoPath := RepoPath(u.Name, repo.Name)
  1231. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1232. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1233. "git", "clone", "--bare", oldRepoPath, repoPath)
  1234. if err != nil {
  1235. return nil, fmt.Errorf("git clone: %v", stderr)
  1236. }
  1237. _, stderr, err = process.ExecDir(-1,
  1238. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1239. "git", "update-server-info")
  1240. if err != nil {
  1241. return nil, fmt.Errorf("git update-server-info: %v", err)
  1242. }
  1243. if err = createUpdateHook(repoPath); err != nil {
  1244. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1245. }
  1246. return repo, sess.Commit()
  1247. }