Skip to content

Add the ability to exclude specific separators from the parsing algor… #55

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ args, err := p.Parse("./foo `echo $SHELL`")
// args should be ["./foo", "/bin/bash"]
```

```go
p := shellwords.NewParser()
p.SetExcludeSeparators('\t',';')
```

# Thanks

This is based on cpan module [Parse::CommandLine](https://metacpan.org/pod/Parse::CommandLine).
Expand Down
32 changes: 32 additions & 0 deletions shellwords.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ type Parser struct {
ParseBacktick bool
Position int
Dir string
excludedSep []rune

// If ParseEnv is true, use this for getenv.
// If nil, use os.Getenv.
Expand All @@ -111,6 +112,7 @@ func NewParser() *Parser {
ParseBacktick: ParseBacktick,
Position: 0,
Dir: "",
excludedSep: []rune{},
}
}

Expand All @@ -122,6 +124,27 @@ const (
argQuoted
)

// isExcluded checks if separator should be ignored
func (p *Parser) isExcluded(r rune) bool {
for _, v := range p.excludedSep {
if v == r {
return true
}
}
return false
}

// SetExcludeSeparators indictes the parser to ignore provided separators when parsing
// example: parser.SetExcludeSeparators(';','\t')
func (p *Parser) SetExcludeSeparators(r ...rune) {
p.excludedSep = r
}

// ExcludedSeparators returns excluded separators
func (p *Parser) ExcludedSeparators() []rune {
return p.excludedSep
}

func (p *Parser) Parse(line string) ([]string, error) {
args := []string{}
buf := ""
Expand Down Expand Up @@ -157,6 +180,15 @@ loop:
continue
}

if p.isExcluded(r) {
got = argSingle
buf += string(r)
if backQuote || dollarQuote {
backtick += string(r)
}
continue
}

if isSpace(r) {
if singleQuoted || doubleQuoted || backQuote || dollarQuote {
buf += string(r)
Expand Down