v2 / vlib / toml / input / input.v
35 lines · 32 sloc · 1.12 KB · 75440344c010b80e7e82453aa926cbf88d66f37f
Raw
1// Copyright (c) 2021 Lars Pontoppidan. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module input
5
6import os
7
8// Config is used to configure input to the toml module.
9// Only one of the fields `text` and `file_path` is allowed to be set at time of configuration.
10pub struct Config {
11pub:
12 text string // TOML text
13 file_path string // '/path/to/file.toml'
14}
15
16// read_input returns either Config.text or the read file contents of Config.file_path
17// depending on which one is not empty.
18pub fn (c Config) read_input() !string {
19 if c.file_path != '' && c.text != '' {
20 return error(@MOD + '.' + @FN +
21 ' ${typeof(c).name} should contain only one of the fields `file_path` OR `text` filled out')
22 }
23 if c.file_path == '' && c.text == '' {
24 // TODO: passing both empty is used *a lot* by `./v vlib/toml/tests/toml_lang_test.v`; investigate why.
25 return ''
26 }
27 if c.text != '' {
28 return c.text
29 }
30 text := os.read_file(c.file_path) or {
31 return error(@MOD + '.' + @STRUCT + '.' + @FN +
32 ' Could not read "${c.file_path}": "${err.msg()}"')
33 }
34 return text
35}
36