-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub.ts
More file actions
193 lines (176 loc) · 6.29 KB
/
github.ts
File metadata and controls
193 lines (176 loc) · 6.29 KB
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import fs from 'fs-extra';
import path from 'path';
import { execa } from 'execa';
import inquirer from 'inquirer';
/**
* Sanitize a package name for use as a GitHub repository name (alphanumeric, hyphens, underscores)
*/
export function sanitizeRepoName(name: string): string {
// Strip npm scope if present (e.g. @scope/package -> package)
const withoutScope = name.startsWith('@') ? name.slice(name.indexOf('/') + 1) : name;
// GitHub allows A-Za-z0-9_.- ; replace invalid chars with hyphen and collapse multiple hyphens
return withoutScope
.toLowerCase()
.replace(/[^a-z0-9_.-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '') || 'my-project';
}
/**
* Check if GitHub CLI is installed and the user is authenticated
*/
export async function checkGhAuth(): Promise<{ ok: true; username: string } | { ok: false; message: string }> {
try {
await execa('gh', ['auth', 'status'], { reject: true });
} catch {
return { ok: false, message: 'GitHub CLI (gh) is not installed or you are not logged in. Install it from https://cli.github.com/ and run "gh auth login".' };
}
try {
const { stdout } = await execa('gh', ['api', 'user', '--jq', '.login'], { encoding: 'utf8' });
const username = stdout?.trim();
if (!username) {
return { ok: false, message: 'Could not determine your GitHub username.' };
}
return { ok: true, username };
} catch {
return { ok: false, message: 'Could not fetch your GitHub username. Ensure "gh auth login" has been run.' };
}
}
/**
* Check if a repository already exists for the given owner and repo name
*/
export async function repoExists(owner: string, repoName: string): Promise<boolean> {
try {
await execa('gh', ['api', `repos/${owner}/${repoName}`], { reject: true });
return true;
} catch {
return false;
}
}
/**
* Ensure the project has at least one commit (for push). Idempotent.
*/
async function ensureInitialCommit(projectPath: string): Promise<void> {
try {
await execa('git', ['rev-parse', '--verify', 'HEAD'], {
cwd: projectPath,
reject: true,
});
} catch {
await execa('git', ['add', '.'], { stdio: 'inherit', cwd: projectPath });
await execa('git', ['commit', '-m', 'Initial commit'], {
stdio: 'inherit',
cwd: projectPath,
});
}
}
/**
* Create a new GitHub repository and return its URL. Does not push.
*/
export async function createRepo(options: {
repoName: string;
projectPath: string;
username: string;
description?: string;
}): Promise<string> {
const gitDir = path.join(options.projectPath, '.git');
if (!(await fs.pathExists(gitDir))) {
await execa('git', ['init'], { stdio: 'inherit', cwd: options.projectPath });
}
await ensureInitialCommit(options.projectPath);
const args = [
'repo',
'create',
options.repoName,
'--public',
`--source=${options.projectPath}`,
'--remote=origin',
'--push',
];
if (options.description) {
args.push(`--description=${options.description}`);
}
await execa('gh', args, { stdio: 'inherit', cwd: options.projectPath });
return `https://github.com/${options.username}/${options.repoName}.git`;
}
/**
* Interactive flow: prompt to create a GitHub repo under the current user, then create it and set origin.
* Returns true if a repo was created (or already had origin), false if skipped or failed.
*/
export async function offerAndCreateGitHubRepo(projectPath: string): Promise<boolean> {
const pkgJsonPath = path.join(projectPath, 'package.json');
if (!(await fs.pathExists(pkgJsonPath))) {
console.log('\nℹ️ No package.json found; skipping GitHub repository creation.\n');
return false;
}
const { createGitHub } = await inquirer.prompt([
{
type: 'confirm',
name: 'createGitHub',
message: 'Would you like to create a GitHub repository for this project?',
default: false,
},
]);
if (!createGitHub) return false;
const auth = await checkGhAuth();
if (!auth.ok) {
console.log(`\n⚠️ ${auth.message}`);
console.log(' Skipping GitHub repository creation.\n');
return false;
}
const pkgJson = await fs.readJson(pkgJsonPath);
const projectName = (pkgJson.name as string) ?? 'my-project';
let repoName = sanitizeRepoName(projectName);
while (await repoExists(auth.username, repoName)) {
console.log(`\n⚠️ A repository named "${repoName}" already exists on GitHub under your account.\n`);
const { alternativeName } = await inquirer.prompt([
{
type: 'input',
name: 'alternativeName',
message: 'Enter an alternative repository name (or leave empty to skip creating a GitHub repository):',
default: '',
},
]);
if (!alternativeName?.trim()) {
repoName = '';
break;
}
repoName = sanitizeRepoName(alternativeName.trim());
}
if (!repoName) return false;
const repoUrl = `https://github.com/${auth.username}/${repoName}`;
console.log('\n📋 The following will happen:\n');
console.log(` • A new public repository will be created at: ${repoUrl}`);
console.log(` • The repository will be created under your GitHub account (${auth.username}).`);
console.log(` • The repository URL will be added to your package.json.`);
console.log(` • The remote "origin" will be set to this repository (you can push when ready).\n`);
const { confirmCreate } = await inquirer.prompt([
{
type: 'confirm',
name: 'confirmCreate',
message: 'Do you want to proceed with creating this repository?',
default: true,
},
]);
if (!confirmCreate) {
console.log('\n❌ GitHub repository was not created.\n');
return false;
}
try {
const createdUrl = await createRepo({
repoName,
projectPath,
username: auth.username,
...(pkgJson.description && { description: String(pkgJson.description) }),
});
pkgJson.repository = { type: 'git', url: createdUrl };
await fs.writeJson(pkgJsonPath, pkgJson, { spaces: 2 });
console.log('\n✅ GitHub repository created successfully!');
console.log(` ${repoUrl}`);
console.log(' Repository URL has been added to your package.json.\n');
return true;
} catch (err) {
console.error('\n❌ Failed to create GitHub repository:');
if (err instanceof Error) console.error(` ${err.message}\n`);
return false;
}
}