arguments.mjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. export class BaseArgumentsProcessor {
  5. constructor(args) {
  6. this.args_ = args;
  7. this.result_ = this.getDefaultResults();
  8. console.assert(this.result_ !== undefined)
  9. console.assert(this.result_.logFileName !== undefined);
  10. this.argsDispatch_ = this.getArgsDispatch();
  11. console.assert(this.argsDispatch_ !== undefined);
  12. }
  13. getDefaultResults() {
  14. throw "Implement in getDefaultResults in subclass";
  15. }
  16. getArgsDispatch() {
  17. throw "Implement getArgsDispatch in subclass";
  18. }
  19. result() { return this.result_ }
  20. static process(args) {
  21. const processor = new this(args);
  22. if (processor.parse()) {
  23. return processor.result();
  24. } else {
  25. processor.printUsageAndExit();
  26. return false;
  27. }
  28. }
  29. printUsageAndExit() {
  30. console.log('Cmdline args: [options] [log-file-name]\n' +
  31. 'Default log file name is "' +
  32. this.result_.logFileName + '".\n');
  33. console.log('Options:');
  34. for (const arg in this.argsDispatch_) {
  35. const synonyms = [arg];
  36. const dispatch = this.argsDispatch_[arg];
  37. for (const synArg in this.argsDispatch_) {
  38. if (arg !== synArg && dispatch === this.argsDispatch_[synArg]) {
  39. synonyms.push(synArg);
  40. delete this.argsDispatch_[synArg];
  41. }
  42. }
  43. console.log(` ${synonyms.join(', ').padEnd(20)} ${dispatch[2]}`);
  44. }
  45. quit(2);
  46. }
  47. parse() {
  48. while (this.args_.length) {
  49. let arg = this.args_.shift();
  50. if (arg.charAt(0) != '-') {
  51. this.result_.logFileName = arg;
  52. continue;
  53. }
  54. let userValue = null;
  55. const eqPos = arg.indexOf('=');
  56. if (eqPos != -1) {
  57. userValue = arg.substr(eqPos + 1);
  58. arg = arg.substr(0, eqPos);
  59. }
  60. if (arg in this.argsDispatch_) {
  61. const dispatch = this.argsDispatch_[arg];
  62. const property = dispatch[0];
  63. const defaultValue = dispatch[1];
  64. if (typeof defaultValue == "function") {
  65. userValue = defaultValue(userValue);
  66. } else if (userValue == null) {
  67. userValue = defaultValue;
  68. }
  69. this.result_[property] = userValue;
  70. } else {
  71. return false;
  72. }
  73. }
  74. return true;
  75. }
  76. }
  77. export function parseBool(str) {
  78. if (str == "true" || str == "1") return true;
  79. return false;
  80. }