-
Notifications
You must be signed in to change notification settings - Fork 240
feat(cli): add wgc grpc-service list-templates & init #2033
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
395f7b5
feat(cli): add wgc grpc-service list-templates & init
jensneuse 21a7256
chore: refactor to use octokit & tar, remove node-fetch
jensneuse 13b7eb1
chore: refactor checkTemplateExists
jensneuse 6de3061
chore: refactor init & generate
jensneuse 105922b
chore: validate template name
jensneuse 55b33c1
chore: improve error handling
jensneuse e9db120
chore: update test
jensneuse df73f34
Update cli/src/commands/grpc-service/commands/init.ts
jensneuse cfe0667
Update cli/src/commands/grpc-service/commands/init.ts
jensneuse 52066b0
chore: fix ts
jensneuse File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| import { existsSync, readdirSync, mkdirSync } from 'node:fs'; | ||
| import os from 'node:os'; | ||
| import { Command, program } from 'commander'; | ||
| import { resolve, join } from 'pathe'; | ||
| import Spinner from 'ora'; | ||
| import { Octokit } from '@octokit/rest'; | ||
| import { extract, t } from 'tar'; | ||
| import fs from 'fs-extra'; | ||
| import pc from 'picocolors'; | ||
| import { BaseCommandOptions } from '../../../core/types/types.js'; | ||
| import { fetchAvailableTemplates } from './list-templates.js'; | ||
|
|
||
| async function checkTemplateExists(template: string): Promise<boolean> { | ||
| const octokit = new Octokit({ | ||
| log: { | ||
| debug: () => {}, | ||
| info: () => {}, | ||
| warn: () => {}, | ||
| error: () => {}, | ||
| }, | ||
| }); | ||
| const owner = 'wundergraph'; | ||
| const repo = 'cosmo-templates'; | ||
| const path = `grpc-service/${template}`; | ||
| try { | ||
| const res = await octokit.repos.getContent({ owner, repo, path }); | ||
| // If it's a directory, res.data will be an array | ||
| return Array.isArray(res.data); | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| async function downloadAndExtractTemplate(template: string, outputDir: string, spinner: any) { | ||
| const octokit = new Octokit(); | ||
| const owner = 'wundergraph'; | ||
| const repo = 'cosmo-templates'; | ||
| const ref = 'main'; // You may want to make this configurable | ||
| const tempTarPath = join(os.tmpdir(), `cosmo-templates-${Date.now()}.tar.gz`); | ||
| const tempExtractDir = join(os.tmpdir(), `cosmo-templates-extract-${Date.now()}`); | ||
|
|
||
| let topLevelDir = ''; | ||
| try { | ||
| await fs.ensureDir(tempExtractDir); | ||
|
|
||
| spinner.text = 'Downloading template from GitHub...'; | ||
| let response; | ||
| try { | ||
| response = await octokit.repos.downloadTarballArchive({ owner, repo, ref }); | ||
| } catch (err: any) { | ||
| throw new Error(`Failed to download template tarball from GitHub: ${err.message || err}`); | ||
| } | ||
| if (response.data instanceof ArrayBuffer) { | ||
| try { | ||
| await fs.writeFile(tempTarPath, new Uint8Array(Buffer.from(response.data))); | ||
| } catch (err: any) { | ||
| throw new Error(`Failed to write tarball to disk: ${err.message || err}`); | ||
| } | ||
| } else { | ||
| throw new TypeError('Unexpected tarball response type'); | ||
| } | ||
|
|
||
| spinner.text = 'Extracting template files...'; | ||
| try { | ||
| await t({ | ||
| file: tempTarPath, | ||
| onentry: (entry: { path: string }) => { | ||
| if (!topLevelDir && entry.path.includes('/')) { | ||
| topLevelDir = entry.path.split('/')[0]; | ||
| } | ||
| }, | ||
| }); | ||
| } catch (err: any) { | ||
| throw new Error(`Failed to inspect tarball for top-level directory: ${err.message || err}`); | ||
| } | ||
| const templatePathInTar = `${topLevelDir}/grpc-service/${template}`; | ||
| let extracted = false; | ||
| try { | ||
| await extract({ | ||
| file: tempTarPath, | ||
| cwd: tempExtractDir, | ||
| filter: (p: string) => p.startsWith(templatePathInTar + '/'), | ||
| strip: templatePathInTar.split('/').length, | ||
| }); | ||
| // Validate extraction | ||
| const extractedTemplateDir = join(tempExtractDir); | ||
| const files = await fs.readdir(extractedTemplateDir); | ||
| if (!files || files.length === 0) { | ||
| throw new Error('Extracted template directory is empty. The template may not exist or is misconfigured.'); | ||
| } | ||
| extracted = true; | ||
| } catch (err: any) { | ||
| throw new Error(`Failed to extract template files: ${err.message || err}`); | ||
| } | ||
|
|
||
| // Copy extracted files to outputDir | ||
| try { | ||
| await fs.copy(tempExtractDir, outputDir, { overwrite: true }); | ||
| } catch (err: any) { | ||
| throw new Error(`Failed to copy extracted files to output directory: ${err.message || err}`); | ||
| } | ||
|
jensneuse marked this conversation as resolved.
Outdated
|
||
| } catch (error: any) { | ||
| spinner.fail(pc.red('Error during template extraction.')); | ||
| throw error; | ||
| } finally { | ||
| // Cleanup | ||
| try { | ||
| await fs.remove(tempTarPath); | ||
| } catch {} | ||
| try { | ||
| await fs.remove(tempExtractDir); | ||
| } catch {} | ||
|
jensneuse marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
jensneuse marked this conversation as resolved.
|
||
|
|
||
| export default (opts: BaseCommandOptions) => { | ||
| const command = new Command(); | ||
| command | ||
| .name('init') | ||
| .description('Scaffold a new gRPC service project from a template') | ||
| .option('-t, --template <template>', 'Template to use', 'typescript-connect-rpc-fastify') | ||
| .option('-d, --directory <directory>', 'Output directory', '.') | ||
| .action(async (options: { template: string; directory: string }) => { | ||
| const spinner = Spinner(); | ||
| const template = options.template || 'typescript-connect-rpc-fastify'; | ||
| const outputDir = resolve(process.cwd(), options.directory || '.'); | ||
|
|
||
| spinner.start(`Checking if template '${template}' exists...`); | ||
| const templateExists = await checkTemplateExists(template); | ||
| if (!templateExists) { | ||
| spinner.start('Fetching available templates...'); | ||
| const templates = await fetchAvailableTemplates(); | ||
| spinner.stop(); | ||
| if (templates.length > 0) { | ||
| console.log(pc.yellow('Available templates:')); | ||
| for (const t of templates) { | ||
| console.log(` - ${t}`); | ||
| } | ||
| console.log(''); | ||
| console.log( | ||
| `\n${pc.yellow('To use a template, run:')}\n wgc grpc-service init --template ${templates[0]} --directory ./output\n`, | ||
| ); | ||
| } else { | ||
| console.log(pc.red('No templates found in wundergraph/cosmo-templates under grpc-service.')); | ||
| } | ||
| program.error( | ||
| `Template '${template}' does not exist in wundergraph/cosmo-templates under grpc-service. Please check the template name and try again.`, | ||
| ); | ||
| } | ||
|
jensneuse marked this conversation as resolved.
|
||
|
|
||
| spinner.text = `Scaffolding gRPC service using template '${template}'...`; | ||
|
|
||
| try { | ||
| if (existsSync(outputDir)) { | ||
| const files = readdirSync(outputDir); | ||
| if (files.length > 0) { | ||
| spinner.fail(pc.red('Output directory is not empty.')); | ||
| program.error( | ||
| `The directory '${outputDir}' is not empty. Please use the --directory argument to specify an empty or new directory.`, | ||
| ); | ||
| } | ||
| } else { | ||
| mkdirSync(outputDir, { recursive: true }); | ||
| } | ||
| await downloadAndExtractTemplate(template, outputDir, spinner); | ||
| spinner.succeed(pc.green(`gRPC service scaffolded in ${outputDir}`)); | ||
| console.log(''); | ||
| console.log( | ||
| ` Checkout the ${pc.bold(pc.italic('README.md'))} file for instructions on how to use your service.`, | ||
| ); | ||
| console.log(''); | ||
| } catch (error: any) { | ||
| spinner.fail(pc.red('Failed to scaffold gRPC service')); | ||
| program.error(error.message || String(error)); | ||
| } | ||
| }); | ||
| return command; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import { Command } from 'commander'; | ||
| import pc from 'picocolors'; | ||
| import Spinner from 'ora'; | ||
| import { Octokit } from '@octokit/rest'; | ||
| import { BaseCommandOptions } from '../../../core/types/types.js'; | ||
|
|
||
| export async function fetchAvailableTemplates(): Promise<string[]> { | ||
| const octokit = new Octokit(); | ||
| const owner = 'wundergraph'; | ||
| const repo = 'cosmo-templates'; | ||
| const path = 'grpc-service'; | ||
|
|
||
| try { | ||
| const res = await octokit.repos.getContent({ owner, repo, path }); | ||
| if (Array.isArray(res.data)) { | ||
| return res.data.filter((item: any) => item.type === 'dir').map((item: any) => item.name); | ||
| } | ||
| } catch { | ||
| console.error('Error listing templates from https://github.com/wundergraph/cosmo-templates/'); | ||
| } | ||
| return []; | ||
| } | ||
|
jensneuse marked this conversation as resolved.
|
||
|
|
||
| export default (_opts: BaseCommandOptions) => { | ||
| const command = new Command('list-templates'); | ||
| command.description('List all available gRPC service templates'); | ||
| command.action(async () => { | ||
| const spinner = Spinner('Fetching available templates...').start(); | ||
| const templates = await fetchAvailableTemplates(); | ||
| spinner.stop(); | ||
|
jensneuse marked this conversation as resolved.
Outdated
|
||
| if (templates.length > 0) { | ||
| console.log(pc.yellow('Available templates:')); | ||
| for (const t of templates) { | ||
| console.log(` - ${t}`); | ||
| } | ||
| console.log(''); | ||
| console.log(pc.yellow('To use a template, run:')); | ||
| console.log(` wgc grpc-service init --template ${templates[0]} --directory ./output`); | ||
| console.log(''); | ||
| } else { | ||
| console.log(pc.red('No templates found in wundergraph/cosmo-templates under grpc-service.')); | ||
| } | ||
| }); | ||
| return command; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,15 @@ | ||
| import { Command } from 'commander'; | ||
| import { BaseCommandOptions } from '../../core/types/types.js'; | ||
| import generateCommand from './commands/generate.js'; | ||
| import initCommand from './commands/init.js'; | ||
| import listTemplatesCommand from './commands/list-templates.js'; | ||
|
|
||
| export default (opts: BaseCommandOptions) => { | ||
| const command = new Command('grpc-service'); | ||
| command.description('Manage protobuf schemas for remote gRPC services'); | ||
| command.addCommand(generateCommand(opts)); | ||
| command.addCommand(initCommand(opts)); | ||
| command.addCommand(listTemplatesCommand(opts)); | ||
|
|
||
| return command; | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.