2021-09-24 21:13:52 +03:00
|
|
|
// Copyright (c) 2021 Lars Pontoppidan. All rights reserved.
|
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
module input
|
|
|
|
|
2021-09-29 14:53:06 +03:00
|
|
|
import os
|
|
|
|
|
2021-09-24 21:13:52 +03:00
|
|
|
// 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 {
|
|
|
|
pub:
|
|
|
|
text string // TOML text
|
|
|
|
file_path string // '/path/to/file.toml'
|
|
|
|
}
|
|
|
|
|
2021-09-29 14:53:06 +03:00
|
|
|
// auto_config returns an, automatic determined, input Config based on heuristics
|
|
|
|
// found in `toml`
|
2022-03-18 23:33:51 +03:00
|
|
|
// One example of several of why it's deprecated:
|
|
|
|
// https://discord.com/channels/592103645835821068/592114487759470596/954101934988615721
|
|
|
|
[deprecated: 'will be removed and not replaced due to flaky heuristics that leads to hard to find bugs']
|
|
|
|
[deprecated_after: '2022-06-18']
|
2022-10-16 09:28:57 +03:00
|
|
|
pub fn auto_config(toml string) !Config {
|
2021-09-29 14:53:06 +03:00
|
|
|
mut config := Config{}
|
|
|
|
if !toml.contains('\n') && os.is_file(toml) {
|
|
|
|
config = Config{
|
|
|
|
file_path: toml
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
config = Config{
|
|
|
|
text: toml
|
|
|
|
}
|
|
|
|
}
|
2022-10-16 09:28:57 +03:00
|
|
|
config.validate()!
|
2021-09-29 14:53:06 +03:00
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
2021-09-26 07:34:47 +03:00
|
|
|
// validate returns an optional error if more than one of the fields
|
|
|
|
// in `Config` has a non-default value (empty string).
|
2022-10-16 09:28:57 +03:00
|
|
|
fn (c Config) validate() ! {
|
2021-09-24 21:13:52 +03:00
|
|
|
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')
|
|
|
|
}
|
|
|
|
}
|
2021-09-29 14:53:06 +03:00
|
|
|
|
2022-03-18 23:33:51 +03:00
|
|
|
// read_input returns either Config.text or the read file contents of Config.file_path
|
|
|
|
// depending on which one is not empty.
|
2022-10-16 09:28:57 +03:00
|
|
|
pub fn (c Config) read_input() !string {
|
|
|
|
c.validate()!
|
2021-09-29 14:53:06 +03:00
|
|
|
mut text := c.text
|
2022-03-18 23:33:51 +03:00
|
|
|
if text == '' && os.is_file(c.file_path) {
|
2021-09-29 14:53:06 +03:00
|
|
|
text = os.read_file(c.file_path) or {
|
|
|
|
return error(@MOD + '.' + @STRUCT + '.' + @FN +
|
2022-11-15 16:53:13 +03:00
|
|
|
' Could not read "${c.file_path}": "${err.msg()}"')
|
2021-09-29 14:53:06 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return text
|
|
|
|
}
|