-
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 2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| import { existsSync, readdirSync } from 'node:fs'; | ||
| import { mkdir } from 'node:fs/promises'; | ||
| 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 url = `https://api.github.com/repos/wundergraph/cosmo-templates/contents/grpc-service/${template}`; | ||
| const res = await fetch(url, { headers: { Accept: 'application/vnd.github.v3+json' } }); | ||
|
jensneuse marked this conversation as resolved.
Outdated
|
||
| if (res.status === 200) { | ||
| const data: any = await res.json(); | ||
| return Array.isArray(data); // Should be an array if it's a directory | ||
| } | ||
| return false; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| 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()}`); | ||
| await fs.ensureDir(tempExtractDir); | ||
|
|
||
| spinner.text = 'Downloading template from GitHub...'; | ||
| const response = await octokit.repos.downloadTarballArchive({ owner, repo, ref }); | ||
| if (response.data instanceof ArrayBuffer) { | ||
| await fs.writeFile(tempTarPath, new Uint8Array(Buffer.from(response.data))); | ||
| } else { | ||
| throw new TypeError('Unexpected tarball response type'); | ||
| } | ||
|
|
||
| spinner.text = 'Extracting template files...'; | ||
| // The tarball will have a top-level directory like cosmo-templates-<sha>/grpc-service/<template>/ | ||
| // We want to extract only grpc-service/<template> and copy its contents to outputDir | ||
| let topLevelDir = ''; | ||
| await t({ | ||
| file: tempTarPath, | ||
| onentry: (entry: { path: string }) => { | ||
| if (!topLevelDir && entry.path.includes('/')) { | ||
| topLevelDir = entry.path.split('/')[0]; | ||
| } | ||
| }, | ||
| }); | ||
| const templatePathInTar = `${topLevelDir}/grpc-service/${template}`; | ||
| await extract({ | ||
| file: tempTarPath, | ||
| cwd: tempExtractDir, | ||
| filter: (p: string) => p.startsWith(templatePathInTar + '/'), | ||
| strip: templatePathInTar.split('/').length, | ||
| }); | ||
|
|
||
| // Copy extracted files to outputDir | ||
| await fs.copy(tempExtractDir, outputDir, { overwrite: true }); | ||
|
|
||
| // Cleanup | ||
| await fs.remove(tempTarPath); | ||
| await fs.remove(tempExtractDir); | ||
| } | ||
|
jensneuse marked this conversation as resolved.
|
||
|
|
||
| export default (opts: BaseCommandOptions) => { | ||
| const command = new Command('init'); | ||
| command.description('Scaffold a new gRPC service project from a template'); | ||
| command.option('-t, --template <template>', 'Template to use', 'typescript-connect-rpc-fastify'); | ||
| command.option('-d, --directory <directory>', 'Output directory', '.'); | ||
| command.action(async (options) => { | ||
| const spinner = Spinner(); | ||
| const template = options.template || 'typescript-connect-rpc-fastify'; | ||
|
jensneuse marked this conversation as resolved.
Outdated
|
||
| const outputDir = resolve(process.cwd(), options.directory || '.'); | ||
|
|
||
| spinner.start(`Checking if template '${template}' exists...`); | ||
| const exists = await checkTemplateExists(template); | ||
| if (!exists) { | ||
| 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(pc.yellow('To use a template, run:')); | ||
| console.log(` wgc grpc-service init --template ${templates[0]} --directory ./output`); | ||
| console.log(''); | ||
|
jensneuse marked this conversation as resolved.
Outdated
|
||
| } 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.`, | ||
| ); | ||
| } | ||
|
|
||
| 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 { | ||
| await mkdir(outputDir, { recursive: true }); | ||
| } | ||
|
jensneuse marked this conversation as resolved.
|
||
| 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; | ||
|
jensneuse marked this conversation as resolved.
Outdated
|
||
| }; | ||
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.