Documentation
¶
Overview ¶
Package forge provides an api to deal with parsing configuration files.
Config file example:
# example.cfg top_level = "a string"; primary { primary_int = 500; sub_section { sub_float = 50.5; # End of line comment } } secondary { secondary_bool = true; secondary_null = null; list = [ "any", 'value', true, 55.5, ] # Reference other config value local_ref = .secondary_null; global_ref = primary.sub_section.sub_float; # Include all files matching the provided pattern include "/etc/app/*.cfg"; }
Config file format:
IDENTIFIER: [_a-zA-Z]([_a-zA-Z0-9]+)? NUMBERS: [0-9]+ END: ';' | '\n' BOOL: 'true' | 'false' NULL: 'null' INTEGER: ('-')? NUMBERS FLOAT: ('-')? NUMBERS '.' NUMBERS STRING: ['"] .* ['"] REFERENCE: (IDENTIFIER)? ('.' IDENTIFIER)+ ENVIRONMENT: '$' IDENTIFIER VALUE: BOOL | NULL | INTEGER | FLOAT | STRING | REFERENCE | ENVIRONMENT LIST: '[' (VALUE | LIST) (',' NEWLINE* (VALUE | LIST))+ ']' INCLUDE: 'include ' STRING END DIRECTIVE: (IDENTIFIER '=' (VALUE | LIST) | INCLUDE) END SECTION: IDENTIFIER '{' (DIRECTIVE | SECTION)* '}' COMMENT: '#' .* '\n' CONFIG_FILE: (COMMENT | DIRECTIVE | SECTION)*
Values
- String: Any value enclosed in double or single quotes (e.g. "string" or 'string'). Double quotes, single quotes, and backslashes can be escaped with backslashes (e.g. "\"quoted\"", '\'quoted\”, and "\\<--backslash")
- Integer: Any number without decimal places (e.g. 500)
- Float: Any number with decimal places (e.g. 500.55)
- Boolean: The identifiers 'true' or 'false' of any case (e.g. TRUE, True, true, FALSE, False, false)
- Null: The identifier 'null' of any case (e.g. NULL, Null, null)
- List: A list value is any number of other values separated by commas and surrounded by brackets. (e.g. [50.5, 'some', "string", true, false])
- Global reference: An identifier which may contain periods, the references are resolved from the global section (e.g. global_value, section.sub_section.value)
- Local reference: An identifier which main contain periods which starts with a period, the references are resolved from the settings current section (e.g. .value, .sub_section.value)
- Environment: An environment is a way to pull in environment variables into your config. Environment variables are identifiers which start with a dollar sign (e.g. $PATH). Environment variables are always represented as strings and are evaluated at parse time.
Directives
- Comment: A comment is a pound symbol ('#') followed by any text any which ends with a newline (e.g. '# I am a comment\n') A comment can either be on a line of it's own or at the end of any line. Nothing can come after the comment until after the newline.
- Directive: A directive is a setting, a identifier and a value. They are in the format '<identifier> = <value>;' All directives must end in either a semicolon or newline. The value can be any of the types defined above.
- Section: A section is a grouping of directives under a common name. They are in the format '<section_name> { <directives> }'. All sections must be wrapped in braces ('{', '}') and must all have a name. They do not end in a semicolon. Sections may be left empty, they do not have to contain any directives.
- Include: An include statement tells the config parser to include the contents of another config file where the include statement is defined. Includes are in the format 'include "<pattern>";'. The <pattern> can be any glob like pattern which is compatible with `path.filepath.Match` http://golang.org/pkg/path/filepath/#Match
Example ¶
package main import ( "fmt" "github.com/go-aah/forge" ) func main() { // Parse a `SectionValue` from `example.cfg` settings, err := forge.ParseFile("example.cfg") if err != nil { panic(err) } // Get a single value if settings.Exists("global") { // Get `global` casted as a string value, _ := settings.GetString("global") fmt.Printf("global = \"%s\"\r\n", value) } // Get a nested value value, err := settings.Resolve("primary.included_setting") fmt.Printf("primary.included_setting = \"%s\"\r\n", value.GetValue()) // You can also traverse down the sections manually primary, err := settings.GetSection("primary") strVal, err := primary.GetString("included_setting") fmt.Printf("primary.included_setting = \"%s\"\r\n", strVal) // Convert settings to a map settingsMap := settings.ToMap() fmt.Printf("global = \"%s\"\r\n", settingsMap["global"]) // Convert settings to JSON jsonBytes, err := settings.ToJSON() fmt.Printf("\r\n\r\n%s\r\n", string(jsonBytes)) }
Output:
Index ¶
- Variables
- func RegisterFS(fileSystem FileSystem)
- type FileSystem
- type List
- func (list *List) Append(value Value)
- func (list *List) Get(idx int) (Value, error)
- func (list *List) GetBoolean(idx int) (bool, error)
- func (list *List) GetFloat(idx int) (float64, error)
- func (list *List) GetInteger(idx int) (int64, error)
- func (list *List) GetList(idx int) (*List, error)
- func (list *List) GetString(idx int) (string, error)
- func (list *List) GetType() ValueType
- func (list *List) GetValue() interface{}
- func (list *List) GetValues() []Value
- func (list *List) Length() int
- func (list *List) Set(idx int, value Value)
- func (list *List) UpdateValue(value interface{}) error
- type NativeFS
- type Parser
- type Primative
- func (primative *Primative) AsBoolean() (bool, error)
- func (primative *Primative) AsFloat() (float64, error)
- func (primative *Primative) AsInteger() (int64, error)
- func (primative *Primative) AsNull() (interface{}, error)
- func (primative *Primative) AsString() (string, error)
- func (primative *Primative) GetType() ValueType
- func (primative *Primative) GetValue() interface{}
- func (primative *Primative) String() string
- func (primative *Primative) UpdateValue(value interface{}) error
- type Reference
- type Scanner
- type Section
- func (section *Section) AddComment(comment string)
- func (section *Section) AddInclude(filename string)
- func (section *Section) AddSection(name string) *Section
- func (section *Section) Exists(name string) bool
- func (section *Section) Get(name string) (Value, error)
- func (section *Section) GetBoolean(name string) (bool, error)
- func (section *Section) GetComments() []string
- func (section *Section) GetFloat(name string) (float64, error)
- func (section *Section) GetIncludes() []string
- func (section *Section) GetInteger(name string) (int64, error)
- func (section *Section) GetList(name string) (*List, error)
- func (section *Section) GetParent() *Section
- func (section *Section) GetSection(name string) (*Section, error)
- func (section *Section) GetString(name string) (string, error)
- func (section *Section) GetType() ValueType
- func (section *Section) GetValue() interface{}
- func (section *Section) HasParent() bool
- func (section *Section) Keys() []string
- func (section *Section) Merge(source *Section) error
- func (section *Section) Resolve(name string) (Value, error)
- func (section *Section) Set(name string, value Value)
- func (section *Section) SetBoolean(name string, value bool)
- func (section *Section) SetFloat(name string, value float64)
- func (section *Section) SetInteger(name string, value int64)
- func (section *Section) SetNull(name string)
- func (section *Section) SetString(name string, value string)
- func (section *Section) ToJSON() ([]byte, error)
- func (section *Section) ToMap() map[string]interface{}
- func (section *Section) UpdateValue(value interface{}) error
- type Value
- type ValueType
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotExists represents a nonexistent value error ErrNotExists = errors.New("value does not exist") )
var Version = "0.8.0"
Version represent current release version of forge.
Functions ¶
func RegisterFS ¶ added in v0.7.0
func RegisterFS(fileSystem FileSystem)
RegisterFS method to register new file system into forge.
Types ¶
type FileSystem ¶ added in v0.7.0
type FileSystem interface { Open(filename string) (io.Reader, error) Glob(pattern string) ([]string, error) }
FileSystem interface to expand configuration file parsing possiblities.
type List ¶ added in v0.1.5
type List struct {
// contains filtered or unexported fields
}
List struct used for holding data neede for Reference data type
func NewList ¶ added in v0.1.5
func NewList() *List
NewList will create and initialize a new List value
func (*List) Append ¶ added in v0.1.5
Append will append a new Value on the end of the internal list
func (*List) GetBoolean ¶ added in v0.1.5
GetBoolean will try to get the value stored at the index as a bool will respond with an error if the value does not exist or cannot be converted to a bool
func (*List) GetFloat ¶ added in v0.1.5
GetFloat will try to get the value stored at the index as a float64 will respond with an error if the value does not exist or cannot be converted to a float64
func (*List) GetInteger ¶ added in v0.1.5
GetInteger will try to get the value stored at the index as a int64 will respond with an error if the value does not exist or cannot be converted to a int64
func (*List) GetList ¶ added in v0.1.5
GetList will try to get the value stored at the index as a List will respond with an error if the value does not exist or is not a List
func (*List) GetString ¶ added in v0.1.5
GetString will try to get the value stored at the index as a string will respond with an error if the value does not exist or cannot be converted to a string
func (*List) GetValue ¶ added in v0.1.5
func (list *List) GetValue() interface{}
GetValue will resolve and return the value from the underlying list this is necessary to inherit from Value
func (*List) UpdateValue ¶ added in v0.1.5
UpdateValue will set the underlying list value
type NativeFS ¶ added in v0.7.0
type NativeFS uint8
NativeFS type defines methods for native file system.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser is a struct to hold data necessary for parsing a config from a scanner
func NewFileParser ¶
NewFileParser will create and initialize a new Parser from a provided from a filename string
func (*Parser) GetSettings ¶
GetSettings will fetch the parsed settings from this Parser
type Primative ¶
type Primative struct {
// contains filtered or unexported fields
}
Primative struct for holding data about primative values
func NewBoolean ¶
NewBoolean will create and initialize a new Boolean type primative value
func NewInteger ¶
NewInteger will create and initialize a new Integer type primative value
func NewNull ¶
func NewNull() *Primative
NewNull will create and initialize a new Null type primative value
func NewPrimative ¶
NewPrimative will create a new empty Primative and call UpdateValue with the provided value
func (*Primative) AsBoolean ¶
AsBoolean tries to convert/return the value stored in this primative as a bool
func (*Primative) AsFloat ¶
AsFloat tries to convert/return the value stored in this primative as a float64
func (*Primative) AsInteger ¶
AsInteger tries to convert/return the value stored in this primative as a int64
func (*Primative) AsNull ¶
AsNull tries to convert/return the value stored in this primative as a null
func (*Primative) AsString ¶
AsString tries to convert/return the value stored in this primative as a string
func (*Primative) GetValue ¶
func (primative *Primative) GetValue() interface{}
GetValue returns the raw interface{} value assigned to this primative
func (*Primative) UpdateValue ¶
UpdateValue will update the internal value and stored ValueType for this primative
type Reference ¶
type Reference struct {
// contains filtered or unexported fields
}
Reference struct used for holding data neede for Reference data type
func NewReference ¶
NewReference will create and initialize a new Reference value
func (*Reference) GetValue ¶
func (reference *Reference) GetValue() interface{}
GetValue will resolve and return the value from the underlying reference
func (*Reference) UpdateValue ¶
UpdateValue will simply throw an error since it is not allowed for References
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner struct used to hold data necessary for parsing tokens from the input reader
func NewScanner ¶
NewScanner creates and initializes a new *Scanner from an io.Readerx
type Section ¶
type Section struct {
// contains filtered or unexported fields
}
Section struct holds a map of values
func ParseBytes ¶
ParseBytes takes a []byte representation of the config file, parses it and responds with `*Section` and potentially an `error` if it cannot properly parse the config
Example ¶
package main import ( "fmt" "github.com/go-aah/forge" ) func main() { // Parse a `SectionValue` from []byte containing the config data := []byte("amount = 500;") settings, err := forge.ParseBytes(data) if err != nil { panic(err) } fmt.Println(settings.GetInteger("amount")) }
Output:
func ParseFile ¶
ParseFile takes a string filename for the config file, parses it and responds with `*Section` and potentially an `error` if it cannot properly parse the configf
Example ¶
package main import ( "fmt" "github.com/go-aah/forge" ) func main() { // Parse a `SectionValue` from `example.cfg` settings, err := forge.ParseFile("example.cfg") if err != nil { panic(err) } fmt.Println(settings) }
Output:
func ParseReader ¶
ParseReader takes an `io.Reader` representation of the config file, parses it and responds with `*Section` and potentially an `error` if it cannot properly parse the config
Example ¶
package main import ( "bytes" "fmt" "github.com/go-aah/forge" ) func main() { // Parse a `SectionValue` from []byte containing the config data := []byte("amount = 500;") reader := bytes.NewBuffer(data) settings, err := forge.ParseReader(reader) if err != nil { panic(err) } fmt.Println(settings.GetInteger("amount")) }
Output:
func ParseString ¶
ParseString takes a string representation of the config file, parses it and responds with `*Section` and potentially an `error` if it cannot properly parse the config
Example ¶
package main import ( "fmt" "github.com/go-aah/forge" ) func main() { // Parse a `SectionValue` from string containing the config data := "amount = 500;" settings, err := forge.ParseString(data) if err != nil { panic(err) } fmt.Println(settings.GetInteger("amount")) }
Output:
func (*Section) AddComment ¶
AddComment will append a new comment into the section
func (*Section) AddInclude ¶
AddInclude will append a new filename into the section
func (*Section) AddSection ¶
AddSection adds a new child section to this Section with the provided name
func (*Section) Get ¶
Get the value (Primative or Section) stored under the name will respond with an error if the value does not exist
func (*Section) GetBoolean ¶
GetBoolean will try to get the value stored under name as a bool will respond with an error if the value does not exist or cannot be converted to a bool
func (*Section) GetComments ¶
GetComments will return all the comments were defined for this Section
func (*Section) GetFloat ¶
GetFloat will try to get the value stored under name as a float64 will respond with an error if the value does not exist or cannot be converted to a float64
func (*Section) GetIncludes ¶
GetIncludes will return the filenames of all the includes were parsed for this Section
func (*Section) GetInteger ¶
GetInteger will try to get the value stored under name as a int64 will respond with an error if the value does not exist or cannot be converted to a int64
func (*Section) GetList ¶ added in v0.1.5
GetList will try to get the value stored under name as a List will respond with an error if the value does not exist or is not a List
func (*Section) GetParent ¶
GetParent will get the parent section associated with this Section or nil if it does not have one
func (*Section) GetSection ¶
GetSection will try to get the value stored under name as a Section will respond with an error if the value does not exist or is not a Section
func (*Section) GetString ¶
GetString will try to get the value stored under name as a string will respond with an error if the value does not exist or cannot be converted to a string
func (*Section) GetType ¶
GetType will respond with the ValueType of this Section (hint, always SECTION)
func (*Section) GetValue ¶
func (section *Section) GetValue() interface{}
GetValue retrieves the raw underlying value stored in this Section
func (*Section) Keys ¶ added in v0.1.1
Keys will return back a list of all setting names in this Section
func (*Section) Merge ¶ added in v0.3.1
Merge merges the given section to current section. Settings from source section overwites the values in the current section
func (*Section) Resolve ¶
Resolve will recursively try to fetch the provided value and will respond with an error if the name does not exist or tries to be resolved through a non-section value
func (*Section) SetBoolean ¶
SetBoolean will set the value for name as a bool
func (*Section) SetInteger ¶
SetInteger will set the value for name as a int64
func (*Section) ToJSON ¶
ToJSON will convert this Section and all it's underlying values and Sections into JSON as a []byte
func (*Section) ToMap ¶
ToMap will convert this Section and all it's underlying values and Sections into a map[string]interface{}
func (*Section) UpdateValue ¶
UpdateValue updates the raw underlying value stored in this Section