index.js
1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"use strict";
var error = require("./error");
var help = require("./help");
var input = require("./input");
var util = require("./util");
var objectAssign = require("object-assign");
var defaultConfig =
{
title: "",
name: "noname",
description: "",
version: "0.0.0",
colors: ["red","green","magenta"],
options: {},
aliases: []
};
// NOTE :: Couldn't be written with `prototype` because nested functions
// like `config.merge()` would have no access to `this`.
function nopter()
{
var api = {};
var config = {};
api.config = function(newValue)
{
if (!newValue)
{
validate(config);
}
else if (newValue && !newValue.options)
{
validate(config, true);
}
else
{
config = objectAssign({}, defaultConfig, newValue);
}
return config;
};
api.config.merge = function(newValues)
{
if (newValues)
{
config = objectAssign(config, newValues);
}
return api.config();
};
api.error = error;
api.help = function()
{
validate(config);
return help(config);
};
api.help.indent = function()
{
return help.indent();
};
api.input = function(args, slice)
{
validate(config);
switch (typeof args)
{
case "string":
{
args = util.splitargs(args);
break;
}
case "undefined":
{
args = process.argv;
break;
}
default:
{
// Unlikely, but possible
if (args !== process.argv)
{
// Force array
args = Array.prototype.slice.call(args);
}
}
}
// Convenience for custom args
if (args!==process.argv && slice==undefined)
{
slice = 0;
}
return input(args, config, slice);
};
api.util = util;
return api;
}
nopter.error = error;
nopter.util = util;
function validate(config, fail)
{
if (!config.options || !Object.keys(config.options).length || fail)
{
throw new Error("options must be defined");
}
}
module.exports = nopter;