Skip to content
This repository has been archived by the owner on Apr 17, 2019. It is now read-only.

[RFR] Ouput results as files #21

Merged
merged 3 commits into from
Jun 22, 2017
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
dist
build
output
24 changes: 0 additions & 24 deletions kiwi.svg

This file was deleted.

2 changes: 1 addition & 1 deletion src/convertToPngDataUrl.js → src/convertToPng.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const getPngFromChrome = async ({ client, url, width, height }) => {
fromSurface: false,
});

return `data:image/png;base64,${screenshot.data}`;
return screenshot.data;
};

export default async svg => {
Expand Down
44 changes: 44 additions & 0 deletions src/outputResultsAsDataUrls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { platform } from 'os';
import chalk from 'chalk';
import writeToClipboard from './writeToClipboard';

const print = console.log; // eslint-disable-line
const formatSource = chalk.bold.green;
const formatMessage = chalk.bold.gray;

export default results => {
Promise.all(
results.map(async result => {
if (results.length === 1) {
print('\n');
print(result.data);

try {
await writeToClipboard(result.data);
print('\n');
print(
formatMessage(
`The data url for ${result.source} has been copied in your clipboard`,
),
);
} catch (error) {
console.error(error);
if (platform() === 'linux') {
print(
formatMessage(
'Install xclip if you want the url to be copied in your clipboard automatically.',
),
);
}
}

return;
}

print('\n');
print(formatSource(result.source));
print('\n');
print(result.data);
}),
);
};
89 changes: 89 additions & 0 deletions src/outputResultsAsFiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import chalk from 'chalk';
import { basename, extname, resolve } from 'path';
import { existsSync, mkdirSync, statSync, writeFileSync } from 'fs';
import readline from './readline';

const print = console.log; // eslint-disable-line
const formatMessage = chalk.bold.gray;
const formatError = chalk.bold.red;

const writeFile = async (path, data) => {
const exists = existsSync(path);
if (extname(path) !== '.png') {
path += '.png';
}

if (exists) {
const rl = readline();
const answer = await rl.question(
`A file named ${path} already exists. Shall we override it? (y/n default n)`,
);

if (answer.toLowerCase() !== 'y') {
print(formatMessage('Exiting without overriding existing file'));
process.exit(0);
}
}

writeFileSync(path, data, {
encoding: 'base64',
flag: 'w',
});
};

const createOutputDirectoryIfNeeded = path => {
const exists = existsSync(path);

if (exists) {
return;
}

mkdirSync(path);
};

export default async (results, { out }) => {
if (results.length > 1) {
if (statSync(out).isFile) {
print(
formatError(
'Please specify a directory path for the out option when specifying multiple sources',
),
);
}

createOutputDirectoryIfNeeded(out);

await Promise.all(
results.map(result =>
writeFile(
resolve(out, `${basename(result.source, '.svg')}.png`),
result.data,
),
),
);

return;
}

let outFileName = out;
let exists = existsSync(out);
const extension = extname(out);
let isDirectory = (exists && statSync(out).isDirectory()) || !extension;

if (isDirectory) {
createOutputDirectoryIfNeeded(out);

outFileName = resolve(
out,
results[0].source === 'stdin'
? 'output.png'
: basename(results[0].source, '.svg'),
);
} else {
outFileName = basename(outFileName, '.svg');
}

writeFile(outFileName, results[0].data);

return;
};
18 changes: 15 additions & 3 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import bodyParser from 'body-parser';
import chalk from 'chalk';
const { choosePort } = require('react-dev-utils/WebpackDevServerUtils');

import convertToPngDataUrl from './convertToPngDataUrl';
import convertToPng from './convertToPng';
import toPngDataUrl from './toPngDataUrl';

const print = console.log; // eslint-disable-line
const formatMessage = chalk.bold.gray;
Expand All @@ -17,9 +18,20 @@ export default (port = 3000) => {

app.post('/', async (req, res) => {
const svg = req.body;
const asDataUrl = req.query['data-url'];

try {
const png = await convertToPngDataUrl(svg);
res.send(png);
const data = await convertToPng(svg);
if (asDataUrl) {
res.end(toPngDataUrl(data));
return;
}

const buffer = new Buffer(data, 'base64');

res.setHeader('Content-Type', 'image/png');
res.setHeader('Content-Length', buffer.length);
res.end(buffer);
} catch (error) {
res.status(500);
res.send(error.message);
Expand Down
66 changes: 24 additions & 42 deletions src/svg_to_png.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import commander from 'commander';
import chalk from 'chalk';
import { readFileSync } from 'fs';
import { platform } from 'os';

import convertToPngDataUrl from './convertToPngDataUrl';
import getSvgFromStdIn from './getSvgFromStdIn';
import readline from './readline';
import startServer from './server';
import writeToClipboard from './writeToClipboard';
import getSvgFromStdIn from './getSvgFromStdIn';
import convertToPng from './convertToPng';
import toPngDataUrl from './toPngDataUrl';
import outputResultsAsDataUrls from './outputResultsAsDataUrls';
import outputResultsAsFiles from './outputResultsAsFiles';

const print = console.log; // eslint-disable-line
const formatSource = chalk.bold.green;
const formatMessage = chalk.bold.gray;

commander
.version('0.0.1')
Expand All @@ -28,6 +25,10 @@ commander
svg_to_png --http
`,
)
.option(
'--out [value]',
'Where to output the file: either a file paht for single source or a directory path for multiple sources',
)
.option('--http', 'Starts the HTTP server')
.option(
'--port <n>',
Expand All @@ -36,6 +37,14 @@ commander
3000,
);

const handleResults = async (results, options) => {
if (options.out) {
return outputResultsAsFiles(results, options);
}

return outputResultsAsDataUrls(results);
};

const executeShellCommand = async options => {
const sources = [];

Expand Down Expand Up @@ -66,50 +75,23 @@ const executeShellCommand = async options => {
sources.push({ svg, source: 'stdin' });
}
const promises = sources.map(({ source, svg }) =>
convertToPngDataUrl(svg).then(pngDataUrl => ({
convertToPng(svg).then(data => ({
source,
pngDataUrl,
data: options.out ? data : toPngDataUrl(data),
})),
);

const results = await Promise.all(promises);
results.forEach(result => {
if (results.length === 1) {
print('\n');
print(result.pngDataUrl);

try {
writeToClipboard(result.pngDataUrl);
print('\n');
print(
formatMessage(
`The data url for ${result.source} has been copied in your clipboard`,
),
);
} catch (error) {
if (platform() === 'linux') {
print(
formatMessage(
'Install xclip if you want the url to be copied in your clipboard automatically.',
),
);
}
}

return;
}

print('\n');
print(formatSource(result.source));
print('\n');
print(result.pngDataUrl);
});
await handleResults(results, options);
};

const options = commander.parse(process.argv);

executeShellCommand({
out: options.out,
files: options.args,
http: options.http,
port: isNaN(options.port) ? undefined : options.port,
}).then(() => process.exit());
})
.then(() => process.exit())
.catch(error => console.error(error));
1 change: 1 addition & 0 deletions src/toPngDataUrl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default data => `data:image/png;base64,${data}`;