Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial work on parseArgs #1

Merged
merged 3 commits into from
Apr 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use strict';

const parseArgs = (
argv = process.argv.slice(require.main ? 2 : 1),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we might want to extend this further to handle environments like electron, I'm not sure of the best approach. Here's what we do in yargs.

options = {}
) => {
if (typeof options !== 'object' || options === null) {
throw new Error('Whoops!')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps open a tracking ticket to add a clearer type checking message eventually 😆 (if you'd like to land this with Whoops!).

}

let result = {
args: {},
values: {},
positionals: []
}

let pos = 0
while (pos < argv.length) {
let arg = argv[pos]

if (arg.startsWith('-')) {
// Everything after a bare '--' is considered a positional argument
// and is returned verbatim
if (arg === '--') {
result.positionals.push(...argv.slice(++pos))

return result
}
// look for shortcodes: -fXzy
else if (arg.charAt(1) !== '-') {
throw new Error('What are we doing with shortcodes!?!')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for this first implementation we're only supporting --foo, --foo bar?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read the FAQ, and opened #2.

}

// Any number of leading dashes are allowed
// remove all leading dashes
arg = arg.replace(/^-+/, '')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could do -----hello world? I guess, why not?


if (arg.includes('=')) {
const argParts = arg.split('=')

result.args[argParts[0]] = true
if (options.withValue) {
result.values[argParts[0]] = argParts[1]
}
}
else {
result.args[arg] = true

}
}

pos++
}

return result
}

module.exports = {
parseArgs
}
Loading