-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.js
More file actions
200 lines (158 loc) Β· 6.1 KB
/
setup.js
File metadata and controls
200 lines (158 loc) Β· 6.1 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
194
195
196
197
198
199
200
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import {execSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function exec(command) {
try {
return execSync(command, {encoding: 'utf8', stdio: ['pipe', 'pipe', 'inherit']});
} catch (error) {
console.error(`β Failed to run: ${command}`, error);
throw error;
}
}
function safeExec(command, description) {
try {
console.log(`β³ ${description}...`);
exec(command);
console.log(`β
${description} complete`);
return true;
} catch (error) {
console.warn(`β οΈ ${description} failed - you may need to do this manually`, error);
return false;
}
}
function updatePackageJson(packageName, repoUrl, isPrivate) {
const packageJsonPath = path.join(__dirname, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
packageJson.name = packageName;
packageJson.description = 'TODO: A short description of what the library does and why people might want to use it.';
packageJson.repository.url = repoUrl;
if (isPrivate) {
packageJson.private = true;
}
fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`);
console.log('β
Updated package.json');
}
function enableGitHubActionsPermissions() {
safeExec('gh repo edit --enable-issues --enable-wiki=false --enable-projects=false', 'Configuring repository settings');
safeExec('gh api repos/:owner/:repo/actions/permissions/fork-pr-contributor-approval -X PUT --input - << \'EOF\'\n{"approval_policy":"first_time_contributors_new_to_github"}\nEOF', 'Enabling first-time contributors to trigger GitHub Actions');
safeExec('gh api repos/:owner/:repo/actions/permissions/workflow -X PUT --input - << \'EOF\'\n{"can_approve_pull_request_reviews":true}\nEOF', 'Allowing GitHub Actions to create and approve pull requests');
}
function setupBranchProtection() {
safeExec(`gh api repos/:owner/:repo/branches/master/protection -X PUT --input - << 'EOF'
{
"required_status_checks": {
"strict": false,
"contexts": ["ci (lts/*)", "ci (current)"]
},
"enforce_admins": false,
"required_pull_request_reviews": {
"required_approving_review_count": 1
},
"restrictions": null,
"allow_force_pushes": true
}
EOF`, 'Setting up branch protection');
}
function addToFileSyncAutomation(repoUrl) {
console.log('β³ Adding repository to file sync automation...');
const repoMatch = repoUrl.match(/github\.com[/:]([\w-]+)\/([\w-]+)/);
if (!repoMatch) {
throw new Error(`Could not parse repository URL: ${repoUrl}`);
}
const [, owner, repo] = repoMatch;
const newRepoEntry = ` ${owner}/${repo}`;
// Create a temporary directory for cloning
const tempDir = path.join(__dirname, `.temp-clone-${Date.now()}`);
try {
// Clone the repository
console.log('β³ Cloning domdomegg/domdomegg repository...');
exec(`git clone git@github.com:domdomegg/domdomegg.git ${tempDir}`);
// Read the sync config file
const syncConfigPath = path.join(tempDir, '.github/workflows/repo-file-sync.yaml');
const syncConfig = fs.readFileSync(syncConfigPath, 'utf8');
// Check if already exists
if (syncConfig.includes(newRepoEntry.trim())) {
console.log('βΉοΈ Repository already in file sync automation');
return;
}
// Update the file content
let updatedConfig = syncConfig;
// Add to Dependabot automation section
updatedConfig = updatedConfig.replace(
/(- name: Dependabot automation[\s\S]*?REPOSITORIES: \|[\s\S]*?)( {12}domdomegg\/typescript-library-template)/,
`$1$2\n${newRepoEntry}`,
);
// Add to Node.js general template section
updatedConfig = updatedConfig.replace(
/(- name: Node\.js general template[\s\S]*?REPOSITORIES: \|[\s\S]*?)( {12}domdomegg\/typescript-library-template)/,
`$1$2\n${newRepoEntry}`,
);
// Write the updated config back to the file
fs.writeFileSync(syncConfigPath, updatedConfig);
// Commit and push changes
console.log('β³ Committing and pushing changes...');
exec(`cd ${tempDir} && git add .github/workflows/repo-file-sync.yaml`);
exec(`cd ${tempDir} && git commit -m "Add ${owner}/${repo} to file sync automation"`);
exec(`cd ${tempDir} && git push origin master`);
console.log('β
Added to file sync automation via direct push');
} finally {
// Clean up temporary directory
if (fs.existsSync(tempDir)) {
exec(`rm -rf ${tempDir}`);
}
}
}
function updateReadme(packageName, isPrivate) {
const readmeContent = `# ${packageName}
TODO: A short description of what the library does and why people might want to use it.
## Usage
TODO: Add usage instructions
## Contributing
Pull requests are welcomed on GitHub! To get started:
1. Install Git and Node.js
2. Clone the repository
3. Install dependencies with \`npm install\`
4. Run \`npm run test\` to run tests
5. Build with \`npm run build\`${isPrivate
? ''
: `
## Releases
Versions follow the [semantic versioning spec](https://semver.org/).
To release:
1. Use \`npm version <major | minor | patch>\` to bump the version
2. Run \`git push --follow-tags\` to push with tags
3. Wait for GitHub Actions to publish to the NPM registry.
`}`;
fs.writeFileSync(path.join(__dirname, 'README.md'), readmeContent);
console.log('β
Updated README.md');
}
function deleteSetupJs() {
fs.unlinkSync(__filename);
console.log('β
Deleted setup.js');
}
async function main() {
console.log('π Setting up your TypeScript library...\n');
// Check git and gh CLI is available
exec('git --version');
exec('gh api user');
// Get current repo info
const remoteUrl = exec('git remote get-url origin').trim();
const repoUrl = remoteUrl;
const match = remoteUrl.match(/([^/]+)\.git$/);
const packageName = match?.[1];
if (!match || !packageName) {
throw new Error('Could not extract package name from git remote');
}
const isPrivate = process.argv.includes('--private');
updatePackageJson(packageName, repoUrl, isPrivate);
enableGitHubActionsPermissions();
setupBranchProtection();
addToFileSyncAutomation(repoUrl);
updateReadme(packageName, isPrivate);
deleteSetupJs();
}
main().catch(console.error);