Skip to content

Commit c8c2372

Browse files
chore: modified snapshot action
1 parent ddb535e commit c8c2372

File tree

3 files changed

+144
-30
lines changed

3 files changed

+144
-30
lines changed
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
const { execSync, spawnSync } = require('child_process');
2+
const fs = require('fs');
3+
const path = require('path');
4+
5+
// Helper function to run commands and handle errors
6+
function runCommand(command, args, options) {
7+
console.log(
8+
`Executing: ${command} ${args.join(' ')} ${options && options.cwd ? `in ${options.cwd}` : ''}`
9+
);
10+
const result = spawnSync(command, args, { stdio: 'inherit', ...options });
11+
if (result.error) {
12+
console.error(`Error executing ${command}:`, result.error);
13+
throw result.error;
14+
}
15+
if (result.status !== 0) {
16+
const message = `Command failed: ${command} ${args.join(' ')} exited with status ${
17+
result.status
18+
}`;
19+
console.error(message);
20+
throw new Error(message);
21+
}
22+
return result;
23+
}
24+
25+
console.log('Starting initial package publishing process...');
26+
27+
let packagesToPublish = [];
28+
const rootDir = process.cwd();
29+
30+
const packagesToExclude = ['@apps/native', '@apps/gallery'];
31+
32+
try {
33+
// Get workspace info using yarn workspaces list --json
34+
// Yarn v1 outputs newline-delimited JSON objects
35+
const rawOutput = execSync('yarn workspaces list --json', { encoding: 'utf8' });
36+
const lines = rawOutput
37+
.trim()
38+
.split('\n')
39+
.filter(line => line.trim() !== '');
40+
const workspacePackages = lines.map(line => JSON.parse(line));
41+
42+
for (const pkgData of workspacePackages) {
43+
// Skip the root package or any package without a defined location
44+
if (pkgData.name === '.' || !pkgData.location) {
45+
continue;
46+
}
47+
48+
// Skip excluded packages
49+
if (packagesToExclude.includes(pkgData.name)) {
50+
console.log(`Skipping excluded package: ${pkgData.name}`);
51+
continue;
52+
}
53+
54+
const pkgName = pkgData.name;
55+
const pkgDir = path.resolve(rootDir, pkgData.location);
56+
57+
// Check if package exists on npm
58+
console.log(`Checking NPM status for ${pkgName}...`);
59+
const npmViewResult = spawnSync('npm', ['view', pkgName, 'version'], { encoding: 'utf8' });
60+
61+
// If npm view exits with 0 and has output, package exists.
62+
// Otherwise (non-zero exit or empty output), it likely doesn't.
63+
if (npmViewResult.status === 0 && npmViewResult.stdout && npmViewResult.stdout.trim() !== '') {
64+
console.log(
65+
`Package ${pkgName} (version: ${npmViewResult.stdout.trim()}) already exists on NPM. Skipping initial publish.`
66+
);
67+
} else {
68+
console.log(
69+
`Package ${pkgName} does not appear to exist on NPM or has no published versions.`
70+
);
71+
if (fs.existsSync(path.join(pkgDir, 'package.json'))) {
72+
packagesToPublish.push({ name: pkgName, dir: pkgDir });
73+
} else {
74+
console.warn(`Skipping ${pkgName}: package.json not found in ${pkgDir}`);
75+
}
76+
}
77+
}
78+
} catch (error) {
79+
console.error('Error processing workspace info or checking NPM status:', error.message);
80+
process.exit(1); // Critical error, exit
81+
}
82+
83+
if (packagesToPublish.length === 0) {
84+
console.log('No new packages to publish initially.');
85+
} else {
86+
console.log(
87+
`Found ${packagesToPublish.length} new package(s) to publish initially: ${packagesToPublish
88+
.map(p => p.name)
89+
.join(', ')}`
90+
);
91+
}
92+
93+
let hasPublishErrors = false;
94+
for (const pkg of packagesToPublish) {
95+
console.log(`Attempting to publish ${pkg.name} from ${pkg.dir} with alpha tag...`);
96+
const packageJsonPath = path.join(pkg.dir, 'package.json');
97+
let originalPackageJson = '';
98+
try {
99+
originalPackageJson = fs.readFileSync(packageJsonPath, 'utf8');
100+
const parsedPackageJson = JSON.parse(originalPackageJson);
101+
102+
console.log(`Temporarily setting version of ${pkg.name} to 0.0.1 for initial publish.`);
103+
parsedPackageJson.version = '0.0.1';
104+
fs.writeFileSync(packageJsonPath, JSON.stringify(parsedPackageJson, null, 2));
105+
106+
// runCommand('yarn', ['npm', 'publish', '--access', 'public', '--tag', 'alpha'], {
107+
// cwd: pkg.dir
108+
// });
109+
console.log(
110+
`DRY RUN: Would publish ${pkg.name} from ${pkg.dir} with version 0.0.1 and alpha tag.`
111+
);
112+
console.log(
113+
`DRY RUN: Command would be: yarn npm publish --access public --tag alpha (in ${pkg.dir})`
114+
);
115+
} catch (publishError) {
116+
// runCommand already logs error details if it's from there
117+
console.error(`Failed to publish ${pkg.name}: ${publishError.message}`);
118+
hasPublishErrors = true; // Mark that an error occurred but continue trying other packages
119+
} finally {
120+
// Restore original package.json
121+
if (originalPackageJson) {
122+
console.log(`Restoring original package.json for ${pkg.name}.`);
123+
try {
124+
fs.writeFileSync(packageJsonPath, originalPackageJson);
125+
} catch (restoreError) {
126+
console.error(
127+
`CRITICAL: Failed to restore original package.json for ${pkg.name}: ${restoreError.message}`
128+
);
129+
// This is a more critical error, as it leaves the repo in a modified state.
130+
// Depending on desired behavior, you might want to ensure this error is highly visible
131+
// or even causes the entire workflow to fail more loudly.
132+
hasPublishErrors = true; // Ensure the overall process is marked as failed.
133+
}
134+
}
135+
}
136+
}
137+
138+
console.log('Initial package publishing process finished.');
139+
if (hasPublishErrors) {
140+
console.error('One or more packages failed during initial publishing.');
141+
process.exit(1); // Exit with error if any package failed to publish
142+
}

.github/workflows/changesets.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ jobs:
2121
- name: Checkout Repo
2222
uses: actions/checkout@v4
2323

24-
- name:
24+
- name: Setup Environment
2525
uses: ./.github/actions/setup
2626

2727
- name: Create Release Pull Request or Publish to NPM

.github/workflows/snapshot.yml

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -23,37 +23,9 @@ jobs:
2323
continue-on-error: false
2424
env:
2525
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
26-
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
2726
run: |
2827
npm config set "//registry.npmjs.org/:_authToken" "$NPM_TOKEN"
29-
# Find packages that don't exist in NPM and publish them with initial version
30-
yarn workspaces list --json | jq -r '.name' | while read pkg; do
31-
if [ "$pkg" != "." ] && ! npm view "$pkg" &>/dev/null; then
32-
echo "Package $pkg doesn't exist in NPM, publishing initial version 0.0.0"
33-
# Get the location of the package
34-
PKG_DIR=$(yarn workspaces info --json | jq -r ".[\"$pkg\"].location")
35-
if [ -d "$PKG_DIR" ] && [ -f "$PKG_DIR/package.json" ]; then
36-
echo "Found package directory at $PKG_DIR"
37-
# Create a backup of the original package.json
38-
cp "$PKG_DIR/package.json" "$PKG_DIR/package.json.bak"
39-
# Update the version to 0.0.0 using Node.js
40-
node -e "
41-
const fs = require('fs');
42-
const pkg = JSON.parse(fs.readFileSync('$PKG_DIR/package.json', 'utf8'));
43-
pkg.version = '0.0.0';
44-
fs.writeFileSync('$PKG_DIR/package.json', JSON.stringify(pkg, null, 2));
45-
"
46-
# Publish from the package directory
47-
(cd "$PKG_DIR" && yarn npm publish --access public --tag alpha)
48-
# Restore the original package.json
49-
mv "$PKG_DIR/package.json.bak" "$PKG_DIR/package.json"
50-
else
51-
echo "Error: Could not find package.json in $PKG_DIR"
52-
echo "Current directory: $(pwd)"
53-
echo "Directory contents: $(ls -la)"
54-
fi
55-
fi
56-
done
28+
node .github/scripts/publish-initial-versions.js
5729
5830
- name: Publish Snapshots
5931
continue-on-error: false

0 commit comments

Comments
 (0)