Skip to content
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

feat(rosetta): tablets can be compressed #3652

Merged
merged 6 commits into from
Jul 11, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/jsii-rosetta/bin/jsii-rosetta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,12 @@ function main() {
describe: 'Ignore missing fixtures and literate markdown files instead of failing',
type: 'boolean',
})
.options('compress-tablet', {
alias: 'z',
type: 'boolean',
describe: 'Compress the resulting tablet file',
default: false,
})
.conflicts('loose', 'strict')
.conflicts('loose', 'fail'),
wrapHandler(async (args) => {
Expand All @@ -252,6 +258,7 @@ function main() {
cacheToFile: absCacheTo,
trimCache: args['trim-cache'],
loose: args.loose,
compressTablet: args['compress-tablet'],
};

const result = args.infuse
Expand Down
14 changes: 12 additions & 2 deletions packages/jsii-rosetta/lib/commands/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as logging from '../logging';
import { RosettaTranslator, RosettaTranslatorOptions } from '../rosetta-translator';
import { TypeScriptSnippet, SnippetParameters } from '../snippet';
import { snippetKey } from '../tablets/key';
import { LanguageTablet, DEFAULT_TABLET_NAME } from '../tablets/tablets';
import { LanguageTablet, DEFAULT_TABLET_NAME, DEFAULT_TABLET_NAME_COMPRESSED } from '../tablets/tablets';
import { RosettaDiagnostic } from '../translate';
import { groupBy, isDefined } from '../util';
import { infuse } from './infuse';
Expand Down Expand Up @@ -73,6 +73,13 @@ export interface ExtractOptions {
* @default false
*/
readonly allowDirtyTranslations?: boolean;

/**
* Compress the resulting tablet file
*
* @default false
*/
readonly compressTablet?: boolean;
}

export async function extractAndInfuse(assemblyLocations: string[], options: ExtractOptions): Promise<ExtractResult> {
Expand Down Expand Up @@ -154,7 +161,10 @@ export async function extractSnippets(
if (options.writeToImplicitTablets ?? true) {
await Promise.all(
Object.entries(snippetsPerAssembly).map(async ([location, snips]) => {
const asmTabletFile = path.join(location, DEFAULT_TABLET_NAME);
const asmTabletFile = path.join(
location,
options.compressTablet ? DEFAULT_TABLET_NAME_COMPRESSED : DEFAULT_TABLET_NAME,
);
logging.debug(`Writing ${snips.length} translations to ${asmTabletFile}`);
const translations = snips.map(({ key }) => translator.tablet.tryGetSnippet(key)).filter(isDefined);

Expand Down
37 changes: 32 additions & 5 deletions packages/jsii-rosetta/lib/tablets/tablets.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as fs from 'fs-extra';
import * as path from 'node:path';
import * as zlib from 'node:zlib';
kaizencc marked this conversation as resolved.
Show resolved Hide resolved

import { TargetLanguage } from '../languages';
import * as logging from '../logging';
Expand All @@ -11,8 +12,16 @@ import { TabletSchema, TranslatedSnippetSchema, ORIGINAL_SNIPPET_KEY } from './s
// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires
const TOOL_VERSION = require('../../package.json').version;

/**
* The default name of the tablet file
*/
export const DEFAULT_TABLET_NAME = '.jsii.tabl.json';

/**
* The default name of the compressed tablet file
*/
export const DEFAULT_TABLET_NAME_COMPRESSED = '.jsii.tabl.json.gz';

export const CURRENT_SCHEMA_VERSION = '2';

/**
Expand Down Expand Up @@ -121,8 +130,17 @@ export class LanguageTablet {
return this.snippets[snippetKey(typeScriptSource)];
}

/**
* Load the tablet from a file. Will automatically detect if the file is in
* compression format ('.gz') and gunzip if it is.
*/
public async load(filename: string) {
const obj = (await fs.readJson(filename, { encoding: 'utf-8' })) as TabletSchema;
let obj: TabletSchema | any = {};
if (path.extname(filename) === '.gz') {
obj = JSON.parse(zlib.gunzipSync(await fs.readFile(filename)).toString()) as TabletSchema;
} else {
obj = (await fs.readJson(filename, { encoding: 'utf-8' })) as TabletSchema;
}
kaizencc marked this conversation as resolved.
Show resolved Hide resolved

if (!obj.toolVersion || !obj.snippets) {
throw new Error(`File '${filename}' does not seem to be a Tablet file`);
Expand All @@ -147,12 +165,21 @@ export class LanguageTablet {
return Object.values(this.snippets);
}

/**
* Saves the tablet schema to a file. If the filename has a '.gz' extension the tablet
* schema will be compressed, otherwise the tablet schema will be written in raw json.
*/
public async save(filename: string) {
await fs.mkdirp(path.dirname(filename));
await fs.writeJson(filename, this.toSchema(), {
encoding: 'utf-8',
spaces: 2,
});

if (path.extname(filename) === '.gz') {
kaizencc marked this conversation as resolved.
Show resolved Hide resolved
await fs.writeFile(filename, zlib.gzipSync(JSON.stringify(this.toSchema())));
} else {
await fs.writeJson(filename, this.toSchema(), {
encoding: 'utf-8',
spaces: 2,
});
}
}

private toSchema(): TabletSchema {
Expand Down
13 changes: 13 additions & 0 deletions packages/jsii-rosetta/test/commands/extract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,19 @@ test('extract samples from test assembly', async () => {
expect(tablet.snippetKeys.length).toEqual(1);
});

test('extract can save/load compressed tablets', async () => {
const compressedCacheFile = path.join(assembly.moduleDirectory, 'test.tabl.gz');
await extract.extractSnippets([assembly.moduleDirectory], {
cacheToFile: compressedCacheFile,
...defaultExtractOptions,
});

const tablet = new LanguageTablet();
await tablet.load(compressedCacheFile);

expect(tablet.snippetKeys.length).toEqual(1);
});

test('extract works from compressed test assembly', async () => {
const compressedAssembly = TestJsiiModule.fromSource(
{
Expand Down