Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
9 changes: 7 additions & 2 deletions jobs/knative-job-fn/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
"homepage": "https://github.com/constructive-io/jobs/tree/master/packages/knative-job-fn#readme",
"license": "SEE LICENSE IN LICENSE",
"main": "dist/index.js",
"bin": {
"knative-job-run": "dist/run.js"
},
"directories": {
"lib": "src",
"test": "__tests__"
Expand All @@ -29,6 +32,8 @@
},
"dependencies": {
"body-parser": "1.19.0",
"express": "5.2.1"
"express": "5.2.1",
"graphql-request": "^6.1.0",
"cross-fetch": "^4.0.0"
}
}
}
116 changes: 116 additions & 0 deletions pgpm/cli/__tests__/function.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { existsSync } from 'fs';
import * as path from 'path';
import { Inquirerer } from 'inquirerer';
import { commands } from '../src/commands';
import { setupTests, TestFixture, withInitDefaults } from '../test-utils';

const beforeEachSetup = setupTests();

describe('cmds:init function', () => {
let fixture: TestFixture;
let mockRepoPath: string;

beforeAll(() => {
fixture = new TestFixture();
mockRepoPath = path.join(fixture.tempDir, 'mock-repo');
const fs = require('fs');

// Create mock repo structure
fs.mkdirSync(path.join(mockRepoPath, 'default/function-template/src'), { recursive: true });
fs.mkdirSync(path.join(mockRepoPath, 'default/function-template/__tests__'), { recursive: true });
fs.mkdirSync(path.join(mockRepoPath, 'default/handler/src'), { recursive: true });

// .boilerplates.json
fs.writeFileSync(path.join(mockRepoPath, '.boilerplates.json'), JSON.stringify({ dir: 'default' }));

// function-template files
fs.writeFileSync(path.join(mockRepoPath, 'default/function-template/.boilerplate.json'), JSON.stringify({ type: 'function' }));
fs.writeFileSync(path.join(mockRepoPath, 'default/function-template/package.json'), JSON.stringify({
name: '@constructive-io/____functionName____',
description: '____functionDesc____',
author: '____author____'
}));
fs.writeFileSync(path.join(mockRepoPath, 'default/function-template/tsconfig.json'), '{}');
fs.writeFileSync(path.join(mockRepoPath, 'default/function-template/Makefile'), 'IMAGE_NAME=____functionName____');

// handler files
fs.writeFileSync(path.join(mockRepoPath, 'default/handler/.boilerplate.json'), JSON.stringify({ type: 'handler' }));
fs.writeFileSync(path.join(mockRepoPath, 'default/handler/src/index.ts'), 'export default async () => ({ status: "ok" });');
});

afterAll(() => {
fixture.cleanup();
});

const runFunctionInitTest = async (argv: any) => {
const { mockInput, mockOutput } = beforeEachSetup();
const prompter = new Inquirerer({
input: mockInput,
output: mockOutput,
noTty: true
});

const args = withInitDefaults({
...argv,
repo: mockRepoPath // Use mock repo created in temp dir
});

await commands(args, prompter, {
noTty: true,
input: mockInput,
output: mockOutput,
version: '1.0.0',
minimistOpts: {}
});

return args.cwd;
};

it('initializes a function with default handler', async () => {
const functionName = 'my-function';
const cwd = fixture.tempDir;

await runFunctionInitTest({
_: ['init', 'function'],
cwd,
functionName,
// Map other required args if needed by non-interactive mode
'function-name': functionName,
functionDesc: 'My test function',
author: 'Tester'
});

const funcDir = path.join(cwd, functionName);

// Check for base template files
expect(existsSync(path.join(funcDir, 'package.json'))).toBe(true);
expect(existsSync(path.join(funcDir, 'tsconfig.json'))).toBe(true);
expect(existsSync(path.join(funcDir, 'Makefile'))).toBe(true);

// Check for handler files (merged)
expect(existsSync(path.join(funcDir, 'src', 'index.ts'))).toBe(true);

// Verify variable replacement in package.json
const pkg = require(path.join(funcDir, 'package.json'));
expect(pkg.name).toBe(`@constructive-io/${functionName}`);
expect(pkg.author).toBe('Tester');
});

it('initializes a function using alias "function" argument', async () => {
// Logic handled in runFunctionInitTest via _=['init', 'function']
// This test ensures the alias map in handleInit works
const functionName = 'aliased-func';
const cwd = fixture.tempDir;

await runFunctionInitTest({
_: ['init', 'function'],
cwd,
functionName,
functionDesc: 'Aliased',
author: 'Tester'
});

const funcDir = path.join(cwd, functionName);
expect(existsSync(path.join(funcDir, 'package.json'))).toBe(true);
});
});
84 changes: 81 additions & 3 deletions pgpm/cli/src/commands/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Examples:
${binaryName} init Initialize new module (default)
${binaryName} init workspace Initialize new workspace
${binaryName} init module Initialize new module explicitly
${binaryName} init function Initialize new cloud function
${binaryName} init workspace --dir <variant> Use variant templates
${binaryName} init --boilerplate Select from available boilerplates
${binaryName} init --repo owner/repo Use templates from GitHub repository
Expand Down Expand Up @@ -90,7 +91,13 @@ async function handleInit(argv: Partial<Record<string, any>>, prompter: Inquirer
}

// Regular init path: default to 'module' if no fromPath provided
const fromPath = positionalFromPath || 'module';
let fromPath = positionalFromPath || 'module';

// Alias 'function' to 'function-template' for better UX match with folder structure
if (fromPath === 'function') {
fromPath = 'function-template';
}

// Track if user explicitly requested module (e.g., `pgpm init module`)
const wasExplicitModuleRequest = positionalFromPath === 'module';

Expand Down Expand Up @@ -118,6 +125,17 @@ async function handleInit(argv: Partial<Record<string, any>>, prompter: Inquirer
});
}

if (templateType === 'function') {
return handleFunctionInit(argv, prompter, {
fromPath,
templateRepo,
branch,
dir,
noTty,
cwd,
});
}

// Default to module init (for 'module' type, 'generic' type, or unknown types)
return handleModuleInit(argv, prompter, {
fromPath,
Expand Down Expand Up @@ -412,8 +430,8 @@ async function handleModuleInit(

const extensions = isPgpmTemplate && answers.extensions
? answers.extensions
.filter((opt: OptionValue) => opt.selected)
.map((opt: OptionValue) => opt.name)
.filter((opt: OptionValue) => opt.selected)
.map((opt: OptionValue) => opt.name)
: [];

const templateAnswers = {
Expand Down Expand Up @@ -484,3 +502,63 @@ async function handleModuleInit(

return { ...argv, ...answers };
}

async function handleFunctionInit(
argv: Partial<Record<string, any>>,
prompter: Inquirerer,
ctx: InitContext
) {
const functionQuestions: Question[] = [
{
name: 'functionName',
message: 'Enter function name',
required: true,
type: 'text'
}
];

const answers = await prompter.prompt(argv, functionQuestions);
const targetPath = path.join(ctx.cwd, sluggify(answers.functionName));

var params = {
...argv,
...answers,
____functionName____: answers.functionName,
____functionDesc____: argv.functionDesc || argv.____functionDesc____ || 'Default Description',
____author____: argv.author || argv.____author____ || 'Constructive',
// Workaround mappings
functionName_: answers.functionName,
functionDesc: argv.functionDesc || argv.____functionDesc____ || 'Default Description',
author: argv.author || argv.____author____ || 'Constructive'
};

await scaffoldTemplate({
fromPath: ctx.fromPath,
outputDir: targetPath,
templateRepo: ctx.templateRepo,
branch: ctx.branch,
dir: ctx.dir,
answers: params,
toolName: DEFAULT_TEMPLATE_TOOL_NAME,
noTty: ctx.noTty,
cwd: ctx.cwd,
prompter
});

await scaffoldTemplate({
fromPath: 'handler',
outputDir: targetPath,
templateRepo: ctx.templateRepo,
branch: ctx.branch,
dir: ctx.dir,
answers: params,
toolName: DEFAULT_TEMPLATE_TOOL_NAME,
noTty: ctx.noTty,
cwd: ctx.cwd,
prompter
});

process.stdout.write(`\n✨ Function created at ${targetPath}\n`);

return { ...argv, ...answers, cwd: targetPath };
}
28 changes: 14 additions & 14 deletions pgpm/core/src/export/export-meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const getTableColumns = async (pool: Pool, schemaName: string, tableName: string
WHERE table_schema = $1 AND table_name = $2
ORDER BY ordinal_position
`, [schemaName, tableName]);

const columns = new Map<string, string>();
for (const row of result.rows) {
columns.set(row.column_name, row.udt_name);
Expand All @@ -80,14 +80,14 @@ const buildDynamicFields = async (
tableConfig: TableConfig
): Promise<Record<string, FieldType>> => {
const actualColumns = await getTableColumns(pool, tableConfig.schema, tableConfig.table);

if (actualColumns.size === 0) {
// Table doesn't exist, return empty fields
return {};
}

const dynamicFields: Record<string, FieldType> = {};

// For each column in the hardcoded config, check if it exists in the database
for (const [fieldName, fieldType] of Object.entries(tableConfig.fields)) {
if (actualColumns.has(fieldName)) {
Expand All @@ -96,7 +96,7 @@ const buildDynamicFields = async (
}
// If column doesn't exist in database, skip it (this fixes the bug)
}

return dynamicFields;
};

Expand Down Expand Up @@ -904,36 +904,36 @@ export const exportMeta = async ({ opts, dbname, database_id }: ExportMetaParams
database: dbname
});
const sql: Record<string, string> = {};

// Cache for dynamically built parsers
const parsers: Record<string, Parser> = {};

// Build parser dynamically by querying actual columns from the database
const getParser = async (key: string): Promise<Parser | null> => {
if (parsers[key]) {
return parsers[key];
}

const tableConfig = config[key];
if (!tableConfig) {
return null;
}

// Build fields dynamically based on actual database columns
const dynamicFields = await buildDynamicFields(pool, tableConfig);

if (Object.keys(dynamicFields).length === 0) {
// No columns found (table doesn't exist or no matching columns)
return null;
}

const parser = new Parser({
schema: tableConfig.schema,
table: tableConfig.table,
conflictDoNothing: tableConfig.conflictDoNothing,
fields: dynamicFields
});
} as any);

parsers[key] = parser;
return parser;
};
Expand All @@ -944,7 +944,7 @@ export const exportMeta = async ({ opts, dbname, database_id }: ExportMetaParams
if (!parser) {
return;
}

const result = await pool.query(query, [database_id]);
if (result.rows.length) {
const parsed = await parser.parse(result.rows);
Expand Down
Loading