Skip to content

ConfigSpec: checking and fixing configurations

Guillaume R edited this page May 3, 2018 · 7 revisions

Principle

NightConfig's ConfigSpec allows you to defines how your configuration should be.

Instead of checking the config values by hand with a lot of conditions, you specify what the values must be like before reading the config, then check it and correct it automatically.

Defining the spec

Create a ConfigSpec and use the define methods.

ConfigSpec spec = new ConfigSpec();
// defines an entry "key" of type String with a default value
spec.define("key", "defaultValue");

// defines an integer in range [min;max], default 0
spec.defineInRange("number", 0, min, max);

// defines an double in range [min;max], default 0.0
spec.defineInRange("number", 0.0, min, max);

// defines an entry "letter" that must be either 'a', 'b' or 'c'; default 'a'
spec.defineInList("letter", 'a', Arrays.asList('a', 'b', 'c'));

You can also use list paths and provide a custom value checker. Please read the documentation for a full list of methods.

Using the spec

Once you've defined your ConfigSpec, you can check the configuration and replace incorrect values by the default ones.

// Checks if the config respects the configuration:
boolean correct = spec.isCorrect(config);

// Corrects the configuration by using the default values where necessary:
spec.correct(config);

If you want to, for instance, print the corrections made by the spec, use correct(config, listener):

CorrectionListener listener = (action, path, incorrectValue, correctedValue) -> {
    String pathString = String.join(",", path);
    System.out.println("Corrected " + pathString + ": was " + incorrectValue + ", is now " + correctedValue);
};
int numberOfCorrections = correct(config, listener);

Try the example!

-> ConfigSpecExample.java