-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsize_var.go
57 lines (50 loc) · 1.62 KB
/
size_var.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package goflags
import (
"fmt"
"strconv"
fileutil "github.com/projectdiscovery/utils/file"
)
type Size int
func (s *Size) Set(size string) error {
sizeInBytes, err := fileutil.FileSizeToByteLen(size)
if err != nil {
return err
}
*s = Size(sizeInBytes)
return nil
}
func (s *Size) String() string {
return strconv.Itoa(int(*s))
}
// SizeVar converts the given fileSize with a unit (kb, mb, gb, or tb) to bytes.
// For example, '2kb' will be converted to 2048.
// If no unit is provided, it will fallback to mb. e.g: '2' will be converted to 2097152.
func (flagSet *FlagSet) SizeVar(field *Size, long string, defaultValue string, usage string) *FlagData {
return flagSet.SizeVarP(field, long, "", defaultValue, usage)
}
// SizeVarP converts the given fileSize with a unit (kb, mb, gb, or tb) to bytes.
// For example, '2kb' will be converted to 2048.
// If no unit is provided, it will fallback to mb. e.g: '2' will be converted to 2097152.
func (flagSet *FlagSet) SizeVarP(field *Size, long, short string, defaultValue string, usage string) *FlagData {
if field == nil {
panic(fmt.Errorf("field cannot be nil for flag -%v", long))
}
if defaultValue != "" {
if err := field.Set(defaultValue); err != nil {
panic(fmt.Errorf("failed to set default value for flag -%v: %v", long, err))
}
}
flagData := &FlagData{
usage: usage,
long: long,
defaultValue: defaultValue,
}
if short != "" {
flagData.short = short
flagSet.CommandLine.Var(field, short, usage)
flagSet.flagKeys.Set(short, flagData)
}
flagSet.CommandLine.Var(field, long, usage)
flagSet.flagKeys.Set(long, flagData)
return flagData
}