Browse Source

transplant ArgsParser from growi-plugin-lsx

Yuki Takei 7 years ago
parent
commit
c7c3abc085

+ 1 - 0
packages/growi-commons/src/index.js

@@ -2,5 +2,6 @@ module.exports = {
   BasicInterceptor: require('./util/basic-interceptor'),
   pathUtils: require('./util/path-utils'),
   // plugin
+  ArgsParser: require('./plugin/util/args-parser'),
   OptionParser: require('./plugin/util/option-parser'),
 };

+ 1 - 0
packages/growi-commons/src/plugin/index.js

@@ -1,3 +1,4 @@
 module.exports = {
+  ArgsParser: require('./util/args-parser'),
   OptionParser: require('./util/option-parser'),
 };

+ 44 - 0
packages/growi-commons/src/plugin/util/args-parser.js

@@ -0,0 +1,44 @@
+class ArgsParser {
+
+  /**
+   * parse plugin argument strings
+   *
+   * @static
+   * @param {string} str
+   * @returns {object} { fistArgsKey: 'key', firstArgsValue: 'val', options: {..} }
+   */
+  static parse(str) {
+    let firstArgsKey = null;
+    let firstArgsValue = null;
+    const options = {};
+
+    if (str != null && str.length > 0) {
+      const splittedArgs = str.split(',');
+
+      splittedArgs.forEach((rawArg, index) => {
+        const arg = rawArg.trim();
+
+        // parse string like 'key1=value1, key2=value2, ...'
+        // see https://regex101.com/r/pYHcOM/1
+        const match = arg.match(/([^=]+)=?(.+)?/);
+        const key = match[1];
+        const value = match[2] || true;
+        options[key] = value;
+
+        if (index === 0) {
+          firstArgsKey = key;
+          firstArgsValue = value;
+        }
+      });
+    }
+
+    return {
+      firstArgsKey,
+      firstArgsValue,
+      options,
+    };
+  }
+
+}
+
+module.exports = ArgsParser;

+ 38 - 0
packages/growi-commons/src/test/plugin/util/args-parser.test.js

@@ -0,0 +1,38 @@
+import each from 'jest-each';
+
+require('module-alias/register');
+
+const ArgsParser = require('@src/plugin/util/args-parser');
+
+describe('args-parser', () => {
+
+  test('.parse(null) returns default object', () => {
+    const result = ArgsParser.parse(null);
+
+    expect(result.firstArgsKey).toBeNull();
+    expect(result.firstArgsValue).toBeNull();
+    expect(result.options).toEqual({});
+  });
+
+  // each`
+  //   arg
+  //   ${'aaa'}
+  //   ${'5++2'}
+  //   ${'5:+2'}
+  // `.test('.parseRange(\'$arg\') returns null', ({ arg }) => {
+  //   expect(OptionParser.parseRange(arg)).toBeNull();
+  // });
+
+  // each`
+  //   arg       | start | end
+  //   ${'1'}    | ${1} | ${1}
+  //   ${'2:1'}  | ${2} | ${1}
+  //   ${'2:'}   | ${2} | ${-1}
+  //   ${'10:-3'}   | ${10} | ${-3}
+  //   ${'5+2'}   | ${5} | ${7}
+  //   ${'5+'}   | ${5} | ${5}
+  // `.test('.parseRange(\'$arg\') returns { start: $start, end : $end }', ({ arg, start, end }) => {
+  //   expect(OptionParser.parseRange(arg)).toEqual({ start, end });
+  // });
+
+});