@@ -3,11 +3,20 @@ package comfunc
33import (
44 "fmt"
55 "strings"
6-
76)
87
98var commentsPrefixes = []string {"#" , ";" , "//" }
109
10+ // ParseEnvLineOption parse env line options
11+ type ParseEnvLineOption struct {
12+ // NotInlineComments dont parse inline comments.
13+ // - default: false. will parse inline comments
14+ NotInlineComments bool
15+ // SkipOnErrorLine skip error line, continue parse next line
16+ // - False: return error, clear parsed map
17+ SkipOnErrorLine bool
18+ }
19+
1120// ParseEnvLines parse simple multiline k-v string to a string-map.
1221// Can use to parse simple INI or DOTENV file contents.
1322//
@@ -17,7 +26,7 @@ var commentsPrefixes = []string{"#", ";", "//"}
1726// - Support comments line starts with: "#", ";", "//"
1827// - Support inline comments split with: " #" eg: name=tom # a comments
1928// - DON'T support submap parse.
20- func ParseEnvLines (text string , parseInlineComments bool ) (mp map [string ]string , err error ) {
29+ func ParseEnvLines (text string , opt ParseEnvLineOption ) (mp map [string ]string , err error ) {
2130 lines := strings .Split (text , "\n " )
2231 ln := len (lines )
2332 if ln == 0 {
@@ -32,11 +41,16 @@ func ParseEnvLines(text string, parseInlineComments bool) (mp map[string]string,
3241 }
3342
3443 // skip comments line
35- if strings . HasPrefix ( line , "#" ) || strings . HasPrefix ( line , ";" ) || strings .HasPrefix (line , "//" ) {
44+ if line [ 0 ] == '#' || line [ 0 ] == ';' || strings .HasPrefix (line , "//" ) {
3645 continue
3746 }
3847
39- if ! strings .ContainsRune (line , '=' ) {
48+ // invalid line
49+ if strings .IndexByte (line , '=' ) < 1 {
50+ if opt .SkipOnErrorLine {
51+ continue
52+ }
53+
4054 strMap = nil
4155 err = fmt .Errorf ("invalid line contents: must match `KEY=VAL`(line: %s)" , line )
4256 return
@@ -45,7 +59,7 @@ func ParseEnvLines(text string, parseInlineComments bool) (mp map[string]string,
4559 key , value := SplitLineToKv (line , "=" )
4660
4761 // check and remove inline comments
48- if parseInlineComments {
62+ if ! opt . NotInlineComments {
4963 if pos := strings .Index (value , " #" ); pos > 0 {
5064 value = strings .TrimRight (value [0 :pos ], " \t " )
5165 }
@@ -58,7 +72,8 @@ func ParseEnvLines(text string, parseInlineComments bool) (mp map[string]string,
5872}
5973
6074// SplitLineToKv parse string line to k-v. eg:
61- // 'DEBUG=true' => ['DEBUG', 'true']
75+ //
76+ // 'DEBUG=true' => ['DEBUG', 'true']
6277//
6378// NOTE: line must contain '=', allow: 'ENV_KEY='
6479func SplitLineToKv (line , sep string ) (string , string ) {
@@ -77,4 +92,4 @@ func SplitLineToKv(line, sep string) (string, string) {
7792 return "" , ""
7893 }
7994 return envKey , strings .TrimSpace (nodes [1 ])
80- }
95+ }
0 commit comments