1
0
mirror of https://github.com/JuanCanham/HackMyResume.git synced 2025-05-12 00:27:08 +01:00

Compare commits

...

62 Commits

Author SHA1 Message Date
bc710b5c6e Merge pull request #77 from hacksalot/dev
v1.3.0 changes
2015-12-31 06:43:34 -05:00
b85d40b1b3 Improve XML encoding for Word docs.
Fix various encoding errors.
2015-12-31 06:38:30 -05:00
069c02ddcc Interim changes supporting v1.3.0. 2015-12-31 03:34:41 -05:00
1f6d77fc28 Bump version to 1.3.0. 2015-12-31 03:18:02 -05:00
2b4266ee42 Merge pull request #69 from zhuangya/missing-extend-def-fix-68
fix: missing extend method
2015-12-30 22:11:20 -05:00
2b3c83c57e Merge branch 'master' of https://github.com/hacksalot/HackMyResume 2015-12-30 22:03:38 -05:00
6f37ccdee3 Merge pull request #75 from hacksalot/dev
Changes for v1.3.0-beta
2015-12-30 21:26:27 -05:00
df27924ac2 Add Johnny Trouble to tests. 2015-12-30 21:07:28 -05:00
3cf24cfb40 Fix PNG generation glitch. 2015-12-30 20:11:21 -05:00
3acf648eb4 Expose helpers to Underscore engine.
Get the same set of helpers working for Underscore and Handlebars
engines. Needs refactoring.
2015-12-30 20:11:09 -05:00
76cafa4249 Fix reference error in explicit themes. 2015-12-30 20:10:14 -05:00
55943bf49a Fix missing semicolon. 2015-12-30 20:09:39 -05:00
a280d8acb2 Support CSS embedding vs. linking. 2015-12-30 19:45:50 -05:00
558a321fe8 Refactor generator logic. 2015-12-30 18:52:41 -05:00
d901047043 Update fluent-themes --> fresh-themes. 2015-12-30 18:50:58 -05:00
d4e0a0fa05 Add {{styleSheet}} helper (placeholder). 2015-12-30 18:19:00 -05:00
22554c61c5 Rename and bump fluent-themes dependency. 2015-12-30 18:18:11 -05:00
72de1bbd33 Scrub. 2015-12-30 15:21:58 -05:00
2ff912e687 Scrub. 2015-12-30 15:11:18 -05:00
ccadb0416f Move freebie formats out of theme class. 2015-12-30 15:03:26 -05:00
5e51beddf7 Refactor. 2015-12-30 14:48:22 -05:00
97c9ba08d0 Fix: Broken HELP command. 2015-12-30 14:00:09 -05:00
39d61c66b9 Finish Theme --> FreshTheme rename. 2015-12-30 13:22:18 -05:00
7a1eadb3fc Tweak error messages.
Stay away from language like "please specify a valid input resume". The
fluentcv fork can use corporate-speak. HackMyResume is more like a
gremlin -- feed it, but never after midnight.
2015-12-30 13:12:51 -05:00
1bcc2f7d0c Add formal support for aliases.
new/create and build/generate
2015-12-30 13:00:30 -05:00
e3cb949992 Fix: Exception when HMR is run without params. 2015-12-30 12:59:21 -05:00
a0c356941c Remove unnecessary line. 2015-12-30 12:44:16 -05:00
3c7868a750 Scrub. 2015-12-30 12:38:01 -05:00
3e7d9c0411 Integrate JRSTheme class. 2015-12-30 12:37:26 -05:00
b21fd93d66 Introduce JRSTheme class.
Start splitting out logic into dedicated abstractions for both FRESH and
JSON Resume themes given the different structure and use cases of each.
2015-12-30 12:08:46 -05:00
37e75acd86 Merge remote-tracking branch 'refs/remotes/origin/master' into dev 2015-12-30 12:06:02 -05:00
6280a18c14 fix: missing extend method
fix #68
2015-12-30 19:20:22 +08:00
5bc8b9c987 Merge remote-tracking branch 'refs/remotes/origin/dev' 2015-12-29 17:58:41 -05:00
0c570f8512 Update README. 2015-12-29 17:43:27 -05:00
7593afa586 Adjust package.json versions.
Relax to v1.3.0-beta and bump fluent-themes version.
2015-12-29 17:33:16 -05:00
417d07f469 Merge pull request #60 from zhuangya/images
Thanks @zhuangya! Nice work.
2015-12-29 17:21:37 -05:00
b803eba934 Scrub string.js.
Will probably be retired in favor of Node reusables.
2015-12-29 10:26:30 -05:00
483207e5a0 Improve Markdown support for JSON Resume themes. 2015-12-29 10:01:45 -05:00
02ef2b2241 Improve error handling.
Better support for spawn errors encountered during generation (for ex,
PDFs through wkhtml) + general refactoring.
2015-12-29 06:35:55 -05:00
13430bcad5 Refactor status codes. 2015-12-29 05:09:05 -05:00
e65c0e128e Fix tests glitch. 2015-12-29 03:50:00 -05:00
bf5c040971 Copy JRS theme assets to target. 2015-12-29 03:10:26 -05:00
5dd3d1a3b4 chore: remove debugging console logs 2015-12-29 03:40:42 +08:00
6b0ea0c7bd add: png format 2015-12-29 03:29:13 +08:00
6bc6b3262e Add tests for FRESH/JRS cross-generation.
Ability to generate JSON Resume themes from FRESH format resumes and
vice-versa.
2015-12-28 04:39:03 -05:00
3c1ae4cbd1 Add baseline support for local generation of JSON Resume themes. 2015-12-28 04:37:42 -05:00
547b87afc6 LINT prior to running tests. 2015-12-28 04:17:48 -05:00
db31744c98 Adjust "npm test" command.
Fix issue with tests being run twice and run tests through Grunt for
LINTing and other pre/post processing.
2015-12-28 04:16:53 -05:00
9423a19842 Remove extraneous references to "tests" plural. 2015-12-28 04:01:30 -05:00
07b303e530 Bump version to 1.3.0. 2015-12-28 03:51:39 -05:00
ec51148374 Introduce interim contribution guidelines. 2015-12-27 00:08:45 -05:00
0514f7805c Add contributors to package.json.
Contributors first, author last.
2015-12-26 22:47:39 -05:00
dfa19899b0 Merge pull request #41 from zhuangya/npm-test
package.json test scripts and travis :)
2015-12-26 21:12:39 -05:00
1265ecab9f chore: remove generated resume, more node ci
- node 0.11 0.12
- remove and ignore `test/sandbox` from git
2015-12-26 19:13:15 +08:00
1ad297ec7a add: missing travis-image url 2015-12-25 07:08:17 +08:00
68628e3304 add: travis yml and badge 2015-12-25 07:06:52 +08:00
1a6d7d5723 change: package.json enhancement
- add `scripts` for something like `npm test` and `npm run grunt`
- add missing devDep: `grunt-cli`
2015-12-25 07:03:16 +08:00
78a8b9c58e Merge pull request #40 from hacksalot/rel/v1.2.2
rel/v1.2.2
2015-12-24 17:44:56 -05:00
5e7abb66bd Safer source format conversions.
Quick fix against missing fields in FRESH and/or JRS (ahead of introing
more robust standalone converter thing). Address portions of #31 and
#33.
2015-12-24 17:51:26 -05:00
358c397bb9 Show call stack on error.
Hat tip @Furchin.
2015-12-24 16:22:29 -05:00
3d41528059 Fix path parsing issue on prev versions of Node.js.
Work around absence of path.parse in Node versions < v0.12. Addresses
#31 and #33.
2015-12-24 16:18:38 -05:00
79637b611a Bump version to 1.2.2. 2015-12-24 16:09:37 -05:00
46 changed files with 1468 additions and 516 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
node_modules/
tests/sandbox/
docs/
npm-debug.log

8
.travis.yml Normal file
View File

@ -0,0 +1,8 @@
language: node_js
node_js:
- "0.11"
- "0.12"
- "4.0"
- "4.1"
- "4.2"
- "5.0"

58
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,58 @@
Contributing
============
*Note: HackMyResume is also available as [FluentCV][fcv]. Contributors are
credited in both.*
HackMyResume needs your help! Our contribution workflow is based on [GitHub
Flow][flow] and we respond to all pull requests and issues, usually within 24
hours. HackMyResume has no corporate affiliation and no commercial basis, which
allows the project to maintain a strict user-first policy, rapid development
velocity, and a liberal stance on contributions and exotic functionality in
keeping with the spirit (and name) of the tool.
In short, your code is welcome here.
## How To Contribute
1. Optional: [**open an issue**][iss] identifying the feature or bug you'd like
to implement or fix. This step isn't required — you can start hacking away on
HackMyResume without clearing it with us — but helps avoid duplication of work
and ensures that your changes will be accepted once submitted.
2. **Fork and clone** the HackMyResume project.
3. Ideally, **create a new feature branch** (eg, `feat/new-awesome-feature` or
similar; call it whatever you like) to perform your work in.
4. **Install dependencies** by running `npm install` in the top-level
HackMyResume folder.
5. Make your **commits** as usual.
6. **Verify** your changes locally with `npm test`.
7. **Push** your commits.
7. **Submit a pull request** from your feature branch to the HackMyResume `dev`
branch.
8. We'll typically **respond** within 24 hours.
9. Your awesome changes will be **merged** after verification.
## Project Maintainers
HackMyResume is currently maintained by [hacksalot][ha] with assistance from
[tomheon][th] and our awesome [contributors][awesome]. Please direct all official
or internal inquiries to:
```
admin@hackmyresume.com
```
You can reach hacksalot directly at:
```
hacksalot@indevious.com
```
Thanks! See you out there in the trenches.
[fcv]: https://github.com/fluentdesk/fluentcv
[flow]: https://guides.github.com/introduction/flow/
[iss]: https://github.com/hacksalot/HackMyResume/issues
[ha]: https://github.com/hacksalot
[th]: https://github.com/tomheon
[awesome]: https://github.com/hacksalot/HackMyResume/graphs/contributors

View File

@ -14,10 +14,10 @@ module.exports = function (grunt) {
ui: 'bdd',
reporter: 'spec'
},
all: { src: ['tests/*.js'] }
all: { src: ['test/*.js'] }
},
clean: ['tests/sandbox'],
clean: ['test/sandbox'],
yuidoc: {
compile: {
@ -38,7 +38,7 @@ module.exports = function (grunt) {
laxcomma: true,
expr: true
},
all: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js']
all: ['Gruntfile.js', 'src/**/*.js', 'test/*.js']
}
};
@ -51,9 +51,9 @@ module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('test', 'Test the HackMyResume library.',
function( config ) { grunt.task.run( ['clean','simplemocha:all'] ); });
function( config ) { grunt.task.run( ['clean','jshint','simplemocha:all'] ); });
grunt.registerTask('document', 'Generate HackMyResume library documentation.',
function( config ) { grunt.task.run( ['yuidoc'] ); });
grunt.registerTask('default', [ 'jshint', 'test', 'yuidoc' ]);
grunt.registerTask('default', [ 'test', 'yuidoc' ]);
};

107
README.md
View File

@ -1,5 +1,8 @@
HackMyResume
============
[![Build status][travis-image]][travis-url]
*Create polished résumés and CVs in multiple formats from your command line or
shell. Author in clean Markdown and JSON, export to Word, HTML, PDF, LaTeX,
plain text, and other arbitrary formats. Fight the power, save trees. Compatible
@ -29,6 +32,7 @@ or Windows.
- Support for multiple input and output resumes.
- Use from your command line or [desktop][7].
- Free and open-source through the MIT license.
- Updated daily.
## Install
@ -39,8 +43,36 @@ Install HackMyResume with NPM:
```
Note: for PDF generation you'll need to install a copy of [wkhtmltopdf][3] for
your platform. For LaTeX generation you'll need a valid LaTeX environment with
access to `xelatex` and similar.
your platform.
## Installing Themes
HackMyResume supports both [FRESH][fresh-themes] and [JSON Resume][jrst]-style
résumé themes.
- FRESH themes currently come preinstalled with HackMyResume.
- JSON Resume themes can be installed from NPM, GitHub, or manually.
To install a JSON Resume theme, just `cd` to the folder where you want to store
your themes and run one of:
```bash
# Install with NPM
npm install jsonresume-theme-[theme-name]
# Install with GitHub
git clone https://github.com/[user-or-org]/[repo-name]
```
Then when you're ready to generate your resume, just reference the location of
the theme folder as you installed it:
```bash
hackmyresume BUILD resume.json TO out/resume.all -t node_modules/jsonresume-theme-classy
```
Note: You can use install themes anywhere on your file system. You don't need a
package.json or other NPM/Node infrastructure.
## Getting Started
@ -95,9 +127,9 @@ Output Format | Ext | Notes
------------- | --- | -----
HTML | .html | A standard HTML 5 + CSS resume format that can be viewed in a browser, deployed to a website, etc.
Markdown | .md | A structured Markdown document that can be used as-is or used to generate HTML.
LaTeX | .tex | A structured LaTeX document (or collection of documents).
MS Word | .doc | A Microsoft Word office document.
Adobe Acrobat (PDF) | .pdf | A binary PDF document driven by an HTML theme.
LaTeX | .tex | A structured LaTeX document (or collection of documents) that can be processed with pdflatex, xelatex, and similar tools.
MS Word | .doc | A Microsoft Word office document (XML-driven; WordProcessingML).
Adobe Acrobat (PDF) | .pdf | A binary PDF document driven by an HTML theme (through wkhtmltopdf).
plain text | .txt | A formatted plain text document appropriate for emails or copy-paste.
JSON | .json | A JSON representation of the resume.
YAML | .yml | A YAML representation of the resume.
@ -105,15 +137,6 @@ RTF | .rtf | Forthcoming.
Textile | .textile | Forthcoming.
image | .png, .bmp | Forthcoming.
## Install
HackMyResume requires a recent version of [Node.js][4] and [NPM][5]. Then:
1. Install the latest official [wkhtmltopdf][3] binary for your platform.
2. Optionally install an updated LaTeX environment (LaTeX resumes only).
2. Install **HackMyResume** with `[sudo] npm install hackmyresume -g`.
3. You're ready to go.
## Use
Assuming you've got a JSON-formatted resume handy, generating resumes in
@ -129,19 +152,19 @@ theme (default to Modern). For example:
```bash
# Generate all resume formats (HTML, PDF, DOC, TXT, YML, etc.)
hackmyresume build resume.json -o out/resume.all -t modern
hackmyresume BUILD resume.json TO out/resume.all -t modern
# Generate a specific resume format
hackmyresume build resume.json TO out/resume.html
hackmyresume build resume.json TO out/resume.pdf
hackmyresume build resume.json TO out/resume.md
hackmyresume build resume.json TO out/resume.doc
hackmyresume build resume.json TO out/resume.json
hackmyresume build resume.json TO out/resume.txt
hackmyresume build resume.json TO out/resume.yml
hackmyresume BUILD resume.json TO out/resume.html
hackmyresume BUILD resume.json TO out/resume.pdf
hackmyresume BUILD resume.json TO out/resume.md
hackmyresume BUILD resume.json TO out/resume.doc
hackmyresume BUILD resume.json TO out/resume.json
hackmyresume BUILD resume.json TO out/resume.txt
hackmyresume BUILD resume.json TO out/resume.yml
# Specify 2 inputs and 3 outputs
hackmyresume build in1.json in2.json TO out.html out.doc out.pdf
hackmyresume BUILD in1.json in2.json TO out.html out.doc out.pdf
```
You should see something to the effect of:
@ -168,8 +191,8 @@ For a predefined theme, include the theme name. For a custom theme, include the
path to the custom theme's folder.
```bash
hackmyresume build resume.json -t modern
hackmyresume build resume.json -t ~/foo/bar/my-custom-theme/
hackmyresume BUILD resume.json TO out/rez.all -t modern
hackmyresume BUILD resume.json TO OUT.rez.all -t ~/foo/bar/my-custom-theme/
```
As of v1.0.0, available predefined themes are `positive`, `modern`, `compact`,
@ -182,7 +205,7 @@ most generic to most specific:
```bash
# Merge specific.json onto base.json and generate all formats
hackmyresume build base.json specific.json -o resume.all
hackmyresume BUILD base.json specific.json TO resume.all
```
This can be useful for overriding a base (generic) resume with information from
@ -193,7 +216,7 @@ resume. Merging follows conventional [extend()][9]-style behavior and there's
no arbitrary limit to how many resumes you can merge:
```bash
hackmyresume build in1.json in2.json in3.json in4.json TO out.html out.doc
hackmyresume BUILD in1.json in2.json in3.json in4.json TO out.html out.doc
Reading JSON resume: in1.json
Reading JSON resume: in2.json
Reading JSON resume: in3.json
@ -209,14 +232,7 @@ You can specify **multiple output targets** and HackMyResume will build them:
```bash
# Generate out1.doc, out1.pdf, and foo.txt from me.json.
hackmyresume build me.json -o out1.doc -o out1.pdf -o foo.txt
```
You can also omit the output file(s) and/or theme completely:
```bash
# Equivalent to "hackmyresume resume.json resume.all -t modern"
hackmyresume build resume.json
hackmyresume BUILD me.json TO out1.doc out1.pdf foo.txt
```
### Using .all
@ -226,7 +242,7 @@ formats for the given resume. For example, this...
```bash
# Generate all resume formats (HTML, PDF, DOC, TXT, etc.)
hackmyresume build me.json -o out/resume.all
hackmyresume BUILD me.json TO out/resume.all
```
..tells HackMyResume to read `me.json` and generate `out/resume.md`,
@ -241,7 +257,7 @@ resumes, use the `validate` command:
```bash
# Validate myresume.json against either the FRESH or JSON Resume schema.
hackmyresume validate resumeA.json resumeB.json
hackmyresume VALIDATE resumeA.json resumeB.json
```
HackMyResume will validate each specified resume in turn:
@ -273,7 +289,7 @@ HTML-formatted resumes. To disable prettification, the `--nopretty` or `-n` flag
can be used:
```bash
hackmyresume generate resume.json out.all --nopretty
hackmyresume BUILD resume.json out.all --nopretty
```
### Silent Mode
@ -281,10 +297,16 @@ hackmyresume generate resume.json out.all --nopretty
Use `-s` or `--silent` to run in silent mode:
```bash
hackmyresume generate resume.json -o someFile.all -s
hackmyresume generate resume.json -o someFile.all --silent
hackmyresume BUILD resume.json -o someFile.all -s
hackmyresume BUILD resume.json -o someFile.all --silent
```
## Contributing
HackMyResume is a community-driven free and open source project under the MIT
License. Contributions are encouraged and we respond to all PRs and issues,
usually within 24 hours. See [CONTRIBUTING.md][contribute] for details.
## License
MIT. Go crazy. See [LICENSE.md][1] for details.
@ -302,3 +324,8 @@ MIT. Go crazy. See [LICENSE.md][1] for details.
[fresh]: https://github.com/fluentdesk/FRESH
[fresca]: https://github.com/fluentdesk/FRESCA
[dry]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
[travis-image]: https://img.shields.io/travis/palomajs/paloma.svg?style=flat-square
[travis-url]: https://travis-ci.org/hacksalot/HackMyResume
[contribute]: CONTRIBUTING.md
[fresh-themes]: https://github.com/fluentdesk/fresh-themes
[jrst]: https://www.npmjs.com/search?q=jsonresume-theme

View File

@ -1,11 +1,15 @@
{
"name": "hackmyresume",
"version": "1.2.1",
"version": "1.3.0",
"description": "Generate polished résumés and CVs in HTML, Markdown, LaTeX, MS Word, PDF, plain text, JSON, XML, YAML, smoke signal, and carrier pigeon.",
"repository": {
"type": "git",
"url": "https://github.com/hacksalot/HackMyResume.git"
},
"scripts": {
"test": "grunt clean && mocha",
"grunt": "grunt"
},
"keywords": [
"resume",
"CV",
@ -25,6 +29,11 @@
"template"
],
"author": "hacksalot <hacksalot@indevious.com> (https://github.com/hacksalot)",
"contributors": [
"Edmund Jorgensen (https://github.com/tomheon)",
"Ya Zhuang (https://github.com/zhuangya)",
"hacksalot <hacksalot@indevious.com> (https://github.com/hacksalot)"
],
"license": "MIT",
"preferGlobal": "true",
"bugs": {
@ -37,22 +46,27 @@
"homepage": "https://github.com/hacksalot/HackMyResume",
"dependencies": {
"colors": "^1.1.2",
"fluent-themes": "~0.7.1-beta",
"copy": "^0.1.3",
"fresca": "~0.2.2",
"fresh-themes": "~0.9.3-beta",
"fs-extra": "^0.24.0",
"handlebars": "^4.0.5",
"html": "0.0.10",
"is-my-json-valid": "^2.12.2",
"json-lint": "^0.1.0",
"jst": "0.0.13",
"lodash": "^3.10.1",
"marked": "^0.3.5",
"minimist": "^1.2.0",
"mkdirp": "^0.5.1",
"moment": "^2.10.6",
"parse-filepath": "^0.6.3",
"path-exists": "^2.1.0",
"recursive-readdir-sync": "^1.0.6",
"simple-html-tokenizer": "^0.2.0",
"string.prototype.startswith": "^0.2.0",
"underscore": "^1.8.3",
"webshot": "^0.16.0",
"wkhtmltopdf": "^0.1.5",
"xml-escape": "^1.0.0",
"yamljs": "^0.2.4"
@ -60,11 +74,17 @@
"devDependencies": {
"chai": "*",
"grunt": "*",
"grunt-cli": "^0.1.13",
"grunt-contrib-clean": "^0.7.0",
"grunt-contrib-jshint": "^0.11.3",
"grunt-contrib-yuidoc": "^0.10.0",
"grunt-simple-mocha": "*",
"jane-q-fullstacker": "fluentdesk/jane-q-fullstacker",
"johnny-trouble-resume": "fluentdesk/johnny-trouble-resume",
"jsonresume-theme-boilerplate": "^0.1.2",
"jsonresume-theme-classy": "^1.0.9",
"jsonresume-theme-modern": "0.0.18",
"jsonresume-theme-sceptile": "^1.0.5",
"mocha": "*",
"resample": "fluentdesk/resample"
}

View File

@ -1,11 +1,13 @@
/**
FRESH to JSON Resume conversion routiens.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@license MIT. See LICENSE.md for details.
@module convert.js
*/
(function(){
var _ = require('underscore');
/**
Convert between FRESH and JRS resume/CV formats.
@class FRESHConverter
@ -16,6 +18,7 @@ FRESH to JSON Resume conversion routiens.
/**
Convert from JSON Resume format to FRESH.
@method toFresh
@todo Refactor
*/
toFRESH: function( src, foreign ) {
@ -25,6 +28,8 @@ FRESH to JSON Resume conversion routiens.
name: src.basics.name,
imp: src.basics.imp,
info: {
label: src.basics.label,
class: src.basics.class, // <--> round-trip
@ -67,6 +72,7 @@ FRESH to JSON Resume conversion routiens.
Convert from FRESH format to JSON Resume.
@param foreign True if non-JSON-Resume properties should be included in
the result, false if those properties should be excluded.
@todo Refactor
*/
toJRS: function( src, foreign ) {
@ -90,7 +96,8 @@ FRESH to JSON Resume conversion routiens.
countryCode: src.location.country,
region: src.location.region
},
profiles: social( src.social, false )
profiles: social( src.social, false ),
imp: src.imp
},
work: employment( src.employment, false ),
@ -107,11 +114,30 @@ FRESH to JSON Resume conversion routiens.
};
},
toSTRING: function( src ) {
function replacerJRS( key,value ) { // Exclude these keys from stringification
return _.some(['imp', 'warnings', 'computed', 'filt', 'ctrl', 'index',
'safeStartDate', 'safeEndDate', 'safeDate', 'safeReleaseDate', 'result',
'isModified', 'htmlPreview', 'display_progress_bar'],
function( val ) { return key.trim() === val; }
) ? undefined : value;
}
function replacerFRESH( key,value ) { // Exclude these keys from stringification
return _.some(['imp', 'warnings', 'computed', 'filt', 'ctrl', 'index',
'safe', 'result', 'isModified', 'htmlPreview', 'display_progress_bar'],
function( val ) { return key.trim() === val; }
) ? undefined : value;
}
return JSON.stringify( src, src.basics ? replacerJRS : replacerFRESH, 2 );
}
};
function meta( direction, obj ) {
//if( !obj ) return obj; // preserve null and undefined
if( direction ) {
obj = obj || { };
obj.format = obj.format || "FRESH@0.1.0";
@ -121,6 +147,7 @@ FRESH to JSON Resume conversion routiens.
}
function employment( obj, direction ) {
if( !obj ) return obj;
if( !direction ) {
return obj && obj.history ?
obj.history.map(function(emp){
@ -147,7 +174,7 @@ FRESH to JSON Resume conversion routiens.
start: job.startDate,
end: job.endDate,
url: job.website,
keywords: "",
keywords: [],
highlights: job.highlights
};
}) : undefined
@ -157,8 +184,10 @@ FRESH to JSON Resume conversion routiens.
function education( obj, direction ) {
if( !obj ) return obj;
if( direction ) {
return obj && obj.length ? {
level: "",
history: obj.map(function(edu){
return {
institution: edu.institution,
@ -166,8 +195,8 @@ FRESH to JSON Resume conversion routiens.
end: edu.endDate,
grade: edu.gpa,
curriculum: edu.courses,
url: edu.website || edu.url || null,
summary: null,
url: edu.website || edu.url || undefined,
summary: edu.summary || "",
area: edu.area,
studyType: edu.studyType
};
@ -191,6 +220,7 @@ FRESH to JSON Resume conversion routiens.
}
function service( obj, direction, foreign ) {
if( !obj ) return obj;
if( direction ) {
return {
history: obj && obj.length ? obj.map(function(vol) {
@ -225,6 +255,7 @@ FRESH to JSON Resume conversion routiens.
}
function social( obj, direction ) {
if( !obj ) return obj;
if( direction ) {
return obj.map(function(pro){
return {
@ -247,6 +278,7 @@ FRESH to JSON Resume conversion routiens.
}
function recognition( obj, direction, foreign ) {
if( !obj ) return obj;
if( direction ) {
return obj && obj.length ? obj.map(
function(awd){
@ -275,6 +307,7 @@ FRESH to JSON Resume conversion routiens.
}
function references( obj, direction ) {
if( !obj ) return obj;
if( direction ) {
return obj && obj.length && obj.map(function(ref){
return {
@ -296,6 +329,7 @@ FRESH to JSON Resume conversion routiens.
}
function writing( obj, direction ) {
if( !obj ) return obj;
if( direction ) {
return obj.map(function( pub ) {
return {

View File

@ -10,10 +10,12 @@
{ name: 'txt', ext: 'txt', gen: new FLUENT.TextGenerator() },
{ name: 'doc', ext: 'doc', fmt: 'xml', gen: new FLUENT.WordGenerator() },
{ name: 'pdf', ext: 'pdf', fmt: 'html', is: false, gen: new FLUENT.HtmlPdfGenerator() },
{ name: 'png', ext: 'png', fmt: 'html', is: false, gen: new FLUENT.HtmlPngGenerator() },
{ name: 'md', ext: 'md', fmt: 'txt', gen: new FLUENT.MarkdownGenerator() },
{ name: 'json', ext: 'json', gen: new FLUENT.JsonGenerator() },
{ name: 'yml', ext: 'yml', fmt: 'yml', gen: new FLUENT.JsonYamlGenerator() },
{ name: 'latex', ext: 'tex', fmt: 'latex', gen: new FLUENT.LaTeXGenerator() }
];
}());

100
src/core/error-handler.js Normal file
View File

@ -0,0 +1,100 @@
/**
@module error-handler.js
*/
(function() {
var HACKMYSTATUS = require('./status-codes')
, PKG = require('../../package.json')
, FS = require('fs')
, FCMD = require('../hackmycmd')
, PATH = require('path')
, title = ('\n*** HackMyResume v' + PKG.version + ' ***').bold.white;
var ErrorHandler = module.exports = {
err: function( ex, shouldExit ) {
var msg = '', exitCode;
if( ex.fluenterror ){
switch( ex.fluenterror ) { // TODO: Remove magic numbers
case HACKMYSTATUS.themeNotFound:
msg = "The specified theme couldn't be found: " + ex.data;
break;
case HACKMYSTATUS.copyCSS:
msg = "Couldn't copy CSS file to destination folder";
break;
case HACKMYSTATUS.resumeNotFound:
msg = 'Please '.guide + 'feed me a resume'.guide.bold +
' in FRESH or JSON Resume format.'.guide;
break;
case HACKMYSTATUS.missingCommand:
msg = title + "\nPlease ".guide + "give me a command".guide.bold +
" (".guide;
msg += Object.keys( FCMD.verbs ).map( function(v, idx, ar) {
return (idx === ar.length - 1 ? 'or '.guide : '') +
v.toUpperCase().guide;
}).join(', '.guide) + ").\n\n".guide;
msg += FS.readFileSync(
PATH.resolve(__dirname, '../use.txt'), 'utf8' ).info.bold;
break;
case HACKMYSTATUS.invalidCommand:
msg = 'Please '.guide + 'specify the output resume file'.guide.bold +
' that should be created.'.guide;
break;
case HACKMYSTATUS.resumeNotFoundAlt:
msg = 'Please '.guide + 'feed me a resume'.guide.bold +
' in either FRESH or JSON Resume format.'.guide;
break;
case HACKMYSTATUS.inputOutputParity:
msg = 'Please '.guide + 'specify an output file name'.guide.bold +
' for every input file you wish to convert.'.guide;
break;
case HACKMYSTATUS.createNameMissing:
msg = 'Please '.guide + 'specify the filename of the resume'.guide.bold +
' to create.'.guide;
break;
case HACKMYSTATUS.wkhtmltopdf:
msg = 'ERROR: PDF generation failed. '.red.bold + ('Make sure wkhtmltopdf is ' +
'installed and accessible from your path.').red;
break;
}
exitCode = ex.fluenterror;
}
else {
msg = ex.toString();
exitCode = 4;
}
var idx = msg.indexOf('Error: ');
var trimmed = idx === -1 ? msg : msg.substring( idx + 7 );
if( !ex.fluenterror || ex.fluenterror < 3 ) { // TODO: magic #s
console.log( ('ERROR: ' + trimmed.toString()).red.bold );
console.log( ex.stack.gray);
}
else {
console.log( trimmed.toString() );
}
if( shouldExit )
process.exit( exitCode );
}
};
}());

View File

@ -13,6 +13,7 @@ Definition of the FRESHResume class.
, __ = require('lodash')
, PATH = require('path')
, moment = require('moment')
, XML = require('xml-escape')
, MD = require('marked')
, CONVERTER = require('./convert')
, JRSResume = require('./jrs-resume');
@ -81,12 +82,90 @@ Definition of the FRESHResume class.
return JSON.stringify( obj, replacer, 2 );
};
/**
Create a copy of this resume in which all string fields have been run through
a transformation function (such as a Markdown filter or XML encoder).
*/
FreshResume.prototype.transformStrings = function( filters, transformer ) {
var that = this;
var ret = this.dupe();
// TODO: refactor recursion
function transformStringsInObject( obj ) {
if( !obj ) return;
if( moment.isMoment( obj ) ) return;
if( _.isArray( obj ) ) {
obj.forEach( function(elem, idx, ar) {
if( typeof elem === 'string' || elem instanceof String )
ar[idx] = transformer( null, elem );
else if (_.isObject(elem))
transformStringsInObject( elem );
});
}
else if (_.isObject( obj )) {
Object.keys( obj ).forEach(function(k) {
var sub = obj[k];
if( typeof sub === 'string' || sub instanceof String ) {
if( filters.length && _.contains(filters, k) )
return;
obj[k] = transformer( k, sub );
}
else if (_.isObject( sub ))
transformStringsInObject( sub );
});
}
}
Object.keys( ret ).forEach(function(member){
transformStringsInObject( ret[ member ] );
});
return ret;
};
/**
Create a copy of this resume in which all fields have been interpreted as
Markdown.
*/
FreshResume.prototype.markdownify = function() {
function MDIN( txt ){
return MD(txt || '' ).replace(/^\s*<p>|<\/p>\s*$/gi, '');
}
function trx(key, val) {
if( key === 'summary' ) {
return MD(val);
}
return MDIN(val);
}
return this.transformStrings( ['skills','url','start','end','date'], trx );
};
/**
Create a copy of this resume in which all fields have been interpreted as
Markdown.
*/
FreshResume.prototype.xmlify = function() {
function trx(key, val) {
return XML(val);
}
return this.transformStrings( [], trx );
};
/**
Create a copy of this resume in which all fields have been interpreted as
Markdown.
*/
FreshResume.prototype.markdownify2 = function() {
var that = this;
var ret = this.dupe();
@ -143,15 +222,12 @@ Definition of the FRESHResume class.
};
/**
Open and parse the specified JSON resume sheet. Merge the JSON object model
onto this Sheet instance with extend() and convert sheet dates to a safe &
Initialize the FreshResume from JSON data.
Open and parse the specified FRESH resume. Merge the JSON object model onto
this Sheet instance with extend() and convert sheet dates to a safe &
consistent format. Then sort each section by startDate descending.
*/
FreshResume.prototype.parse = function( stringData, opts ) {
// Parse the incoming JSON representation
var rep = JSON.parse( stringData );
FreshResume.prototype.parseJSON = function( rep, opts ) {
// Convert JSON Resume to FRESH if necessary
if( rep.basics ) {
rep = CONVERTER.toFRESH( rep );
@ -178,6 +254,13 @@ Definition of the FRESHResume class.
return this;
};
/**
Initialize the the FreshResume from string data.
*/
FreshResume.prototype.parse = function( stringData, opts ) {
return this.parseJSON( JSON.parse( stringData ), opts );
};
/**
Return a unique list of all keywords across all skills.
*/

View File

@ -1,46 +1,58 @@
/**
Definition of the Theme class.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@module theme.js
Definition of the FRESHTheme class.
@module fresh-theme.js
@license MIT. See LICENSE.md for details.
*/
(function() {
var FS = require('fs')
, extend = require('../utils/extend')
, validator = require('is-my-json-valid')
, _ = require('underscore')
, PATH = require('path')
, parsePath = require('parse-filepath')
, pathExists = require('path-exists').sync
, EXTEND = require('../utils/extend')
, moment = require('moment')
, RECURSIVE_READ_DIR = require('recursive-readdir-sync');
, READFILES = require('recursive-readdir-sync');
/**
The Theme class is a representation of a HackMyResume theme asset.
@class Theme
The FRESHTheme class is a representation of a FRESH theme
asset. See also: JRSTheme.
@class FRESHTheme
*/
function Theme() {
function FRESHTheme() {
}
/**
Open and parse the specified theme.
*/
Theme.prototype.open = function( themeFolder ) {
FRESHTheme.prototype.open = function( themeFolder ) {
this.folder = themeFolder;
// Open the [theme-name].json file; should have the same name as folder
this.folder = themeFolder;
var pathInfo = PATH.parse( themeFolder );
var themeFile = PATH.join( themeFolder, pathInfo.base + '.json' );
var pathInfo = parsePath( themeFolder );
// Set up a formats hash for the theme
var formatsHash = { };
// Load the theme
var themeFile = PATH.join( themeFolder, pathInfo.basename + '.json' );
var themeInfo = JSON.parse( FS.readFileSync( themeFile, 'utf8' ) );
var that = this;
// Move properties from the theme JSON file to the theme object
EXTEND( true, this, themeInfo );
// Set up a formats has for the theme
var formatsHash = { };
// Check for an explicit "formats" entry in the theme JSON. If it has one,
// then this theme declares its files explicitly.
if( !!this.formats ) {
@ -51,33 +63,38 @@ Definition of the Theme class.
formatsHash = loadImplicit.call( this );
}
// Add freebie formats every theme gets
formatsHash.json = { title: 'json', outFormat: 'json', pre: 'json', ext: 'json', path: null, data: null };
formatsHash.yml = { title: 'yaml', outFormat: 'yml', pre: 'yml', ext: 'yml', path: null, data: null };
// Cache
this.formats = formatsHash;
// Set the official theme name
this.name = PATH.parse( this.folder ).name;
this.name = parsePath( this.folder ).name;
return this;
};
/**
Determine if the theme supports the specified output format.
*/
Theme.prototype.hasFormat = function( fmt ) {
FRESHTheme.prototype.hasFormat = function( fmt ) {
return _.has( this.formats, fmt );
};
/**
Determine if the theme supports the specified output format.
*/
Theme.prototype.getFormat = function( fmt ) {
FRESHTheme.prototype.getFormat = function( fmt ) {
return this.formats[ fmt ];
};
/**
Load the theme implicitly, by scanning the theme folder for
files. TODO: Refactor duplicated code with loadExplicit.
*/
function loadImplicit() {
// Set up a hash of formats supported by this theme.
@ -91,17 +108,17 @@ Definition of the Theme class.
// Iterate over all files in the theme folder, producing an array, fmts,
// containing info for each file. While we're doing that, also build up
// the formatsHash object.
var fmts = RECURSIVE_READ_DIR( tplFolder ).map( function( absPath ) {
var fmts = READFILES(tplFolder).map( function(absPath) {
// If this file lives in a specific format folder within the theme,
// such as "/latex" or "/html", then that format is the output format
// for all files within the folder.
var pathInfo = PATH.parse(absPath);
var pathInfo = parsePath(absPath);
var outFmt = '', isMajor = false;
var portion = pathInfo.dir.replace(tplFolder,'');
var portion = pathInfo.dirname.replace(tplFolder,'');
if( portion && portion.trim() ) {
if( portion[1] === '_' ) return;
var reg = /^(?:\/|\\)(html|latex|doc|pdf|partials)(?:\/|\\)?/ig;
var reg = /^(?:\/|\\)(html|latex|doc|pdf|png|partials)(?:\/|\\)?/ig;
var res = reg.exec( portion );
if( res ) {
if( res[1] !== 'partials' ) {
@ -119,7 +136,7 @@ Definition of the Theme class.
// compact-[outputformat].[extension], for ex, compact-pdf.html.
if( !outFmt ) {
var idx = pathInfo.name.lastIndexOf('-');
outFmt = ( idx === -1 ) ? pathInfo.name : pathInfo.name.substr( idx + 1 );
outFmt = (idx === -1) ? pathInfo.name : pathInfo.name.substr(idx + 1);
isMajor = true;
}
@ -135,7 +152,7 @@ Definition of the Theme class.
path: absPath,
major: isMajor,
orgPath: PATH.relative(tplFolder, absPath),
ext: pathInfo.ext.slice(1),
ext: pathInfo.extname.slice(1),
title: friendlyName( outFmt ),
pre: outFmt,
// outFormat: outFmt || pathInfo.name,
@ -149,9 +166,13 @@ Definition of the Theme class.
});
// Now, get all the CSS files...
(this.cssFiles = fmts.filter(function( fmt ){ return fmt && (fmt.ext === 'css'); }))
(this.cssFiles = fmts.filter(function( fmt ){
return fmt && (fmt.ext === 'css');
}))
// For each CSS file, get its corresponding HTML file
.forEach(function( cssf ) {
// For each CSS file, get its corresponding HTML file
var idx = _.findIndex(fmts, function( fmt ) {
return fmt && fmt.pre === cssf.pre && fmt.ext === 'html';
});
@ -168,33 +189,39 @@ Definition of the Theme class.
return formatsHash;
}
/**
Load the theme explicitly, by following the 'formats' hash
in the theme's JSON settings file.
*/
function loadExplicit() {
var that = this;
// Set up a hash of formats supported by this theme.
// Housekeeping
var formatsHash = { };
// Establish the base theme folder
var tplFolder = PATH.join( this.folder, 'src' );
var act = null;
var that = this;
// Iterate over all files in the theme folder, producing an array, fmts,
// containing info for each file. While we're doing that, also build up
// the formatsHash object.
var fmts = RECURSIVE_READ_DIR( tplFolder ).map( function( absPath ) {
var fmts = READFILES( tplFolder ).map( function( absPath ) {
act = null;
// If this file is mentioned in the theme's JSON file under "transforms"
var pathInfo = PATH.parse(absPath);
var pathInfo = parsePath(absPath);
var absPathSafe = absPath.trim().toLowerCase();
var outFmt = _.find( Object.keys( that.formats ), function( fmtKey ) {
var fmtVal = that.formats[ fmtKey ];
return _.some( fmtVal.transform, function( fpath ) {
var absPathB = PATH.join( that.folder, fpath ).trim().toLowerCase();
return absPathB === absPathSafe;
var outFmt = _.find(
Object.keys( that.formats ),
function( fmtKey ) {
var fmtVal = that.formats[ fmtKey ];
return _.some( fmtVal.transform, function(fpath) {
var absPathB = PATH.join( that.folder, fpath )
.trim().toLowerCase();
return absPathB === absPathSafe;
});
});
});
if( outFmt ) {
act = 'transform';
}
@ -203,7 +230,7 @@ Definition of the Theme class.
// such as "/latex" or "/html", then that format is the output format
// for all files within the folder.
if( !outFmt ) {
var portion = pathInfo.dir.replace(tplFolder,'');
var portion = pathInfo.dirname.replace(tplFolder,'');
if( portion && portion.trim() ) {
var reg = /^(?:\/|\\)(html|latex|doc|pdf)(?:\/|\\)?/ig;
var res = reg.exec( portion );
@ -215,7 +242,7 @@ Definition of the Theme class.
// compact-[outputformat].[extension], for ex, compact-pdf.html.
if( !outFmt ) {
var idx = pathInfo.name.lastIndexOf('-');
outFmt = ( idx === -1 ) ? pathInfo.name : pathInfo.name.substr( idx + 1 );
outFmt = (idx === -1) ? pathInfo.name : pathInfo.name.substr(idx + 1);
}
// We should have a valid output format now.
@ -231,7 +258,7 @@ Definition of the Theme class.
action: act,
orgPath: PATH.relative(that.folder, absPath),
path: absPath,
ext: pathInfo.ext.slice(1),
ext: pathInfo.extname.slice(1),
title: friendlyName( outFmt ),
pre: outFmt,
// outFormat: outFmt || pathInfo.name,
@ -245,7 +272,11 @@ Definition of the Theme class.
});
// Now, get all the CSS files...
(this.cssFiles = fmts.filter(function( fmt ){ return fmt.ext === 'css'; }))
(this.cssFiles = fmts.filter(function( fmt ){
return fmt.ext === 'css';
}))
// For each CSS file, get its corresponding HTML file
.forEach(function( cssf ) {
// For each CSS file, get its corresponding HTML file
var idx = _.findIndex(fmts, function( fmt ) {
@ -263,12 +294,22 @@ Definition of the Theme class.
return formatsHash;
}
/**
Return a more friendly name for certain formats.
TODO: Refactor
*/
function friendlyName( val ) {
val = val.trim().toLowerCase();
var friendly = { yml: 'yaml', md: 'markdown', txt: 'text' };
return friendly[val] || val;
}
module.exports = Theme;
module.exports = FRESHTheme;
}());

View File

@ -1,6 +1,6 @@
/**
Definition of the JRSResume class.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@license MIT. See LICENSE.md for details.
@module jrs-resume.js
*/
@ -11,6 +11,8 @@ Definition of the JRSResume class.
, validator = require('is-my-json-valid')
, _ = require('underscore')
, PATH = require('path')
, MD = require('marked')
, CONVERTER = require('./convert')
, moment = require('moment');
/**
@ -50,6 +52,24 @@ Definition of the JRSResume class.
return this;
};
/**
Save the sheet to disk in a specific format, either FRESH or JRS.
*/
JRSResume.prototype.saveAs = function( filename, format ) {
if( format === 'JRS' ) {
this.basics.imp.fileName = filename || this.imp.fileName;
FS.writeFileSync( this.basics.imp.fileName, this.stringify(), 'utf8' );
}
else {
var newRep = CONVERTER.toFRESH( this );
var stringRep = CONVERTER.toSTRING( newRep );
FS.writeFileSync( filename, stringRep, 'utf8' );
}
return this;
};
/**
Convert this object to a JSON string, sanitizing meta-properties along the
way. Don't override .toString().
@ -70,6 +90,7 @@ Definition of the JRSResume class.
};
/**
Initialize the JRS Resume from string data.
Open and parse the specified JSON resume sheet. Merge the JSON object model
onto this Sheet instance with extend() and convert sheet dates to a safe &
consistent format. Then sort each section by startDate descending.
@ -77,12 +98,20 @@ Definition of the JRSResume class.
JRSResume.prototype.parse = function( stringData, opts ) {
opts = opts || { };
var rep = JSON.parse( stringData );
return this.parseJSON( rep, opts );
};
/**
Initialize the JRSRume from JSON data.
*/
JRSResume.prototype.parseJSON = function( rep, opts ) {
opts = opts || { };
extend( true, this, rep );
// Set up metadata
if( opts.imp === undefined || opts.imp ) {
this.basics.imp = this.basics.imp || { };
this.basics.imp.title = (opts.title || this.basics.imp.title) || this.basics.name;
this.basics.imp.orgFormat = 'JRS';
}
// Parse dates, sort dates, and calculate computed values
(opts.date === undefined || opts.date) && _parseDates.call( this );
@ -230,6 +259,70 @@ Definition of the JRSResume class.
};
JRSResume.prototype.dupe = function() {
var rnew = new JRSResume();
rnew.parse( this.stringify(), { } );
return rnew;
};
/**
Create a copy of this resume in which all fields have been interpreted as
Markdown.
*/
JRSResume.prototype.harden = function() {
var that = this;
var ret = this.dupe();
function HD(txt) {
return '@@@@~' + txt + '~@@@@';
}
function HDIN(txt){
//return MD(txt || '' ).replace(/^\s*<p>|<\/p>\s*$/gi, '');
return HD(txt);
}
// TODO: refactor recursion
function hardenStringsInObject( obj, inline ) {
if( !obj ) return;
inline = inline === undefined || inline;
if( Object.prototype.toString.call( obj ) === '[object Array]' ) {
obj.forEach(function(elem, idx, ar){
if( typeof elem === 'string' || elem instanceof String )
ar[idx] = inline ? HDIN(elem) : HD( elem );
else
hardenStringsInObject( elem );
});
}
else if (typeof obj === 'object') {
Object.keys( obj ).forEach(function(key) {
var sub = obj[key];
if( typeof sub === 'string' || sub instanceof String ) {
if( _.contains(['skills','url','website','startDate','endDate','releaseDate','date','phone','email','address','postalCode','city','country','region'], key) )
return;
if( key === 'summary' )
obj[key] = HD( obj[key] );
else
obj[key] = inline ? HDIN( obj[key] ) : HD( obj[key] );
}
else
hardenStringsInObject( sub );
});
}
}
Object.keys( ret ).forEach(function(member){
hardenStringsInObject( ret[ member ] );
});
return ret;
};
/**
Convert human-friendly dates into formal Moment.js dates for all collections.
We don't want to lose the raw textual date as entered by the user, so we store

85
src/core/jrs-theme.js Normal file
View File

@ -0,0 +1,85 @@
/**
Definition of the JRSTheme class.
@module jrs-theme.js
@license MIT. See LICENSE.MD for details.
*/
(function() {
var _ = require('underscore')
, PATH = require('path')
, parsePath = require('parse-filepath')
, pathExists = require('path-exists').sync;
/**
The JRSTheme class is a representation of a JSON Resume
theme asset. See also: FRESHTheme.
@class JRSTheme
*/
function JRSTheme() {
}
/**
Open and parse the specified theme.
@method open
*/
JRSTheme.prototype.open = function( thFolder ) {
this.folder = thFolder;
// Open the [theme-name].json file; should have the same
// name as folder
var pathInfo = parsePath( thFolder );
// Open and parse the theme's package.json file.
var pkgJsonPath = PATH.join( thFolder, 'package.json' );
if( pathExists( pkgJsonPath )) {
var thApi = require( thFolder )
, thPkg = require( pkgJsonPath );
this.name = thPkg.name;
this.render = (thApi && thApi.render) || undefined;
this.formats = {
html: { title:'html', outFormat:'html', ext:'html' }
};
}
else {
throw { fluenterror: 10 };
}
return this;
};
/**
Determine if the theme supports the output format.
@method hasFormat
*/
JRSTheme.prototype.hasFormat = function( fmt ) {
return _.has( this.formats, fmt );
};
/**
Return the requested output format.
@method getFormat
*/
JRSTheme.prototype.getFormat = function( fmt ) {
return this.formats[ fmt ];
};
module.exports = JRSTheme;
}());

View File

@ -1,13 +0,0 @@
(function(){
var FRESHResume = require('../core/fresh-resume');
module.exports = function loadSourceResumes( src, log, fn ) {
return src.map( function( res ) {
log( 'Reading '.info + 'SOURCE'.infoBold + ' resume: '.info +
res.cyan.bold );
return (fn && fn(res)) || (new FRESHResume()).open( res );
});
};
}());

107
src/core/resume-factory.js Normal file
View File

@ -0,0 +1,107 @@
/**
Definition of the ResumeFactory class.
@license MIT. See LICENSE.md for details.
@module resume-factory.js
*/
(function(){
require('string.prototype.startswith');
var FS = require('fs');
var ResumeConverter = require('./convert');
/**
A simple factory class for FRESH and JSON Resumes.
@class ResumeFactory
*/
var ResumeFactory = module.exports = {
/**
Load one or more resumes from disk.
*/
load: function ( sources, log, toFormat, objectify ) {
// Loop over all inputs, parsing each to JSON and then to a FRESHResume
// or JRSResume object.
var that = this;
return sources.map( function( src ) {
return that.loadOne( src, log, toFormat, objectify );
});
},
/**
Load a single resume from disk.
*/
loadOne: function( src, log, toFormat, objectify ) {
// Get the destination format. Can be 'fresh', 'jrs', or null/undefined.
toFormat && (toFormat = toFormat.toLowerCase().trim());
// Load and parse the resume JSON
var info = _parse( src, log, toFormat );
if( info.error ) return info;
var json = info.json;
// Determine the resume format: FRESH or JRS
var orgFormat = ( json.meta && json.meta.format &&
json.meta.format.startsWith('FRESH@') ) ?
'fresh' : 'jrs';
// Convert between formats if necessary
if( toFormat && (orgFormat !== toFormat) ) {
json = ResumeConverter[ 'to' + toFormat.toUpperCase() ]( json );
}
// Objectify the resume, that is, convert it from JSON to a FRESHResume
// or JRSResume object.
var rez;
if( objectify ) {
var ResumeClass = require('../core/' + (toFormat || orgFormat) + '-resume');
rez = new ResumeClass().parseJSON( json );
}
return {
file: src,
json: info.json,
rez: rez
};
}
};
function _parse( fileName, log, toFormat ) {
var rawData;
try {
// TODO: Core should not log
log( 'Reading '.info + /*orgFormat.toUpperCase().infoBold +*/
'resume: '.info + fileName.cyan.bold );
rawData = FS.readFileSync( fileName, 'utf8' );
return {
json: JSON.parse( rawData )
};
}
catch(ex) {
return {
error: ex,
raw: rawData
};
}
}
}());

22
src/core/spawn-watch.js Normal file
View File

@ -0,0 +1,22 @@
/**
@module spawn-watch.js
*/
(function() {
// Catch various out-of-band child process errors such as ENOENT for PDFs
// http://stackoverflow.com/q/27688804
var SpawnWatcher = module.exports = function() {
var childProcess = require("child_process");
var oldSpawn = childProcess.spawn;
childProcess.spawn = function() {
return oldSpawn.apply(this, arguments)
.on('error', function(err) {
require('./error-handler').err( err, false );
});
};
}();
//SpawnWatcher();
}());

23
src/core/status-codes.js Normal file
View File

@ -0,0 +1,23 @@
/**
Status codes for HackMyResume.
@module status-codes.js
@license MIT. See LICENSE.MD for details.
*/
(function(){
module.exports = {
success: 0,
themeNotFound: 1,
copyCss: 2,
resumeNotFound: 3,
missingCommand: 4,
invalidCommand: 5,
resumeNotFoundAlt: 6,
inputOutputParity: 7,
createNameMissing: 8,
wkhtmltopdf: 9,
missingPackageJSON: 10
};
}());

View File

@ -1,6 +1,6 @@
/**
Generic template helper definitions for FluentCV.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
Generic template helper definitions for HackMyResume / FluentCV.
@license MIT. See LICENSE.md for details.
@module generic-helpers.js
*/
@ -9,6 +9,7 @@ Generic template helper definitions for FluentCV.
var MD = require('marked')
, H2W = require('../utils/html-to-wpml')
, XML = require('xml-escape')
, moment = require('moment')
, _ = require('underscore');
@ -33,10 +34,12 @@ Generic template helper definitions for FluentCV.
wpml: function( txt, inline ) {
if(!txt) return '';
inline = (inline && !inline.hash) || false;
txt = XML(txt.trim());
txt = inline ?
MD(txt.trim()).replace(/^\s*<p>|<\/p>\s*$/gi, '') :
MD(txt.trim());
txt = H2W( txt.trim() );
MD(txt).replace(/^\s*<p>|<\/p>\s*$/gi, '') :
MD(txt);
txt = H2W( txt );
console.log(txt);
return txt;
},
@ -114,6 +117,16 @@ Generic template helper definitions for FluentCV.
if (lhs || rhs) return options.fn(this);
},
/**
Conditional stylesheet link. Either display the link or embed the stylesheet
via <style></style> tag.
*/
styleSheet: function( file, options ) {
return ( this.opts.css === 'link') ?
'<link href="' + file + '" rel="stylesheet" type="text/css">' :
'<style>' + this.cssInfo.data + '</style>';
},
/**
Perform a generic comparison.
See: http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates

View File

@ -35,11 +35,17 @@ Definition of the HandlebarsGenerator class.
// Compile and run the Handlebars template.
var template = HANDLEBARS.compile(jst);
var encData = json;
( format === 'html' || format === 'pdf' ) && (encData = json.markdownify());
( format === 'doc' ) && (encData = json.xmlify());
return template({
r: format === 'html' || format === 'pdf' ? json.markdownify() : json,
r: encData,
RAW: json,
filt: opts.filters,
cssInfo: cssInfo,
opts: opts,
headFragment: opts.headFragment || ''
});

View File

@ -11,7 +11,6 @@ Definition of the UnderscoreGenerator class.
var _ = require('underscore');
/**
Perform template-based resume generation using Underscore.js.
@class UnderscoreGenerator
@ -32,21 +31,27 @@ Definition of the UnderscoreGenerator class.
// Strip {# comments #}
jst = jst.replace( delims.comment, '');
var helpers = require('./generic-helpers');
helpers.opts = opts;
helpers.cssInfo = cssInfo;
// Compile and run the template. TODO: avoid unnecessary recompiles.
var compiled = _.template(jst);
var ret = compiled({
r: format === 'html' || format === 'pdf' ? json.markdownify() : json,
r: format === 'html' || format === 'pdf' || format === 'png' ? json.markdownify() : json,
filt: opts.filters,
XML: require('xml-escape'),
RAW: json,
cssInfo: cssInfo,
headFragment: opts.headFragment || ''
headFragment: opts.headFragment || '',
opts: opts,
h: helpers
});
return ret;
}
};
}());

View File

@ -1,7 +1,7 @@
/**
Definition of the BaseGenerator class.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@module base-generator.js
@license MIT. See LICENSE.md for details.
*/
(function() {
@ -26,14 +26,7 @@ Definition of the BaseGenerator class.
/**
Status codes.
*/
codes: {
success: 0,
themeNotFound: 1,
copyCss: 2,
resumeNotFound: 3,
missingCommand: 4,
invalidCommand: 5
},
codes: require('../core/status-codes'),
/**
Generator options.

View File

@ -1,6 +1,5 @@
/**
Definition of the HtmlPdfGenerator class.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@module html-pdf-generator.js
*/
@ -23,7 +22,7 @@ Definition of the HtmlPdfGenerator class.
Generate the binary PDF.
*/
onBeforeSave: function( info ) {
pdf( info.mk, info.outputFile );
pdf.call( this, info.mk, info.outputFile );
return null; // halt further processing
}
@ -34,39 +33,50 @@ Definition of the HtmlPdfGenerator class.
*/
function pdf( markup, fOut ) {
var pdfCount = 0;
if( false ) { //( _opts.pdf === 'phantom' || _opts.pdf == 'all' ) {
pdfCount++;
require('phantom').create( function( ph ) {
ph.createPage( function( page ) {
page.setContent( markup );
page.set('paperSize', {
format: 'A4',
orientation: 'portrait',
margin: '1cm'
});
page.set("viewportSize", {
width: 1024, // TODO: option-ify
height: 768 // TODO: Use "A" sizes
});
page.set('onLoadFinished', function(success) {
page.render( fOut );
pdfCount++;
ph.exit();
});
},
{ dnodeOpts: { weak: false } } );
});
pdf_wkhtmltopdf.call( this, markup, fOut );
}
/**
Generate a PDF from HTML using wkhtmltopdf.
*/
function pdf_wkhtmltopdf( markup, fOut ) {
var wk;
try {
wk = require('wkhtmltopdf');
wk( markup, { pageSize: 'letter' } )
.pipe( FS.createWriteStream( fOut ) );
}
if( true ) { // _opts.pdf === 'wkhtmltopdf' || _opts.pdf == 'all' ) {
var fOut2 = fOut;
if( pdfCount == 1 ) {
fOut2 = fOut2.replace(/\.pdf$/g, '.b.pdf');
}
require('wkhtmltopdf')( markup, { pageSize: 'letter' } )
.pipe( FS.createWriteStream( fOut2 ) );
pdfCount++;
catch(ex) {
// { [Error: write EPIPE] code: 'EPIPE', errno: 'EPIPE', syscall: 'write' }
// { [Error: ENOENT] }
throw { fluenterror: this.codes.wkhtmltopdf };
}
}
// function pdf_phantom() {
// pdfCount++;
// require('phantom').create( function( ph ) {
// ph.createPage( function( page ) {
// page.setContent( markup );
// page.set('paperSize', {
// format: 'A4',
// orientation: 'portrait',
// margin: '1cm'
// });
// page.set("viewportSize", {
// width: 1024, // TODO: option-ify
// height: 768 // TODO: Use "A" sizes
// });
// page.set('onLoadFinished', function(success) {
// page.render( fOut );
// pdfCount++;
// ph.exit();
// });
// },
// { dnodeOpts: { weak: false } } );
// });
// }
}());

View File

@ -0,0 +1,47 @@
/**
Definition of the HtmlPngGenerator class.
@license MIT. See LICENSE.MD for details.
@module html-png-generator.js
*/
(function() {
var TemplateGenerator = require('./template-generator')
, FS = require('fs-extra')
, HTML = require( 'html' );
/**
An HTML-based PNG resume generator for HackMyResume.
*/
var HtmlPngGenerator = module.exports = TemplateGenerator.extend({
init: function() {
this._super( 'png', 'html' );
},
invoke: function( rez, themeMarkup, cssInfo, opts ) {
//return YAML.stringify( JSON.parse( rez.stringify() ), Infinity, 2 );
},
generate: function( rez, f, opts ) {
var htmlResults = opts.targets.filter(function(t){
return t.fmt.outFormat === 'html';
});
var htmlFile = htmlResults[0].final.files.filter(function(fl){
return fl.info.ext === 'html';
});
png(htmlFile[0].data, f);
}
});
/**
Generate a PNG from HTML.
*/
function png( markup, fOut ) {
// require('webshot')( markup , { encoding: 'binary', siteType: 'html' } )
// .pipe( FS.createWriteStream( fOut ) );
require('webshot')( markup , fOut, { siteType: 'html' }, function(err) { } );
}
}());

View File

@ -1,6 +1,6 @@
/**
Definition of the TemplateGenerator class.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@license MIT. See LICENSE.md for details.
@module template-generator.js
*/
@ -13,10 +13,12 @@ Definition of the TemplateGenerator class.
, MD = require( 'marked' )
, XML = require( 'xml-escape' )
, PATH = require('path')
, parsePath = require('parse-filepath')
, MKDIRP = require('mkdirp')
, BaseGenerator = require( './base-generator' )
, EXTEND = require('../utils/extend')
, Theme = require('../core/theme');
, FRESHTheme = require('../core/fresh-theme')
, JRSTheme = require('../core/jrs-theme');
@ -76,7 +78,14 @@ Definition of the TemplateGenerator class.
@method invoke
@param rez A FreshResume object.
@param opts Generator options.
@returns An array of strings representing generated output files.
@returns An array of objects representing the generated output files. Each
object has this format:
{
files: [ { info: { }, data: [ ] }, { ... } ],
themeInfo: { }
}
*/
invoke: function( rez, opts ) {
@ -127,7 +136,7 @@ Definition of the TemplateGenerator class.
var theme = themeInfo.theme;
var tFolder = themeInfo.folder;
var tplFolder = PATH.join( tFolder, 'src' );
var outFolder = PATH.parse(f).dir;
var outFolder = parsePath(f).dirname;
var curFmt = theme.getFormat( this.format );
var that = this;
@ -155,7 +164,7 @@ Definition of the TemplateGenerator class.
{ outputFile: fileName, mk: file.data } );
}
catch(ex) {
console.log(ex);
require('../core/error-handler').err(ex, false);
}
}
else if( file.info.action === null/* && theme.explicit*/ ) {
@ -176,11 +185,13 @@ Definition of the TemplateGenerator class.
var absLoc = PATH.join(outFolder, loc);
var absTarg = PATH.join(PATH.dirname(absLoc), curFmt.symLinks[loc]);
// 'file', 'dir', or 'junction' (Windows only)
var type = PATH.parse( absLoc ).ext ? 'file' : 'junction';
var type = parsePath( absLoc ).extname ? 'file' : 'junction';
FS.symlinkSync( absTarg, absLoc, type);
});
}
return genInfo;
},
@ -219,20 +230,28 @@ Definition of the TemplateGenerator class.
Given a theme title, load the corresponding theme.
*/
function themeFromMoniker() {
// Verify the specified theme name/path
var tFolder = PATH.join(
PATH.parse( require.resolve('fluent-themes') ).dir,
parsePath( require.resolve('fresh-themes') ).dirname,
this.opts.theme
);
var exists = require('path-exists').sync;
if( !exists( tFolder ) ) {
tFolder = PATH.resolve( this.opts.theme );
if( !exists( tFolder ) ) {
throw { fluenterror: this.codes.themeNotFound, data: this.opts.theme};
}
}
var t = this.opts.themeObj || new Theme().open( tFolder );
var t;
if( this.opts.theme.startsWith('jsonresume-theme-') ) {
console.log('LOADING JSON RESUME');
t = new JRSTheme().open( tFolder );
}
else {
var exists = require('path-exists').sync;
if( !exists( tFolder ) ) {
tFolder = PATH.resolve( this.opts.theme );
if( !exists( tFolder ) ) {
throw { fluenterror: this.codes.themeNotFound, data: this.opts.theme};
}
}
t = this.opts.themeObj || new FRESHTheme().open( tFolder );
}
// Load the theme and format
return {

View File

@ -8,7 +8,8 @@ module.exports = {
Sheet: require('./core/fresh-resume'),
FRESHResume: require('./core/fresh-resume'),
JRSResume: require('./core/jrs-resume'),
Theme: require('./core/theme'),
FRESHTheme: require('./core/fresh-theme'),
JRSTheme: require('./core/jrs-theme'),
FluentDate: require('./core/fluent-date'),
HtmlGenerator: require('./gen/html-generator'),
TextGenerator: require('./gen/text-generator'),
@ -18,5 +19,6 @@ module.exports = {
JsonGenerator: require('./gen/json-generator'),
YamlGenerator: require('./gen/yaml-generator'),
JsonYamlGenerator: require('./gen/json-yaml-generator'),
LaTeXGenerator: require('./gen/latex-generator')
LaTeXGenerator: require('./gen/latex-generator'),
HtmlPngGenerator: require('./gen/html-png-generator')
};

View File

@ -8,29 +8,34 @@ Internal resume generation logic for HackMyResume.
module.exports = function () {
var unused = require('./utils/string')
, PATH = require('path');
, PATH = require('path')
, FS = require('fs');
/**
Display help documentation.
*/
function help() {
console.log( FS.readFileSync( PATH.join(__dirname, 'use.txt'), 'utf8' )
.useful.bold );
var manPage = FS.readFileSync( PATH.join(__dirname, 'use.txt'), 'utf8' );
console.log( manPage.useful.bold );
}
/**
Internal module interface. Used by FCV Desktop and HMR.
*/
var v = {
build: require('./verbs/generate'),
validate: require('./verbs/validate'),
convert: require('./verbs/convert'),
new: require('./verbs/create'),
help: help
};
return {
verbs: {
generate: require('./verbs/generate'),
build: require('./verbs/generate'),
validate: require('./verbs/validate'),
convert: require('./verbs/convert'),
create: require('./verbs/create'),
new: require('./verbs/create'),
help: help
verbs: v,
alias: {
generate: v.build,
create: v.build
},
lib: require('./hackmyapi'),
options: require('./core/default-options'),

View File

@ -2,27 +2,32 @@
/**
Command-line interface (CLI) for HackMyResume.
@license MIT. Copyright (c) 2015 James M. Devlin / FluentDesk.
@license MIT. Copyright (c) 2015 hacksalot (https://github.com/hacksalot)
@module index.js
*/
var ARGS = require( 'minimist' )
var SPAWNW = require('./core/spawn-watch')
, ARGS = require( 'minimist' )
, FCMD = require( './hackmycmd')
, PKG = require('../package.json')
, COLORS = require('colors')
, FS = require('fs')
, PATH = require('path')
, HACKMYSTATUS = require('./core/status-codes')
, opts = { }
, title = ('\n*** HackMyResume v' + PKG.version + ' ***').bold.white
, _ = require('underscore');
try {
main();
}
catch( ex ) {
handleError( ex );
require('./core/error-handler').err( ex, true );
}
@ -50,7 +55,7 @@ function main() {
// Get the action to be performed
var params = a._.map( function(p){ return p.toLowerCase().trim(); });
var verb = params[0];
if( !FCMD.verbs[ verb ] ) {
if( !FCMD.verbs[ verb ] && !FCMD.alias[ verb ] ) {
logMsg('Invalid command: "'.warn + verb.warn.bold + '"'.warn);
return;
}
@ -68,11 +73,10 @@ function main() {
// Massage inputs and outputs
var src = a._.slice(1, splitAt === -1 ? undefined : splitAt );
var dst = splitAt === -1 ? [] : a._.slice( splitAt + 1 );
( splitAt === -1 ) && src.length > 1 && dst.push( src.pop() ); // Allow omitting TO keyword
var parms = [ src, dst, opts, logMsg ];
( splitAt === -1 ) && (src.length > 1) && (verb !== 'validate') && dst.push( src.pop() ); // Allow omitting TO keyword
// Invoke the action
FCMD.verbs[ verb ].apply( null, parms );
(FCMD.verbs[verb] || FCMD.alias[verb]).apply(null, [src, dst, opts, logMsg]);
}
@ -87,47 +91,7 @@ function getOpts( args ) {
theme: args.t || 'modern',
format: args.f || 'FRESH',
prettify: !noPretty,
silent: args.s || args.silent
silent: args.s || args.silent,
css: args.css || 'embed'
};
}
function handleError( ex ) {
var msg = '', exitCode;
if( ex.fluenterror ){
switch( ex.fluenterror ) { // TODO: Remove magic numbers
case 1: msg = "The specified theme couldn't be found: " + ex.data; break;
case 2: msg = "Couldn't copy CSS file to destination folder"; break;
case 3: msg = 'Please '.guide + 'specify a valid input resume'.guide.bold + ' in FRESH or JSON Resume format.'.guide; break;
case 4: msg = title + "\nPlease ".guide + "specify a command".guide.bold + " (".guide +
Object.keys( FCMD.verbs ).map( function(v, idx, ar) {
return (idx === ar.length - 1 ? 'or '.guide : '') +
v.toUpperCase().guide;
}).join(', '.guide) + ").\n\n".guide + FS.readFileSync( PATH.join(__dirname, 'use.txt'), 'utf8' ).info.bold;
break;
//case 4: msg = title + '\n' + ; break;
case 5: msg = 'Please '.guide + 'specify the output resume file'.guide.bold + ' that should be created.'.guide; break;
case 6: msg = 'Please '.guide + 'specify a valid input resume'.guide.bold + ' in either FRESH or JSON Resume format.'.guide; break;
case 7: msg = 'Please '.guide + 'specify an output file name'.guide.bold + ' for every input file you wish to convert.'.guide; break;
case 8: msg = 'Please '.guide + 'specify the filename of the resume'.guide.bold + ' to create.'.guide; break;
}
exitCode = ex.fluenterror;
}
else {
msg = ex.toString();
exitCode = 4;
}
var idx = msg.indexOf('Error: ');
var trimmed = idx === -1 ? msg : msg.substring( idx + 7 );
if( !ex.fluenterror || ex.fluenterror < 3 )
console.log( ('ERROR: ' + trimmed.toString()).red.bold );
else
console.log( trimmed.toString() );
process.exit( exitCode );
}

View File

@ -47,6 +47,7 @@ Definition of the Markdown to WordProcessingML conversion routine.
break;
case 'Chars':
if( tok.chars.trim().length ) {
var style = is_bold ? '<w:b/>' : '';
style += is_italic ? '<w:i/>': '';
style += is_link ? '<w:rStyle w:val="Hyperlink"/>' : '';
@ -54,6 +55,7 @@ Definition of the Markdown to WordProcessingML conversion routine.
(is_link ? ('<w:hlink w:dest="' + link_url + '">') : '') +
'<w:r><w:rPr>' + style + '</w:rPr><w:t>' + tok.chars +
'</w:t></w:r>' + (is_link ? '</w:hlink>' : '');
}
break;
}
});

View File

@ -1,6 +1,5 @@
/**
Definitions of string utility functions.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@module string.js
*/
@ -10,14 +9,18 @@ See: http://stackoverflow.com/a/32800728/4942583
@method isNullOrWhitespace
*/
String.isNullOrWhitespace = function( input ) {
return !input || !input.trim();
};
(function() {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
String.isNullOrWhitespace = function( input ) {
return !input || !input.trim();
};
String.is = function( val ) {
return typeof val === 'string' || val instanceof String;
};
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
String.is = function( val ) {
return typeof val === 'string' || val instanceof String;
};
}());

View File

@ -0,0 +1,40 @@
/**
Definition of the SyntaxErrorEx class.
@module syntax-error-ex.js
*/
(function() {
/**
Represents a SyntaxError exception with line and column info.
Collect syntax error information from the provided exception object. The
JavaScript `SyntaxError` exception isn't interpreted uniformly across environ-
ments, so we first check for a .lineNumber and .columnNumber and, if that's
not present, fall back to the JSONLint library, which provides that info.
See: http://stackoverflow.com/q/13323356
@class SyntaxErrorEx
*/
module.exports = function SyntaxErrorEx( ex, rawData ) {
var lineNum = null, colNum = null;
if( ex.lineNumber !== undefined && ex.lineNumber !== null ) {
lineNum = ex.lineNumber;
}
if( ex.columnNumber !== undefined && ex.columnNumber !== null ) {
colNum = ex.columnNumber;
}
if( lineNum === null || colNum === null ) {
var JSONLint = require('json-lint');
var lint = JSONLint( rawData, { comments: false } );
if( lineNum === null ) lineNum = (lint.error ? lint.line : '???');
if( colNum === null ) colNum = (lint.error ? lint.character : '???');
}
this.line = lineNum;
this.col = colNum;
};
}());

View File

@ -1,26 +1,33 @@
/**
Implementation of the 'convert' verb for HackMyResume.
@module convert.js
@license MIT. See LICENSE.md for details.
*/
(function(){
var loadSourceResumes = require('../core/load-source-resumes');
var ResumeFactory = require('../core/resume-factory');
/**
Convert between FRESH and JRS formats.
*/
module.exports = function convert( src, dst, opts, logger ) {
module.exports = function convert( sources, dst, opts, logger ) {
var _log = logger || console.log;
if( !src || !src.length ) { throw { fluenterror: 6 }; }
if( !sources || !sources.length ) { throw { fluenterror: 6 }; }
if( !dst || !dst.length ) {
if( src.length === 1 ) { throw { fluenterror: 5 }; }
else if( src.length === 2 ) { dst = [ src[1] ]; src = [ src[0] ]; }
if( sources.length === 1 ) { throw { fluenterror: 5 }; }
else if( sources.length === 2 ) { dst = [ sources[1] ]; sources = [ sources[0] ]; }
else { throw { fluenterror: 5 }; }
}
if( src && dst && src.length && dst.length && src.length !== dst.length ) {
if( sources && dst && sources.length && dst.length && sources.length !== dst.length ) {
throw { fluenterror: 7 };
}
var sheets = loadSourceResumes( src, _log );
sheets.forEach(function(sheet, idx){
var sourceFormat = sheet.imp.orgFormat === 'JRS' ? 'JRS' : 'FRESH';
var sourceResumes = ResumeFactory.load( sources, _log, null, true );
sourceResumes.forEach(function( src, idx ) {
var sheet = src.rez;
var sourceFormat = ((sheet.basics && sheet.basics.imp) || sheet.imp).orgFormat === 'JRS' ? 'JRS' : 'FRESH';
var targetFormat = sourceFormat === 'JRS' ? 'FRESH' : 'JRS';
_log( 'Converting '.useful + sheet.imp.fileName.useful.bold + (' (' +
_log( 'Converting '.useful + src.file.useful.bold + (' (' +
sourceFormat + ') to ').useful + dst[0].useful.bold +
(' (' + targetFormat + ').').useful );
sheet.saveAs( dst[idx], targetFormat );

View File

@ -1,3 +1,9 @@
/**
Implementation of the 'create' verb for HackMyResume.
@module create.js
@license MIT. See LICENSE.md for details.
*/
(function(){
var FLUENT = require('../hackmyapi')

View File

@ -1,14 +1,30 @@
/**
Implementation of the 'generate' verb for HackMyResume.
@module generate.js
@license MIT. See LICENSE.md for details.
*/
(function() {
var PATH = require('path')
, FS = require('fs')
, MD = require('marked')
, MKDIRP = require('mkdirp')
, EXTEND = require('../utils/extend')
, parsePath = require('parse-filepath')
, _opts = require('../core/default-options')
, FluentTheme = require('../core/theme')
, loadSourceResumes = require('../core/load-source-resumes')
, FluentTheme = require('../core/fresh-theme')
, JRSTheme = require('../core/jrs-theme')
, ResumeFactory = require('../core/resume-factory')
, _ = require('underscore')
, _fmts = require('../core/default-formats')
, extend = require('../utils/extend')
, _err, _log, rez;
/**
Handle an exception.
*/
@ -16,129 +32,138 @@
throw ex;
}
module.exports =
/**
Given a source JSON resume, a destination resume path, and a theme file,
generate 0..N resumes in the desired formats.
Given a source resume in FRESH or JRS format, a destination resume path, and a
theme file, generate 0..N resumes in the desired formats.
@param src Path to the source JSON resume file: "rez/resume.json".
@param dst An array of paths to the target resume file(s).
@param theme Friendly name of the resume theme. Defaults to "modern".
@param logger Optional logging override.
*/
function generate( src, dst, opts, logger, errHandler ) {
function build( src, dst, opts, logger, errHandler ) {
// Housekeeping...
_log = logger || console.log;
_err = errHandler || error;
//_opts = extend( true, _opts, opts );
_opts.theme = (opts.theme && opts.theme.toLowerCase().trim())|| 'modern';
_opts.prettify = opts.prettify === true ? _opts.prettify : false;
_opts.css = opts.css;
// Load the theme...
var tFolder = verify_theme( _opts.theme );
var theme = load_theme( tFolder );
// Load input resumes...
if( !src || !src.length ) { throw { fluenterror: 3 }; }
var sheets = loadSourceResumes( src, _log );
var sheets = ResumeFactory.load(src, _log, theme.render ? 'JRS' : 'FRESH', true);
// Merge input resumes...
var msg = '';
rez = _.reduceRight( sheets, function( a, b, idx ) {
var rezRep = _.reduceRight( sheets, function( a, b, idx ) {
msg += ((idx == sheets.length - 2) ?
'Merging '.gray+ a.imp.fileName : '') + ' onto '.gray + b.imp.fileName;
return extend( true, b, a );
'Merging '.gray + a.rez.imp.fileName : '') + ' onto '.gray + b.rez.fileName;
return extend( true, b.rez, a.rez );
});
rez = rezRep.rez;
msg && _log(msg);
// Verify the specified theme name/path
var relativeThemeFolder = '../../node_modules/fluent-themes/themes';
var tFolder = PATH.resolve( __dirname, relativeThemeFolder, _opts.theme);
var exists = require('path-exists').sync;
if (!exists( tFolder )) {
tFolder = PATH.resolve( _opts.theme );
if (!exists( tFolder )) {
throw { fluenterror: 1, data: _opts.theme };
}
}
// Load the theme
var theTheme = new FluentTheme().open( tFolder );
_opts.themeObj = theTheme;
_log( 'Applying '.info + theTheme.name.toUpperCase().infoBold +
(' theme (' + Object.keys(theTheme.formats).length + ' formats)').info);
// Expand output resumes... (can't use map() here)
var targets = [], that = this;
( (dst && dst.length && dst) || ['resume.all'] ).forEach( function(t) {
var to = PATH.resolve(t),
pa = PATH.parse(to),
fmat = pa.ext || '.all';
targets.push.apply(targets, fmat === '.all' ?
Object.keys( theTheme.formats ).map(function(k){
var z = theTheme.formats[k];
return { file: to.replace(/all$/g,z.outFormat), fmt: z };
}) : [{ file: to, fmt: theTheme.getFormat( fmat.slice(1) ) }]);
});
// Expand output resumes...
var targets = expand( dst, theme );
// Run the transformation!
var finished = targets.map( function(t) { return single(t, theTheme); });
targets.forEach( function(t) {
t.final = single( t, theme, targets );
});
// Don't send the client back empty-handed
return { sheet: rez, targets: targets, processed: finished };
};
return { sheet: rez, targets: targets, processed: targets };
}
/**
Generate a single resume of a specific format.
@param f Full path to the destination resume to generate, for example,
"/foo/bar/resume.pdf" or "c:\foo\bar\resume.txt".
Generate a single target resume such as "out/rez.html" or "out/rez.doc".
@param targInfo Information for the target resume.
@param theme A FRESHTheme or JRSTheme object.
@returns
*/
function single( targInfo, theme ) {
function single( targInfo, theme, finished ) {
function MDIN(txt) { // TODO: Move this
return MD(txt || '' ).replace(/^\s*<p>|<\/p>\s*$/gi, '');
}
try {
var f = targInfo.file
, fType = targInfo.fmt.outFormat
, fName = PATH.basename(f, '.' + fType)
, theFormat;
// If targInfo.fmt.files exists, this theme has an explicit "files"
// section in its theme.json file.
if( targInfo.fmt.files && targInfo.fmt.files.length ) {
_log( 'Generating '.useful +
targInfo.fmt.outFormat.toUpperCase().useful.bold +
' resume: '.useful + PATH.relative(process.cwd(), f ).replace(/\\/g,'/').useful.bold);
' resume: '.useful + PATH.relative(process.cwd(), f ).useful.bold );
// If targInfo.fmt.files exists, this format is backed by a document.
// Fluent/FRESH themes are handled here.
if( targInfo.fmt.files && targInfo.fmt.files.length ) {
theFormat = _fmts.filter(
function(fmt) { return fmt.name === targInfo.fmt.outFormat; })[0];
MKDIRP.sync( PATH.dirname( f ) ); // Ensure dest folder exists;
theFormat.gen.generate( rez, f, _opts );
// targInfo.fmt.files.forEach( function( form ) {
//
// if( form.action === 'transform' ) {
// var theFormat = _fmts.filter( function( fmt ) {
// return fmt.name === targInfo.fmt.outFormat;
// })[0];
// MKDIRP.sync( PATH.dirname( f ) ); // Ensure dest folder exists;
// theFormat.gen.generate( rez, f, _opts );
// }
// else if( form.action === null ) {
// // Copy the file
// }
//
// });
_opts.targets = finished;
return theFormat.gen.generate( rez, f, _opts );
}
// Otherwise the theme has no files section
else {
_log( 'Generating '.useful +
targInfo.fmt.outFormat.toUpperCase().useful.bold +
' resume: '.useful + PATH.relative(process.cwd(), f ).replace(/\\/g,'/').useful.bold);
theFormat = _fmts.filter(
function(fmt) { return fmt.name === targInfo.fmt.outFormat; })[0];
MKDIRP.sync( PATH.dirname( f ) ); // Ensure dest folder exists;
theFormat.gen.generate( rez, f, _opts );
// Otherwise this is either a) a JSON Resume theme or b) an ad-hoc format
// (JSON, YML, or PNG) that every theme gets "for free".
else {
theFormat = _fmts.filter( function(fmt) {
return fmt.name === targInfo.fmt.outFormat;
})[0];
var outFolder = PATH.dirname( f );
MKDIRP.sync( outFolder ); // Ensure dest folder exists;
// JSON Resume themes have a 'render' method that needs to be called
if( theme.render ) {
var COPY = require('copy');
var globs = [ /*'**',*/ '*.css', '*.js', '*.png', '*.jpg', '*.gif', '*.bmp' ];
COPY.sync( globs , outFolder, {
cwd: theme.folder, nodir: true,
ignore: ['node_modules/','node_modules/**']
// rewrite: function(p1, p2) {
// return PATH.join(p2, p1);
// }
});
// Prevent JSON Resume theme .js from chattering (TODO: redirect IO)
var consoleLog = console.log;
console.log = function() { };
// Call the theme's render method
var rezDupe = rez.harden();
var rezHtml = theme.render( rezDupe );
// Turn logging back on
console.log = consoleLog;
// Unharden
rezHtml = rezHtml.replace( /@@@@~.+?~@@@@/g, function(val){
return MDIN( val.replace( /~@@@@/gm,'' ).replace( /@@@@~/gm,'' ) );
});
// Save the file
FS.writeFileSync( f, rezHtml );
// Return markup to the client
return rezHtml;
}
else {
return theFormat.gen.generate( rez, f, _opts );
}
}
}
catch( ex ) {
@ -146,4 +171,117 @@
}
}
/**
Expand output files. For example, "foo.all" should be expanded to
["foo.html", "foo.doc", "foo.pdf", "etc"].
@param dst An array of output files as specified by the user.
@param theTheme A FRESHTheme or JRSTheme object.
*/
function expand( dst, theTheme ) {
// Add freebie formats (JSON, YAML, PNG) every theme gets...
// Add HTML-driven PNG only if the theme has an HTML format.
theTheme.formats.json = theTheme.formats.json || {
freebie: true, title: 'json', outFormat: 'json', pre: 'json',
ext: 'json', path: null, data: null
};
theTheme.formats.yml = theTheme.formats.yml || {
freebie: true, title: 'yaml', outFormat: 'yml', pre: 'yml',
ext: 'yml', path: null, data: null
};
if( theTheme.formats.html && !theTheme.formats.png ) {
theTheme.formats.png = {
freebie: true, title: 'png', outFormat: 'png',
ext: 'yml', path: null, data: null
};
}
// Set up the destination collection. It's either the array of files passed
// by the user or 'out/resume.all' if no targets were specified.
var destColl = (dst && dst.length && dst) ||
[PATH.normalize('out/resume.all')];
// Assemble an array of expanded target files... (can't use map() here)
var targets = [];
destColl.forEach( function(t) {
var to = PATH.resolve(t), pa = parsePath(to),fmat = pa.extname || '.all';
var explicitFormats = _.omit( theTheme.formats, function(val, key) {
return !val.freebie;
});
var implicitFormats = _.omit( theTheme.formats, function(val) {
return val.freebie;
});
targets.push.apply(
targets, fmat === '.all' ?
Object.keys( implicitFormats ).map( function( k ) {
var z = theTheme.formats[k];
return { file: to.replace( /all$/g, z.outFormat ), fmt: z };
}) :
[{ file: to, fmt: theTheme.getFormat( fmat.slice(1) ) }]);
targets.push.apply(
targets, fmat === '.all' ?
Object.keys( explicitFormats ).map( function( k ) {
var z = theTheme.formats[k];
return { file: to.replace( /all$/g, z.outFormat ), fmt: z };
}) :
[{ file: to, fmt: theTheme.getFormat( fmat.slice(1) ) }]);
});
return targets;
}
/**
Verify the specified theme name/path.
*/
function verify_theme( themeNameOrPath ) {
var tFolder = PATH.resolve(
__dirname,
'../../node_modules/fresh-themes/themes',
themeNameOrPath
);
var exists = require('path-exists').sync;
if( !exists( tFolder ) ) {
tFolder = PATH.resolve( themeNameOrPath );
if( !exists( tFolder ) ) {
throw { fluenterror: 1, data: _opts.theme };
}
}
return tFolder;
}
/**
Load the specified theme.
*/
function load_theme( tFolder ) {
// Create a FRESH or JRS theme object
var theTheme = _opts.theme.indexOf('jsonresume-theme-') > -1 ?
new JRSTheme().open(tFolder) : new FluentTheme().open( tFolder );
// Cache the theme object
_opts.themeObj = theTheme;
// Output a message TODO: core should not log
var numFormats = Object.keys(theTheme.formats).length;
_log( 'Applying '.info + theTheme.name.toUpperCase().infoBold +
(' theme (' + numFormats + ' formats)').info);
return theTheme;
}
module.exports = build;
}());

View File

@ -1,16 +1,23 @@
/**
Implementation of the 'validate' verb for HackMyResume.
@module validate.js
@license MIT. See LICENSE.md for details.
*/
(function() {
var FS = require('fs');
var loadSourceResumes = require('../core/load-source-resumes');
var ResumeFactory = require('../core/resume-factory');
var SyntaxErrorEx = require('../utils/syntax-error-ex');
module.exports =
/**
Validate 1 to N resumes in either FRESH or JSON Resume format.
*/
function validate( src, unused, opts, logger ) {
function validate( sources, unused, opts, logger ) {
var _log = logger || console.log;
if( !src || !src.length ) { throw { fluenterror: 6 }; }
if( !sources || !sources.length ) { throw { fluenterror: 6 }; }
var isValid = true;
var validator = require('is-my-json-valid');
@ -20,67 +27,51 @@
};
// Load input resumes...
var sheets = loadSourceResumes(src, _log, function( res ) {
try {
return {
file: res,
raw: FS.readFileSync( res, 'utf8' )
};
}
catch( ex ) {
throw ex;
}
});
sources.forEach(function( src ) {
sheets.forEach( function( rep ) {
var result = ResumeFactory.loadOne( src, function(){}, null, false );
if( result.error ) {
_log( 'Validating '.info + src.infoBold + ' against '.info + 'AUTO'.infoBold + ' schema:'.info + ' BROKEN'.red.bold );
var rez;
try {
rez = JSON.parse( rep.raw );
}
catch( ex ) { // Note [1]
_log('Validating '.info + rep.file.infoBold +
' against FRESH/JRS schema: '.info + 'ERROR!'.error.bold);
if (ex instanceof SyntaxError) {
// Invalid JSON
_log( '--> '.bold.red + rep.file.toUpperCase().red +
' contains invalid JSON. Unable to validate.'.red );
_log( (' INTERNAL: ' + ex).red );
var ex = result.error; // alias
if ( ex instanceof SyntaxError) {
var info = new SyntaxErrorEx( ex, result.raw );
_log( ('--> '.warn.bold + src.toUpperCase() + ' contains invalid JSON on line ' +
info.line + ' column ' + info.col + '.').warn +
' Unable to validate.'.warn );
_log( (' INTERNAL: ' + ex).warn );
}
else {
_log(('ERROR: ' + ex.toString()).red.bold);
_log(('ERROR: ' + ex.toString()).warn.bold);
}
return;
}
var json = result.json;
var isValid = false;
var style = 'useful';
var errors = [];
var fmt = rez.meta &&
(rez.meta.format === 'FRESH@0.1.0') ? 'fresh':'jars';
var fmt = json.meta && (json.meta.format==='FRESH@0.1.0') ? 'fresh':'jars';
try {
var validate = validator( schemas[ fmt ], { // Note [1]
formats: {
date: /^\d{4}(?:-(?:0[0-9]{1}|1[0-2]{1})(?:-[0-9]{2})?)?$/
}
});
isValid = validate( rez );
isValid = validate( json );
if( !isValid ) {
style = 'warn';
errors = validate.errors;
}
}
catch(ex) {
catch(exc) {
return;
}
_log( 'Validating '.info + rep.file.infoBold + ' against '.info +
_log( 'Validating '.info + result.file.infoBold + ' against '.info +
fmt.replace('jars','JSON Resume').toUpperCase().infoBold +
' schema: '.info + (isValid ? 'VALID!' : 'INVALID')[style].bold );
@ -93,5 +84,4 @@
});
};
}());

1
test/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
sandbox/

View File

@ -43,15 +43,15 @@ describe('Testing CLI interface', function () {
silent: true
};
run( 'new', ['tests/sandbox/new-fresh-resume.json'], [], opts, ' (FRESH format)' );
run( 'new', ['tests/sandbox/new-jrs-resume.json'], [], opts2, ' (JRS format)' );
run( 'new', ['tests/sandbox/new-1.json', 'tests/sandbox/new-2.json', 'tests/sandbox/new-3.json'], [], opts, ' (multiple FRESH resumes)' );
run( 'new', ['tests/sandbox/new-jrs-1.json', 'tests/sandbox/new-jrs-2.json', 'tests/sandbox/new-jrs-3.json'], [], opts, ' (multiple JRS resumes)' );
run( 'new', ['tests/sandbox/new-jrs-resume.json'], [], opts2, ' (JRS format)' );
run( 'new', ['test/sandbox/new-fresh-resume.json'], [], opts, ' (FRESH format)' );
run( 'new', ['test/sandbox/new-jrs-resume.json'], [], opts2, ' (JRS format)' );
run( 'new', ['test/sandbox/new-1.json', 'test/sandbox/new-2.json', 'test/sandbox/new-3.json'], [], opts, ' (multiple FRESH resumes)' );
run( 'new', ['test/sandbox/new-jrs-1.json', 'test/sandbox/new-jrs-2.json', 'test/sandbox/new-jrs-3.json'], [], opts, ' (multiple JRS resumes)' );
run( 'new', ['test/sandbox/new-jrs-resume.json'], [], opts2, ' (JRS format)' );
fail( 'new', [], [], opts, " (when a filename isn't specified)" );
run( 'validate', ['node_modules/jane-q-fullstacker/resume/jane-resume.json'], [], opts, ' (FRESH format)' );
run( 'validate', ['tests/sandbox/new-fresh-resume.json'], [], opts, ' (FRESH format)' );
run( 'validate', ['test/sandbox/new-fresh-resume.json'], [], opts, ' (FRESH format)' );
function run( verb, src, dst, opts, msg ) {
msg = msg || '.';

62
test/test-fresh-sheet.js Normal file
View File

@ -0,0 +1,62 @@
var chai = require('chai')
, expect = chai.expect
, should = chai.should()
, path = require('path')
, _ = require('underscore')
, FRESHResume = require('../src/core/fresh-resume')
, validator = require('is-my-json-valid');
chai.config.includeStack = false;
function testResume(opts) {
describe( opts.title + ' (FRESH)', function () {
var _sheet;
it('should open without throwing an exception', function () {
function tryOpen() {
_sheet = new FRESHResume().open( opts.path );
}
tryOpen.should.not.Throw();
});
it('should have one or more of each section', function() {
var newObj = _.pick( _sheet, opts.sections );
expect( Object.keys(newObj).length ).to.equal( opts.sections.length );
});
it('should have a work duration of ' + opts.duration + ' years', function() {
_sheet.computed.numYears.should.equal( opts.duration );
});
it('should save without throwing an exception', function(){
function trySave() {
_sheet.save( 'test/sandbox/' + opts.title + '.json' );
}
trySave.should.not.Throw();
});
it('should not be modified after saving', function() {
var savedSheet = new FRESHResume().open('test/sandbox/' + opts.title + '.json');
_sheet.stringify().should.equal( savedSheet.stringify() );
});
it('should validate against the FRESH resume schema', function() {
var result = _sheet.isValid();
// var schemaJson = require('fresca');
// var validate = validator( schemaJson, { verbose: true } );
// var result = validate( JSON.parse( _sheet.imp.raw ) );
result || console.log("\n\nOops, resume didn't validate. " +
"Validation errors:\n\n", _sheet.imp.validationErrors, "\n\n");
result.should.equal( true );
});
});
}
var sects = [ 'info', 'employment', 'service', 'skills', 'education', 'writing', 'recognition', 'references' ];
testResume({ title: 'jane-q-fullstacker', path: 'node_modules/jane-q-fullstacker/resume/jane-resume.json', duration: 7, sections: sects });
testResume({ title: 'johnny-trouble-resume', path: 'node_modules/johnny-trouble-resume/src/johnny-trouble.fresh.json', duration: 3, sections: sects });

View File

@ -38,14 +38,14 @@ function testResume( opts ) {
it('should save without throwing an exception', function() {
var that = this;
function trySave() {
_sheet.save( 'tests/sandbox/' + opts.title + '.json' );
_sheet.save( 'test/sandbox/' + opts.title + '.json' );
}
trySave.should.not.Throw();
});
it('should not be modified after saving', function() {
var savedSheet = new JRSResume().open( 'tests/sandbox/' + opts.title + '.json' );
_sheet.stringify().should.equal( savedSheet.stringify() )
var savedSheet = new JRSResume().open( 'test/sandbox/' + opts.title + '.json' );
_sheet.stringify().should.equal( savedSheet.stringify() );
});
it('should ' + (opts.isValid ? '' : 'NOT ') + 'validate against the JSON Resume schema', function() {

68
test/test-themes.js Normal file
View File

@ -0,0 +1,68 @@
var SPAWNWATCHER = require('../src/core/spawn-watch')
, chai = require('chai')
, expect = chai.expect
, should = chai.should()
, path = require('path')
, _ = require('underscore')
, FRESHResume = require('../src/core/fresh-resume')
, FCMD = require( '../src/hackmycmd')
, validator = require('is-my-json-valid')
, COLORS = require('colors');
chai.config.includeStack = false;
function genThemes( title, src, fmt ) {
describe('Testing themes against ' + title.toUpperCase() + ' resume ' + '(' + fmt + ')' , function () {
var _sheet;
COLORS.setTheme({
title: ['white','bold'],
info: process.platform === 'win32' ? 'gray' : ['white','dim'],
infoBold: ['white','dim'],
warn: 'yellow',
error: 'red',
guide: 'yellow',
status: 'gray',//['white','dim'],
useful: 'green',
});
function genTheme( fmt, src, themeName, themeLoc, testTitle ) {
themeLoc = themeLoc || themeName;
testTitle = themeName.toUpperCase() + ' theme (' + fmt + ') should generate without throwing an exception';
it( testTitle, function () {
function tryOpen() {
//var src = ['node_modules/jane-q-fullstacker/resume/jane-resume.json'];
var dst = ['test/sandbox/' + fmt + '/' + title + '/' + themeName + '/resume.all'];
var opts = {
theme: themeLoc,
format: fmt,
prettify: true,
silent: true
};
FCMD.verbs.build( src, dst, opts, function() {} );
}
tryOpen.should.not.Throw();
});
}
genTheme(fmt, src, 'hello-world');
genTheme(fmt, src, 'compact');
genTheme(fmt, src, 'modern');
genTheme(fmt, src, 'minimist');
genTheme(fmt, src, 'awesome');
genTheme(fmt, src, 'positive');
genTheme(fmt, src, 'jsonresume-theme-boilerplate', 'node_modules/jsonresume-theme-boilerplate' );
genTheme(fmt, src, 'jsonresume-theme-sceptile', 'node_modules/jsonresume-theme-sceptile' );
genTheme(fmt, src, 'jsonresume-theme-modern', 'node_modules/jsonresume-theme-modern' );
genTheme(fmt, src, 'jsonresume-theme-classy', 'node_modules/jsonresume-theme-classy' );
});
}
genThemes( 'jane-q-fullstacker', ['node_modules/jane-q-fullstacker/resume/jane-resume.json'], 'FRESH' );
genThemes( 'johnny-trouble', ['node_modules/johnny-trouble-resume/src/johnny-trouble.fresh.json'], 'FRESH' );
genThemes( 'richard-hendriks', ['test/resumes/jrs-0.0.0/richard-hendriks.json'], 'JRS' );

View File

@ -1,67 +0,0 @@
var chai = require('chai')
, expect = chai.expect
, should = chai.should()
, path = require('path')
, _ = require('underscore')
, FRESHResume = require('../src/core/fresh-resume')
, validator = require('is-my-json-valid');
chai.config.includeStack = false;
describe('jane-doe.json (FRESH)', function () {
var _sheet;
it('should open without throwing an exception', function () {
function tryOpen() {
_sheet = new FRESHResume().open(
'node_modules/jane-q-fullstacker/resume/jane-resume.json' );
}
tryOpen.should.not.Throw();
});
it('should have one or more of each section', function() {
expect(
//(_sheet.basics) &&
_sheet.name && _sheet.info && _sheet.location && _sheet.contact &&
(_sheet.employment.history && _sheet.employment.history.length > 0) &&
(_sheet.skills && _sheet.skills.list.length > 0) &&
(_sheet.education.history && _sheet.education.history.length > 0) &&
(_sheet.service.history && _sheet.service.history.length > 0) &&
(_sheet.writing && _sheet.writing.length > 0) &&
(_sheet.recognition && _sheet.recognition.length > 0) &&
(_sheet.samples && _sheet.samples.length > 0) &&
(_sheet.references && _sheet.references.length > 0) &&
(_sheet.interests && _sheet.interests.length > 0)
).to.equal( true );
});
it('should have a work duration of 7 years', function() {
_sheet.computed.numYears.should.equal( 7 );
});
it('should save without throwing an exception', function(){
function trySave() {
_sheet.save( 'tests/sandbox/jane-q-fullstacker.json' );
}
trySave.should.not.Throw();
});
it('should not be modified after saving', function() {
var savedSheet = new FRESHResume().open('tests/sandbox/jane-q-fullstacker.json');
_sheet.stringify().should.equal( savedSheet.stringify() )
});
it('should validate against the FRESH resume schema', function() {
var result = _sheet.isValid();
// var schemaJson = require('fresca');
// var validate = validator( schemaJson, { verbose: true } );
// var result = validate( JSON.parse( _sheet.imp.raw ) );
result || console.log("\n\nOops, resume didn't validate. " +
"Validation errors:\n\n", _sheet.imp.validationErrors, "\n\n");
result.should.equal( true );
});
});

View File

@ -1,53 +0,0 @@
var chai = require('chai')
, expect = chai.expect
, should = chai.should()
, path = require('path')
, _ = require('underscore')
, FRESHResume = require('../src/core/fresh-resume')
, FCMD = require( '../src/hackmycmd')
, validator = require('is-my-json-valid')
, COLORS = require('colors');
chai.config.includeStack = false;
describe('Testing themes', function () {
var _sheet;
COLORS.setTheme({
title: ['white','bold'],
info: process.platform === 'win32' ? 'gray' : ['white','dim'],
infoBold: ['white','dim'],
warn: 'yellow',
error: 'red',
guide: 'yellow',
status: 'gray',//['white','dim'],
useful: 'green',
});
function genTheme( themeName ) {
it( themeName.toUpperCase() + ' theme should generate without throwing an exception', function () {
function tryOpen() {
var src = ['node_modules/jane-q-fullstacker/resume/jane-resume.json'];
var dst = ['tests/sandbox/' + themeName + '/resume.all'];
var opts = {
theme: themeName,
format: 'FRESH',
prettify: true,
silent: true
};
FCMD.verbs.build( src, dst, opts, function() { } );
}
tryOpen.should.not.Throw();
});
}
genTheme('hello-world');
genTheme('compact');
genTheme('modern');
genTheme('minimist');
genTheme('awesome');
genTheme('positive');
});