Skip to content

Commit

Permalink
prettify
Browse files Browse the repository at this point in the history
  • Loading branch information
dalen committed Jun 9, 2018
1 parent 7882a32 commit 6d1129c
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 86 deletions.
54 changes: 27 additions & 27 deletions cli.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
#!/usr/bin/env node
/* eslint no-console: "off" */
const os = require("os");
const commander = require("commander");
const puppetdbquery = require("./main");
const querystring = require("querystring");
const fs = require("fs");
const http = require("http");
const https = require("https");
const os = require('os');
const commander = require('commander');
const puppetdbquery = require('./main');
const querystring = require('querystring');
const fs = require('fs');
const http = require('http');
const https = require('https');

const opts = commander
.command("find-nodes [options] <query>")
.option("-H, --host <host>", "PuppetDB host")
.option("-p, --port <port>", "PuppetDB port", 8080)
.option("-s, --ssl", "Use SSL")
.command('find-nodes [options] <query>')
.option('-H, --host <host>', 'PuppetDB host')
.option('-p, --port <port>', 'PuppetDB port', 8080)
.option('-s, --ssl', 'Use SSL')
.option(
"--key <keyfile>",
"Private SSL key file",
`/etc/puppet/ssl/private_keys/${os.hostname()}.pem`
'--key <keyfile>',
'Private SSL key file',
`/etc/puppet/ssl/private_keys/${os.hostname()}.pem`,
)
.option(
"--cert <certfile>",
"SSL certificate file",
`/etc/puppet/ssl/certs/${os.hostname()}.pem`
'--cert <certfile>',
'SSL certificate file',
`/etc/puppet/ssl/certs/${os.hostname()}.pem`,
)
.option("--ca <cafile>", "SSL CA certificate file", "/etc/puppet/ssl/ca.pem")
.option("-P, --print", "Print parsed query and exit")
.option('--ca <cafile>', 'SSL CA certificate file', '/etc/puppet/ssl/ca.pem')
.option('-P, --print', 'Print parsed query and exit')
.parse(process.argv);

let query;
Expand All @@ -45,8 +45,8 @@ if (opts.print) {
port: opts.port,
path: `/pdb/query/v4/nodes?${querystring.stringify({ query })}`,
headers: {
Accept: "application/json"
}
Accept: 'application/json',
},
};
let httplib;
if (opts.ssl) {
Expand All @@ -61,17 +61,17 @@ if (opts.print) {
// We have the full response, parse it and print the node names
httplib
.get(options, res => {
let data = "";
res.on("data", chunk => {
let data = '';
res.on('data', chunk => {
data += chunk;
});

return res.on("end", () =>
JSON.parse(data).forEach(node => console.log(node.certname))
return res.on('end', () =>
JSON.parse(data).forEach(node => console.log(node.certname)),
);
})

.on("error", e =>
console.log(`Error fetching from ${opts.host} : ${opts.port} ${e}`)
.on('error', e =>
console.log(`Error fetching from ${opts.host} : ${opts.port} ${e}`),
);
}
25 changes: 10 additions & 15 deletions lib/ast.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ const isBoolean = builtin.boolean;
const defaults = shared.defaults;
const geq = shared.geq;

def('Printable')
.field('loc',
or(def('SourceLocation'), null),
defaults.null,
true);
def('Printable').field(
'loc',
or(def('SourceLocation'), null),
defaults.null,
true,
);

def('Node')
.bases('Printable')
Expand All @@ -31,8 +32,7 @@ def('Position')
.field('line', geq(1))
.field('column', geq(0));

def('Literal')
.bases('Node');
def('Literal').bases('Node');

// Merge literals into Literal type?
def('Boolean')
Expand All @@ -55,8 +55,7 @@ def('Date')
.build('value')
.field('value', isString);

def('Expression')
.bases('Node');
def('Expression').bases('Node');

def('BinaryExpression')
.bases('Expression')
Expand Down Expand Up @@ -112,9 +111,7 @@ def('IdentifierPath')
def('Query')
.bases('Node')
.build('expression')
.field('expression',
or(def('Expression'), null),
defaults.null);
.field('expression', or(def('Expression'), null), defaults.null);

def('Subquery')
.bases('Expression')
Expand All @@ -128,9 +125,7 @@ def('Resource')
.field('res_type', isString)
.field('title', def('Identifier'))
.field('exported', isBoolean)
.field('parameters',
or(def('BlockExpression'), null),
defaults.null);
.field('parameters', or(def('BlockExpression'), null), defaults.null);

def('RegexpNodeMatch')
.bases('Expression')
Expand Down
79 changes: 54 additions & 25 deletions lib/evaluator.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import timespec from 'timespec';
import { visit } from './ast';
import { formatLocation, capitalizeClass, regexpEscape, capitalize } from './util';
import {
formatLocation,
capitalizeClass,
regexpEscape,
capitalize,
} from './util';

const comparison = (operator, left, right) => {
if (operator === '!=' || operator === '!~') {
Expand All @@ -9,19 +14,29 @@ const comparison = (operator, left, right) => {
return [operator, left, right];
};

export default (ast) => {
export default ast => {
const mode = ['fact'];
return visit(ast, {
visitComparison(path) {
this.traverse(path);
// Function to handle negating comparisons
if (mode[0] === 'fact') {
return ['in', 'certname',
['extract', 'certname',
['select_fact_contents',
['and',
return [
'in',
'certname',
[
'extract',
'certname',
[
'select_fact_contents',
[
'and',
path.node.left,
comparison(path.node.operator, 'value', path.node.right)]]]];
comparison(path.node.operator, 'value', path.node.right),
],
],
],
];
} else if (mode[0] === 'subquery') {
let left;
if (path.node.left.length === 1) {
Expand All @@ -32,9 +47,17 @@ export default (ast) => {
return comparison(path.node.operator, left, path.node.right);
} else if (mode[0] === 'resource') {
if (path.node.left[0] === 'tag') {
return comparison(path.node.operator, path.node.left[0], path.node.right);
return comparison(
path.node.operator,
path.node.left[0],
path.node.right,
);
}
return comparison(path.node.operator, ['parameter', path.node.left[0]], path.node.right);
return comparison(
path.node.operator,
['parameter', path.node.left[0]],
path.node.right,
);
}
throw Error(`Unknown mode ${mode}`);
},
Expand Down Expand Up @@ -85,9 +108,15 @@ export default (ast) => {
mode.unshift('subquery');
this.traverse(path);
mode.shift();
return ['in', 'certname',
['extract', 'certname',
[`select_${path.node.endpoint}s`, path.node.expression]]];
return [
'in',
'certname',
[
'extract',
'certname',
[`select_${path.node.endpoint}s`, path.node.expression],
],
];
},
visitRegexpNodeMatch(path) {
mode.unshift('regexp');
Expand All @@ -98,11 +127,7 @@ export default (ast) => {
visitIdentifierPath(path) {
this.traverse(path);
if (mode[0] === 'fact') {
return [
(path.node.regexp ? '~>' : '='),
'path',
path.node.components,
];
return [path.node.regexp ? '~>' : '=', 'path', path.node.components];
}
return path.node.components;
},
Expand All @@ -116,24 +141,28 @@ export default (ast) => {
return path.node.name;
},
visitResource(path) {
const regexp = (path.node.title.type === 'RegexpIdentifier');
const regexp = path.node.title.type === 'RegexpIdentifier';
mode.unshift('resource');
this.traverse(path);
mode.shift();
let { title } = path.node;
if (!regexp && capitalize(path.node.res_type) === 'Class') {
title = capitalizeClass(title);
}
const andExpr = ['and',
['=', 'type', capitalizeClass(path.node.res_type)],
[(regexp ? '~' : '='), 'title', title],
['=', 'exported', path.node.exported]];
const andExpr = [
'and',
['=', 'type', capitalizeClass(path.node.res_type)],
[regexp ? '~' : '=', 'title', title],
['=', 'exported', path.node.exported],
];
if (path.node.parameters) {
andExpr.push(path.node.parameters);
}
return ['in', 'certname',
['extract', 'certname',
['select_resources', andExpr]]];
return [
'in',
'certname',
['extract', 'certname', ['select_resources', andExpr]],
];
},
});
};
8 changes: 2 additions & 6 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@ import './util';
import parser from './parser.jison';
import evaluator from './evaluator';

const parse = (query) => {
const parse = query => {
const ast = parser.parse(query);
return evaluator(ast);
};

export {
evaluator,
parser,
parse,
};
export { evaluator, parser, parse };
26 changes: 13 additions & 13 deletions lib/util.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
import ast from './ast';

const capitalize = s => s[0].toUpperCase() + s.slice(1).toLowerCase();
const capitalizeClass = s => s.split('::').map(module.exports.capitalize)
const capitalizeClass = s =>
s
.split('::')
.map(module.exports.capitalize)
.join('::');

const regexpEscape = s => String(s).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1');
const regexpEscape = s =>
String(s).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1');

const loc = (location) => {
const loc = location => {
const b = ast.builders;
return b.sourceLocation(
b.position(location.first_line, location.first_column),
b.position(location.last_line, location.last_column)
b.position(location.last_line, location.last_column),
);
};

const formatLocation = (astnode) => {
const formatLocation = astnode => {
if (astnode.loc != null) {
const l = astnode.loc;
if (l.start.line === l.end.line && l.start.column === l.end.column) {
return `line ${l.start.line}:${l.start.column}`;
}
return `line ${l.start.line}:${l.start.column} - line ${l.end.line}:${l.end.column}`;
return `line ${l.start.line}:${l.start.column} - line ${l.end.line}:${
l.end.column
}`;
}
return '';
};

export {
capitalize,
capitalizeClass,
regexpEscape,
loc,
formatLocation,
};
export { capitalize, capitalizeClass, regexpEscape, loc, formatLocation };

0 comments on commit 6d1129c

Please sign in to comment.