您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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