@beyondwork/wb-cli 0.1.0 → 0.1.2

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.
Files changed (2) hide show
  1. package/out/cli.js +222 -10
  2. package/package.json +5 -3
package/out/cli.js CHANGED
@@ -38,11 +38,52 @@ const fs = __importStar(require("fs"));
38
38
  const path = __importStar(require("path"));
39
39
  const commander_1 = require("commander");
40
40
  const lib_1 = require("./lib");
41
- // Setup logger
41
+ const child_process_1 = require("child_process");
42
+ const glob_1 = require("glob");
42
43
  const logger = new lib_1.ConsoleLogger();
44
+ // Helper function for submitting workblocks
45
+ async function performSubmitWorkblock(workblockPathIdentifier, // Path used for logging, can be relative or absolute
46
+ publishUrl, basePathForResolution, // The path from which workblockPathIdentifier is resolved if relative
47
+ loggerToUse) {
48
+ const absoluteWorkblockPath = path.resolve(basePathForResolution, workblockPathIdentifier);
49
+ loggerToUse.log(`Attempting to assemble workblock from: ${absoluteWorkblockPath} (identifier: ${workblockPathIdentifier})`);
50
+ if (!fs.existsSync(absoluteWorkblockPath)) {
51
+ loggerToUse.error(`Directory does not exist: ${absoluteWorkblockPath}`);
52
+ throw new Error(`Directory does not exist: ${absoluteWorkblockPath}`);
53
+ }
54
+ const workblock = await (0, lib_1.assembleWorkblock)(absoluteWorkblockPath, loggerToUse);
55
+ if (!workblock) {
56
+ loggerToUse.error(`Failed to assemble workblock from ${absoluteWorkblockPath}`);
57
+ throw new Error(`Failed to assemble workblock from ${absoluteWorkblockPath}`);
58
+ }
59
+ const output = JSON.stringify(workblock, null, 2);
60
+ loggerToUse.log(`Submitting workblock from ${workblockPathIdentifier} to ${publishUrl}...`);
61
+ const response = await fetch(publishUrl, {
62
+ method: 'POST',
63
+ headers: {
64
+ 'Content-Type': 'application/json',
65
+ },
66
+ body: output,
67
+ });
68
+ if (response.ok) {
69
+ loggerToUse.log(`Workblock from ${workblockPathIdentifier} submitted successfully to ${publishUrl}. Status: ${response.status}`);
70
+ const responseBody = await response.text();
71
+ if (responseBody) {
72
+ loggerToUse.log(`Response: ${responseBody}`);
73
+ }
74
+ }
75
+ else {
76
+ loggerToUse.error(`Failed to submit workblock from ${workblockPathIdentifier}. Status: ${response.status}`);
77
+ const errorBody = await response.text();
78
+ if (errorBody) {
79
+ loggerToUse.error(`Error details: ${errorBody}`);
80
+ }
81
+ throw new Error(`Failed to submit workblock from ${workblockPathIdentifier}. Status: ${response.status}`);
82
+ }
83
+ }
43
84
  // Define CLI
44
85
  commander_1.program
45
- .name('beyondwork')
86
+ .name('wb-cli') // Updated name
46
87
  .description('CLI for working with Beyond Work workblocks')
47
88
  .version(process.env.npm_package_version || '0.0.0');
48
89
  commander_1.program
@@ -51,22 +92,17 @@ commander_1.program
51
92
  .option('-o, --output <file>', 'Output file (defaults to stdout)')
52
93
  .action(async (directory, options) => {
53
94
  try {
54
- // Resolve absolute path
55
- const dirPath = path.resolve(directory);
56
- // Check if directory exists
95
+ const dirPath = path.resolve(directory); // Resolves from CWD
57
96
  if (!fs.existsSync(dirPath)) {
58
97
  logger.error(`Directory does not exist: ${dirPath}`);
59
98
  process.exit(1);
60
99
  }
61
- // Assemble workblock
62
100
  const workblock = await (0, lib_1.assembleWorkblock)(dirPath, logger);
63
101
  if (!workblock) {
64
102
  logger.error('Failed to assemble workblock');
65
103
  process.exit(1);
66
104
  }
67
- // Format output
68
105
  const output = JSON.stringify(workblock, null, 2);
69
- // Write to file or stdout
70
106
  if (options.output) {
71
107
  const outputPath = path.resolve(options.output);
72
108
  fs.writeFileSync(outputPath, output);
@@ -77,9 +113,185 @@ commander_1.program
77
113
  }
78
114
  }
79
115
  catch (error) {
80
- logger.error(`Error: ${error}`);
116
+ const errorMessage = error instanceof Error ? error.message : String(error);
117
+ logger.error(`Error: ${errorMessage}`);
118
+ process.exit(1);
119
+ }
120
+ });
121
+ commander_1.program
122
+ .command('submit <directory> <url>')
123
+ .description('Assemble a workblock and POST it to a URL')
124
+ .option('-w, --workspace <path>', 'Workspace path, if directory is relative to it', '.')
125
+ .action(async (directory, url, options) => {
126
+ try {
127
+ // 'directory' is user input. 'options.workspace' is CWD by default.
128
+ // performSubmitWorkblock resolves 'directory' relative to 'options.workspace'.
129
+ await performSubmitWorkblock(directory, url, options.workspace, logger);
130
+ }
131
+ catch (error) {
132
+ const errorMessage = error instanceof Error ? error.message : String(error);
133
+ logger.error(`Error: ${errorMessage}`);
134
+ process.exit(1);
135
+ }
136
+ });
137
+ // New command: publish-changed-workblocks
138
+ commander_1.program
139
+ .command('publish-changed-workblocks')
140
+ .description('Detects changed workblocks based on git diff and submits them. Optionally comments on a PR.')
141
+ .requiredOption('-u, --publish-url <url>', 'URL to publish/submit the workblocks to')
142
+ .requiredOption('-b, --workblock-base-dir <dir>', 'Base directory within the workspace where workblocks are located')
143
+ .option('-w, --workspace <path>', 'Path to the git workspace root', '.')
144
+ .option('-t, --github-token <token>', 'GitHub token for PR commenting and API interactions')
145
+ .option('--git-diff-base <ref>', 'Base ref for git diff (e.g., HEAD^, origin/main)', 'HEAD^')
146
+ .option('--git-diff-head <ref>', 'Head ref for git diff', 'HEAD')
147
+ .action(async (options) => {
148
+ const { publishUrl, workblockBaseDir, workspace, githubToken, gitDiffBase, gitDiffHead, } = options;
149
+ // Dynamically import Octokit
150
+ const { Octokit } = await import("@octokit/rest");
151
+ let octokitInstance;
152
+ if (githubToken) {
153
+ octokitInstance = new Octokit({ auth: githubToken });
154
+ }
155
+ const workspaceAbsPath = path.resolve(workspace);
156
+ logger.log('Determining changed workblock directories...');
157
+ logger.log(`Workspace: ${workspaceAbsPath}`);
158
+ logger.log(`Workblock Base Directory (relative to workspace): ${workblockBaseDir}`);
159
+ let diffOutput = '';
160
+ try {
161
+ const diffCommand = `git diff --name-only "${gitDiffBase}" "${gitDiffHead}"`;
162
+ logger.log(`Running git diff: ${diffCommand} in ${workspaceAbsPath}`);
163
+ diffOutput = (0, child_process_1.execSync)(diffCommand, { cwd: workspaceAbsPath, encoding: 'utf8' });
164
+ }
165
+ catch (e) {
166
+ const errorDetails = e instanceof Error ? e.message : String(e);
167
+ logger.error(`Failed to run git diff: ${errorDetails}`);
168
+ if (e && typeof e === 'object' && 'stderr' in e && e.stderr) {
169
+ logger.error(`Git stderr: ${String(e.stderr)}`);
170
+ }
81
171
  process.exit(1);
82
172
  }
173
+ const allChangedFiles = diffOutput.split('\n').filter(f => f.trim() !== '');
174
+ logger.log(`All changed files (${allChangedFiles.length}): ${allChangedFiles.join(', ') || 'None'}`);
175
+ if (allChangedFiles.length === 0) {
176
+ logger.log('No files changed according to git diff. Exiting.');
177
+ return;
178
+ }
179
+ const manifestPattern = path.join(workblockBaseDir, '**/{manifest.yaml,*manifest.yaml}');
180
+ logger.log(`Searching for manifest files with pattern: ${manifestPattern} (relative to ${workspaceAbsPath})`);
181
+ // globSync expects patterns relative to its CWD option, or absolute paths.
182
+ const manifestFiles = (0, glob_1.sync)(manifestPattern, { cwd: workspaceAbsPath, nodir: true, absolute: true });
183
+ logger.log(`Found manifest files (${manifestFiles.length}): ${manifestFiles.join(', ') || 'None'}`);
184
+ if (manifestFiles.length === 0) {
185
+ logger.log('No manifest files found. Exiting.');
186
+ return;
187
+ }
188
+ const dirsToProcess = new Set();
189
+ for (const manifestFileAbs of manifestFiles) {
190
+ const workblockRootDirAbs = path.dirname(manifestFileAbs);
191
+ logger.log(`Potential workblock root (absolute): ${workblockRootDirAbs}`);
192
+ for (const changedFileRelative of allChangedFiles) {
193
+ const fullChangedFilePathAbs = path.resolve(workspaceAbsPath, changedFileRelative);
194
+ if (fullChangedFilePathAbs.startsWith(workblockRootDirAbs + path.sep) || fullChangedFilePathAbs === workblockRootDirAbs) {
195
+ const relativeWorkblockPath = path.relative(workspaceAbsPath, workblockRootDirAbs);
196
+ dirsToProcess.add(relativeWorkblockPath);
197
+ logger.log(`Found changed file '${changedFileRelative}' in workblock '${relativeWorkblockPath}'. Adding to process list.`);
198
+ break;
199
+ }
200
+ }
201
+ }
202
+ // New: Determine PR info if githubToken is provided
203
+ let prNumberForComment;
204
+ let prRepoOwner;
205
+ let prRepoName;
206
+ if (octokitInstance) { // This implies githubToken is present
207
+ logger.log('Attempting to determine PR information from the current commit...');
208
+ try {
209
+ const commitSha = (0, child_process_1.execSync)('git rev-parse HEAD', { cwd: workspaceAbsPath, encoding: 'utf8' }).trim();
210
+ logger.log(`Current commit SHA: ${commitSha}`);
211
+ const remoteUrl = (0, child_process_1.execSync)('git remote get-url origin', { cwd: workspaceAbsPath, encoding: 'utf8' }).trim();
212
+ logger.log(`Git remote origin URL: ${remoteUrl}`);
213
+ // Regex to capture owner and repo from https or git@github.com URLs
214
+ const repoMatch = remoteUrl.match(/(?:git@github\\.com:|https:\/\/github\\.com\/)([^\/]+)\/([^\.\\s]+)(?:\\.git)?$/);
215
+ if (!repoMatch || repoMatch.length < 3) {
216
+ logger.log(`Could not parse owner/repo from git remote URL: '${remoteUrl}'. Skipping PR interaction.`);
217
+ }
218
+ else {
219
+ prRepoOwner = repoMatch[1];
220
+ prRepoName = repoMatch[2];
221
+ logger.log(`Inferred repository: ${prRepoOwner}/${prRepoName}`);
222
+ const { data: prsAssociatedWithCommit } = await octokitInstance.rest.repos.listPullRequestsAssociatedWithCommit({
223
+ owner: prRepoOwner,
224
+ repo: prRepoName,
225
+ commit_sha: commitSha,
226
+ });
227
+ if (prsAssociatedWithCommit.length > 0) {
228
+ const openPr = prsAssociatedWithCommit.find(pr => pr.state === 'open');
229
+ const selectedPr = openPr || prsAssociatedWithCommit[0]; // Prefer open PR, fallback to the first one
230
+ prNumberForComment = selectedPr.number;
231
+ logger.log(`Found PR #${prNumberForComment} (state: ${selectedPr.state}) associated with commit ${commitSha} in ${prRepoOwner}/${prRepoName}.`);
232
+ }
233
+ else {
234
+ logger.log(`No PRs found associated with commit ${commitSha} in ${prRepoOwner}/${prRepoName}.`);
235
+ }
236
+ }
237
+ }
238
+ catch (e) {
239
+ const errorMsg = e instanceof Error ? e.message : String(e);
240
+ logger.error(`Error determining PR information: ${errorMsg}. Skipping PR interaction.`);
241
+ }
242
+ }
243
+ if (dirsToProcess.size === 0) {
244
+ logger.log('No changed workblock directories (containing a manifest and changes) found.');
245
+ return;
246
+ }
247
+ logger.log(`Found ${dirsToProcess.size} changed workblock directories to process: ${[...dirsToProcess].join(', ')}`);
248
+ let anySubmissionFailed = false;
249
+ for (const dirRelToWorkspace of dirsToProcess) {
250
+ logger.log(`Processing directory: ${dirRelToWorkspace}`);
251
+ try {
252
+ await performSubmitWorkblock(dirRelToWorkspace, publishUrl, workspaceAbsPath, logger);
253
+ logger.log(`Successfully submitted workblock for directory: ${dirRelToWorkspace}`);
254
+ }
255
+ catch (error) {
256
+ const errorMessage = error instanceof Error ? error.message : String(error);
257
+ logger.error(`Failed to submit workblock for directory ${dirRelToWorkspace}: ${errorMessage}`);
258
+ anySubmissionFailed = true;
259
+ }
260
+ }
261
+ if (prNumberForComment && prRepoOwner && prRepoName && octokitInstance && dirsToProcess.size > 0) { // New condition
262
+ logger.log(`Attempting to comment on PR #${prNumberForComment} in repo ${prRepoOwner}/${prRepoName}`);
263
+ let commentBody = 'The following workblock directories were processed by `wb-cli publish-changed-workblocks`:\\\\n';
264
+ for (const dir of dirsToProcess) {
265
+ commentBody += `- \\\`\\\`\\\`${dir}\\\`\\\`\\\`\\\\n`; // Using backticks for dirs
266
+ }
267
+ if (anySubmissionFailed) {
268
+ commentBody += '\\\\nNote: One or more submissions failed. Check logs for details.';
269
+ }
270
+ try {
271
+ await octokitInstance.rest.issues.createComment({
272
+ owner: prRepoOwner, // Use determined owner
273
+ repo: prRepoName, // Use determined repo name
274
+ issue_number: prNumberForComment, // Use determined PR number
275
+ body: commentBody,
276
+ });
277
+ logger.log(`Successfully commented on PR #${prNumberForComment}.`);
278
+ }
279
+ catch (error) {
280
+ const errorMessage = error instanceof Error ? error.message : String(error);
281
+ logger.error(`Failed to comment on PR #${prNumberForComment}: ${errorMessage}`);
282
+ anySubmissionFailed = true;
283
+ }
284
+ }
285
+ else if (dirsToProcess.size > 0 && githubToken) { // Modified condition to check githubToken directly
286
+ logger.log('Workblock directories were processed. PR commenting skipped: Could not automatically determine PR information, no relevant PR found for the current commit, or GitHub token was missing/invalid.');
287
+ }
288
+ if (anySubmissionFailed) {
289
+ logger.error("One or more operations failed during 'publish-changed-workblocks'.");
290
+ process.exit(1);
291
+ }
292
+ else {
293
+ logger.log("'publish-changed-workblocks' completed successfully.");
294
+ }
83
295
  });
84
- commander_1.program.parse();
296
+ commander_1.program.parse(process.argv);
85
297
  //# sourceMappingURL=cli.js.map
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publisher": "beyondwork",
4
4
  "displayName": "Beyond Work",
5
5
  "description": "Beyond Work is a tool for managing your work in a way that is easy to use and understand.",
6
- "version": "0.1.0",
6
+ "version": "0.1.2",
7
7
  "engines": {
8
8
  "vscode": "^1.94.0",
9
9
  "node": ">=16.0.0"
@@ -16,7 +16,8 @@
16
16
  },
17
17
  "files": [
18
18
  "out/lib/**/*",
19
- "out/cli.js"
19
+ "out/cli.js",
20
+ "out/extension.js"
20
21
  ],
21
22
  "main": "./out/extension.js",
22
23
  "private": false,
@@ -77,7 +78,7 @@
77
78
  "explorer": [
78
79
  {
79
80
  "id": "beyondworkConnections",
80
- "name": "Beyond Work"
81
+ "name": "@beyondwork/wb-cli"
81
82
  }
82
83
  ]
83
84
  }
@@ -99,6 +100,7 @@
99
100
  "typescript": "^5.6.3"
100
101
  },
101
102
  "dependencies": {
103
+ "@octokit/rest": "^21.1.1",
102
104
  "@types/glob": "^8.1.0",
103
105
  "@types/mime-types": "^2.1.4",
104
106
  "@types/ws": "^8.5.12",