repo.go 42 KB

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