| 38 | import org.tomlj.TomlTable; |
| 39 | |
| 40 | public class TomlConfig implements Config { |
| 41 | |
| 42 | private final TomlParseResult toml; |
| 43 | |
| 44 | public TomlConfig(Reader reader) { |
| 45 | try { |
| 46 | toml = Toml.parse(reader); |
| 47 | |
| 48 | if (toml.hasErrors()) { |
| 49 | String error = |
| 50 | toml.errors().stream().map(TomlParseError::toString).collect(Collectors.joining("\n")); |
| 51 | |
| 52 | throw new ConfigException(error); |
| 53 | } |
| 54 | } catch (IOException e) { |
| 55 | throw new ConfigException("Unable to read TOML.", e); |
| 56 | } catch (TomlParseError e) { |
| 57 | throw new ConfigException( |
| 58 | e.getCause() |
| 59 | + "\n Validate the config using https://www.toml-lint.com/. " |
| 60 | + "\n Refer to https://toml.io/en/ for TOML usage guidance. "); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | public static Config from(Path path) { |
| 65 | Require.nonNull("Path to read", path); |
| 66 | |
| 67 | try (Reader reader = Files.newBufferedReader(path)) { |
| 68 | return new TomlConfig(reader); |
| 69 | } catch (IOException e) { |
| 70 | throw new ConfigException(String.format("Unable to parse: %s", path), e); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | @Override |
| 75 | public Optional<List<String>> getAll(String section, String option) { |
| 76 | Require.nonNull("Section to read", section); |
| 77 | Require.nonNull("Option to read", option); |
| 78 | |
| 79 | if (!toml.contains(section)) { |
| 80 | return Optional.empty(); |
| 81 | } |
| 82 | |
| 83 | Object raw = toml.get(section); |
| 84 | if (!(raw instanceof TomlTable)) { |
| 85 | throw new ConfigException(String.format("Section %s is not a section! %s", section, raw)); |
| 86 | } |
| 87 | |
| 88 | TomlTable table = toml.getTable(section); |
| 89 | Object value = null; |
| 90 | if (table != null) { |
| 91 | value = table.get(option); |
| 92 | } |
| 93 | |
| 94 | if (value == null) { |
| 95 | return Optional.empty(); |
| 96 | } |
| 97 |
nothing calls this directly
no outgoing calls
no test coverage detected