Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleCommandLineUtils.java
    /**
     * Merges multiple configuration sources by priority. The merge order is as follows, from high to low:
     * 1) Command line arguments
     * 2) Properties passed as key=value pairs via command line
     * 3) Configuration files
     * 4) Default values set by tool scripts
     */
    public static Map<String, Object> mergeByPriority(OptionSet options, OptionSpec<String> configOpt, OptionSpec<String> propertyOpt, Map<String, Object> overrides, Map<String, Object> defaultMap) throws IOException {
        Map<String, Object> map = new HashMap<>();

        if (defaultMap != null) {
            map.putAll(defaultMap);
        }
        if (configOpt != null && options.has(configOpt)) {
            map.putAll(Utils.propsToMap(
                Utils.loadProps(options.valueOf(configOpt)))
            );
        }
        if (propertyOpt != null && options.has(propertyOpt)) {
            map.putAll(Utils.propsToMap(
                parseKeyValueArgs(options.valuesOf(propertyOpt)))
            );
        }
        if (overrides != null) {
            map.putAll(overrides);
        }

        return map;
    }

    /**
     * Merge the option into {@code map} for the given {@code key}, using the following precedence, from highest to lowest:
     * 1) Merge an option value into the map if present
     * 2) Use the default value {@code defaultValue} if specified
     * 3) Otherwise, do nothing
     */
     public static void maybeMergeOption(OptionSet options, Map<String, Object> map, String key, OptionSpec<?> spec, Object defaultValue)
    {
        Object value = null;
        if (options.has(spec)) {
            value = options.valueOf(spec);
            // This can also be null. For example, --compression-codec specified without a value, and with no default value set in the option as we as for default value passed to the method
			if (value == null && defaultValue == null) {
				System.err.println("No value specified for option \"" + key + "\" and no default value provided.");
				Exit.exit(1);
			}
        }

        if (value == null) {
            value = defaultValue;
        }

        if (value != null) {
            map.put(key, value);
        }
    }

...