master
1import fs from 'node:fs'
2import path from 'node:path'
3import { Badge } from './badges.js'
4import { $ as _$ } from './utils.js'
5import { Context } from './context.js'
6import { log } from './log.js'
7
8export function getRepo({
9 gitDir,
10 ghToken,
11 ghRepoOwner,
12 ghRepoName,
13 gitName,
14 gitEmail,
15 badgesDatafile,
16}: Context) {
17 let ready = false
18
19 const cwd = gitDir
20 const dryrun = !ghRepoOwner || !ghRepoName
21 const basicAuth = ghToken ? `${ghRepoOwner}:${ghToken}@` : ''
22 const gitUrl = `https://${basicAuth}github.com/${ghRepoOwner}/${ghRepoName}.git`
23 const $ = _$({
24 on: {
25 stdout(data) {
26 log.info(data.toString())
27 },
28 stderr(e) {
29 log.error(e.toString())
30 },
31 },
32 cwd,
33 sync: true,
34 })
35 return {
36 get ready() {
37 return ready
38 },
39 pull() {
40 if (dryrun) return
41 log.info('Fetching from git...')
42 if (fs.existsSync(path.resolve(cwd, '.git'))) {
43 $`git pull`
44 } else {
45 $`git clone --depth=1 ${gitUrl} .`
46 $`git config user.name ${gitName}`
47 $`git config user.email ${gitEmail}`
48 }
49 ready = true
50 },
51 push() {
52 if (!ready) return
53 log.info('Pushing to git...')
54 $`git add .`
55 $`git status`
56 $`git commit -m 'Update badges'`
57 $`git push`
58 },
59 hasChanges(): boolean {
60 if (!ready) return false
61 return $`git status --porcelain`.stdout.trim() !== ''
62 },
63 getUserBadges(): Badge[] {
64 if (!fs.existsSync(badgesDatafile)) return []
65
66 const data = fs.readFileSync(badgesDatafile, 'utf8')
67 return JSON.parse(data)
68 },
69 }
70}