1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

toml: easier scanner configuration (#12016)

This commit is contained in:
Larpon
2021-09-29 13:53:06 +02:00
committed by GitHub
parent f2c710d306
commit 4ff061927b
3 changed files with 43 additions and 13 deletions

View File

@@ -3,6 +3,8 @@
// that can be found in the LICENSE file.
module input
import os
// Config is used to configure input to the toml module.
// Only one of the fields `text` and `file_path` is allowed to be set at time of configuration.
pub struct Config {
@@ -11,6 +13,23 @@ pub:
file_path string // '/path/to/file.toml'
}
// auto_config returns an, automatic determined, input Config based on heuristics
// found in `toml`
pub fn auto_config(toml string) ?Config {
mut config := Config{}
if !toml.contains('\n') && os.is_file(toml) {
config = Config{
file_path: toml
}
} else {
config = Config{
text: toml
}
}
config.validate() ?
return config
}
// validate returns an optional error if more than one of the fields
// in `Config` has a non-default value (empty string).
pub fn (c Config) validate() ? {
@@ -22,3 +41,14 @@ pub fn (c Config) validate() ? {
' ${typeof(c).name} must either contain a valid `file_path` OR a non-empty `text` field')
}
}
pub fn (c Config) read_input() ?string {
mut text := c.text
if os.is_file(c.file_path) {
text = os.read_file(c.file_path) or {
return error(@MOD + '.' + @STRUCT + '.' + @FN +
' Could not read "$c.file_path": "$err.msg"')
}
}
return text
}