• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2017 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5export class BaseArgumentsProcessor {
6  constructor(args) {
7    this.args_ = args;
8    this.result_ = this.getDefaultResults();
9    console.assert(this.result_ !== undefined)
10    console.assert(this.result_.logFileName !== undefined);
11    this.argsDispatch_ = this.getArgsDispatch();
12    console.assert(this.argsDispatch_ !== undefined);
13  }
14
15  getDefaultResults() {
16    throw "Implement in getDefaultResults in subclass";
17  }
18
19  getArgsDispatch() {
20    throw "Implement getArgsDispatch in subclass";
21  }
22
23  result() { return this.result_ }
24
25  static process(args) {
26    const processor = new this(args);
27    if (processor.parse()) {
28      return processor.result();
29    } else {
30      processor.printUsageAndExit();
31      return false;
32    }
33  }
34
35  printUsageAndExit() {
36    console.log('Cmdline args: [options] [log-file-name]\n' +
37          'Default log file name is "' +
38          this.result_.logFileName + '".\n');
39          console.log('Options:');
40    for (const arg in this.argsDispatch_) {
41      const synonyms = [arg];
42      const dispatch = this.argsDispatch_[arg];
43      for (const synArg in this.argsDispatch_) {
44        if (arg !== synArg && dispatch === this.argsDispatch_[synArg]) {
45          synonyms.push(synArg);
46          delete this.argsDispatch_[synArg];
47        }
48      }
49      console.log(`  ${synonyms.join(', ').padEnd(20)} ${dispatch[2]}`);
50    }
51    quit(2);
52  }
53
54  parse() {
55    while (this.args_.length) {
56      let arg = this.args_.shift();
57      if (arg.charAt(0) != '-') {
58        this.result_.logFileName = arg;
59        continue;
60      }
61      let userValue = null;
62      const eqPos = arg.indexOf('=');
63      if (eqPos != -1) {
64        userValue = arg.substr(eqPos + 1);
65        arg = arg.substr(0, eqPos);
66      }
67      if (arg in this.argsDispatch_) {
68        const dispatch = this.argsDispatch_[arg];
69        const property = dispatch[0];
70        const defaultValue = dispatch[1];
71        if (typeof defaultValue == "function") {
72          userValue = defaultValue(userValue);
73        } else if (userValue == null) {
74          userValue = defaultValue;
75        }
76        this.result_[property] = userValue;
77      } else {
78        return false;
79      }
80    }
81    return true;
82  }
83}
84
85export function parseBool(str) {
86  if (str == "true" || str == "1") return true;
87  return false;
88}
89