complete other snippets

This commit is contained in:
2020-04-18 17:24:41 +02:00
parent 3c44614298
commit f383ed0ce4
18 changed files with 213 additions and 550 deletions

View File

@ -19,42 +19,48 @@ import { CopyrightOptions } from './copyright_options';
export default class Copyright implements Snippet {
private options: CopyrightOptions | null = null;
private cwd: string = '';
private loaded_from_config: boolean = false;
private cwd = '';
private loaded_from_config = false;
async start (cwd: string): Promise<void> {
this.cwd = cwd;
await this.load_options_file();
await this.load_options_file ();
if (!this.options)
await this.gather_options ();
await FileMapper.map_all_files (
this.cwd,
this.fix_file_license.bind(this)
this.fix_file_license.bind (this)
);
if (!this.loaded_from_config && await new Confirm({
message: 'should those settings be saved for the next run?'
}).run().catch(DialogHandler.catch)) {
this.save_options_file();
}
if (!this.loaded_from_config && await new Confirm (
{ message: 'should those settings be saved for the next run?' }
)
.run ()
.catch (DialogHandler.catch))
this.save_options_file ();
}
private async gather_options (): Promise<void> {
this.options = (new CopyrightOptions);
this.options.author = await new Input ({ message: 'author' })
.run ().catch(DialogHandler.catch);
.run ()
.catch (DialogHandler.catch);
this.options.email = await new Input ({ message: 'email' })
.run ().catch(DialogHandler.catch);
.run ()
.catch (DialogHandler.catch);
this.options.company = await new Input ({ message: 'company' })
.run ().catch(DialogHandler.catch);
.run ()
.catch (DialogHandler.catch);
this.options.software = await new Input ({ message: 'software name' })
.run ().catch(DialogHandler.catch);
.run ()
.catch (DialogHandler.catch);
this.options.has_license = await new Confirm ({
message:
'would you like to specify a license?'
})
.run ().catch(DialogHandler.catch);
.run ()
.catch (DialogHandler.catch);
if (this.options.has_license) {
this.options.license = await new AutoComplete ({
name: 'license',
@ -62,7 +68,8 @@ export default class Copyright implements Snippet {
limit: 10,
choices: findLicense ('')
})
.run ().catch(DialogHandler.catch);
.run ()
.catch (DialogHandler.catch);
}
}
@ -74,26 +81,32 @@ export default class Copyright implements Snippet {
const options = JSON.parse (
await fs.readFile (file_path, 'utf-8')
);
// eslint-disable-next-line no-console
console.log(`author: ${options.author}
// eslint-disable-next-line no-console
console.log (`author: ${options.author}
email: ${options.email}
company: ${options.company}
software name: ${options.software}
license: ${options.license}`);
const should_load = await new Confirm({
message: 'should those options be used?'
}).run().catch(DialogHandler.catch);
if (should_load){
const should_load = await new Confirm (
{ message: 'should those options be used?' }
)
.run ()
.catch (DialogHandler.catch);
if (should_load) {
this.options = options;
this.loaded_from_config = true;
}
}
}
private async save_options_file(): Promise<void> {
private async save_options_file (): Promise<void> {
const file_path = path.join (this.cwd, '.liconfig.json');
await fs.writeFile (file_path, JSON.stringify (this.options, null, 2), 'utf-8');
await fs.writeFile (
file_path,
JSON.stringify (this.options, null, 2),
'utf-8'
);
}
private fix_file_license (
@ -107,7 +120,9 @@ license: ${options.license}`);
if (!(/\.(?:js|ts|mjs)$/u).test (filename) && !regex.test (data))
return null;
return (shebang_line ? shebang_line[0] : '')
+ CopyrightGenerator.get_copyright_notice (this.options as CopyrightOptions)
+ CopyrightGenerator.get_copyright_notice (
this.options as CopyrightOptions
)
+ data.replace (regex, '')
.replace (shebang, '');
}

View File

@ -1,228 +0,0 @@
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, April 2020
*/
/* eslint-disable no-magic-numbers */
/* eslint-disable no-console */
'use strict';
const fs = require ('fs-extra');
/**
* convert short type notation to knex notation
*
* @param {string} short short type
* @returns {string} type
*/
function get_type (short) {
switch (short) {
case '\'\'':
return 'string';
case '#':
return 'integer';
case '#.#':
return 'double';
case '✓':
return 'boolean';
case '🖹':
return 'text';
case '🕓':
return 'timestamp';
default:
return '';
}
}
/**
* returns columns and attributes for a table
*
* @param {string} str table definition
* @returns {object} table info
*/
function get_table_info (str) {
const lines = str.split (/\n/ug);
lines.splice (0, 2);
lines.splice (lines.length - 2, 2);
const name_line = lines.shift ();
const { name } = (/<b>(?<name>\S+)<\/b>/u).exec (name_line).groups;
const columns = [];
while (lines.length > 0) {
const col = {};
const l = lines.shift ();
const regex = /<tr><td.*?>(?<props>.*?)<\/td><\/tr>/u;
const data = regex.exec (l).groups.props.split (/\s+/gu);
if (data.length === 3 || data[0] === '🔑') {
const opt = data.shift ();
if (opt === '★')
col.unique = true;
if (opt === '🔑')
col.type = 'increments';
}
col.name = data.shift ();
if (data.length > 0)
col.type = get_type (data.shift ());
if (typeof col.type === 'undefined')
console.error (`column type is undefined: ${col.name} table: ${name}`);
columns.push (col);
}
return { name, columns, foreign_keys: [] };
}
/**
* get all tables from a structure file
*
* @param {string} file path to the structure file
* @returns {Promise<object>} tables and foreign keys
*/
async function get_tables (file) {
const lines = (await fs.readFile (file, 'utf-8')).split (/\n/gu);
const curr = [];
const tables = [];
const foreign = [];
for (const l of lines) {
if (curr.length > 0 || (/\S+ \[label=</u).test (l))
curr.push (l);
if ((/>.*?\]/u).test (l)) {
const val = curr.join ('\n');
if (val)
tables.push (get_table_info (val));
curr.splice (0, curr.length);
}
get_foreign_key (l, foreign);
}
for (const fk of foreign) {
for (let i = 0; i < tables.length; i++) {
if (tables[i].name === fk.table) {
tables[i].foreign_keys.push (fk);
break;
}
}
}
return tables;
}
/**
* gets foreign keys from a line
*
* @param {string} line line to check
* @param {Array<object>} foreign_keys array to add to
*/
function get_foreign_key (line, foreign_keys) {
const fk = (/(?<col>\S+) -> (?<ref>\S+)/u).exec (line);
if (fk) {
const col = fk.groups.col.split (':');
const ref = fk.groups.ref.split (':');
const foreign_key = {
table: col[0],
column: col[1],
ref_table: ref[0],
ref_column: ref[1]
};
foreign_keys.push (foreign_key);
}
}
/**
* creates a function for creating a table
*
* @param {object} table table to create a function for
* @returns {string} function
*/
function create_table_function (table) {
let func = `/**
* create table ${table.name}
*
* @param {any} knex database connection
* @returns {Promise} result
*/
function create_${table.name} (knex) {
return knex.schema.createTable ('${table.name}', (table) => {
${table.columns
.map ((col) => `table.${col.type} ('${col.name}');`)
.join ('\n ')}
`;
const unique = table.columns.filter ((val) => val.unique);
if (unique.length > 0) {
func += `\n table.unique (${unique
.map ((val) => `'${val.name}'`)
.join (', ')});\n`;
}
if (table.foreign_keys.length > 0) {
func += '\n';
for (const fk of table.foreign_keys) {
func += ` table.foreign ('${fk.column}')
.references ('${fk.ref_column}')
.inTable ('${fk.ref_table}');\n`;
}
}
func += ` });
}`;
return func;
}
/**
* creates the migration function
*
* @param {Array<object>} tables table array
* @returns {string} function
*/
function create_up_function (tables) {
const func = `async function up (knex) {
${tables.map ((val) => ` await create_${val.name} (knex);`)
.join ('\n')}
}`;
return func;
}
/**
* creates the complete migration file for a graph
*
* @param {string} file_path file to scan
* @returns {Promise<string>} file
*/
async function create_migration (file_path) {
const tables = await get_tables (file_path);
const functions = tables.map ((tab) => create_table_function (tab));
const file = `'use strict';
${functions.join ('\n\n')}
/**
* run migration
*
* @param {any} knex db connection
*/
${create_up_function (tables)}
/**
* revert migration
*/
function down () {
// noop
}
module.exports = { up, down };
`;
return file;
}
module.exports = { get_tables, create_table_function, create_migration };

View File

@ -1,66 +0,0 @@
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, April 2020
*/
/* eslint-disable no-magic-numbers */
/* eslint-disable no-sync */
/* eslint-disable no-console */
'use strict';
const fs = require ('fs-extra');
const path = require ('path');
const dot_parser = require ('./dot_parser');
/**
* copies the full template to a new folder named after arg[0]
*
* @param {string} folder folder to run in
* @param {Array} args function arguments
*/
async function run (folder, args) {
const graph = path.join (folder, args[0]);
const migration = path.join (folder, args[1]);
const db_migration = await dot_parser.create_migration (graph);
await fs.writeFile (migration, db_migration, 'utf-8');
}
/**
* checks if the arguments meet the requirements
*
* @param {string} folder folder to run in
* @param {Array} args function arguments
* @returns {boolean} true if arguments match requirements
*/
function assert (folder, args) {
const tests = [
{
f: () => (args.length === 2
&& typeof args[0] === 'string'
&& typeof args[1] === 'string'),
reason: 'db [graph] [migration]'
},
{
f: () => (typeof folder === 'string'),
reason: 'cwd is not a folder (internal error)'
},
{
f: () => (fs.existsSync (folder)),
reason: 'cwd does not exist (internal error)'
}
];
for (const test of tests) {
if (!test.f ()) {
console.log (test.reason);
return false;
}
}
return true;
}
module.exports = { run, assert };

View File

@ -1,78 +0,0 @@
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, April 2020
*/
/* eslint-disable no-sync */
/* eslint-disable no-console */
'use strict';
const fs = require ('fs-extra');
const path = require ('path');
/**
* copies the full template to a new folder named after arg[0]
*
* @param {string} folder folder to run in
* @param {Array} args function arguments
*/
function run (folder, args) {
const is_node = args.length === 1 && (/^node$/ui).test (args[0]);
const template = path.join (
__dirname,
'template',
is_node
? 'node'
: 'general'
);
for (const f of fs.readdirSync (template)) {
fs.copy (
path.join (template, f),
path.join (folder, f),
{ filter: (src, dest) => !fs.existsSync (dest) }
);
}
if (is_node) {
const pkg = path.join (folder, 'package.json');
if (fs.existsSync (pkg)) {
const json = JSON.parse (fs.readFileSync (pkg, 'utf-8'));
json.scripts.ci = 'yarn && node jenkins.js';
fs.writeFileSync (pkg, JSON.stringify (json, null, 2), 'utf-8');
}
}
}
/**
* checks if the arguments meet the requirements
*
* @param {string} folder folder to run in
* @returns {boolean} true if arguments match requirements
*/
function assert (folder) {
const tests = [
{
f: () => (typeof folder === 'string'),
reason: 'cwd is not a folder (internal error)'
},
{
f: () => (fs.existsSync (folder)),
reason: 'cwd does not exist (internal error)'
}
];
for (const test of tests) {
if (!test.f ()) {
console.log (test.reason);
return false;
}
}
return true;
}
module.exports = { run, assert };

View File

@ -0,0 +1,36 @@
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, April 2020
*/
import { Confirm } from 'enquirer';
import { Snippet } from '../../Snippet';
import { apply_template, modify_json } from '../../Helper';
import node_js from './template/node/jenkins.js.asset';
import node_jenkinsfile from './template/node/Jenkinsfile.asset';
import general_jenkinsfile from './template/general/Jenkinsfile.asset';
export class Jenkins implements Snippet {
public async start (): Promise<void> {
const is_node = await new Confirm ({
message: 'is the current project using nodejs?',
initial: true
})
.run ();
if (is_node) {
await apply_template (node_js, 'jenkins.js');
await apply_template (node_jenkinsfile, 'Jenkinsfile');
await modify_json ((obj) => {
obj.scripts.ci = 'yarn && node jenkins.js';
return obj;
});
}
else {
await apply_template (general_jenkinsfile, 'Jenkinsfile');
}
}
}

View File

@ -22,6 +22,8 @@ fs.writeFileSync ('package.json', JSON.stringify (pkg, null, 2));
child_process.execSync ('yarn lint', { stdio: 'inherit' });
if (typeof pkg.scripts !== 'undefined' && typeof pkg.scripts.test === 'string')
child_process.execSync ('yarn test', { stdio: 'inherit' });
if (typeof pkg.scripts !== 'undefined' && typeof pkg.scripts.compile === 'string')
child_process.execSync ('yarn compile', { stdio: 'inherit' });
child_process.exec ('git log -1 | grep \'\\[no publish\\]\'')
.addListener ('exit', (code) => {

View File

@ -1,127 +0,0 @@
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, April 2020
*/
/* eslint-disable no-sync */
/* eslint-disable no-console */
'use strict';
const fs = require ('fs-extra');
const path = require ('path');
const child_process = require ('child_process');
/**
* copies the full template to a new folder named after arg[0]
*
* @param {string} folder folder to run in
* @param {Array} args function arguments
*/
async function run (folder, args) {
const snip_folder_path = [ folder ];
if (args.length > 0)
snip_folder_path.push (args[0]);
const snip_folder = path.join (...snip_folder_path);
const template = path.join (__dirname, 'template');
if (!fs.existsSync (snip_folder))
fs.mkdir (snip_folder);
for (const f of fs.readdirSync (template)) {
fs.copy (
path.join (template, f),
path.join (snip_folder, f),
{
recursive: true,
filter: (src, dest) => !fs.existsSync (dest)
}
);
}
child_process.execSync (
'git init',
{ cwd: snip_folder, stdio: 'inherit' }
);
child_process.execSync (
'yarn init -y',
{ cwd: snip_folder, stdio: 'inherit' }
);
child_process.execSync (
'yarn add --dev @scode/eslint-config eslint nyc ava',
{ cwd: snip_folder, stdio: 'inherit' }
);
const package_json = JSON.parse (
await fs.readFile (path.join (snip_folder, 'package.json'), 'utf-8')
);
package_json.scripts = {
lint: 'eslint . --ext .js,.jsx,.ts,.tsx,.vue,.mjs',
test: 'nyc ava'
};
await fs.writeFile (
path.join (snip_folder, 'package.json'),
JSON.stringify (package_json, null, 2)
);
await fs.writeFile (
path.join (snip_folder, '.gitignore'),
`/node_modules/
/dist/
/.nyc_output/
/coverage/`
);
}
/**
* checks if the arguments meet the requirements
*
* @param {string} folder folder to run in
* @param {Array} args function arguments
* @returns {boolean} true if arguments match requirements
*/
function assert (folder, args) {
const tests = [
{
f: () => (args.length < 2),
reason: 'too many arguments'
},
{
f: () => (args.length === 0 || typeof args[0] === 'string'),
reason: 'name is not a string'
},
{
f: () => (args.length === 0 || (/^[a-z-]+$/iu).test (args[0])),
reason: 'name can only contain [a-z-]'
},
{
f: () => (typeof folder === 'string'),
reason: 'cwd is not a folder (internal error)'
},
{
f: () => (fs.existsSync (folder)),
reason: 'cwd does not exist (internal error)'
},
{
f: () => (args.length === 1 || fs.readdirSync (folder).length === 0),
reason: 'folder is not empty'
},
{
f: () => (args.length === 0
|| !fs.existsSync (path.join (folder, args[0]))),
reason: 'folder already exists'
}
];
for (const test of tests) {
if (!test.f ()) {
console.log (test.reason);
return false;
}
}
return true;
}
module.exports = { run, assert };

View File

@ -0,0 +1,46 @@
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, April 2020
*/
import path from 'path';
import { Input } from 'enquirer';
import { Snippet } from '../../Snippet';
import { apply_template, modify_json, run_command } from '../../Helper';
import eslintrc from './template/eslintrc.asset';
import npmrc from './template/npmrc.asset';
import index from './template/index.asset';
import gitignore from './template/gitignore.asset';
export class Node implements Snippet {
public async start (): Promise<void> {
const folder = await new Input (
{ message: 'project name (leave empty for current folder):' }
)
.run ();
await apply_template (eslintrc, path.join (folder, '.eslintrc.js'));
await apply_template (npmrc, path.join (folder, '.npmrc'));
await apply_template (index, path.join (folder, 'index.js'));
await apply_template (gitignore, path.join (folder, '.gitignore'));
await run_command ('git init', folder);
await run_command ('yarn init -y', folder);
await run_command (
'yarn add --dev @scode/eslint-config eslint nyc ava',
folder
);
await modify_json ((obj) => {
obj.scripts = {
lint: 'eslint . --ext .js,.jsx,.ts,.tsx,.vue,.mjs',
test: 'nyc ava'
};
return obj;
}, path.join (folder, 'package.json'));
}
}

View File

@ -0,0 +1,4 @@
/node_modules/
/dist/
/.nyc_output/
/coverage/