gh-setup-git-identity 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Publish to npm using OIDC trusted publishing
5
+ * Usage: node scripts/publish-to-npm.mjs [--should-pull]
6
+ * should_pull: Optional flag to pull latest changes before publishing (for release job)
7
+ *
8
+ * Uses link-foundation libraries:
9
+ * - use-m: Dynamic package loading without package.json dependencies
10
+ * - command-stream: Modern shell command execution with streaming support
11
+ * - lino-arguments: Unified configuration from CLI args, env vars, and .lenv files
12
+ */
13
+
14
+ import { readFileSync, appendFileSync } from 'fs';
15
+
16
+ // Load use-m dynamically
17
+ const { use } = eval(
18
+ await (await fetch('https://unpkg.com/use-m/use.js')).text()
19
+ );
20
+
21
+ // Import link-foundation libraries
22
+ const { $ } = await use('command-stream');
23
+ const { makeConfig } = await use('lino-arguments');
24
+
25
+ // Parse CLI arguments using lino-arguments
26
+ const config = makeConfig({
27
+ yargs: ({ yargs, getenv }) =>
28
+ yargs.option('should-pull', {
29
+ type: 'boolean',
30
+ default: getenv('SHOULD_PULL', false),
31
+ describe: 'Pull latest changes before publishing',
32
+ }),
33
+ });
34
+
35
+ const { shouldPull } = config;
36
+ const MAX_RETRIES = 3;
37
+ const RETRY_DELAY = 10000; // 10 seconds
38
+
39
+ /**
40
+ * Sleep for specified milliseconds
41
+ * @param {number} ms
42
+ */
43
+ function sleep(ms) {
44
+ return new Promise((resolve) => globalThis.setTimeout(resolve, ms));
45
+ }
46
+
47
+ /**
48
+ * Append to GitHub Actions output file
49
+ * @param {string} key
50
+ * @param {string} value
51
+ */
52
+ function setOutput(key, value) {
53
+ const outputFile = process.env.GITHUB_OUTPUT;
54
+ if (outputFile) {
55
+ appendFileSync(outputFile, `${key}=${value}\n`);
56
+ }
57
+ }
58
+
59
+ async function main() {
60
+ try {
61
+ if (shouldPull) {
62
+ // Pull the latest changes we just pushed
63
+ await $`git pull origin main`;
64
+ }
65
+
66
+ // Get current version
67
+ const packageJson = JSON.parse(readFileSync('./package.json', 'utf8'));
68
+ const currentVersion = packageJson.version;
69
+ console.log(`Current version to publish: ${currentVersion}`);
70
+
71
+ // Check if this version is already published on npm
72
+ console.log(
73
+ `Checking if version ${currentVersion} is already published...`
74
+ );
75
+ const checkResult =
76
+ await $`npm view "gh-setup-git-identity@${currentVersion}" version`.run({
77
+ capture: true,
78
+ });
79
+
80
+ // command-stream returns { code: 0 } on success, { code: 1 } on failure (e.g., E404)
81
+ // Exit code 0 means version exists, non-zero means version not found
82
+ if (checkResult.code === 0) {
83
+ console.log(`Version ${currentVersion} is already published to npm`);
84
+ setOutput('published', 'true');
85
+ setOutput('published_version', currentVersion);
86
+ setOutput('already_published', 'true');
87
+ return;
88
+ } else {
89
+ // Version not found on npm (E404), proceed with publish
90
+ console.log(
91
+ `Version ${currentVersion} not found on npm, proceeding with publish...`
92
+ );
93
+ }
94
+
95
+ // Publish to npm using OIDC trusted publishing with retry logic
96
+ for (let i = 1; i <= MAX_RETRIES; i++) {
97
+ console.log(`Publish attempt ${i} of ${MAX_RETRIES}...`);
98
+ try {
99
+ await $`npm run changeset:publish`;
100
+ setOutput('published', 'true');
101
+ setOutput('published_version', currentVersion);
102
+ console.log(`Published gh-setup-git-identity@${currentVersion} to npm`);
103
+ return;
104
+ } catch (_error) {
105
+ if (i < MAX_RETRIES) {
106
+ console.log(
107
+ `Publish failed, waiting ${RETRY_DELAY / 1000}s before retry...`
108
+ );
109
+ await sleep(RETRY_DELAY);
110
+ }
111
+ }
112
+ }
113
+
114
+ console.error(`Failed to publish after ${MAX_RETRIES} attempts`);
115
+ process.exit(1);
116
+ } catch (error) {
117
+ console.error('Error:', error.message);
118
+ process.exit(1);
119
+ }
120
+ }
121
+
122
+ main();
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Update npm for OIDC trusted publishing
5
+ * npm trusted publishing requires npm >= 11.5.1
6
+ * Node.js 20.x ships with npm 10.x, so we need to update
7
+ *
8
+ * Uses link-foundation libraries:
9
+ * - use-m: Dynamic package loading without package.json dependencies
10
+ * - command-stream: Modern shell command execution with streaming support
11
+ */
12
+
13
+ // Load use-m dynamically
14
+ const { use } = eval(
15
+ await (await fetch('https://unpkg.com/use-m/use.js')).text()
16
+ );
17
+
18
+ // Import command-stream for shell command execution
19
+ const { $ } = await use('command-stream');
20
+
21
+ try {
22
+ // Get current npm version
23
+ const currentResult = await $`npm --version`.run({ capture: true });
24
+ const currentVersion = currentResult.stdout.trim();
25
+ console.log(`Current npm version: ${currentVersion}`);
26
+
27
+ // Update npm to latest
28
+ await $`npm install -g npm@latest`;
29
+
30
+ // Get updated npm version
31
+ const updatedResult = await $`npm --version`.run({ capture: true });
32
+ const updatedVersion = updatedResult.stdout.trim();
33
+ console.log(`Updated npm version: ${updatedVersion}`);
34
+ } catch (error) {
35
+ console.error('Error updating npm:', error.message);
36
+ process.exit(1);
37
+ }
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Validate changeset for CI - ensures exactly one valid changeset exists
5
+ */
6
+
7
+ import { readdirSync, readFileSync } from 'fs';
8
+ import { join } from 'path';
9
+
10
+ try {
11
+ // Count changeset files (excluding README.md and config.json)
12
+ const changesetDir = '.changeset';
13
+ const changesetFiles = readdirSync(changesetDir).filter(
14
+ (file) => file.endsWith('.md') && file !== 'README.md'
15
+ );
16
+
17
+ const changesetCount = changesetFiles.length;
18
+ console.log(`Found ${changesetCount} changeset file(s)`);
19
+
20
+ // Ensure exactly one changeset file exists
21
+ if (changesetCount === 0) {
22
+ console.error(
23
+ "::error::No changeset found. Please add a changeset by running 'npm run changeset' and commit the result."
24
+ );
25
+ process.exit(1);
26
+ } else if (changesetCount > 1) {
27
+ console.error(
28
+ `::error::Multiple changesets found (${changesetCount}). Each PR should have exactly ONE changeset.`
29
+ );
30
+ console.error('::error::Found changeset files:');
31
+ changesetFiles.forEach((file) => console.error(` ${file}`));
32
+ process.exit(1);
33
+ }
34
+
35
+ // Get the changeset file
36
+ const changesetFile = join(changesetDir, changesetFiles[0]);
37
+ console.log(`Validating changeset: ${changesetFile}`);
38
+
39
+ // Read the changeset file
40
+ const content = readFileSync(changesetFile, 'utf-8');
41
+
42
+ // Check if changeset has a valid type (major, minor, or patch)
43
+ const versionTypeRegex = /^['"]gh-setup-git-identity['"]:\s+(major|minor|patch)/m;
44
+ if (!versionTypeRegex.test(content)) {
45
+ console.error(
46
+ '::error::Changeset must specify a version type: major, minor, or patch'
47
+ );
48
+ console.error(`::error::Expected format in ${changesetFile}:`);
49
+ console.error('::error::---');
50
+ console.error("::error::'gh-setup-git-identity': patch");
51
+ console.error('::error::---');
52
+ console.error('::error::');
53
+ console.error('::error::Your description here');
54
+ console.error('\nFile content:');
55
+ console.error(content);
56
+ process.exit(1);
57
+ }
58
+
59
+ // Extract description (everything after the closing ---) and check it's not empty
60
+ const parts = content.split('---');
61
+ if (parts.length < 3) {
62
+ console.error(
63
+ '::error::Changeset must include a description of the changes'
64
+ );
65
+ console.error(
66
+ "::error::The description should appear after the closing '---' in the changeset file"
67
+ );
68
+ console.error(`::error::Current content of ${changesetFile}:`);
69
+ console.error(content);
70
+ process.exit(1);
71
+ }
72
+
73
+ const description = parts.slice(2).join('---').trim();
74
+ if (!description) {
75
+ console.error(
76
+ '::error::Changeset must include a description of the changes'
77
+ );
78
+ console.error(
79
+ "::error::The description should appear after the closing '---' in the changeset file"
80
+ );
81
+ console.error(`::error::Current content of ${changesetFile}:`);
82
+ console.error(content);
83
+ process.exit(1);
84
+ }
85
+
86
+ // Extract version type
87
+ const versionTypeMatch = content.match(versionTypeRegex);
88
+ const versionType = versionTypeMatch ? versionTypeMatch[1] : 'unknown';
89
+
90
+ console.log('Changeset validation passed');
91
+ console.log(` Type: ${versionType}`);
92
+ console.log(` Description: ${description}`);
93
+ } catch (error) {
94
+ console.error('Error during changeset validation:', error.message);
95
+ if (process.env.DEBUG) {
96
+ console.error('Stack trace:', error.stack);
97
+ }
98
+ process.exit(1);
99
+ }
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Version packages and commit to main
5
+ * Usage: node scripts/version-and-commit.mjs --mode <changeset|instant> [--bump-type <type>] [--description <desc>]
6
+ * changeset: Run changeset version
7
+ * instant: Run instant version bump with bump_type (patch|minor|major) and optional description
8
+ *
9
+ * Uses link-foundation libraries:
10
+ * - use-m: Dynamic package loading without package.json dependencies
11
+ * - command-stream: Modern shell command execution with streaming support
12
+ * - lino-arguments: Unified configuration from CLI args, env vars, and .lenv files
13
+ */
14
+
15
+ import { readFileSync, appendFileSync, readdirSync } from 'fs';
16
+
17
+ // Load use-m dynamically
18
+ const { use } = eval(
19
+ await (await fetch('https://unpkg.com/use-m/use.js')).text()
20
+ );
21
+
22
+ // Import link-foundation libraries
23
+ const { $ } = await use('command-stream');
24
+ const { makeConfig } = await use('lino-arguments');
25
+
26
+ // Parse CLI arguments using lino-arguments
27
+ const config = makeConfig({
28
+ yargs: ({ yargs, getenv }) =>
29
+ yargs
30
+ .option('mode', {
31
+ type: 'string',
32
+ default: getenv('MODE', 'changeset'),
33
+ describe: 'Version mode: changeset or instant',
34
+ choices: ['changeset', 'instant'],
35
+ })
36
+ .option('bump-type', {
37
+ type: 'string',
38
+ default: getenv('BUMP_TYPE', ''),
39
+ describe: 'Version bump type for instant mode: major, minor, or patch',
40
+ })
41
+ .option('description', {
42
+ type: 'string',
43
+ default: getenv('DESCRIPTION', ''),
44
+ describe: 'Description for instant version bump',
45
+ }),
46
+ });
47
+
48
+ const { mode, bumpType, description } = config;
49
+
50
+ // Debug: Log parsed configuration
51
+ console.log('Parsed configuration:', {
52
+ mode,
53
+ bumpType,
54
+ description: description || '(none)',
55
+ });
56
+
57
+ // Detect if positional arguments were used (common mistake)
58
+ const args = process.argv.slice(2);
59
+ if (args.length > 0 && !args[0].startsWith('--')) {
60
+ console.error('Error: Positional arguments detected!');
61
+ console.error('Command line arguments:', args);
62
+ console.error('');
63
+ console.error(
64
+ 'This script requires named arguments (--mode, --bump-type, --description).'
65
+ );
66
+ console.error('Usage:');
67
+ console.error(' Changeset mode:');
68
+ console.error(' node scripts/version-and-commit.mjs --mode changeset');
69
+ console.error(' Instant mode:');
70
+ console.error(
71
+ ' node scripts/version-and-commit.mjs --mode instant --bump-type <major|minor|patch> [--description <desc>]'
72
+ );
73
+ console.error('');
74
+ console.error('Examples:');
75
+ console.error(
76
+ ' node scripts/version-and-commit.mjs --mode instant --bump-type patch --description "Fix bug"'
77
+ );
78
+ console.error(' node scripts/version-and-commit.mjs --mode changeset');
79
+ process.exit(1);
80
+ }
81
+
82
+ // Validation: Ensure mode is set correctly
83
+ if (mode !== 'changeset' && mode !== 'instant') {
84
+ console.error(`Invalid mode: "${mode}". Expected "changeset" or "instant".`);
85
+ console.error('Command line arguments:', process.argv.slice(2));
86
+ process.exit(1);
87
+ }
88
+
89
+ // Validation: Ensure bump type is provided for instant mode
90
+ if (mode === 'instant' && !bumpType) {
91
+ console.error('Error: --bump-type is required for instant mode');
92
+ console.error(
93
+ 'Usage: node scripts/version-and-commit.mjs --mode instant --bump-type <major|minor|patch> [--description <desc>]'
94
+ );
95
+ process.exit(1);
96
+ }
97
+
98
+ /**
99
+ * Append to GitHub Actions output file
100
+ * @param {string} key
101
+ * @param {string} value
102
+ */
103
+ function setOutput(key, value) {
104
+ const outputFile = process.env.GITHUB_OUTPUT;
105
+ if (outputFile) {
106
+ appendFileSync(outputFile, `${key}=${value}\n`);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Count changeset files (excluding README.md)
112
+ */
113
+ function countChangesets() {
114
+ try {
115
+ const changesetDir = '.changeset';
116
+ const files = readdirSync(changesetDir);
117
+ return files.filter((f) => f.endsWith('.md') && f !== 'README.md').length;
118
+ } catch {
119
+ return 0;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Get package version
125
+ * @param {string} source - 'local' or 'remote'
126
+ */
127
+ async function getVersion(source = 'local') {
128
+ if (source === 'remote') {
129
+ const result = await $`git show origin/main:package.json`.run({
130
+ capture: true,
131
+ });
132
+ return JSON.parse(result.stdout).version;
133
+ }
134
+ return JSON.parse(readFileSync('./package.json', 'utf8')).version;
135
+ }
136
+
137
+ async function main() {
138
+ try {
139
+ // Configure git
140
+ await $`git config user.name "github-actions[bot]"`;
141
+ await $`git config user.email "github-actions[bot]@users.noreply.github.com"`;
142
+
143
+ // Check if remote main has advanced (handles re-runs after partial success)
144
+ console.log('Checking for remote changes...');
145
+ await $`git fetch origin main`;
146
+
147
+ const localHeadResult = await $`git rev-parse HEAD`.run({ capture: true });
148
+ const localHead = localHeadResult.stdout.trim();
149
+
150
+ const remoteHeadResult = await $`git rev-parse origin/main`.run({
151
+ capture: true,
152
+ });
153
+ const remoteHead = remoteHeadResult.stdout.trim();
154
+
155
+ if (localHead !== remoteHead) {
156
+ console.log(
157
+ `Remote main has advanced (local: ${localHead}, remote: ${remoteHead})`
158
+ );
159
+ console.log('This may indicate a previous attempt partially succeeded.');
160
+
161
+ // Check if the remote version is already the expected bump
162
+ const remoteVersion = await getVersion('remote');
163
+ console.log(`Remote version: ${remoteVersion}`);
164
+
165
+ // Check if there are changesets to process
166
+ const changesetCount = countChangesets();
167
+
168
+ if (changesetCount === 0) {
169
+ console.log('No changesets to process and remote has advanced.');
170
+ console.log(
171
+ 'Assuming version bump was already completed in a previous attempt.'
172
+ );
173
+ setOutput('version_committed', 'false');
174
+ setOutput('already_released', 'true');
175
+ setOutput('new_version', remoteVersion);
176
+ return;
177
+ } else {
178
+ console.log('Rebasing on remote main to incorporate changes...');
179
+ await $`git rebase origin/main`;
180
+ }
181
+ }
182
+
183
+ // Get current version before bump
184
+ const oldVersion = await getVersion();
185
+ console.log(`Current version: ${oldVersion}`);
186
+
187
+ if (mode === 'instant') {
188
+ console.log('Running instant version bump...');
189
+ // Run instant version bump script
190
+ // Rely on command-stream's auto-quoting for proper argument handling
191
+ if (description) {
192
+ await $`node scripts/instant-version-bump.mjs --bump-type ${bumpType} --description ${description}`;
193
+ } else {
194
+ await $`node scripts/instant-version-bump.mjs --bump-type ${bumpType}`;
195
+ }
196
+ } else {
197
+ console.log('Running changeset version...');
198
+ // Run changeset version to bump versions and update CHANGELOG
199
+ await $`npm run changeset:version`;
200
+ }
201
+
202
+ // Get new version after bump
203
+ const newVersion = await getVersion();
204
+ console.log(`New version: ${newVersion}`);
205
+ setOutput('new_version', newVersion);
206
+
207
+ // Check if there are changes to commit
208
+ const statusResult = await $`git status --porcelain`.run({ capture: true });
209
+ const status = statusResult.stdout.trim();
210
+
211
+ if (status) {
212
+ console.log('Changes detected, committing...');
213
+
214
+ // Stage all changes (package.json, package-lock.json, CHANGELOG.md, deleted changesets)
215
+ await $`git add -A`;
216
+
217
+ // Commit with version number as message
218
+ const commitMessage = newVersion;
219
+ const escapedMessage = commitMessage.replace(/"/g, '\\"');
220
+ await $`git commit -m "${escapedMessage}"`;
221
+
222
+ // Push directly to main
223
+ await $`git push origin main`;
224
+
225
+ console.log('Version bump committed and pushed to main');
226
+ setOutput('version_committed', 'true');
227
+ } else {
228
+ console.log('No changes to commit');
229
+ setOutput('version_committed', 'false');
230
+ }
231
+ } catch (error) {
232
+ console.error('Error:', error.message);
233
+ process.exit(1);
234
+ }
235
+ }
236
+
237
+ main();
package/src/cli.js ADDED
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * gh-setup-git-identity CLI
5
+ *
6
+ * Command-line interface for setting up git identity based on GitHub user
7
+ */
8
+
9
+ import { makeConfig } from 'lino-arguments';
10
+ import { setupGitIdentity, isGhAuthenticated } from './index.js';
11
+
12
+ // Parse command-line arguments with environment variable and .lenv support
13
+ const config = makeConfig({
14
+ yargs: ({ yargs, getenv }) =>
15
+ yargs
16
+ .usage('Usage: $0 [options]')
17
+ .option('global', {
18
+ alias: 'g',
19
+ type: 'boolean',
20
+ description: 'Set git config globally (default)',
21
+ default: false
22
+ })
23
+ .option('local', {
24
+ alias: 'l',
25
+ type: 'boolean',
26
+ description: 'Set git config locally (in current repository)',
27
+ default: getenv('GH_SETUP_GIT_IDENTITY_LOCAL', false)
28
+ })
29
+ .option('verbose', {
30
+ alias: 'v',
31
+ type: 'boolean',
32
+ description: 'Enable verbose output',
33
+ default: getenv('GH_SETUP_GIT_IDENTITY_VERBOSE', false)
34
+ })
35
+ .option('dry-run', {
36
+ alias: 'dry',
37
+ type: 'boolean',
38
+ description: 'Dry run mode - show what would be done without making changes',
39
+ default: getenv('GH_SETUP_GIT_IDENTITY_DRY_RUN', false)
40
+ })
41
+ .check((argv) => {
42
+ // --global and --local are mutually exclusive
43
+ if (argv.global && argv.local) {
44
+ throw new Error('Arguments global and local are mutually exclusive');
45
+ }
46
+ return true;
47
+ })
48
+ .example('$0', 'Setup git identity globally using GitHub user')
49
+ .example('$0 --local', 'Setup git identity for current repository only')
50
+ .example('$0 --dry-run', 'Show what would be configured without making changes')
51
+ .help('h')
52
+ .alias('h', 'help')
53
+ .version('0.1.0')
54
+ .strict(),
55
+ });
56
+
57
+ /**
58
+ * Main CLI function
59
+ */
60
+ async function main() {
61
+ try {
62
+ // Determine scope
63
+ const scope = config.local ? 'local' : 'global';
64
+
65
+ // Check if gh is authenticated
66
+ const authenticated = await isGhAuthenticated({ verbose: config.verbose });
67
+
68
+ if (!authenticated) {
69
+ console.log('');
70
+ console.log('GitHub CLI is not authenticated.');
71
+ console.log('');
72
+ console.log('Please run the following command to login:');
73
+ console.log('');
74
+ console.log(' gh auth login -h github.com -s repo,workflow,user,read:org,gist');
75
+ console.log('');
76
+ console.log('After logging in, run gh-setup-git-identity again.');
77
+ process.exit(1);
78
+ }
79
+
80
+ // Prepare options
81
+ const options = {
82
+ scope,
83
+ dryRun: config.dryRun,
84
+ verbose: config.verbose
85
+ };
86
+
87
+ if (options.verbose) {
88
+ console.log('Options:', options);
89
+ console.log('');
90
+ }
91
+
92
+ if (options.dryRun) {
93
+ console.log('DRY MODE - No actual changes will be made');
94
+ console.log('');
95
+ }
96
+
97
+ // Setup git identity
98
+ const result = await setupGitIdentity(options);
99
+
100
+ // Display results
101
+ console.log('');
102
+ console.log(`${options.dryRun ? '[DRY MODE] Would configure' : 'Git configured'}:`);
103
+ console.log('');
104
+ console.log(` user.name: ${result.username}`);
105
+ console.log(` user.email: ${result.email}`);
106
+ console.log('');
107
+ console.log(`Scope: ${scope === 'global' ? 'global (--global)' : 'local (--local)'}`);
108
+ console.log('');
109
+
110
+ if (!options.dryRun) {
111
+ console.log('Git identity setup complete!');
112
+ }
113
+
114
+ process.exit(0);
115
+ } catch (error) {
116
+ console.error('');
117
+ console.error('Error:', error.message);
118
+
119
+ if (config.verbose) {
120
+ console.error('');
121
+ console.error('Stack trace:');
122
+ console.error(error.stack);
123
+ }
124
+
125
+ process.exit(1);
126
+ }
127
+ }
128
+
129
+ // Run the CLI
130
+ main();