OptionImpl.java

/*
 * Copyright (c) 2016, Stein Eldar Johnsen
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.terminal.args.impl;

import net.morimekta.terminal.args.ArgException;
import net.morimekta.terminal.args.Option;

import java.util.List;
import java.util.function.Consumer;

import static java.util.Locale.US;
import static java.util.Objects.requireNonNull;
import static net.morimekta.strings.NamingUtil.splitNameSource;

/**
 * Named option that for each invocation takes a single argument value,
 * either the next argument, or from the same argument after a '='
 * delimiter.
 */
public class OptionImpl extends BaseOption implements Option {
    public static class BuilderImpl implements Option.Builder {
        private final String           name;
        private final String           shortNames;
        private final String           usage;
        private final Consumer<String> consumer;
        private       String           metaVar;
        private       String           defaultValue;
        private       boolean          repeated;
        private       boolean          required;
        private       boolean          hidden;

        public BuilderImpl(String name, String shortNames, String usage, Consumer<String> consumer) {
            this.name = name;
            this.shortNames = shortNames;
            this.usage = usage;
            this.consumer = requireNonNull(consumer, "consumer == null");
            if (shortNames != null) {
                this.metaVar = String.valueOf(shortNames.charAt(0)).toUpperCase(US);
            } else {
                var list = splitNameSource(name);
                this.metaVar = list.get(list.size() - 1).toUpperCase(US);
            }
        }

        @Override
        public Option build() {
            return new OptionImpl(name, shortNames, metaVar, usage, consumer, defaultValue, repeated, required, hidden);
        }

        @Override
        public BuilderImpl metaVar(String metaVar) {
            this.metaVar = metaVar;
            return this;
        }

        @Override
        public BuilderImpl defaultValue(Object object) {
            this.defaultValue = String.valueOf(object);
            return this;
        }

        @Override
        public BuilderImpl repeated() {
            this.repeated = true;
            return this;
        }

        @Override
        public BuilderImpl required() {
            this.required = true;
            return this;
        }

        @Override
        public BuilderImpl hidden() {
            this.hidden = true;
            return this;
        }
    }

    @Override
    public int applyShort(String opts, List<String> args) {
        if (applied && !isRepeated()) {
            throw new ArgException("Option %s already applied", nameOrShort());
        }
        applied = true;

        if (opts.length() == 1) {
            if (args.size() > 1) {
                setter.accept(args.get(1));
            } else {
                throw new ArgException("Missing value after -%s", opts);
            }
            return 2;
        } else {
            String value = opts.substring(1);
            setter.accept(value);
            return 1;
        }
    }

    @Override
    public void validate() throws ArgException {
        if (isRequired() && !applied) {
            throw new ArgException("Option %s is required", nameOrShort());
        }
    }

    @Override
    public int apply(List<String> args) throws ArgException {
        if (applied && !isRepeated()) {
            throw new ArgException("Option %s already applied", nameOrShort());
        }
        if (getName() == null) {
            throw new IllegalStateException("No long option for -[" + getShortNames() + "]");
        }
        applied = true;

        String current = args.get(0);
        if (current.startsWith(getName() + "=")) {
            String value = current.substring(getName().length() + 1);
            setter.accept(value);
            return 1;
        } else if (current.equals(getName())) {
            if (args.size() < 2) {
                throw new ArgException("Missing value after %s", getName());
            }
            setter.accept(args.get(1));
            return 2;
        } else {
            throw new IllegalArgumentException("Argument not matching option " + nameOrShort() + ": " + current);
        }
    }

    private final Consumer<String> setter;

    private boolean applied = false;

    private OptionImpl(String name,
                       String shortNames,
                       String metaVar,
                       String usage,
                       Consumer<String> setter,
                       String defaultValue,
                       boolean repeated,
                       boolean required,
                       boolean hidden) {
        super(name, shortNames, metaVar, usage, defaultValue, repeated, required, hidden);
        this.setter = setter;
    }
}