All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.yin.flags.MapParser Maven / Gradle / Ivy

Go to download

Easy to use command-line parser, which enables you to define cmdline flags directly the class they are used in.

There is a newer version: 0.3.0-beta2
Show newest version
package com.github.yin.flags;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Parses a {@link Map} of flags and {@link String} values.
 */
public class MapParser implements Parser> {
    private static final Logger log = LoggerFactory.getLogger(GflagsParser.class);
    private final FlagIndex flags;

    public MapParser(@Nonnull FlagIndex flags) {
        this.flags = flags;
    }

    @Override
    public List parse(Map args) {
        for (Map.Entry arg : args.entrySet()) {
            next(arg.getKey(), arg.getValue());
        }
        return Collections.EMPTY_LIST;
    }

    protected void next(String key, String value) {
        Collection flagsByName = flags.byName().get(key);
        if (flagsByName.size() == 1) {
            flagsByName.iterator().next().flag().parse(value);
        } else if (flagsByName.isEmpty()) {
            errorUnknownFlag(key);
        } else {
            errorAmbigousFlag(key, flagsByName);
        }
    }

    protected void errorUnknownFlag(String flag) {
        log.error("Unknown flag: {}", flag);
    }

    protected void errorAmbigousFlag(String flag, Collection flagsByName) {
        log.error("Flag {} resolves in multiple classes: {}", flag,
                flagsByName.stream().map(meta -> meta.flagID()).toArray());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy