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

repo.go 40KB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "errors"
  7. "fmt"
  8. "html/template"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/Unknwon/cae/zip"
  20. "github.com/Unknwon/com"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/bindata"
  23. "github.com/gogits/gogs/modules/git"
  24. "github.com/gogits/gogs/modules/log"
  25. "github.com/gogits/gogs/modules/process"
  26. "github.com/gogits/gogs/modules/setting"
  27. )
  28. const (
  29. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  30. )
  31. var (
  32. ErrRepoAlreadyExist = errors.New("Repository already exist")
  33. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  34. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  35. ErrMirrorNotExist = errors.New("Mirror does not exist")
  36. ErrInvalidReference = errors.New("Invalid reference specified")
  37. )
  38. var (
  39. Gitignores, Licenses []string
  40. )
  41. var (
  42. DescPattern = regexp.MustCompile(`https?://\S+`)
  43. )
  44. func LoadRepoConfig() {
  45. // Load .gitignore and license files.
  46. types := []string{"gitignore", "license"}
  47. typeFiles := make([][]string, 2)
  48. for i, t := range types {
  49. files, err := bindata.AssetDir("conf/" + t)
  50. if err != nil {
  51. log.Fatal(4, "Fail to get %s files: %v", t, err)
  52. }
  53. customPath := path.Join(setting.CustomPath, "conf", t)
  54. if com.IsDir(customPath) {
  55. customFiles, err := com.StatDir(customPath)
  56. if err != nil {
  57. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  58. }
  59. for _, f := range customFiles {
  60. if !com.IsSliceContainsStr(files, f) {
  61. files = append(files, f)
  62. }
  63. }
  64. }
  65. typeFiles[i] = files
  66. }
  67. Gitignores = typeFiles[0]
  68. Licenses = typeFiles[1]
  69. sort.Strings(Gitignores)
  70. sort.Strings(Licenses)
  71. }
  72. func NewRepoContext() {
  73. zip.Verbose = false
  74. // Check Git installation.
  75. if _, err := exec.LookPath("git"); err != nil {
  76. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  77. }
  78. // Check Git version.
  79. ver, err := git.GetVersion()
  80. if err != nil {
  81. log.Fatal(4, "Fail to get Git version: %v", err)
  82. }
  83. reqVer, err := git.ParseVersion("1.7.1")
  84. if err != nil {
  85. log.Fatal(4, "Fail to parse required Git version: %v", err)
  86. }
  87. if ver.LessThan(reqVer) {
  88. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  89. }
  90. // Git requires setting user.name and user.email in order to commit changes.
  91. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
  92. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  93. // ExitError indicates this config is not set
  94. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  95. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  96. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  97. }
  98. log.Info("Git config %s set to %s", configKey, defaultValue)
  99. } else {
  100. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  101. }
  102. }
  103. }
  104. // Set git some configurations.
  105. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  106. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  107. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  108. }
  109. }
  110. // Repository represents a git repository.
  111. type Repository struct {
  112. Id int64
  113. OwnerId int64 `xorm:"UNIQUE(s)"`
  114. Owner *User `xorm:"-"`
  115. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  116. Name string `xorm:"INDEX NOT NULL"`
  117. Description string
  118. Website string
  119. DefaultBranch string
  120. NumWatches int
  121. NumStars int
  122. NumForks int
  123. NumIssues int
  124. NumClosedIssues int
  125. NumOpenIssues int `xorm:"-"`
  126. NumPulls int
  127. NumClosedPulls int
  128. NumOpenPulls int `xorm:"-"`
  129. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  130. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumOpenMilestones int `xorm:"-"`
  132. NumTags int `xorm:"-"`
  133. IsPrivate bool
  134. IsBare bool
  135. IsMirror bool
  136. *Mirror `xorm:"-"`
  137. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  138. ForkId int64
  139. ForkRepo *Repository `xorm:"-"`
  140. Created time.Time `xorm:"CREATED"`
  141. Updated time.Time `xorm:"UPDATED"`
  142. }
  143. func (repo *Repository) getOwner(e Engine) (err error) {
  144. if repo.Owner == nil {
  145. repo.Owner, err = getUserById(e, repo.OwnerId)
  146. }
  147. return err
  148. }
  149. func (repo *Repository) GetOwner() (err error) {
  150. return repo.getOwner(x)
  151. }
  152. func (repo *Repository) GetMirror() (err error) {
  153. repo.Mirror, err = GetMirror(repo.Id)
  154. return err
  155. }
  156. func (repo *Repository) GetForkRepo() (err error) {
  157. if !repo.IsFork {
  158. return nil
  159. }
  160. repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
  161. return err
  162. }
  163. func (repo *Repository) RepoPath() (string, error) {
  164. if err := repo.GetOwner(); err != nil {
  165. return "", err
  166. }
  167. return RepoPath(repo.Owner.Name, repo.Name), nil
  168. }
  169. func (repo *Repository) RepoLink() (string, error) {
  170. if err := repo.GetOwner(); err != nil {
  171. return "", err
  172. }
  173. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  174. }
  175. func (repo *Repository) HasAccess(u *User) bool {
  176. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  177. return has
  178. }
  179. func (repo *Repository) IsOwnedBy(u *User) bool {
  180. return repo.OwnerId == u.Id
  181. }
  182. // DescriptionHtml does special handles to description and return HTML string.
  183. func (repo *Repository) DescriptionHtml() template.HTML {
  184. sanitize := func(s string) string {
  185. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  186. }
  187. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  188. }
  189. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  190. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  191. has, err := x.Get(&Repository{
  192. OwnerId: u.Id,
  193. LowerName: strings.ToLower(repoName),
  194. })
  195. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  196. }
  197. // CloneLink represents different types of clone URLs of repository.
  198. type CloneLink struct {
  199. SSH string
  200. HTTPS string
  201. Git string
  202. }
  203. // CloneLink returns clone URLs of repository.
  204. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  205. if err = repo.GetOwner(); err != nil {
  206. return cl, err
  207. }
  208. if setting.SSHPort != 22 {
  209. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSHDomain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  210. } else {
  211. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSHDomain, repo.Owner.LowerName, repo.LowerName)
  212. }
  213. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  214. return cl, nil
  215. }
  216. var (
  217. reservedNames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  218. reservedPatterns = []string{"*.git", "*.keys"}
  219. )
  220. // IsUsableName checks if name is reserved or pattern of name is not allowed.
  221. func IsUsableName(name string) error {
  222. name = strings.ToLower(name)
  223. for i := range reservedNames {
  224. if name == reservedNames[i] {
  225. return ErrNameReserved{name}
  226. }
  227. }
  228. for _, pat := range reservedPatterns {
  229. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  230. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  231. return ErrNamePatternNotAllowed{pat}
  232. }
  233. }
  234. return nil
  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 err = IsUsableName(name); err != nil {
  439. return nil, err
  440. }
  441. has, err := IsRepositoryExist(u, name)
  442. if err != nil {
  443. return nil, fmt.Errorf("IsRepositoryExist: %v", err)
  444. } else if has {
  445. return nil, ErrRepoAlreadyExist
  446. }
  447. repo := &Repository{
  448. OwnerId: u.Id,
  449. Owner: u,
  450. Name: name,
  451. LowerName: strings.ToLower(name),
  452. Description: desc,
  453. IsPrivate: isPrivate,
  454. }
  455. sess := x.NewSession()
  456. defer sessionRelease(sess)
  457. if err = sess.Begin(); err != nil {
  458. return nil, err
  459. }
  460. if _, err = sess.Insert(repo); err != nil {
  461. return nil, err
  462. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  463. return nil, err
  464. }
  465. // TODO fix code for mirrors?
  466. // Give access to all members in owner team.
  467. if u.IsOrganization() {
  468. t, err := u.getOwnerTeam(sess)
  469. if err != nil {
  470. return nil, fmt.Errorf("getOwnerTeam: %v", err)
  471. } else if err = t.addRepository(sess, repo); err != nil {
  472. return nil, fmt.Errorf("addRepository: %v", err)
  473. }
  474. } else {
  475. // Organization called this in addRepository method.
  476. if err = repo.recalculateAccesses(sess); err != nil {
  477. return nil, fmt.Errorf("recalculateAccesses: %v", err)
  478. }
  479. }
  480. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  481. return nil, fmt.Errorf("watchRepo: %v", err)
  482. } else if err = newRepoAction(sess, u, repo); err != nil {
  483. return nil, fmt.Errorf("newRepoAction: %v", err)
  484. }
  485. // No need for init mirror.
  486. if !isMirror {
  487. repoPath := RepoPath(u.Name, repo.Name)
  488. if err = initRepository(sess, repoPath, u, repo, initReadme, lang, license); err != nil {
  489. if err2 := os.RemoveAll(repoPath); err2 != nil {
  490. log.Error(4, "initRepository: %v", err)
  491. return nil, fmt.Errorf(
  492. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  493. }
  494. return nil, fmt.Errorf("initRepository: %v", err)
  495. }
  496. _, stderr, err := process.ExecDir(-1,
  497. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  498. "git", "update-server-info")
  499. if err != nil {
  500. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  501. }
  502. }
  503. return repo, sess.Commit()
  504. }
  505. // CountRepositories returns number of repositories.
  506. func CountRepositories() int64 {
  507. count, _ := x.Count(new(Repository))
  508. return count
  509. }
  510. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  511. // It also auto-gets corresponding users.
  512. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  513. repos := make([]*Repository, 0, num)
  514. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  515. return nil, err
  516. }
  517. for _, repo := range repos {
  518. repo.Owner = &User{Id: repo.OwnerId}
  519. has, err := x.Get(repo.Owner)
  520. if err != nil {
  521. return nil, err
  522. } else if !has {
  523. return nil, ErrUserNotExist
  524. }
  525. }
  526. return repos, nil
  527. }
  528. // RepoPath returns repository path by given user and repository name.
  529. func RepoPath(userName, repoName string) string {
  530. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  531. }
  532. // TransferOwnership transfers all corresponding setting from old user to new one.
  533. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  534. newOwner, err := GetUserByName(newOwnerName)
  535. if err != nil {
  536. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  537. }
  538. // Check if new owner has repository with same name.
  539. has, err := IsRepositoryExist(newOwner, repo.Name)
  540. if err != nil {
  541. return fmt.Errorf("IsRepositoryExist: %v", err)
  542. } else if has {
  543. return ErrRepoAlreadyExist
  544. }
  545. sess := x.NewSession()
  546. defer sessionRelease(sess)
  547. if err = sess.Begin(); err != nil {
  548. return fmt.Errorf("sess.Begin: %v", err)
  549. }
  550. owner := repo.Owner
  551. // Note: we have to set value here to make sure recalculate accesses is based on
  552. // new owner.
  553. repo.OwnerId = newOwner.Id
  554. repo.Owner = newOwner
  555. // Update repository.
  556. if _, err := sess.Id(repo.Id).Update(repo); err != nil {
  557. return fmt.Errorf("update owner: %v", err)
  558. }
  559. // Remove redundant collaborators.
  560. collaborators, err := repo.GetCollaborators()
  561. if err != nil {
  562. return fmt.Errorf("GetCollaborators: %v", err)
  563. }
  564. // Dummy object.
  565. collaboration := &Collaboration{RepoID: repo.Id}
  566. for _, c := range collaborators {
  567. collaboration.UserID = c.Id
  568. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  569. if _, err = sess.Delete(collaboration); err != nil {
  570. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  571. }
  572. }
  573. }
  574. // Remove old team-repository relations.
  575. if owner.IsOrganization() {
  576. if err = owner.getTeams(sess); err != nil {
  577. return fmt.Errorf("getTeams: %v", err)
  578. }
  579. for _, t := range owner.Teams {
  580. if !t.hasRepository(sess, repo.Id) {
  581. continue
  582. }
  583. t.NumRepos--
  584. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  585. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  586. }
  587. }
  588. if err = owner.removeOrgRepo(sess, repo.Id); err != nil {
  589. return fmt.Errorf("removeOrgRepo: %v", err)
  590. }
  591. }
  592. if newOwner.IsOrganization() {
  593. t, err := newOwner.GetOwnerTeam()
  594. if err != nil {
  595. return fmt.Errorf("GetOwnerTeam: %v", err)
  596. } else if err = t.addRepository(sess, repo); err != nil {
  597. return fmt.Errorf("add to owner team: %v", err)
  598. }
  599. } else {
  600. // Organization called this in addRepository method.
  601. if err = repo.recalculateAccesses(sess); err != nil {
  602. return fmt.Errorf("recalculateAccesses: %v", err)
  603. }
  604. }
  605. // Update repository count.
  606. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  607. return fmt.Errorf("increase new owner repository count: %v", err)
  608. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  609. return fmt.Errorf("decrease old owner repository count: %v", err)
  610. }
  611. if err = watchRepo(sess, newOwner.Id, repo.Id, true); err != nil {
  612. return fmt.Errorf("watchRepo: %v", err)
  613. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  614. return fmt.Errorf("transferRepoAction: %v", err)
  615. }
  616. // Update mirror information.
  617. if repo.IsMirror {
  618. mirror, err := getMirror(sess, repo.Id)
  619. if err != nil {
  620. return fmt.Errorf("getMirror: %v", err)
  621. }
  622. mirror.RepoName = newOwner.LowerName + "/" + repo.LowerName
  623. if err = updateMirror(sess, mirror); err != nil {
  624. return fmt.Errorf("updateMirror: %v", err)
  625. }
  626. }
  627. // Change repository directory name.
  628. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  629. return fmt.Errorf("rename directory: %v", err)
  630. }
  631. return sess.Commit()
  632. }
  633. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  634. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  635. oldRepoName = strings.ToLower(oldRepoName)
  636. newRepoName = strings.ToLower(newRepoName)
  637. if err = IsUsableName(newRepoName); err != nil {
  638. return err
  639. }
  640. has, err := IsRepositoryExist(u, newRepoName)
  641. if err != nil {
  642. return fmt.Errorf("IsRepositoryExist: %v", err)
  643. } else if has {
  644. return ErrRepoAlreadyExist
  645. }
  646. // Change repository directory name.
  647. return os.Rename(RepoPath(u.LowerName, oldRepoName), RepoPath(u.LowerName, newRepoName))
  648. }
  649. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  650. repo.LowerName = strings.ToLower(repo.Name)
  651. if len(repo.Description) > 255 {
  652. repo.Description = repo.Description[:255]
  653. }
  654. if len(repo.Website) > 255 {
  655. repo.Website = repo.Website[:255]
  656. }
  657. if _, err = e.Id(repo.Id).AllCols().Update(repo); err != nil {
  658. return fmt.Errorf("update: %v", err)
  659. }
  660. if visibilityChanged {
  661. if err = repo.getOwner(e); err != nil {
  662. return fmt.Errorf("getOwner: %v", err)
  663. }
  664. if !repo.Owner.IsOrganization() {
  665. return nil
  666. }
  667. // Organization repository need to recalculate access table when visivility is changed.
  668. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  669. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  670. }
  671. }
  672. return nil
  673. }
  674. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  675. sess := x.NewSession()
  676. defer sessionRelease(sess)
  677. if err = sess.Begin(); err != nil {
  678. return err
  679. }
  680. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  681. return fmt.Errorf("updateRepository: %v", err)
  682. }
  683. return sess.Commit()
  684. }
  685. // DeleteRepository deletes a repository for a user or organization.
  686. func DeleteRepository(uid, repoID int64, userName string) error {
  687. repo := &Repository{Id: repoID, OwnerId: uid}
  688. has, err := x.Get(repo)
  689. if err != nil {
  690. return err
  691. } else if !has {
  692. return ErrRepoNotExist{repoID, uid, ""}
  693. }
  694. // In case is a organization.
  695. org, err := GetUserById(uid)
  696. if err != nil {
  697. return err
  698. }
  699. if org.IsOrganization() {
  700. if err = org.GetTeams(); err != nil {
  701. return err
  702. }
  703. }
  704. sess := x.NewSession()
  705. defer sessionRelease(sess)
  706. if err = sess.Begin(); err != nil {
  707. return err
  708. }
  709. if org.IsOrganization() {
  710. for _, t := range org.Teams {
  711. if !t.hasRepository(sess, repoID) {
  712. continue
  713. } else if err = t.removeRepository(sess, repo, false); err != nil {
  714. return err
  715. }
  716. }
  717. }
  718. if _, err = sess.Delete(&Repository{Id: repoID}); err != nil {
  719. return err
  720. } else if _, err = sess.Delete(&Access{RepoID: repo.Id}); err != nil {
  721. return err
  722. } else if _, err = sess.Delete(&Action{RepoID: repo.Id}); err != nil {
  723. return err
  724. } else if _, err = sess.Delete(&Watch{RepoID: repoID}); err != nil {
  725. return err
  726. } else if _, err = sess.Delete(&Mirror{RepoId: repoID}); err != nil {
  727. return err
  728. } else if _, err = sess.Delete(&IssueUser{RepoId: repoID}); err != nil {
  729. return err
  730. } else if _, err = sess.Delete(&Milestone{RepoId: repoID}); err != nil {
  731. return err
  732. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  733. return err
  734. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  735. return err
  736. }
  737. // Delete comments.
  738. issues := make([]*Issue, 0, 25)
  739. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  740. return err
  741. }
  742. for i := range issues {
  743. if _, err = sess.Delete(&Comment{IssueId: issues[i].Id}); err != nil {
  744. return err
  745. }
  746. }
  747. if _, err = sess.Delete(&Issue{RepoId: repoID}); err != nil {
  748. return err
  749. }
  750. if repo.IsFork {
  751. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkId); err != nil {
  752. return err
  753. }
  754. }
  755. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  756. return err
  757. }
  758. // Remove repository files.
  759. if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
  760. desc := fmt.Sprintf("delete repository files(%s/%s): %v", userName, repo.Name, err)
  761. log.Warn(desc)
  762. if err = CreateRepositoryNotice(desc); err != nil {
  763. log.Error(4, "add notice: %v", err)
  764. }
  765. }
  766. return sess.Commit()
  767. }
  768. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  769. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  770. func GetRepositoryByRef(ref string) (*Repository, error) {
  771. n := strings.IndexByte(ref, byte('/'))
  772. if n < 2 {
  773. return nil, ErrInvalidReference
  774. }
  775. userName, repoName := ref[:n], ref[n+1:]
  776. user, err := GetUserByName(userName)
  777. if err != nil {
  778. return nil, err
  779. }
  780. return GetRepositoryByName(user.Id, repoName)
  781. }
  782. // GetRepositoryByName returns the repository by given name under user if exists.
  783. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  784. repo := &Repository{
  785. OwnerId: uid,
  786. LowerName: strings.ToLower(repoName),
  787. }
  788. has, err := x.Get(repo)
  789. if err != nil {
  790. return nil, err
  791. } else if !has {
  792. return nil, ErrRepoNotExist{0, uid, repoName}
  793. }
  794. return repo, err
  795. }
  796. func getRepositoryById(e Engine, id int64) (*Repository, error) {
  797. repo := new(Repository)
  798. has, err := e.Id(id).Get(repo)
  799. if err != nil {
  800. return nil, err
  801. } else if !has {
  802. return nil, ErrRepoNotExist{id, 0, ""}
  803. }
  804. return repo, nil
  805. }
  806. // GetRepositoryById returns the repository by given id if exists.
  807. func GetRepositoryById(id int64) (*Repository, error) {
  808. return getRepositoryById(x, id)
  809. }
  810. // GetRepositories returns a list of repositories of given user.
  811. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  812. repos := make([]*Repository, 0, 10)
  813. sess := x.Desc("updated")
  814. if !private {
  815. sess.Where("is_private=?", false)
  816. }
  817. err := sess.Find(&repos, &Repository{OwnerId: uid})
  818. return repos, err
  819. }
  820. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  821. func GetRecentUpdatedRepositories(num int) (repos []*Repository, err error) {
  822. err = x.Where("is_private=?", false).Limit(num).Desc("updated").Find(&repos)
  823. return repos, err
  824. }
  825. // GetRepositoryCount returns the total number of repositories of user.
  826. func GetRepositoryCount(user *User) (int64, error) {
  827. return x.Count(&Repository{OwnerId: user.Id})
  828. }
  829. type SearchOption struct {
  830. Keyword string
  831. Uid int64
  832. Limit int
  833. Private bool
  834. }
  835. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  836. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  837. if len(opt.Keyword) == 0 {
  838. return repos, nil
  839. }
  840. opt.Keyword = strings.ToLower(opt.Keyword)
  841. repos = make([]*Repository, 0, opt.Limit)
  842. // Append conditions.
  843. sess := x.Limit(opt.Limit)
  844. if opt.Uid > 0 {
  845. sess.Where("owner_id=?", opt.Uid)
  846. }
  847. if !opt.Private {
  848. sess.And("is_private=false")
  849. }
  850. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  851. return repos, err
  852. }
  853. // DeleteRepositoryArchives deletes all repositories' archives.
  854. func DeleteRepositoryArchives() 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 os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  862. })
  863. }
  864. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  865. func RewriteRepositoryUpdateHook() error {
  866. return x.Where("id > 0").Iterate(new(Repository),
  867. func(idx int, bean interface{}) error {
  868. repo := bean.(*Repository)
  869. if err := repo.GetOwner(); err != nil {
  870. return err
  871. }
  872. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  873. })
  874. }
  875. var (
  876. // Prevent duplicate tasks.
  877. isMirrorUpdating = false
  878. isGitFscking = false
  879. )
  880. // MirrorUpdate checks and updates mirror repositories.
  881. func MirrorUpdate() {
  882. if isMirrorUpdating {
  883. return
  884. }
  885. isMirrorUpdating = true
  886. defer func() { isMirrorUpdating = false }()
  887. mirrors := make([]*Mirror, 0, 10)
  888. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  889. m := bean.(*Mirror)
  890. if m.NextUpdate.After(time.Now()) {
  891. return nil
  892. }
  893. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
  894. if _, stderr, err := process.ExecDir(10*time.Minute,
  895. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  896. "git", "remote", "update"); err != nil {
  897. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  898. log.Error(4, desc)
  899. if err = CreateRepositoryNotice(desc); err != nil {
  900. log.Error(4, "Fail to add notice: %v", err)
  901. }
  902. return nil
  903. }
  904. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  905. mirrors = append(mirrors, m)
  906. return nil
  907. }); err != nil {
  908. log.Error(4, "MirrorUpdate: %v", err)
  909. }
  910. for i := range mirrors {
  911. if err := UpdateMirror(mirrors[i]); err != nil {
  912. log.Error(4, "UpdateMirror", fmt.Sprintf("%s: %v", mirrors[i].RepoName, err))
  913. }
  914. }
  915. }
  916. // GitFsck calls 'git fsck' to check repository health.
  917. func GitFsck() {
  918. if isGitFscking {
  919. return
  920. }
  921. isGitFscking = true
  922. defer func() { isGitFscking = false }()
  923. args := append([]string{"fsck"}, setting.Git.Fsck.Args...)
  924. if err := x.Where("id > 0").Iterate(new(Repository),
  925. func(idx int, bean interface{}) error {
  926. repo := bean.(*Repository)
  927. if err := repo.GetOwner(); err != nil {
  928. return err
  929. }
  930. repoPath := RepoPath(repo.Owner.Name, repo.Name)
  931. _, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  932. if err != nil {
  933. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  934. log.Warn(desc)
  935. if err = CreateRepositoryNotice(desc); err != nil {
  936. log.Error(4, "Fail to add notice: %v", err)
  937. }
  938. }
  939. return nil
  940. }); err != nil {
  941. log.Error(4, "repo.Fsck: %v", err)
  942. }
  943. }
  944. func GitGcRepos() error {
  945. args := append([]string{"gc"}, setting.Git.GcArgs...)
  946. return x.Where("id > 0").Iterate(new(Repository),
  947. func(idx int, bean interface{}) error {
  948. repo := bean.(*Repository)
  949. if err := repo.GetOwner(); err != nil {
  950. return err
  951. }
  952. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  953. if err != nil {
  954. return fmt.Errorf("%v: %v", err, stderr)
  955. }
  956. return nil
  957. })
  958. }
  959. // _________ .__ .__ ___. __ .__
  960. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  961. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  962. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  963. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  964. // \/ \/ \/ \/ \/
  965. // A Collaboration is a relation between an individual and a repository
  966. type Collaboration struct {
  967. ID int64 `xorm:"pk autoincr"`
  968. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  969. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  970. Created time.Time `xorm:"CREATED"`
  971. }
  972. // Add collaborator and accompanying access
  973. func (repo *Repository) AddCollaborator(u *User) error {
  974. collaboration := &Collaboration{
  975. RepoID: repo.Id,
  976. UserID: u.Id,
  977. }
  978. has, err := x.Get(collaboration)
  979. if err != nil {
  980. return err
  981. } else if has {
  982. return nil
  983. }
  984. if err = repo.GetOwner(); err != nil {
  985. return fmt.Errorf("GetOwner: %v", err)
  986. }
  987. sess := x.NewSession()
  988. defer sessionRelease(sess)
  989. if err = sess.Begin(); err != nil {
  990. return err
  991. }
  992. if _, err = sess.InsertOne(collaboration); err != nil {
  993. return err
  994. }
  995. if repo.Owner.IsOrganization() {
  996. err = repo.recalculateTeamAccesses(sess, 0)
  997. } else {
  998. err = repo.recalculateAccesses(sess)
  999. }
  1000. if err != nil {
  1001. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1002. }
  1003. return sess.Commit()
  1004. }
  1005. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1006. collaborations := make([]*Collaboration, 0)
  1007. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil {
  1008. return nil, err
  1009. }
  1010. users := make([]*User, len(collaborations))
  1011. for i, c := range collaborations {
  1012. user, err := getUserById(e, c.UserID)
  1013. if err != nil {
  1014. return nil, err
  1015. }
  1016. users[i] = user
  1017. }
  1018. return users, nil
  1019. }
  1020. // GetCollaborators returns the collaborators for a repository
  1021. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1022. return repo.getCollaborators(x)
  1023. }
  1024. // Delete collaborator and accompanying access
  1025. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1026. collaboration := &Collaboration{
  1027. RepoID: repo.Id,
  1028. UserID: u.Id,
  1029. }
  1030. sess := x.NewSession()
  1031. defer sessionRelease(sess)
  1032. if err = sess.Begin(); err != nil {
  1033. return err
  1034. }
  1035. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1036. return err
  1037. } else if err = repo.recalculateAccesses(sess); err != nil {
  1038. return err
  1039. }
  1040. return sess.Commit()
  1041. }
  1042. // __ __ __ .__
  1043. // / \ / \_____ _/ |_ ____ | |__
  1044. // \ \/\/ /\__ \\ __\/ ___\| | \
  1045. // \ / / __ \| | \ \___| Y \
  1046. // \__/\ / (____ /__| \___ >___| /
  1047. // \/ \/ \/ \/
  1048. // Watch is connection request for receiving repository notification.
  1049. type Watch struct {
  1050. ID int64 `xorm:"pk autoincr"`
  1051. UserID int64 `xorm:"UNIQUE(watch)"`
  1052. RepoID int64 `xorm:"UNIQUE(watch)"`
  1053. }
  1054. // IsWatching checks if user has watched given repository.
  1055. func IsWatching(uid, repoId int64) bool {
  1056. has, _ := x.Get(&Watch{0, uid, repoId})
  1057. return has
  1058. }
  1059. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1060. if watch {
  1061. if IsWatching(uid, repoId) {
  1062. return nil
  1063. }
  1064. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1065. return err
  1066. }
  1067. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1068. } else {
  1069. if !IsWatching(uid, repoId) {
  1070. return nil
  1071. }
  1072. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1073. return err
  1074. }
  1075. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1076. }
  1077. return err
  1078. }
  1079. // Watch or unwatch repository.
  1080. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1081. return watchRepo(x, uid, repoId, watch)
  1082. }
  1083. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1084. watches := make([]*Watch, 0, 10)
  1085. err := e.Find(&watches, &Watch{RepoID: rid})
  1086. return watches, err
  1087. }
  1088. // GetWatchers returns all watchers of given repository.
  1089. func GetWatchers(rid int64) ([]*Watch, error) {
  1090. return getWatchers(x, rid)
  1091. }
  1092. func notifyWatchers(e Engine, act *Action) error {
  1093. // Add feeds for user self and all watchers.
  1094. watches, err := getWatchers(e, act.RepoID)
  1095. if err != nil {
  1096. return fmt.Errorf("get watchers: %v", err)
  1097. }
  1098. // Add feed for actioner.
  1099. act.UserID = act.ActUserID
  1100. if _, err = e.InsertOne(act); err != nil {
  1101. return fmt.Errorf("insert new actioner: %v", err)
  1102. }
  1103. for i := range watches {
  1104. if act.ActUserID == watches[i].UserID {
  1105. continue
  1106. }
  1107. act.ID = 0
  1108. act.UserID = watches[i].UserID
  1109. if _, err = e.InsertOne(act); err != nil {
  1110. return fmt.Errorf("insert new action: %v", err)
  1111. }
  1112. }
  1113. return nil
  1114. }
  1115. // NotifyWatchers creates batch of actions for every watcher.
  1116. func NotifyWatchers(act *Action) error {
  1117. return notifyWatchers(x, act)
  1118. }
  1119. // _________ __
  1120. // / _____// |______ _______
  1121. // \_____ \\ __\__ \\_ __ \
  1122. // / \| | / __ \| | \/
  1123. // /_______ /|__| (____ /__|
  1124. // \/ \/
  1125. type Star struct {
  1126. Id int64
  1127. Uid int64 `xorm:"UNIQUE(s)"`
  1128. RepoId int64 `xorm:"UNIQUE(s)"`
  1129. }
  1130. // Star or unstar repository.
  1131. func StarRepo(uid, repoId int64, star bool) (err error) {
  1132. if star {
  1133. if IsStaring(uid, repoId) {
  1134. return nil
  1135. }
  1136. if _, err = x.Insert(&Star{Uid: uid, RepoId: repoId}); err != nil {
  1137. return err
  1138. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1139. return err
  1140. }
  1141. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1142. } else {
  1143. if !IsStaring(uid, repoId) {
  1144. return nil
  1145. }
  1146. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1147. return err
  1148. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1149. return err
  1150. }
  1151. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1152. }
  1153. return err
  1154. }
  1155. // IsStaring checks if user has starred given repository.
  1156. func IsStaring(uid, repoId int64) bool {
  1157. has, _ := x.Get(&Star{0, uid, repoId})
  1158. return has
  1159. }
  1160. // ___________ __
  1161. // \_ _____/__________| | __
  1162. // | __)/ _ \_ __ \ |/ /
  1163. // | \( <_> ) | \/ <
  1164. // \___ / \____/|__| |__|_ \
  1165. // \/ \/
  1166. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1167. has, err := IsRepositoryExist(u, name)
  1168. if err != nil {
  1169. return nil, fmt.Errorf("IsRepositoryExist: %v", err)
  1170. } else if has {
  1171. return nil, ErrRepoAlreadyExist
  1172. }
  1173. // In case the old repository is a fork.
  1174. if oldRepo.IsFork {
  1175. oldRepo, err = GetRepositoryById(oldRepo.ForkId)
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. }
  1180. repo := &Repository{
  1181. OwnerId: u.Id,
  1182. Owner: u,
  1183. Name: name,
  1184. LowerName: strings.ToLower(name),
  1185. Description: desc,
  1186. IsPrivate: oldRepo.IsPrivate,
  1187. IsFork: true,
  1188. ForkId: oldRepo.Id,
  1189. }
  1190. sess := x.NewSession()
  1191. defer sessionRelease(sess)
  1192. if err = sess.Begin(); err != nil {
  1193. return nil, err
  1194. }
  1195. if _, err = sess.Insert(repo); err != nil {
  1196. return nil, err
  1197. }
  1198. if err = repo.recalculateAccesses(sess); err != nil {
  1199. return nil, err
  1200. } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
  1201. return nil, err
  1202. }
  1203. if u.IsOrganization() {
  1204. // Update owner team info and count.
  1205. t, err := u.getOwnerTeam(sess)
  1206. if err != nil {
  1207. return nil, fmt.Errorf("getOwnerTeam: %v", err)
  1208. } else if err = t.addRepository(sess, repo); err != nil {
  1209. return nil, fmt.Errorf("addRepository: %v", err)
  1210. }
  1211. } else {
  1212. if err = watchRepo(sess, u.Id, repo.Id, true); err != nil {
  1213. return nil, fmt.Errorf("watchRepo: %v", err)
  1214. }
  1215. }
  1216. if err = newRepoAction(sess, u, repo); err != nil {
  1217. return nil, fmt.Errorf("newRepoAction: %v", err)
  1218. }
  1219. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.Id); err != nil {
  1220. return nil, err
  1221. }
  1222. oldRepoPath, err := oldRepo.RepoPath()
  1223. if err != nil {
  1224. return nil, fmt.Errorf("get old repository path: %v", err)
  1225. }
  1226. repoPath := RepoPath(u.Name, repo.Name)
  1227. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1228. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1229. "git", "clone", "--bare", oldRepoPath, repoPath)
  1230. if err != nil {
  1231. return nil, fmt.Errorf("git clone: %v", stderr)
  1232. }
  1233. _, stderr, err = process.ExecDir(-1,
  1234. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1235. "git", "update-server-info")
  1236. if err != nil {
  1237. return nil, fmt.Errorf("git update-server-info: %v", err)
  1238. }
  1239. if err = createUpdateHook(repoPath); err != nil {
  1240. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1241. }
  1242. return repo, sess.Commit()
  1243. }