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(cli): Creating function from all available templates #857

Merged
merged 3 commits into from
May 28, 2024
Merged
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
33 changes: 26 additions & 7 deletions templates/cli/lib/commands/init.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const ID = require("../id");
const { localConfig, globalConfig } = require("../config");
const {
questionsCreateFunction,
questionsCreateFunctionSelectTemplate,
questionsCreateBucket,
questionsCreateMessagingTopic,
questionsCreateCollection,
Expand Down Expand Up @@ -133,6 +134,8 @@ const initFunction = async () => {

const functionId = answers.id === 'unique()' ? ID.unique() : answers.id;
const functionDir = path.join(functionFolder, functionId);
const templatesDir = path.join(functionFolder, `${functionId}-templates`);
const runtimeDir = path.join(templatesDir, answers.runtime.name);

if (fs.existsSync(functionDir)) {
throw new Error(`( ${functionId} ) already exists in the current directory. Please choose another name.`);
Expand All @@ -156,21 +159,24 @@ const initFunction = async () => {
})

fs.mkdirSync(functionDir, "777");
fs.mkdirSync(templatesDir, "777");

let gitInitCommands = "git clone -b v3 --single-branch --depth 1 --sparse https://github.com/{{ sdk.gitUserName }}/functions-starter ."; // depth prevents fetching older commits reducing the amount fetched
let gitInitCommands = "git clone --single-branch --depth 1 --sparse https://github.com/{{ sdk.gitUserName }}/templates ."; // depth prevents fetching older commits reducing the amount fetched

let gitPullCommands = `git sparse-checkout add ${answers.runtime.name}`;
Copy link
Contributor

@Meldiron Meldiron May 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this doesnt work. From video I see loading templates is slow. Mabe it's because it's cloning everything. Here We need node not node-21.0

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Runtime name is a new field, and it's just node.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm okie, Ill try to run with timings to see what takes 2-3 seconds


let gitPullCommands = `git sparse-checkout add ${answers.runtime.id}`;

/* Force use CMD as powershell does not support && */
if (process.platform === 'win32') {
gitInitCommands = 'cmd /c "' + gitInitCommands + '"';
gitPullCommands = 'cmd /c "' + gitPullCommands + '"';
}

log('Loading templates...');
/* Execute the child process but do not print any std output */
try {
childProcess.execSync(gitInitCommands, { stdio: 'pipe', cwd: functionDir });
childProcess.execSync(gitPullCommands, { stdio: 'pipe', cwd: functionDir });
childProcess.execSync(gitInitCommands, { stdio: 'pipe', cwd: templatesDir });
childProcess.execSync(gitPullCommands, { stdio: 'pipe', cwd: templatesDir });
} catch (error) {
/* Specialised errors with recommended actions to take */
if (error.message.includes('error: unknown option')) {
Expand All @@ -182,7 +188,20 @@ const initFunction = async () => {
}
}

fs.rmSync(path.join(functionDir, ".git"), { recursive: true });
fs.rmSync(path.join(templatesDir, ".git"), { recursive: true });
const templates = ['Starter'];
templates.push(...fs.readdirSync(runtimeDir, { withFileTypes: true })
.filter(item => item.isDirectory() && item.name !== 'starter')
.map(dirent => dirent.name));

let selected = { template: 'starter' };

if (templates.length > 1) {
selected = await inquirer.prompt(questionsCreateFunctionSelectTemplate(templates))
}



const copyRecursiveSync = (src, dest) => {
let exists = fs.existsSync(src);
let stats = exists && fs.statSync(src);
Expand All @@ -199,9 +218,9 @@ const initFunction = async () => {
fs.copyFileSync(src, dest);
}
};
copyRecursiveSync(path.join(functionDir, answers.runtime.id), functionDir);
copyRecursiveSync(path.join(runtimeDir, selected.template), functionDir);

fs.rmSync(`${functionDir}/${answers.runtime.id}`, { recursive: true, force: true });
fs.rmSync(templatesDir, { recursive: true, force: true });

const readmePath = path.join(process.cwd(), 'functions', functionId, 'README.md');
const readmeFile = fs.readFileSync(readmePath).toString();
Expand Down
19 changes: 19 additions & 0 deletions templates/cli/lib/questions.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ const questionsCreateFunction = [
name: `${runtime.name} (${runtime['$id']})`,
value: {
id: runtime['$id'],
name: runtime['$id'].split('-')[0],
entrypoint: getEntrypoint(runtime['$id']),
ignore: getIgnores(runtime['$id']),
commands: getInstallCommand(runtime['$id'])
Expand All @@ -274,6 +275,23 @@ const questionsCreateFunction = [
}
];

const questionsCreateFunctionSelectTemplate = (templates) => {
return [
{
type: "list",
name: "template",
message: "What template would you like to use?",
choices: templates.map((template) => {
const name =`${template[0].toUpperCase()}${template.split('').slice(1).join('')}`.replace(/[-_]/g,' ');

return { value: template, name }
})
}
];
};



const questionsCreateBucket = [
{
type: "input",
Expand Down Expand Up @@ -617,6 +635,7 @@ const questionsMfaChallenge = [
module.exports = {
questionsInitProject,
questionsCreateFunction,
questionsCreateFunctionSelectTemplate,
questionsCreateBucket,
questionsCreateCollection,
questionsCreateMessagingTopic,
Expand Down