'a'
mh-two-thousand-and-two
2024-04-12 44d2c92345cd156a59fc327b3060292a282d2893
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
'use strict'
 
/**
 * Properly parse the given array in regards to object strings
 * e.g. [ '--headers={Foo:', '5,', 'bar:', '6}' ] -> [ '--headers={"Foo": 5, "bar": 6}' ]
 * @param {Array} args
 */
function splitArgObjects (args) {
  const newArgs = []
  let index = 0
 
  while (index < args.length) {
    const arg = args[index]
 
    if (arg.indexOf('{') !== -1) {
      const temp = []
 
      while (args[index].indexOf('}') === -1) {
        temp.push(args[index])
        index++
      }
      temp.push(args[index])
 
      newArgs.push(temp.join(' ').replace(/([\w\d-]+):\s*([\w\d-]*)/g, '"$1": "$2"'))
    } else {
      newArgs.push(arg)
    }
 
    index++
  }
 
  return newArgs
}
 
const parse = function parse (args = [], options = {}) {
  if (!args.length) {
    args = process.argv.slice(2)
  }
 
  if (args[0] && args[0].match(/node$/)) {
    args = args.slice(2)
  }
 
  const newArgs = splitArgObjects(args)
  function parseArgs (args, obj) {
    // Check if end reached
    if (!args.length) {
      return obj
    }
 
    const arg = args[0]
 
    // if statement match conditions:
    // 1. --key=value || -key=value
    // 2. --no-key
    // 3. --key value|nothing
    // else add to unknown arr
    if (/^(--|-).+=/.test(arg)) {
      const match = arg.match(/^(--|-)([^=]+)=([\s\S]*)$/)
      // Set key(match[2]) = value(match[3])
      obj[match[2]] = match[3]
    } else if (/^--no-.+/.test(arg)) {
      // Set key = true
      obj[arg.match(/^--no-(.+)/)[1]] = false
    } else if (/^(--|-).+/.test(arg)) {
      const key = arg.match(/^(--|-)(.+)/)[2]
      const next = args[1]
 
      // If next value exist and not prefixed with - or --
      if (next && !/^(-|--)/.test(next)) {
        obj[key] = next
        return parseArgs(args.slice(2), obj)
      } else {
        obj[key] = true
      }
    } else {
      obj.unknown.push(arg)
    }
 
    return parseArgs(args.slice(1), obj)
  }
 
  const parseResult = parseArgs(newArgs, { unknown: [] })
 
  // Covert to proper type
  for (let prop in parseResult) {
    try {
      parseResult[prop] = JSON.parse(parseResult[prop])
    } catch (e) {
      continue
    }
  }
 
  return parseResult
}
 
module.exports = parse