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

repo.go 40 kB

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