Skip to content

Commit

Permalink
Automatic exports (but only public entities)
Browse files Browse the repository at this point in the history
  • Loading branch information
hejny committed Oct 24, 2023
1 parent 24b5039 commit 4fe9495
Show file tree
Hide file tree
Showing 10 changed files with 793 additions and 153 deletions.
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "always",
"printWidth": 80
"printWidth": 120
}
602 changes: 602 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,15 @@
"@types/jest": "27.0.2",
"glob-promise": "^6.0.5",
"jest": "27.3.1",
"organize-imports-cli": "^0.10.0",
"rollup": "2.58.1",
"ts-jest": "27.0.7",
"tslib": "2.3.1",
"tslint": "6.1.3",
"tslint-config-prettier": "1.18.0",
"typescript": "4.4.4"
},
"dependencies": {
"spacetrim": "^0.9.1"
}
}
46 changes: 9 additions & 37 deletions scripts/generate-main-exports/generate-main-exports.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#!/usr/bin/env ts-node

import { readFile, writeFile } from 'fs';
import glob from 'glob-promise';
import { writeFile } from 'fs';
import { join, relative } from 'path';
import { promisify } from 'util';
import { findAllProjectEntities } from '../utils/findAllProjectEntities';

main();

Expand All @@ -13,56 +13,28 @@ async function main() {
'⚠ Warning: Do not edit by hand, all changes will be lost on next execution!',
];

const filesPath = await glob(
join(__dirname, '../../src/**/*.ts').split('\\').join('/'),
const entities = await findAllProjectEntities();
const publicEntities = entities.filter(
({ tags, filePath }) => !tags.includes('@private') && !filePath.includes('_'),
);
const files = await Promise.all(
filesPath.map(async (path) => ({
path,
content: await promisify(readFile)(path, 'utf8'),
})),
);

const exports: Array<{ path: string; name: string }> = [];
for (const file of files) {
let execArray: any; // RegExpExecArray | null;
const regExp =
/^export\s+(?!abstract)\s*(async)?\s*[a-z]+\s+(?<name>[a-zA-Z0-9_]+)/gm;
while ((execArray = regExp.exec(file.content))) {
const { name, annotationRaw } = execArray.groups!;
console.log('!!!', { name, annotationRaw });
exports.push({ path: file.path, name });
}
}

let content = '';

content += comments.map((comment) => `// ${comment}`).join('\n');
content += '\n\n';

content += exports
content += publicEntities
.map(
({ name, path }) =>
`import { ${name} } from './${relative(
join(__dirname, '../../src'),
path,
)
({ name, filePath }) =>
`import { ${name} } from './${relative(join(__dirname, '../../src'), filePath)
.split('\\')
.join('/')
.replace(/\.tsx?$/, '')}';`,
)
.join('\n');
content += '\n\n';

content += `export {\n${exports
.sort(
(a, b) =>
a.name.length > b.name.length
? 1
: -1 /* TODO: Maybe some better sorting */,
)
.map(({ name }) => name)
.join(',\n')}\n};`;
content += `export {\n${publicEntities.map(({ name }) => name).join(',\n')}\n};`;

await promisify(writeFile)(join(__dirname, '../../src/index.ts'), content);
}
Expand Down
55 changes: 55 additions & 0 deletions scripts/utils/findAllProjectEntities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { readAllProjectFiles } from './readAllProjectFiles';

/**
* All possible entity types in javascript and typescript
*/
type IEntityType =
| 'const'
| 'let'
| 'class'
| 'function'
| 'interface'
| 'type' /* <- TODO: More */;

/**
* Metadata of entity in javascript and typescript
*/
export interface IEntity {
filePath: string;
type: IEntityType;
name: string;
anotation?: string;
tags: string[];
// TODO: Detect other things like abstract, async...
}

export async function findAllProjectEntities(): Promise<IEntity[]> {
const files = await readAllProjectFiles();


const entitities: IEntity[] = [];
for (const file of files) {
for (const match of file.content.matchAll(
/(?<anotation>\/\*\*((?!\/\*\*).)*?\*\/\s*)?export(?:\s+declare)?(?:\s+abstract)?(?:\s+async)?(?:\s+(?<type>[a-z]+))(?:\s+(?<name>[a-zA-Z0-9_]+))/gs,
)) {
const { type, name, anotation } = match.groups!;

const tags = Array.from(
anotation?.match(/@([a-zA-Z0-9_-]+)*/g) || [],
);

entitities.push({
filePath: file.path,
type: type as IEntityType,
name,
anotation,
tags,
});
}
}

//console.log(entitities.map(({ name }) => name));
//process.exit(0);

return entitities;
}
8 changes: 8 additions & 0 deletions scripts/utils/findAllProjectFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import glob from 'glob-promise';
import { join } from 'path';

export async function findAllProjectFiles(): Promise<Array<string>> {
return await glob(
join(__dirname, '../../src/**/*.{ts,tsx}').split('\\').join('/'),
);
}
24 changes: 19 additions & 5 deletions scripts/utils/prettify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,19 @@ import { promisify } from 'util';
* @param parser language of parser to use
* @returns Prettified file contents
*/
export async function prettify(fileContents: string, parser = 'typescript'): Promise<string> {
export async function prettify(
fileContents: string,
parser = 'typescript',
): Promise<string> {
try {
return prettier.format(fileContents, {
parser,
...(JSON.parse(await promisify(readFile)(join(process.cwd(), '.prettierrc'), 'utf8')) as any),
...(JSON.parse(
await promisify(readFile)(
join(process.cwd(), '.prettierrc'),
'utf8',
),
) as any),
});
} catch (error) {
if (!(error instanceof Error)) {
Expand All @@ -25,19 +33,25 @@ export async function prettify(fileContents: string, parser = 'typescript'): Pro
console.error(error);
return spaceTrim(
(block) => `
${block(spaceTrim(fileContents))}
/*
TODO: ${'!'}${'!'}${'!'} ${(error as Error).name} occurred during prettify:
TODO: ${'!'}${'!'}${'!'} ${
(error as Error).name
} occurred during prettify:
${block((error as Error).message)}
*/
`,
);
}
}

/**
* TODO: !!! Use fs/promises instead of fs
*/
21 changes: 21 additions & 0 deletions scripts/utils/readAllProjectFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { readFile } from 'fs';
import { promisify } from 'util';
import { findAllProjectFiles } from './findAllProjectFiles';

export async function readAllProjectFiles(): Promise<
Array<{ path: string; content: string }>
> {
return await Promise.all(
(
await findAllProjectFiles()
).map(async (path) => ({
path,
content: await promisify(readFile)(path, 'utf8'),
})),
);
}


/**
* TODO: !!! Use fs/promises instead of fs
*/
2 changes: 1 addition & 1 deletion src/conversion/validatePromptTemplatePipelineJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,5 @@ export function validatePromptTemplatePipelineJson(ptp: PromptTemplatePipelineJs
* > * It checks:
* > * - it has a valid structure
* > * - ...
* > export function validatePromptTemplatePipelineJson(ptp: unknown): asserts ptp is PromptTemplatePipelineJson {
* > ex port function validatePromptTemplatePipelineJson(ptp: unknown): asserts ptp is PromptTemplatePipelineJson {
*/
Loading

0 comments on commit 4fe9495

Please sign in to comment.