aboutsummaryrefslogtreecommitdiff
path: root/src/shared/commands/parsers.js
diff options
context:
space:
mode:
authorShin'ya Ueoka <ueokande@i-beam.org>2018-01-11 13:02:14 +0000
committerGitHub <noreply@github.com>2018-01-11 13:02:14 +0000
commitf5dfdb0bd7ab850c77cae523928c876fe5e002fa (patch)
tree083a7c9dcd4e85daef7f8323067454b48730c6e6 /src/shared/commands/parsers.js
parentc3d1535224231cd379cf503a4c4937342ef27383 (diff)
parentfad8f96a663d83792138cc986474ec4228b6c6c9 (diff)
Merge pull request #303 from ueokande/properties
Properties support
Diffstat (limited to 'src/shared/commands/parsers.js')
-rw-r--r--src/shared/commands/parsers.js59
1 files changed, 59 insertions, 0 deletions
diff --git a/src/shared/commands/parsers.js b/src/shared/commands/parsers.js
new file mode 100644
index 0000000..fb37d2a
--- /dev/null
+++ b/src/shared/commands/parsers.js
@@ -0,0 +1,59 @@
+const normalizeUrl = (args, searchConfig) => {
+ let concat = args.join(' ');
+ try {
+ return new URL(concat).href;
+ } catch (e) {
+ if (concat.includes('.') && !concat.includes(' ')) {
+ return 'http://' + concat;
+ }
+ let query = concat;
+ let template = searchConfig.engines[
+ searchConfig.default
+ ];
+ for (let key in searchConfig.engines) {
+ if (args[0] === key) {
+ query = args.slice(1).join(' ');
+ template = searchConfig.engines[key];
+ }
+ }
+ return template.replace('{}', encodeURIComponent(query));
+ }
+};
+
+const mustNumber = (v) => {
+ let num = Number(v);
+ if (isNaN(num)) {
+ throw new Error('Not number: ' + v);
+ }
+ return num;
+};
+
+const parseSetOption = (word, types) => {
+ let [key, value] = word.split('=');
+ if (value === undefined) {
+ value = !key.startsWith('no');
+ key = value ? key : key.slice(2);
+ }
+ let type = types[key];
+ if (!type) {
+ throw new Error('Unknown property: ' + key);
+ }
+ if (type === 'boolean' && typeof value !== 'boolean' ||
+ type !== 'boolean' && typeof value === 'boolean') {
+ throw new Error('Invalid argument: ' + word);
+ }
+
+ switch (type) {
+ case 'string': return [key, value];
+ case 'number': return [key, mustNumber(value)];
+ case 'boolean': return [key, value];
+ }
+};
+
+const parseCommandLine = (line) => {
+ let words = line.trim().split(/ +/);
+ let name = words.shift();
+ return [name, words];
+};
+
+export { normalizeUrl, parseCommandLine, parseSetOption };