Skip to content

Commit

Permalink
Merge pull request #3 from robbieferrero/feature/AddOptions
Browse files Browse the repository at this point in the history
Add additional options
  • Loading branch information
abhisheksoni27 authored Jan 7, 2018
2 parents 5626987 + 8d1338e commit 9314524
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 153 deletions.
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ $ copper (filename) [options|flags]

## Options

## `-o, --output` : define output path

Define the output filepath for image. Defaults to: `location/of/file.png`

```bash
$ copper index.js --output ~/index.png
```

## `-t, --theme` : defines theme

To change the theme, pass this argument. To see the available themes, see [themes.md](/themes.md)
Expand Down Expand Up @@ -123,6 +131,7 @@ Change the default font size. (Don't pass in units, or it won't work.)
```bash
$ copper index.js --fontSize 25 Raleway //uses '25px' instead of '20px'
```

---

## Module Usage
Expand Down Expand Up @@ -152,9 +161,28 @@ An object via which you can pass in the following parameters.
resolution: 1,
theme: 'hybrid',
font: 'Source Code Pro',
fontSize: 20
}
fontSize: 20,
background: '#fff',
prettify: true, // use prettify to format `js`
style: null, // override code styles injected by theme
webshotCustomConfig: { // Using webshot default options
shotSize: {
width: 'window',
height: 'window'
},
windowSize: {
width: 1024,
height: 768
},
shotOffset: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
}
```
*See [webshot](https://www.npmjs.com/package/webshot) for a description of webshot options.*
## Available Themes
Expand Down
5 changes: 2 additions & 3 deletions cli/cli.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
#!/usr/bin/env node

const cli = require('yargs');

const codeSnipper = require(__dirname + '/../code-snipper.js');

var passedArguments = cli
.usage('Usage: code-snipper <file-name> [options]')
.help('h')
.version()
.describe('o', 'Set output file')
.describe('r', 'Change resolution(1-5)')
.describe('t', 'Change syntax theme. Supports all themes available in highlight.js')
.describe('f', 'Change font. See documentation for more details.')
.describe('fontSize', 'Adjust font-size')
.alias('h', 'help')
.alias('o', 'output')
.alias('r', 'resolution')
.alias('t', 'theme')
.alias('f', 'font')
Expand All @@ -21,8 +22,6 @@ var passedArguments = cli
.epilog('© 2017')
.argv;

//initialize an empty object

const options = {};

//delete optional options
Expand Down
176 changes: 82 additions & 94 deletions code-snipper.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,44 @@
const fs = require('fs');
const path = require('path');

const webshot = require('webshot');

const request = require('request');

const utility = require('./utility/utility.js');

const styleNames = require('./utility/styleNames.js');

const prettier = require('prettier');

const untildify = require('untildify');
const gm = require('gm').subClass({
'imageMagick': true
imageMagick: true
});

const path = require('path');

const VERSION = '9.10.0';

const opts = {
resolution: 1,
theme: 'hybrid',
font: 'Source Code Pro',
fontSize: 20,
background: '#fff'
}
background: '#fff',
output: null,
prettify: true, // use prettify to format `js`
style: null, // override code styles injected by theme
webshotCustomConfig: {
// Using webshots default options
shotSize: {
width: 'window',
height: 'window'
},
windowSize: {
width: 1024,
height: 768
},
shotOffset: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
}
};

/**
* Function to check whether file is JS or JSX.
Expand All @@ -33,54 +47,42 @@ const opts = {
* @param fileName: Name of the file.
* @returns string: '.js' or '.jsx'
*/

function checkFileExtension(fileName) {

const ext = '';

if (fileName.endsWith('.js'))
if (fileName.endsWith('.js')) {
return '.js';

return ext;
}
return '';
}

function insertMissingOptions(options) {
return Object.assign(opts, options);
}
/**
* Prettify code based on the extension of the file.
*/

const prettify = (source, ext) => {

switch (ext) {
case '.js':
{

return prettier.format(source, {
printWidth: 80,
tabWidth: 4,
singleQuote: true,
trailingComma: "none",
bracketSpacing: true,
parser: 'babylon'
});
}
case '.js': {
return prettier.format(source, {
printWidth: 80,
tabWidth: 4,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: true,
parser: 'babylon'
});
}

default: {
return source;
}
}
};

}

function checkIfThemeExists(themeName){
if(styleNames.indexOf(themeName)!==-1) return true;
function checkIfThemeExists(themeName) {
if (styleNames.indexOf(themeName) !== -1) return true;
return false;
}

function setBackground(cssURL, options) {
request(cssURL, function (error, response, html) {
request(cssURL, function(error, response, html) {
if (!error && response.statusCode == 200) {
let location,
firstOccurence,
Expand All @@ -89,9 +91,7 @@ function setBackground(cssURL, options) {
colonOccurence;
let sliced;

location = html
.toString()
.indexOf('.hljs{');
location = html.toString().indexOf('.hljs{');
sliced = html.slice(location);
firstOccurence = sliced.indexOf('}') + 1;
sliced = sliced.slice(0, firstOccurence);
Expand All @@ -101,58 +101,43 @@ function setBackground(cssURL, options) {
semiColonOccurence = sliced.indexOf(';');
sliced = sliced.slice(colonOccurence, semiColonOccurence);
options['background'] = sliced;

}
});
}

function generateHTML(sourceCode, options) {
let htmlTag = 'html';

let bodyTag = 'body';

let headTag = 'head';

let preTag = 'pre';

let codeTag = 'code';

let styleTag = 'style'

let themeName = options.theme.toLowerCase();

let theme = checkIfThemeExists(themeName) ? `${themeName}.min.css` : 'hybrid.min.css';

let theme = checkIfThemeExists(themeName)
? `${themeName}.min.css`
: 'hybrid.min.css';

let cssURL = `https://cdnjs.cloudflare.com/ajax/libs/highlight.js/${VERSION}/styles/${theme}`;

setBackground(cssURL, options);

let scriptURL = `https://cdnjs.cloudflare.com/ajax/libs/highlight.js/${VERSION}/highlight.min.js`;

let style = options.style || `code{font-family: '${options.font}'; font-size:${options.fontSize}px; padding:20px}`;
let style = options.style ||
`code{font-family: '${options.font}'; font-size:${options.fontSize}px; padding:20px}`;

return `<${htmlTag}>
<${headTag}>
<${styleTag}>
return `<html>
<head>
<style>
${style}
</${styleTag}>
</style>
<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet">
<link rel="stylesheet" href="${cssURL}" />
<script src="${scriptURL}"></script>
<script>hljs.initHighlightingOnLoad();</script>
</${headTag}>
<${bodyTag}>
<${preTag}>
<${codeTag}>
${sourceCode}
</${codeTag}>
</${preTag}>
</${bodyTag}}
</${htmlTag}>
</head>
<body>
<pre>
<code>${sourceCode}</code>
</pre>
</body}
</html>
`;

}

/**Main function.
Expand All @@ -161,56 +146,59 @@ ${sourceCode}
*/

function codeSnipper(fileName, options = opts) {

//Add extension to the options
options['ext'] = checkFileExtension(fileName);

options = insertMissingOptions(options);
options = {
...opts,
ext: checkFileExtension(fileName),
...options
};

// Initialize webshot's configuration, setting resolution(zoomFactor) if passed.
var webshotConfig = {
let webshotConfig = {
siteType: 'html',
zoomFactor: options.resolution || 2.5
}

const imagePath = process.cwd() + path.sep + fileName;
zoomFactor: options.resolution || 2.5,
...options.webshotCustomConfig
};

const imagePath = path.join(process.cwd(), fileName);

const imageName = imagePath + '.png';
const imageName = options.output
? untildify(options.output)
: imagePath + '.png';

//Read File and prettify code. Synchronous version is used for simplicity
var sourceCode = '';
let sourceCode = '';
fs.readFile(imagePath, (err, data) => {

if (err) {
throw new Error(err);
}

sourceCode = prettify(data.toString(), options.ext);
sourceCode = options.prettify
? prettify(data.toString(), options.ext)
: data.toString();

//Generate HTML
const htmlString = generateHTML(sourceCode, options);

webshot(htmlString, imageName, webshotConfig, (err) => {
webshot(htmlString, imageName, webshotConfig, err => {
if (!err) {
console.log('Image successfully saved as %s', imageName);
gm(imageName)
.trim()
.trim()
.borderColor(options.background)
.border(20, 20)
.write(imageName, (err) => {
.write(imageName, err => {
if (err) {
throw new Error(err)
throw new Error(err);
}
});
} else {
throw new Error(err)
throw new Error(err);
}
return;
});

});
return 0;
}

module.exports = codeSnipper;
module.exports = codeSnipper;
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "code-snipper",
"version": "0.0.21",
"version": "0.0.22",
"description": "Export code snippets as PNG",
"main": "code-snipper.js",
"scripts": {
Expand All @@ -14,6 +14,7 @@
"prettier": "^0.22.0",
"standard": "^10.0.2",
"taffydb": "^2.7.3",
"untildify": "^3.0.2",
"webshot": "^0.18.0",
"yargs": "^7.0.2"
},
Expand Down
Loading

0 comments on commit 9314524

Please sign in to comment.