1 | var Metalsmith = require('metalsmith')
|
2 | var exists = require('fs').existsSync
|
3 | var assign = require('object-assign')
|
4 | var resolve = require('path').resolve
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | var defaults = {
|
11 | config: 'metalsmith.json'
|
12 | }
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | function 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 |
|
31 |
|
32 |
|
33 | function 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 |
|
43 |
|
44 |
|
45 | function 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 |
|
59 |
|
60 |
|
61 | function 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 |
|
86 | e.message = '[' + name + '] ' + e.message
|
87 | throw e
|
88 | }
|
89 | }
|
90 | })
|
91 | }
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 | function 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 |
|
113 | module.exports = ms
|