Skip to content

Commit

Permalink
feat: split logic for related model, new command added
Browse files Browse the repository at this point in the history
  • Loading branch information
gerard2perez committed Mar 21, 2017
1 parent 0a1010b commit 6988264
Show file tree
Hide file tree
Showing 23 changed files with 188 additions and 201 deletions.
1 change: 1 addition & 0 deletions koaton
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ require('babel-register')({
]
});
require('./src');

// require('./lib');
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"dependencies": {
"bluebird": "^3.3.5",
"chokidar": "^1.5.0",
"cmd-line": "^1.0.0",
"cmd-line": "^1.0.1",
"co": "^4.6.0",
"co-prompt": "^1.0.0",
"colors": "^1.1.2",
Expand All @@ -39,6 +39,7 @@
"imagemin-mozjpeg": "^6.0.0",
"imagemin-pngquant": "^5.0.0",
"inflection": "^1.12.0",
"koaton": "^1.2.0",
"less": "^2.7.1",
"less-plugin-clean-css": "^1.5.1",
"node-notifier": "^5.0.2",
Expand Down
11 changes: 8 additions & 3 deletions src/commands/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ const buildcss = async function buildBundleCSS (target, bundle, development, onl
concat.add(basename, content.css, concat.map);
}
} else if (file.indexOf('.css')) {
watchinFiles[index + target] = glob(file);
watchinFiles[index + target] = glob(ProyPath(file));
if (watchinFiles[index + target].length === 0) {
error.push(`${__nok.red} Pattern ${file} ${'not found'.red}`);
}
Expand Down Expand Up @@ -204,9 +204,14 @@ async function buildNginx () {
hostname: scfg.host,
port: scfg.port
});
for (const idx in configuration.server.subdomains) {
let childsubdomains = glob('koaton_modules/**/config/server.js').map((c) => {
return require(ProyPath(c)).default.subdomains;
});
childsubdomains.push(configuration.server.subdomains);
let allsubdomains = [].concat.apply([], childsubdomains).filter((f, i, a) => a.indexOf(f) === i);
for (const idx in allsubdomains) {
nginxConf += utils.compile(serverTemplate, {
subdomain: configuration.server.subdomains[idx],
subdomain: allsubdomains[idx],
hostname: scfg.host,
port: scfg.port
});
Expand Down
5 changes: 2 additions & 3 deletions src/commands/ember.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'colors';
import * as path from 'upath';
import * as buildcmd from './build';
import * as buildcmd from '../functions/emberBuilder';
import utils from '../utils';
import Command from 'cmd-line/lib/Command';
import * as fs from 'fs-extra';
Expand All @@ -19,7 +19,7 @@ const newproyect = async function newproyect (appName, options) {
};

export default (new Command(__filename, 'Creates a new ember app with the especified named.'))
.Args('appName')
.Args('?appName')
.Options([
['-l', '--list', 'Shows all the ember apps of the project'],
['-f', '--force', 'Overrides the current app.'],
Expand Down Expand Up @@ -61,7 +61,6 @@ export default (new Command(__filename, 'Creates a new ember app with the especi
} else {
options.mount = path.join('/', options.mount || '').replace(/\\/igm, '/');
res = await newproyect(appName, options);
console.log('END NEW PROJET');
res &= !((await utils.mkdir(ProyPath('ember', appName, 'app', 'adapters'))) &&
utils.render(TemplatePath('ember_apps', 'adapter.js'), ProyPath('ember', appName, 'app', 'adapters', 'application.js'), {
adapter: `http:\\\\${configuration.server.host}:${configuration.server.port}`
Expand Down
75 changes: 9 additions & 66 deletions src/commands/model.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import 'colors';
import * as fs from 'fs-extra';
import * as path from 'path';
import datatypes from '../support/DataTypes';
import utils from '../utils';
import Command from 'cmd-line/lib/Command';
import inflector from '../support/inflector';

let description = `Creates a new model. fields must be sourrounded by ''.
let description = `Creates a new model. fields must be sourrounded by "".
${'Fields syntax'.yellow}:
${'field_name'}:${'type'.cyan} ${'[ '.yellow + Object.keys(datatypes).map((c) => {
return c.toLowerCase().cyan;
Expand All @@ -16,77 +12,24 @@ let description = `Creates a new model. fields must be sourrounded by ''.
koaton model User hasmany Phone as Phones
koaton model User hasmany Phone phones phoneId
`;
const emberrel = [
'',
'hasMany',
'belongsTo'
],
linkactions = {
no: 0,
hasmany: 1,
belongsto: 2
};
import persistmodel from '../functions/persistmodel';

export default (new Command(__filename, description))
.Args('name', 'fields|linkaction', '?destmodel', '?as', '?relationProperty', '?foreignKey')
.Args('name', 'fields')
.Options([
['-e', '--ember <app>', 'Generates the model also for the app especified.'],
['-f', '--force', 'Deletes the model if exists.'],
['-r', '--rest', 'Makes the model REST enabled.']
])
.Action(async function (...args) {
let [name, fields, destmodel, as, relationProperty, foreignKey, options] = args;
.Action(async function (name, fields, options) {
if (!name || !fields) {
console.log(' The command cannot be run this way.\n\tkoaton adapter -h\n to see help.'.yellow);
console.log(' The command cannot be run this way.\n\tkoaton model -h\n to see help.'.yellow);
return 0;
}
let modelname = inflector.singularize(name.toLowerCase()),
cmd = `koaton model ${modelname} ${fields} ${destmodel || ''} ${as || ''} ${relationProperty || ''} ${foreignKey || ''}`.trim(),
targetmodel = inflector.singularize((destmodel || '').toLowerCase());
cmd = `koaton model ${modelname} ${fields}`;

scfg.commands.add(cmd);
let linkaction = null;
if (as === 'as') {
linkaction = linkactions[fields.toLowerCase()];
scfg.database[modelname].relation(relationProperty, targetmodel, emberrel[linkaction], foreignKey);
}
let model = scfg.database[modelname] || scfg.database.add(modelname, fields)[modelname],
override = await utils.challenge(ProyPath('models', `${modelname.toLowerCase()}.js`), `The model ${modelname.green} already exits,do you want to override it?`, options.force);
/* istanbul ignore else */
if (override) {
utils.write(ProyPath('models', modelname + '.js'), model.toCaminte());
if (options.rest) {
var restcontroller = "'use strict';\nexports.default = {\n\tREST:true\n};";
utils.write(ProyPath('controllers', `${modelname.toLowerCase()}.js`), restcontroller);
}
}
if (override && options.ember) {
/* istanbul ignore next */
if (!fs.existsSync(ProyPath('/ember/', options.ember))) {
console.log(`The app ${options.ember} does not exists.`.red);
return 1;
}
utils.write(ProyPath('ember', options.ember, 'app', 'models', modelname + '.js'), model.toEmberModel());
/* istanbul ignore else */
if (options.rest) {
utils.write(ProyPath('ember', options.ember, 'app', 'controllers', `${modelname}.js`), model.toCRUDTable());
utils.write(
ProyPath('ember', options.ember, 'app', 'templates', `${modelname}.hbs`),
'{{crud-table\n\tfields=this.fieldDefinition\n}}'
);
let router = await utils.read(path.join(process.cwd(), 'ember', options.ember, 'app', 'router.js'), {
encoding: 'utf-8'
});
/* istanbul ignore else */
if (router.indexOf(`this.route('${modelname}')`) === -1) {
router = router.replace(/Router.map\(.*?function\(.*?\).*?{/igm, `Router.map(function() {\n\tthis.route('${modelname}');\n`);
utils.write(ProyPath('ember', options.ember, 'app', 'router.js'), router, 1);
}
}
}
/* istanbul ignore else */
if (scfg.database.has(model)) {
scfg.database.remove(model);
}
scfg.database.add(model);
return 0;
let model = scfg.database[modelname] || scfg.database.add(modelname, fields)[modelname];
return await persistmodel(model, modelname, options);
});
6 changes: 3 additions & 3 deletions src/commands/modulify.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const Dest = function Dest (...args) {
};
export default (new Command(__filename, 'Run the needed commands to'))
.Action(async function () {
await Events('events', 'pre', 'modulify');
await Events('pre', 'modulify');
fs.emptyDirSync(Dest());

await utils.mkdir(Dest('commands'));
Expand Down Expand Up @@ -109,6 +109,6 @@ export default (new Command(__filename, 'Run the needed commands to'))
utils.rmdir(Dest('public', emberAPP, 'crossdomain.xml'));
utils.rmdir(Dest('public', emberAPP, 'robots.txt'));
});

await Events('events', 'post', 'modulify', Dest());
//
await Events('post', 'modulify', Dest());
});
45 changes: 18 additions & 27 deletions src/commands/nginx.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,9 @@ import * as path from 'upath';
import 'colors';
import * as fs from 'fs-extra';
import utils from '../utils';
import {getnginxpath} from '../functions/nginx';
import Command from 'cmd-line/lib/Command';

let nginxpath;
async function getnginxpath () {
if (nginxpath === undefined) {
let log = await utils.exec('nginx -t');
log = log.stdout || log.stderr;
nginxpath = log.toString().match(/.* file (.*)nginx\.conf test/)[1];
}
return nginxpath;
}

export async function copyconf (name) {
await utils.copy(ProyPath(name), path.join(await getnginxpath(), 'enabled_sites', name));
console.log(` ${'copying'.cyan}: ${name}`);
Expand All @@ -22,33 +13,33 @@ export async function copyconf (name) {

export default (new Command(__filename, 'helps bind the server to nginx'))
.Options([
['-g', '--generate', 'create a .conf file for the project']
['-i', '--install', 'creates and install the .conf in your nginx path.']
])
.Action(async function (options) {
let conf = fs.readFileSync(await getnginxpath() + 'nginx.conf', 'utf-8');
let nginxpath = await getnginxpath();
let conf = fs.readFileSync(`${nginxpath}nginx.conf`, 'utf-8');
if (conf.indexOf('include enabled_sites/*') === -1) {
conf = conf.replace(/http ?\{/igm, 'http {\n\tinclude enabled_sites/*.conf;');
fs.writeFileSync(nginxpath + 'nginx.conf', conf);
console.log(` ${'updated'.cyan}: nginx.conf`);
await utils.mkdir(nginxpath + 'enabled_sites');
}
if (options.generate) {
let serverTemplate = await utils.read(TemplatePath('subdomain.conf'), 'utf-8');
let nginxConf = await utils.read(TemplatePath('server.conf'), 'utf-8');
nginxConf = utils.compile(nginxConf, {
hostname: scfg.hostname,
let serverTemplate = await utils.read(TemplatePath('subdomain.conf'), 'utf-8');
let nginxConf = await utils.read(TemplatePath('server.conf'), 'utf-8');
nginxConf = utils.compile(nginxConf, {
hostname: scfg.host,
port: scfg.port
});
const subdomains = require(`${process.cwd()}/config/server`).subdomains;
for (const idx in subdomains) {
nginxConf += utils.compile(serverTemplate, {
subdomain: subdomains[idx],
hostname: scfg.host,
port: scfg.port
});
const subdomains = require(`${process.cwd()}/config/server`).subdomains;
for (const idx in subdomains) {
nginxConf += utils.compile(serverTemplate, {
subdomain: subdomains[idx],
hostname: scfg.hostname,
port: scfg.port
});
}
utils.write(path.join(process.cwd(), `${require(path.join(process.cwd(), 'package.json')).name}.conf`), nginxConf);
} else {
}
utils.write(path.join(process.cwd(), `${require(path.join(process.cwd(), 'package.json')).name}.conf`), nginxConf);
if (options.copy) {
await copyconf(`${scfg.name}.conf`);
}
});
42 changes: 42 additions & 0 deletions src/commands/relation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Command from 'cmd-line/lib/Command';
import inflector from '../support/inflector';
import persistmodel from '../functions/persistmodel';

let linkmodes = {
'hasmany': 'hasmany',
'belongsto': 'belongsto'
};
let emberrel = {
'hasmany': 'hasMany',
'belongsto': 'belongsTo'
};

export default (new Command(__filename, 'makes a relation betwen two models\n linkmode: hasMany|belongsTo'))
.Args('sourcemodel', 'hasMany|hasOne', 'targetmodel')
.Options([
['-re', '--relation-property', 'Selects the relation property'],
['-fe', '--foreing-key', 'Selects the foreing key to use'],
['-e', '--ember <app>', 'Generates the model also for the app especified.'],
['-f', '--force', 'Deletes the model if exists.'],
['-r', '--rest', 'Makes the model REST enabled.']
])
.Action(async function (sourcemodel, linkmode, targetmodel, options) {
let mode = linkmodes[linkmode.toLowerCase()];
if (!mode) {
console.log(`Invalid mode selected: ${linkmode.red}\nAvaliable options ${'hasMany, belongsTo'.cyan}.`);
return 501;
}
let relationProperty = options.relationProperty || mode === linkmodes.hasmany ? inflector.pluralize(targetmodel) : targetmodel;
let foreignKey = options.foreignKey || inflector.singularize(targetmodel) + 'Id';
let model = scfg.database[sourcemodel];
if (!model || !scfg.database[targetmodel]) {
if (!model) {
console.log(`Source model (${sourcemodel}) does not exists.`);
} else {
console.log(`Target model (${targetmodel}) does not exists.`);
}
return 404;
}
model.relation(relationProperty, targetmodel, emberrel[mode], foreignKey);
return await persistmodel(model, sourcemodel, options);
});
25 changes: 24 additions & 1 deletion src/commands/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,29 @@ export default (new Command(__filename, 'Runs your awsome Koaton applicaction es
building.push(preBuildEmber(emberAPP, configuration).then(() => {
return serveEmber(emberAPP, embercfg[emberAPP], index).then((result) => {
if (typeof result === 'object') {
return postBuildEmber(emberAPP, configuration).then(() => {
return postBuildEmber(emberAPP, configuration).then((file) => {
console.log('IM GONA WATHC', ProyPath('public', configuration.directory, 'index.html'));
let watcher = new Watch(ProyPath('public', configuration.directory, 'index.html'), {
persistent: true,
ignoreInitial: true,
alwaysStat: false,
awaitWriteFinish: {
stabilityThreshold: 1000,
pollInterval: 100
}
});
watching.push(watcher);
let rebuildview = function () {
console.log('rebuildview');
postBuildEmber(emberAPP, configuration).then((f) => {
console.log(f);
livereload.reload();
});
};
watcher
.on('change', rebuildview);
// .on('unlink', deleted)
// .on('add', compress);
result.config = embercfg[emberAPP];
return result;
});
Expand All @@ -193,6 +215,7 @@ export default (new Command(__filename, 'Runs your awsome Koaton applicaction es
return Promise.all(building).then((reports) => {
console.log(' Ember apps:');
for (const report of reports) {
report.log = true;
console.log(` ${report.result}`);
}
screen.line1();
Expand Down
7 changes: 3 additions & 4 deletions src/functions/emberBuilder.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ const prebuildember = async function preBuildEmber (application, options) {
}
let raw = fs.readFileSync(ProyPath('ember', application, 'app', 'adapters', 'application.js'), 'utf-8');
var exp = (/host: (.*),?/i).exec(raw);
if (raw.indexOf('K:custom-adapter') === -1) {
fs.writeFileSync(ProyPath('ember', application, 'app', 'adapters', 'application.js'), raw.replace(exp[1], `'${adapter}'`));
}
write(ProyPath('ember', application, 'app', 'adapters', 'application.js'), raw.replace(exp[1], `'${adapter}'`));
let embercfg = await read(join(emberProyectPath, 'config', 'environment.js'), {
encoding: 'utf-8'
});
Expand Down Expand Up @@ -94,5 +92,6 @@ const postBuildEmber = co.wrap(postbuildember);
export {
postBuildEmber,
preBuildEmber,
buildEmber
buildEmber,
getInflections
};
3 changes: 3 additions & 0 deletions src/functions/nginx.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ async function getnginxpath () {
if (nginxpath === undefined) {
let log = await exec('nginx -t');
log = log.stdout || log.stderr;
if (log === undefined) {
throw new Error('Err! are you sure nginx is running and well configured.'.red);
}
nginxpath = log.toString().match(/.* file (.*)nginx\.conf test/)[1];
}
return nginxpath;
Expand Down
Loading

0 comments on commit 6988264

Please sign in to comment.