Share flag consumption between parsing and completion
This commit is contained in:
@@ -65,3 +65,47 @@ func (lookup FlagLookup) Find(spelling string) (Flag, bool) {
|
||||
}
|
||||
return flag, ok
|
||||
}
|
||||
|
||||
// FlagConsumption describes one flag within an option token. NextOffset is zero
|
||||
// when the token is exhausted; otherwise it identifies the next short spelling.
|
||||
type FlagConsumption struct {
|
||||
Flag Flag
|
||||
Spelling string
|
||||
Found bool
|
||||
Value string
|
||||
Attached bool
|
||||
NeedsNext bool
|
||||
NextOffset int
|
||||
}
|
||||
|
||||
// ConsumeFlag reads a long option or a short option at offset in a cluster.
|
||||
func ConsumeFlag(lookup FlagLookup, token string, offset int) FlagConsumption {
|
||||
var result FlagConsumption
|
||||
if ClassifyFlagToken(token) == LongFlagToken {
|
||||
result.Spelling, result.Value, result.Attached = SplitLongFlag(token)
|
||||
result.Flag, result.Found = lookup.Find(result.Spelling)
|
||||
result.NeedsNext = result.Found && !result.Flag.Boolean && !result.Attached
|
||||
return result
|
||||
}
|
||||
result.Spelling = "-" + token[offset:offset+1]
|
||||
result.Flag, result.Found = lookup.Find(result.Spelling)
|
||||
if !result.Found {
|
||||
return result
|
||||
}
|
||||
suffix := token[offset+1:]
|
||||
if result.Flag.Boolean {
|
||||
if strings.HasPrefix(suffix, "=") {
|
||||
result.Attached, result.Value = true, suffix[1:]
|
||||
} else if suffix != "" {
|
||||
result.NextOffset = offset + 1
|
||||
}
|
||||
return result
|
||||
}
|
||||
if suffix == "" {
|
||||
result.NeedsNext = true
|
||||
return result
|
||||
}
|
||||
result.Attached = true
|
||||
result.Value = strings.TrimPrefix(suffix, "=")
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user