-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
143 lines (121 loc) · 3.74 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import { $ } from 'bun'
import { readdir } from 'node:fs/promises'
import path from 'node:path'
import type { components } from '@octokit/openapi-types'
class GithubApiError extends Error {
constructor(status: number, statusText: string) {
super(`GitHub API Response: ${status} ${statusText}`)
this.name = 'GithubApiError'
}
}
class GitCommandError extends Error {
constructor(command: string, repo: string, error: unknown) {
super(`Git '${command} failed for '${repo}': ${error}`)
this.name = 'GitCommandError'
}
}
type Repo = components['schemas']['repository']
type RepoInfo = {
git_url: string | null
default_branch: string | null
}
type GitConfig = {
localRepoDir: string
githubUser: string
strategy: 'rebase' | 'merge'
}
const config: GitConfig = {
localRepoDir: 'C:\\Users\\svora\\repositories\\',
githubUser: 'alexsvorada',
strategy: 'rebase',
}
async function _listRepos(): Promise<{
remoteRepos: Map<string, RepoInfo>
localRepos: Map<string, RepoInfo>
}> {
try {
const [remoteReposResponse, localRepos] = await Promise.all([
fetch(`https://api.github.com/users/${config.githubUser}/repos`),
readdir(config.localRepoDir),
])
if (!remoteReposResponse.ok) {
throw new GithubApiError(remoteReposResponse.status, remoteReposResponse.statusText)
}
const remoteRepos = (await remoteReposResponse.json()) as Repo[]
return {
remoteRepos: new Map(
remoteRepos.map((repo): [string, RepoInfo] => [
repo.name,
{
git_url: repo.git_url,
default_branch: repo.default_branch,
},
])
),
localRepos: new Map(
localRepos.map((repoName): [string, RepoInfo] => [
repoName,
{
git_url: null,
default_branch: null,
},
])
),
}
} catch (err) {
if (err instanceof GithubApiError) {
throw err
}
throw new Error(`Failed to list repositories: ${err}`)
}
}
async function getReposByDifference(): Promise<{
matchingRepos: Map<string, RepoInfo>
missingOnLocalRepos: Map<string, RepoInfo>
missingOnRemoteRepos: Map<string, RepoInfo>
}> {
const { remoteRepos, localRepos } = await _listRepos()
return {
matchingRepos: new Map([...remoteRepos].filter(([k]) => localRepos.has(k))),
missingOnLocalRepos: new Map([...remoteRepos].filter(([k]) => !localRepos.has(k))),
missingOnRemoteRepos: new Map([...localRepos].filter(([k]) => !remoteRepos.has(k))),
}
}
async function _cloneMissingRepos(): Promise<void> {
const { missingOnLocalRepos } = await getReposByDifference()
for (const [name, info] of missingOnLocalRepos) {
try {
console.log(`Cloning ${name}...`)
await $`git clone ${info.git_url} ${config.localRepoDir}/${name}`
} catch (err) {
throw new GitCommandError('clone', name, err)
}
}
}
async function _pullMatchingRepos(): Promise<void> {
const { matchingRepos } = await getReposByDifference()
for (const [name] of matchingRepos) {
try {
const repoPath = path.join(config.localRepoDir, name)
const hasChanges = (await $`git -C ${repoPath} status --porcelain`).toString().length > 0
if (!hasChanges) {
await $`git -C ${repoPath} pull --${config.strategy}`
continue
}
await $`git -C ${repoPath} stash push -m "automated_backup_${_currentDate()}"`
await $`git -C ${repoPath} pull --${config.strategy}`
try {
await $`git -C ${repoPath} stash pop`
} catch {
const stashRef = (await $`git -C ${repoPath} stash list`).toString().split('\n')[0].split(':')[0]
await $`git -C ${repoPath} stash apply ${stashRef}`
console.warn(`Stash conflicts ${name}. ` + `Changes preserved in ${stashRef}. Manual resolution required.`)
}
} catch (error) {
throw new GitCommandError('pull', name, error)
}
}
}
function _currentDate(): string {
return new Date().toISOString().split('T')[0].split('-').reverse().join('.')
}