toml: return an error from toml.parse_file(), when the passed file path does not exist (#20912)

This commit is contained in:
Rodrigo Abt 2024-02-27 09:22:48 -03:00 committed by GitHub
parent d8c4a84f71
commit aa002a4019
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -13,28 +13,23 @@ pub:
file_path string // '/path/to/file.toml' file_path string // '/path/to/file.toml'
} }
// validate returns an optional error if more than one of the fields
// in `Config` has a non-default value (empty string).
fn (c Config) validate() ! {
if c.file_path != '' && c.text != '' {
error(@MOD + '.' + @FN +
' ${typeof(c).name} should contain only one of the fields `file_path` OR `text` filled out')
} else if c.file_path == '' && c.text == '' {
error(@MOD + '.' + @FN +
' ${typeof(c).name} must either contain a valid `file_path` OR a non-empty `text` field')
}
}
// read_input returns either Config.text or the read file contents of Config.file_path // read_input returns either Config.text or the read file contents of Config.file_path
// depending on which one is not empty. // depending on which one is not empty.
pub fn (c Config) read_input() !string { pub fn (c Config) read_input() !string {
c.validate()! if c.file_path != '' && c.text != '' {
mut text := c.text return error(@MOD + '.' + @FN +
if text == '' && os.is_file(c.file_path) { ' ${typeof(c).name} should contain only one of the fields `file_path` OR `text` filled out')
text = os.read_file(c.file_path) or { }
return error(@MOD + '.' + @STRUCT + '.' + @FN + if c.file_path == '' && c.text == '' {
' Could not read "${c.file_path}": "${err.msg()}"') // TODO: passing both empty is used *a lot* by `./v vlib/toml/tests/burntsushi_toml_test.v`; investigate why.
} return ''
}
if c.text != '' {
return c.text
}
text := os.read_file(c.file_path) or {
return error(@MOD + '.' + @STRUCT + '.' + @FN +
' Could not read "${c.file_path}": "${err.msg()}"')
} }
return text return text
} }