@ggdna/dna-scripts 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) ggsuite
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # dna_scripts
2
+
3
+ The DNA layer for the node scripts a repo automates its workflow with —
4
+ deterministic given local git and file system state, no GitHub API calls.
5
+
6
+ ## Guides
7
+
8
+ - `dna/doc/guides/scripts-guide.md` — what belongs here, what does not,
9
+ and how to add a script
10
+
11
+ ## Skills
12
+
13
+ - `/scripts` — checks every script parses, every import resolves, and
14
+ reports duplicated logic that should be a shared function
15
+
16
+ ## Scripts
17
+
18
+ - `dna/scripts/functions/colors.js` — ANSI colors for console output
19
+ - `dna/scripts/functions/current-branch.js` — the current git branch
20
+ - `dna/scripts/functions/directories.js` — the script's own directory
21
+ - `dna/scripts/functions/get-version.js` — the version from `package.json`
22
+ - `dna/scripts/functions/is-clean-repo.js` — whether `main` is checked
23
+ out, clean and in sync with `origin/main`
24
+ - `dna/scripts/functions/is-main-up-to-date.js` — whether local `main`
25
+ matches `origin/main`
26
+ - `dna/scripts/functions/run-command.js` — runs a shell command, logs
27
+ and returns its output
28
+ - `dna/scripts/functions/sync-folders.js` — recursively copies one
29
+ folder into another
30
+ - `dna/scripts/functions/get-repo-urls.js` — lists a GitHub
31
+ organization's repository URLs via `gh`
32
+ - `dna/scripts/functions/pull-request-url.js` — the URL of the current
33
+ branch's pull request via `gh`
34
+ - `dna/scripts/delete-feature-branch.js` — deletes the current feature
35
+ branch locally and on the remote once it is merged
36
+ - `dna/scripts/rename-class.js` — renames every occurrence of a class
37
+ and file name across the repo
38
+ - `dna/scripts/setup-github-repo.js` — applies the branch protection
39
+ rules a new repo needs
40
+ - `dna/scripts/wait-for-pr.js` — waits for the current pull request to
41
+ merge
42
+
43
+ ## Layers
44
+
45
+ Orthogonal: this layer carries only its own topic and is combined with
46
+ other layers by the consuming repo.
47
+
48
+ ## Variables
49
+
50
+ - `dnaCopyrightHolder` — the name in the license header of every file
51
+
52
+ ## Usage
53
+
54
+ Declare it as a dev-dependency and initialize once:
55
+
56
+ ```bash
57
+ pnpm add -D @ggdna/dna-scripts # TypeScript projects
58
+ dart pub add dev:dna_scripts # Dart projects
59
+ helix init
60
+ ```
61
+
62
+ The placed test instantiates and verifies the DNA on every test run.
63
+
64
+ ## Development
65
+
66
+ The `dna/` folder is hand-authored source and is never generated. The repo
67
+ instantiates its own DNA — run `dart test` after changes; commit first, a
68
+ file the DNA would overwrite must not carry uncommitted work.
package/dna/_dna.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ // This package is a DNA layer: dna/ is hand-authored source and is the
3
+ // last layer of its own instantiation.
4
+ "version": 1,
5
+
6
+ // No parent DNA. This layer is orthogonal: it carries only its own topic
7
+ // and is combined with other layers by the consumer.
8
+ "layers": []
9
+ }
@@ -0,0 +1,96 @@
1
+ {
2
+ "version": 1,
3
+ "layers": [
4
+ {
5
+ "name": "base",
6
+ "package": "helix",
7
+ "ecosystem": null,
8
+ "resolvedVersion": "1.0.1",
9
+ "via": null,
10
+ "hash": "0x705e486e88a93125"
11
+ },
12
+ {
13
+ "name": "self",
14
+ "package": null,
15
+ "ecosystem": null,
16
+ "resolvedVersion": null,
17
+ "via": null,
18
+ "hash": "0x9ee08ef13ab4c8d3"
19
+ }
20
+ ],
21
+ "claude": {
22
+ "claudeMdInclude": null
23
+ },
24
+ "baseVersion": "1.0.1",
25
+ "baseHash": "0x705e486e88a93125",
26
+ "instances": [
27
+ {
28
+ "path": ".claude/skills/scripts/SKILL.md",
29
+ "hash": "0xa12593aa0af31ed2"
30
+ },
31
+ {
32
+ "path": "doc/guides/scripts-guide.md",
33
+ "hash": "0x426857c389049083"
34
+ },
35
+ {
36
+ "path": "doc/hello_world.md",
37
+ "hash": "0x0903f7fc5224f6f1"
38
+ },
39
+ {
40
+ "path": "scripts/delete-feature-branch.js",
41
+ "hash": "0x219ac0a3635ee644"
42
+ },
43
+ {
44
+ "path": "scripts/functions/colors.js",
45
+ "hash": "0xdfd97f3804665811"
46
+ },
47
+ {
48
+ "path": "scripts/functions/current-branch.js",
49
+ "hash": "0xb9ebbadf45893278"
50
+ },
51
+ {
52
+ "path": "scripts/functions/directories.js",
53
+ "hash": "0x148d4ebb8aa75523"
54
+ },
55
+ {
56
+ "path": "scripts/functions/get-repo-urls.js",
57
+ "hash": "0x4c7b3897973acec3"
58
+ },
59
+ {
60
+ "path": "scripts/functions/get-version.js",
61
+ "hash": "0xfe46316558755cf2"
62
+ },
63
+ {
64
+ "path": "scripts/functions/is-clean-repo.js",
65
+ "hash": "0x8aa95ca51d9d6517"
66
+ },
67
+ {
68
+ "path": "scripts/functions/is-main-up-to-date.js",
69
+ "hash": "0xe1ab1826d0ddd039"
70
+ },
71
+ {
72
+ "path": "scripts/functions/pull-request-url.js",
73
+ "hash": "0x5398755a61a59928"
74
+ },
75
+ {
76
+ "path": "scripts/functions/run-command.js",
77
+ "hash": "0x085b390fcb9256ab"
78
+ },
79
+ {
80
+ "path": "scripts/functions/sync-folders.js",
81
+ "hash": "0x4f83165fd92ec49d"
82
+ },
83
+ {
84
+ "path": "scripts/rename-class.js",
85
+ "hash": "0xa9daec4f3ea514b7"
86
+ },
87
+ {
88
+ "path": "scripts/setup-github-repo.js",
89
+ "hash": "0xff571fadb664af32"
90
+ },
91
+ {
92
+ "path": "scripts/wait-for-pr.js",
93
+ "hash": "0x1360c661984b78a8"
94
+ }
95
+ ]
96
+ }
package/dna/_vars.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "dnaCopyrightHolder": "ggsuite"
3
+ }
@@ -0,0 +1,25 @@
1
+ <!--
2
+ @license
3
+ Copyright (c) dnaCopyrightHolder
4
+
5
+ Use of this source code is governed by terms that can be
6
+ found in the LICENSE file in the root of this package.
7
+ -->
8
+
9
+ # Scripts Guide
10
+
11
+ The node scripts a repo automates its workflow with, and the functions they
12
+ share — from reading local git state to calling the GitHub API.
13
+
14
+ ## Use a function instead of repeating a command
15
+
16
+ - Import from `dna/scripts/functions/`, never duplicate a `git`, `gh` or
17
+ file system call across scripts
18
+ - Keep a function pure where possible: same input, same output, no
19
+ printing
20
+
21
+ ## Add a script
22
+
23
+ - Put it in `dna/scripts/`, its shared parts in `dna/scripts/functions/`
24
+ - Give it the license header every file here carries
25
+ - Call it from a guide of the layer that needs it
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: scripts
3
+ description: Checks that every script in dna/scripts is syntactically valid, imports resolve and logic is not duplicated. Use when the user says "/scripts" or asks whether the scripts still work.
4
+ ---
5
+
6
+ <!--
7
+ @license
8
+ Copyright (c) dnaCopyrightHolder
9
+
10
+ Use of this source code is governed by terms that can be
11
+ found in the LICENSE file in the root of this package.
12
+ -->
13
+
14
+ # Scripts
15
+
16
+ Read `doc/guides/scripts-guide.md` and follow it.
17
+
18
+ ## 1. Check every script parses
19
+
20
+ Run `node --check` on each file in `scripts/` and `scripts/functions/`.
21
+
22
+ Report any file that fails.
23
+
24
+ ## 2. Check the imports resolve
25
+
26
+ For each `import … from './functions/…'`, verify the target file exists
27
+ and exports the named symbol.
28
+
29
+ Report an import that resolves to nothing.
30
+
31
+ ## 3. Check for duplication
32
+
33
+ Report a `git`, `fs` or `child_process` call that is copied across two
34
+ scripts instead of living in one shared function.
35
+
36
+ ## 4. Fix
37
+
38
+ Write the corrections, then show the diff before committing.
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ import { gray, green, red, yellow } from './functions/colors.js';
10
+ import { runCommand } from './functions/run-command.js';
11
+
12
+ // Check for uncommitted changes
13
+ function hasUncommittedChanges() {
14
+ console.log(gray('Check for uncommitted changes'));
15
+ const status = runCommand('git status --porcelain');
16
+ return status.length > 0;
17
+ }
18
+
19
+ // Check for unpushed commits
20
+ function hasUnpushedCommits(branch) {
21
+ try {
22
+ console.log(gray('Check for unpushed commits'));
23
+ runCommand(`git rev-parse --abbrev-ref ${branch}@{u}`);
24
+ const ahead = runCommand(`git rev-list --count ${branch}@{u}..${branch}`);
25
+ return parseInt(ahead, 10) > 0;
26
+ } catch {
27
+ return true;
28
+ }
29
+ }
30
+
31
+ // Try a test merge into main and check if it introduces changes
32
+ function isBranchEffectivelyMerged(featureBranch) {
33
+ console.log(gray('Check if feature was fully merged'));
34
+
35
+ try {
36
+ runCommand(`git merge --no-commit --no-ff ${featureBranch}`);
37
+ const changed = hasUncommittedChanges();
38
+ runCommand('git merge --abort');
39
+ return !changed;
40
+ } catch {
41
+ try {
42
+ runCommand('git merge --abort');
43
+ } catch {}
44
+ return false;
45
+ }
46
+ }
47
+
48
+ try {
49
+ console.log(gray('Get current branch name'));
50
+ const currentBranch = runCommand('git rev-parse --abbrev-ref HEAD');
51
+
52
+ if (currentBranch === 'main') {
53
+ console.log(yellow('Please call this script from a feature branch.'));
54
+ process.exit(0);
55
+ }
56
+
57
+ if (hasUncommittedChanges()) {
58
+ console.error(red('❌ You have uncommitted changes.'));
59
+ console.error(
60
+ yellow('Please commit or stash your changes before continuing.'),
61
+ );
62
+ process.exit(1);
63
+ }
64
+
65
+ if (hasUnpushedCommits(currentBranch)) {
66
+ console.error(red('❌ You have unpushed commits.'));
67
+ console.error(yellow('Please push your branch before continuing.'));
68
+ process.exit(1);
69
+ }
70
+
71
+ console.log(gray(`Fetching and pulling 'main'...`));
72
+ runCommand('git fetch');
73
+ runCommand('git checkout main');
74
+ runCommand('git pull origin main');
75
+
76
+ const isMerged = isBranchEffectivelyMerged(currentBranch);
77
+
78
+ if (isMerged) {
79
+ runCommand(`git branch -d ${currentBranch}`);
80
+ console.log(green(`✅ Branch '${currentBranch}' has been deleted.`));
81
+ } else {
82
+ console.error(
83
+ red(`❌ Branch '${currentBranch}' is not merged into 'main'.`),
84
+ );
85
+ console.log(
86
+ yellow(`Please (create and) merge a pull request and try again.`),
87
+ );
88
+ runCommand(`git checkout ${currentBranch}`);
89
+ console.log(gray(`Switched back to '${currentBranch}'.`));
90
+ }
91
+ } catch (error) {
92
+ console.error(red(`Error: ${error.message}`));
93
+ try {
94
+ runCommand('git merge --abort');
95
+ } catch {}
96
+ process.exit(1);
97
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ export const red = (str) => `\x1b[31m${str}\x1b[0m`;
10
+ export const green = (str) => `\x1b[32m${str}\x1b[0m`;
11
+ export const yellow = (str) => `\x1b[33m${str}\x1b[0m`;
12
+ export const blue = (str) => `\x1b[34m${str}\x1b[0m`;
13
+ export const magenta = (str) => `\x1b[35m${str}\x1b[0m`;
14
+ export const cyan = (str) => `\x1b[36m${str}\x1b[0m`;
15
+ export const white = (str) => `\x1b[37m${str}\x1b[0m`;
16
+ export const black = (str) => `\x1b[30m${str}\x1b[0m`;
17
+ export const bgRed = (str) => `\x1b[41m${str}\x1b[0m`;
18
+ export const bgGreen = (str) => `\x1b[42m${str}\x1b[0m`;
19
+ export const bgYellow = (str) => `\x1b[43m${str}\x1b[0m`;
20
+ export const bgBlue = (str) => `\x1b[44m${str}\x1b[0m`;
21
+ export const bgMagenta = (str) => `\x1b[45m${str}\x1b[0m`;
22
+ export const bgCyan = (str) => `\x1b[46m${str}\x1b[0m`;
23
+ export const bgWhite = (str) => `\x1b[47m${str}\x1b[0m`;
24
+ export const bgBlack = (str) => `\x1b[40m${str}\x1b[0m`;
25
+ export const gray = (str) => `\x1b[90m${str}\x1b[0m`;
26
+ export const lightGray = (str) => `\x1b[37m${str}\x1b[0m`;
27
+ export const reset = (str) => `\x1b[0m${str}\x1b[0m`;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ export const currentBranch = () => {
10
+ return execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
11
+ };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ // Get the name of this file
10
+ import { dirname, join } from 'path';
11
+ import { fileURLToPath } from 'url';
12
+
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = dirname(__filename);
15
+
16
+ export const workSpaceDir = join(__dirname, '..', '..');
17
+ export const distDir = join(workSpaceDir, 'dist');
18
+ export const srcDir = join(workSpaceDir, 'src');
19
+ export const testDir = join(workSpaceDir, 'test');
20
+ export const scriptsDir = join(workSpaceDir, 'scripts');
21
+ export const goldensDir = join(testDir, 'goldens');
22
+ export const nodeModulesDir = join(workSpaceDir, 'node_modules');
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ // Import Node.js built-in module for working with child processes
10
+ import { exec } from 'child_process';
11
+ import { promisify } from 'util';
12
+ import { green, yellow } from './colors.js';
13
+
14
+ // Convert exec to return a Promise for async/await usage
15
+ const execAsync = promisify(exec);
16
+
17
+ // GitHub organization or user
18
+ const org = 'rljson';
19
+
20
+ export async function getRepoUrls() {
21
+ try {
22
+ // Use the GitHub CLI to list repositories in JSON format
23
+ const { stdout } = await execAsync(
24
+ `gh repo list ${org} --limit 1000 --json url`,
25
+ );
26
+
27
+ // Parse the JSON output
28
+ const repos = JSON.parse(stdout);
29
+
30
+ // Map to name + URL and print to console
31
+ return repos.map((repo) => repo.url);
32
+ } catch (error) {
33
+ if (error.message.match('gh auth login').length == 1) {
34
+ throw Error(
35
+ [yellow('Not yet logged in. Please run:'), green('gh auth login')].join(
36
+ '\n',
37
+ ),
38
+ );
39
+ }
40
+
41
+ throw error;
42
+ }
43
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ import { readFile } from 'fs/promises';
10
+
11
+ export const getVersion = async () => {
12
+ const packageJson = JSON.parse(await readFile('package.json', 'utf8'));
13
+ return packageJson.version;
14
+ };
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ // checkRepo.js
10
+ import { execSync } from 'child_process';
11
+
12
+ export function isCleanRepo(path) {
13
+ const cwd = path ?? '.';
14
+
15
+ try {
16
+ // Aktuellen Branch ermitteln
17
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', {
18
+ cwd,
19
+ })
20
+ .toString()
21
+ .trim();
22
+ if (branch !== 'main') {
23
+ return false;
24
+ }
25
+
26
+ // Git-Fetch ausführen (still)
27
+ execSync('git fetch', { stdio: 'ignore', cwd });
28
+
29
+ // Prüfen, ob Arbeitsverzeichnis sauber ist
30
+ const status = execSync('git status --porcelain', { cwd })
31
+ .toString()
32
+ .trim();
33
+ if (status.length > 0) {
34
+ return false;
35
+ }
36
+
37
+ // Prüfen, ob main auf dem neuesten Stand mit origin/main ist
38
+ const revList = execSync(
39
+ 'git rev-list --left-right --count origin/main...main',
40
+ { cwd },
41
+ )
42
+ .toString()
43
+ .trim();
44
+
45
+ const [behind, ahead] = revList.split('\t').map(Number);
46
+ return behind === 0 && ahead === 0;
47
+ } catch (err) {
48
+ console.error('Git error:', err.message);
49
+ return false;
50
+ }
51
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ export const isMainUpToDate = () => {
10
+ try {
11
+ execSync('git fetch origin main');
12
+ const localHash = execSync('git rev-parse main').toString().trim();
13
+ const remoteHash = execSync('git rev-parse origin/main').toString().trim();
14
+ return localHash === remoteHash;
15
+ } catch (error) {
16
+ console.error(red('Error checking branch status:'), error);
17
+ return false;
18
+ }
19
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ export function pullRequestUrl() {
10
+ const json = execSync('gh pr view --json url', {
11
+ encoding: 'utf-8',
12
+ }).trim();
13
+
14
+ const parsed = JSON.parse(json);
15
+ const url = parsed.url;
16
+ return url;
17
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ import { execSync } from 'child_process';
10
+ import { gray } from './colors.js';
11
+
12
+ // Execute a shell command and return trimmed output
13
+ // Execute a shell command and return trimmed output
14
+ export function runCommand(command, silent = true, logCommand = true) {
15
+ if (logCommand) {
16
+ console.log(gray(`${command}`));
17
+ }
18
+ return execSync(command, {
19
+ encoding: 'utf-8',
20
+ stdio: silent ? ['pipe', 'pipe', 'pipe'] : undefined,
21
+ }).trim();
22
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ import * as fs from 'fs';
10
+ import * as path from 'path';
11
+
12
+ // Create a node.js script that recursively copies all files from one folder
13
+ // to another
14
+
15
+ export async function syncFolders(
16
+ source,
17
+ target,
18
+ options = { excludeHidden: true },
19
+ ) {
20
+ if (!fs.existsSync(source)) {
21
+ console.error(`Source folder "${source}" does not exist.`);
22
+ return;
23
+ }
24
+
25
+ if (!fs.existsSync(target)) {
26
+ await fs.promises.mkdir(target, { recursive: true });
27
+ }
28
+
29
+ const items = await fs.promises.readdir(source);
30
+
31
+ for (const item of items) {
32
+ if (options.excludeHidden && item.startsWith('.')) {
33
+ continue; // Skip hidden files and folders
34
+ }
35
+
36
+ const sourcePath = path.join(source, item);
37
+ const targetPath = path.join(target, item);
38
+
39
+ const stat = await fs.promises.lstat(sourcePath);
40
+ if (stat.isDirectory()) {
41
+ await syncFolders(sourcePath, targetPath, options.excludeHidden);
42
+ } else {
43
+ await fs.promises.copyFile(sourcePath, targetPath);
44
+ }
45
+ }
46
+ }
@@ -0,0 +1,147 @@
1
+ #!/bin/node
2
+
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { blue, gray, green, red, yellow } from './functions/colors.js';
6
+
7
+ // .............................................................................
8
+ const excludedFiles = ['create-new-repo.md', 'rename-class.js'];
9
+
10
+ // .............................................................................
11
+
12
+ const isExcluded = (fileName) => {
13
+ return excludedFiles.includes(fileName);
14
+ };
15
+
16
+ const shouldProcessFile = (file) => !isExcluded(file);
17
+
18
+ // Binary files must not be rewritten as UTF-8, that would corrupt them.
19
+ const readTextFile = (fullPath) => {
20
+ const buffer = fs.readFileSync(fullPath);
21
+ if (buffer.includes(0)) return null;
22
+ return buffer.toString('utf8');
23
+ };
24
+
25
+ const writeTextFile = (fullPath, oldContent, newContent) => {
26
+ if (newContent === oldContent) return;
27
+ fs.writeFileSync(fullPath, newContent, 'utf8');
28
+ };
29
+
30
+ if (process.argv.length < 4) {
31
+ const usage = red('Usage:');
32
+ const script = yellow(path.basename(process.argv[1]));
33
+ const classA = green('ClassA');
34
+ const classB = blue('ClassB');
35
+ console.error([usage, script, classA, classB].join(' '));
36
+ process.exit(1);
37
+ }
38
+
39
+ const classA = process.argv[2];
40
+ const classB = process.argv[3];
41
+
42
+ const toSnakeCase = (str) => {
43
+ return str.replace(/(?<=[a-z0-9])([A-Z])/g, '-$1').toLowerCase();
44
+ };
45
+
46
+ const toLowerCamelCase = (str) => {
47
+ return str.replace(/([-_]\w)/g, (matches) => matches[1].toUpperCase());
48
+ };
49
+
50
+ const toUpperCamelCase = (str) => {
51
+ return str.replace(/(?:^|[-_])(\w)/g, (_, c) => (c ? c.toUpperCase() : ''));
52
+ };
53
+
54
+ const classALower = toLowerCamelCase(classA);
55
+ const classBLower = toLowerCamelCase(classB);
56
+ const classAUpper = toUpperCamelCase(classA);
57
+ const classBUpper = toUpperCamelCase(classB);
58
+ const classASnake = toSnakeCase(classA);
59
+ const classBSnake = toSnakeCase(classB);
60
+ const classASnakeUnderscore = classASnake.replace(/-/g, '_');
61
+ const classBSnakeUnderscore = classBSnake.replace(/-/g, '_');
62
+
63
+ const replaceIncludesFirst = (directory) => {
64
+ const files = fs.readdirSync(directory, { withFileTypes: true });
65
+
66
+ for (const file of files) {
67
+ const fullPath = path.join(directory, file.name);
68
+
69
+ if (file.isDirectory()) {
70
+ if (file.name.startsWith('.') || file.name === 'node_modules') continue;
71
+ replaceIncludesFirst(fullPath);
72
+ } else if (shouldProcessFile(file.name)) {
73
+ const original = readTextFile(fullPath);
74
+ if (original === null) continue;
75
+ const content = original
76
+ .replace(
77
+ new RegExp(`(\\/)${classASnake}(\\.ts)?([\\.\\/\\'\\\"\\\\])`, 'g'),
78
+ `$1${classBSnake}$2$3`,
79
+ )
80
+ .replace(
81
+ new RegExp(
82
+ `(\\/)${classASnakeUnderscore}(\\.ts)?([\\.\\/\\'\\\"\\\\])`,
83
+ 'g',
84
+ ),
85
+ `$1${classBSnakeUnderscore}$2$3`,
86
+ );
87
+ writeTextFile(fullPath, original, content);
88
+ }
89
+ }
90
+ };
91
+
92
+ const replaceInFiles = (directory) => {
93
+ const files = fs.readdirSync(directory, { withFileTypes: true });
94
+
95
+ for (const file of files) {
96
+ const fullPath = path.join(directory, file.name);
97
+
98
+ if (file.isDirectory()) {
99
+ if (file.name.startsWith('.') || file.name === 'node_modules') continue;
100
+ replaceInFiles(fullPath);
101
+ } else if (shouldProcessFile(file.name)) {
102
+ const original = readTextFile(fullPath);
103
+ if (original === null) continue;
104
+ const content = original
105
+ .replace(new RegExp(classAUpper, 'g'), classBUpper)
106
+ .replace(new RegExp(classALower, 'g'), classBLower)
107
+ .replace(new RegExp(classASnake, 'g'), classBSnake)
108
+ .replace(
109
+ new RegExp(classASnakeUnderscore, 'g'),
110
+ classBSnakeUnderscore,
111
+ );
112
+ writeTextFile(fullPath, original, content);
113
+ }
114
+ }
115
+ };
116
+
117
+ const renameFiles = (directory) => {
118
+ const files = fs.readdirSync(directory, { withFileTypes: true });
119
+
120
+ for (const file of files) {
121
+ const fullPath = path.join(directory, file.name);
122
+
123
+ if (file.isDirectory()) {
124
+ if (file.name.startsWith('.') || file.name === 'node_modules') continue;
125
+ renameFiles(fullPath);
126
+ } else if (
127
+ file.name.includes(classASnake) ||
128
+ file.name.includes(classASnakeUnderscore)
129
+ ) {
130
+ const newFileName = file.name
131
+ .replace(classASnake, classBSnake)
132
+ .replace(classASnakeUnderscore, classBSnakeUnderscore);
133
+ fs.renameSync(fullPath, path.join(directory, newFileName));
134
+ }
135
+ }
136
+ };
137
+
138
+ console.log(gray('Replacing includes first...'));
139
+ replaceIncludesFirst('.');
140
+
141
+ console.log(gray('Renaming files...'));
142
+ renameFiles('.');
143
+
144
+ console.log(gray('Replacing occurrences in files...'));
145
+ replaceInFiles('.');
146
+
147
+ console.log(green('Done.'));
@@ -0,0 +1,221 @@
1
+ /*
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ import { execSync } from 'child_process';
10
+ import { writeFileSync } from 'fs';
11
+ import { tmpdir } from 'os';
12
+ import { join } from 'path';
13
+ import {
14
+ blue,
15
+ cyan,
16
+ gray,
17
+ green,
18
+ red,
19
+ white,
20
+ yellow,
21
+ } from './functions/colors.js';
22
+ import { runCommand } from './functions/run-command.js';
23
+
24
+ // The name of the branch ruleset managed by this script
25
+ const rulesetName = 'Default';
26
+
27
+ // The status check that must pass before merging. It is provided by the
28
+ // GitHub Actions app, i.e. not by "Any source".
29
+ const requiredStatusCheck = 'dnaGitQuickCheckPipelineName';
30
+ const gitHubActionsAppId = 15368;
31
+
32
+ // ...........................................................................
33
+ // Make sure the GitHub CLI is available and authenticated
34
+ function checkGhCli() {
35
+ console.log(gray('Check GitHub CLI'));
36
+
37
+ try {
38
+ runCommand('gh --version');
39
+ } catch {
40
+ throw new Error(
41
+ [
42
+ yellow('GitHub CLI is not installed. Please install it:'),
43
+ green('brew install gh'),
44
+ ].join('\n'),
45
+ );
46
+ }
47
+
48
+ try {
49
+ runCommand('gh auth status');
50
+ } catch {
51
+ throw new Error(
52
+ [yellow('Not yet logged in. Please run:'), green('gh auth login')].join(
53
+ '\n',
54
+ ),
55
+ );
56
+ }
57
+ }
58
+
59
+ // ...........................................................................
60
+ // Get "org/repo" either from the first argument or from the current directory
61
+ function repoSlug() {
62
+ const fromArgs = process.argv.slice(2).find((a) => !a.startsWith('--'));
63
+ if (fromArgs) {
64
+ if (!/^[^/]+\/[^/]+$/.test(fromArgs)) {
65
+ throw new Error(`Invalid repository '${fromArgs}'. Expected 'org/repo'.`);
66
+ }
67
+ return fromArgs;
68
+ }
69
+
70
+ console.log(gray('Get repository from current directory'));
71
+ try {
72
+ const json = runCommand('gh repo view --json nameWithOwner');
73
+ return JSON.parse(json).nameWithOwner;
74
+ } catch {
75
+ throw new Error(
76
+ [
77
+ yellow('Could not determine the repository.'),
78
+ yellow('Please call this script from a GitHub repository or run:'),
79
+ green('node dna/scripts/setup-github-repo.js org/repo'),
80
+ ].join('\n'),
81
+ );
82
+ }
83
+ }
84
+
85
+ // ...........................................................................
86
+ // Call the GitHub API with a JSON body
87
+ function ghApi(method, path, body) {
88
+ const file = join(tmpdir(), `setup-github-repo-${process.pid}.json`);
89
+ writeFileSync(file, JSON.stringify(body));
90
+ console.log(gray(`gh api --method ${method} ${path}`));
91
+ return execSync(`gh api --method ${method} ${path} --input ${file}`, {
92
+ encoding: 'utf-8',
93
+ stdio: ['pipe', 'pipe', 'pipe'],
94
+ }).trim();
95
+ }
96
+
97
+ // ...........................................................................
98
+ // Only allow squash merges, auto merge and delete branches after merge
99
+ function pullRequestSettings() {
100
+ return {
101
+ allow_merge_commit: false,
102
+ allow_squash_merge: true,
103
+ // Default commit message: "Pull request title"
104
+ squash_merge_commit_title: 'PR_TITLE',
105
+ squash_merge_commit_message: 'BLANK',
106
+ allow_rebase_merge: false,
107
+ allow_auto_merge: true,
108
+ allow_update_branch: true,
109
+ delete_branch_on_merge: true,
110
+ };
111
+ }
112
+
113
+ // ...........................................................................
114
+ function setupPullRequestSettings(slug) {
115
+ console.log(gray('Setup pull request settings'));
116
+
117
+ ghApi('PATCH', `repos/${slug}`, pullRequestSettings());
118
+
119
+ console.log(green('✅ Pull request settings applied.'));
120
+ }
121
+
122
+ // ...........................................................................
123
+ // The ruleset protecting the default branch
124
+ function ruleset(requireReview) {
125
+ return {
126
+ name: rulesetName,
127
+ target: 'branch',
128
+ enforcement: 'active',
129
+ conditions: {
130
+ ref_name: { include: ['~DEFAULT_BRANCH'], exclude: [] },
131
+ },
132
+ rules: [
133
+ { type: 'deletion' },
134
+ { type: 'non_fast_forward' },
135
+ { type: 'required_linear_history' },
136
+ {
137
+ type: 'pull_request',
138
+ parameters: {
139
+ required_approving_review_count: requireReview ? 1 : 0,
140
+ dismiss_stale_reviews_on_push: false,
141
+ require_code_owner_review: false,
142
+ require_last_push_approval: requireReview,
143
+ required_review_thread_resolution: requireReview,
144
+ allowed_merge_methods: ['squash'],
145
+ },
146
+ },
147
+ {
148
+ type: 'required_status_checks',
149
+ parameters: {
150
+ strict_required_status_checks_policy: true,
151
+ required_status_checks: [
152
+ {
153
+ context: requiredStatusCheck,
154
+ integration_id: gitHubActionsAppId,
155
+ },
156
+ ],
157
+ },
158
+ },
159
+ ],
160
+ };
161
+ }
162
+
163
+ // ...........................................................................
164
+ // Find the id of an already existing ruleset with the same name
165
+ function existingRulesetId(slug) {
166
+ const json = runCommand(`gh api repos/${slug}/rulesets`);
167
+ const found = JSON.parse(json).find((r) => r.name === rulesetName);
168
+ return found ? found.id : undefined;
169
+ }
170
+
171
+ // ...........................................................................
172
+ // Create the ruleset or update it when it already exists
173
+ function setupBranchRules(slug, requireReview) {
174
+ console.log(gray('Setup branch rules'));
175
+
176
+ const id = existingRulesetId(slug);
177
+
178
+ if (id) {
179
+ ghApi('PUT', `repos/${slug}/rulesets/${id}`, ruleset(requireReview));
180
+ console.log(green(`✅ Ruleset '${rulesetName}' has been updated.`));
181
+ } else {
182
+ ghApi('POST', `repos/${slug}/rulesets`, ruleset(requireReview));
183
+ console.log(green(`✅ Ruleset '${rulesetName}' has been created.`));
184
+ }
185
+ }
186
+
187
+ // ...........................................................................
188
+ // Print the repo and the settings without changing anything
189
+ function dryRun(slug, requireReview) {
190
+ console.log(cyan(slug));
191
+ console.log(white(JSON.stringify(pullRequestSettings(), null, 2)));
192
+ console.log(white(JSON.stringify(ruleset(requireReview), null, 2)));
193
+ }
194
+
195
+ // ...........................................................................
196
+ function main() {
197
+ const requireReview = process.argv.includes('--require-review');
198
+ const isDryRun = !process.argv.includes('--apply');
199
+
200
+ checkGhCli();
201
+ const slug = repoSlug();
202
+
203
+ if (isDryRun) {
204
+ dryRun(slug, requireReview);
205
+ return;
206
+ }
207
+
208
+ console.log(blue(`https://github.com/${slug}`));
209
+
210
+ setupPullRequestSettings(slug);
211
+ setupBranchRules(slug, requireReview);
212
+
213
+ console.log(green(`✅ Repository '${slug}' has been set up.`));
214
+ }
215
+
216
+ try {
217
+ main();
218
+ } catch (error) {
219
+ console.error(red(`Error: ${error.message}`));
220
+ process.exit(1);
221
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) ggsuite
4
+ *
5
+ * Use of this source code is governed by terms that can be
6
+ * found in the LICENSE file in the root of this package.
7
+ */
8
+
9
+ import { blue, green, red, yellow } from './functions/colors.js';
10
+ import { runCommand } from './functions/run-command.js';
11
+
12
+ function getPRUrl() {
13
+ try {
14
+ const json = runCommand('gh pr view --json url').trim();
15
+
16
+ const parsed = JSON.parse(json);
17
+ const url = parsed.url;
18
+ console.log(blue(url));
19
+ } catch (error) {
20
+ console.error(yellow('No PR available'));
21
+ process.exit(1);
22
+ }
23
+ }
24
+
25
+ function getPRStatus() {
26
+ try {
27
+ const jsonString = runCommand(
28
+ 'gh pr view --json state',
29
+ true,
30
+ false,
31
+ ).trim();
32
+
33
+ const jsonParsed = JSON.parse(jsonString);
34
+ return jsonParsed.state;
35
+ } catch (error) {
36
+ console.error(red('Error fetching PR status'));
37
+ process.exit(1);
38
+ }
39
+ }
40
+
41
+ async function checkIfPipelineHasFailed() {
42
+ try {
43
+ const json = runCommand(
44
+ 'gh run list --repo rljson/template-project --limit 1 --json status,conclusion',
45
+ true,
46
+ false,
47
+ ).trim();
48
+
49
+ const jsonParsed = JSON.parse(json);
50
+ if (jsonParsed.length) {
51
+ if (jsonParsed[0].conclusion === 'failure') {
52
+ console.error(red('Pipeline has failed. Please fix.'));
53
+ process.exit(1);
54
+ }
55
+ }
56
+ } catch (e) {
57
+ console.error(red('Error fetching pipeline status'));
58
+ process.exit(1);
59
+ }
60
+ }
61
+
62
+ async function waitForPRClosure() {
63
+ console.log(yellow('Wait for pipelines, code review and merge ...'));
64
+
65
+ while (true) {
66
+ const status = getPRStatus();
67
+
68
+ if (status === 'MERGED') {
69
+ console.log(green('PR has been merged.'));
70
+ break;
71
+ } else if (status === 'CLOSED') {
72
+ console.log(green('PR has been closed.'));
73
+ break;
74
+ } else if (status === 'FAILED') {
75
+ console.log(red('Error: PR has failed.'));
76
+ break;
77
+ }
78
+
79
+ await checkIfPipelineHasFailed();
80
+
81
+ await new Promise((resolve) => setTimeout(resolve, 2000));
82
+ }
83
+ }
84
+
85
+ async function main() {
86
+ getPRUrl();
87
+ await waitForPRClosure();
88
+ }
89
+
90
+ main();
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@ggdna/dna-scripts",
3
+ "version": "0.1.0",
4
+ "description": "DNA layer: deterministic node scripts and their shared functions",
5
+ "keywords": [
6
+ "dna",
7
+ "helix",
8
+ "conventions",
9
+ "scaffolding"
10
+ ],
11
+ "homepage": "https://github.com/ggdna/dna_scripts",
12
+ "bugs": "https://github.com/ggdna/dna_scripts/issues",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/ggdna/dna_scripts.git"
17
+ },
18
+ "type": "module",
19
+ "files": [
20
+ "dna",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "engines": {
25
+ "node": ">=22"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "test:dart": "dart test",
32
+ "test": "pnpm run test:dart",
33
+ "prepublishOnly": "pnpm run test",
34
+ "format": "prettier --write .",
35
+ "format:check": "prettier --check ."
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^26.2.0",
39
+ "prettier": "^3.9.6"
40
+ }
41
+ }