UNPKG

2.33 kBJavaScriptView Raw
1var Metalsmith = require('metalsmith')
2var exists = require('fs').existsSync
3var assign = require('object-assign')
4var resolve = require('path').resolve
5
6/*
7 * Defaults
8 */
9
10var defaults = {
11 config: 'metalsmith.json'
12}
13
14/**
15 * Returns metalsmith object for `dir`
16 */
17
18function ms (dir, options) {
19 options = assign({}, defaults, options || {})
20
21 var path = resolve(dir, options.config)
22 var json = loadJson(path, options.config)
23 var metalsmith = loadMetalsmith(dir, json)
24 loadPlugins(metalsmith, dir, json.plugins)
25
26 return metalsmith
27}
28
29/*
30 * Internal: Loads a JSON file
31 */
32
33function loadJson (path, config) {
34 try {
35 return require(path)
36 } catch (e) {
37 throw new Error('it seems like ' + config + ' is malformed.')
38 }
39}
40
41/**
42 * Initializes a metalsmith instance
43 */
44
45function loadMetalsmith (dir, json) {
46 var metalsmith = new Metalsmith(dir)
47
48 if (json.source) metalsmith.source(json.source)
49 if (json.destination) metalsmith.destination(json.destination)
50 if (json.concurrency) metalsmith.concurrency(json.concurrency)
51 if (json.metadata) metalsmith.metadata(json.metadata)
52 if (typeof json.clean === 'boolean') metalsmith.clean(json.clean)
53
54 return metalsmith
55}
56
57/*
58 * Loads `plugins` onto `metalsmith` instance
59 */
60
61function loadPlugins (metalsmith, dir, plugins) {
62 normalize(plugins).forEach(function (plugin) {
63 for (var name in plugin) {
64 var opts = plugin[name]
65 var mod
66
67 try {
68 var local = resolve(dir, name)
69 var npm = resolve(dir, 'node_modules', name)
70
71 if (exists(local) || exists(local + '.js')) {
72 mod = require(local)
73 } else if (exists(npm)) {
74 mod = require(npm)
75 } else {
76 mod = require(name)
77 }
78 } catch (e) {
79 throw new Error('failed to require plugin "' + name + '".')
80 }
81
82 try {
83 metalsmith.use(mod(opts))
84 } catch (e) {
85 // prepend with plugin
86 e.message = '[' + name + '] ' + e.message
87 throw e
88 }
89 }
90 })
91}
92
93/**
94 * Normalize an `obj` of plugins.
95 *
96 * @param {Array or Object} obj
97 * @return {Array}
98 */
99
100function normalize (obj) {
101 if (obj instanceof Array) return obj
102 var ret = []
103
104 for (var key in obj) {
105 var plugin = {}
106 plugin[key] = obj[key]
107 ret.push(plugin)
108 }
109
110 return ret
111}
112
113module.exports = ms