ConfigCLI.java

package org.docascode.config;

import org.docascode.git.ConfigCtrl;
import org.docascode.utils.DocAsCodeRepository;
import org.docascode.utils.DocAsCodeRepository.ConfigLevel;
import org.docascode.utils.ExitCode;
import org.docascode.utils.Utils;
import org.eclipse.jgit.errors.ConfigInvalidException;
import picocli.CommandLine;

import java.io.File;
import java.io.IOException;

@CommandLine.Command(name = "config")
public class ConfigCLI implements Runnable {
    @CommandLine.Option(names = "--system", description  = "For writing options: write to system-wide $(prefix)/etc/gitconfig rather than the repository .git/config." )
    private boolean system;

    @CommandLine.Option(names = "--global", description = "For writing options: write to global ~/.gitconfig file rather than the repository .git/config")
    private boolean global;

    @CommandLine.Option(names = "--local", description = "For writing options: write to local .git/config file. This is the default behavior.")
    private boolean local;

    @CommandLine.Option(names = "--project", description = "For writing options: write to local .docascode/config file. This file is shared by developpers.")
    private boolean project;

    @CommandLine.Option(names = "--get", description = "Get the value for a given key")
    private boolean get;

    @CommandLine.Option(names = "--add", description = "Add the value for a given key")
    private boolean add;

    @CommandLine.Parameters(index = "0", arity = "0..1", description = "The key to get or set.")
    private String key;

    @CommandLine.Parameters(index = "1", arity = "0..1", description = "For writing options: the value to set")
    private String value;

    public void run() {
        DocAsCodeRepository repository = new DocAsCodeRepository(new File("."));
        ConfigCtrl configCtrl = new ConfigCtrl(repository);
        ConfigLevel level = ConfigLevel.LOCAL;
        if (project) {level = ConfigLevel.PROJECT;}
        if (global) {level = ConfigLevel.GLOBAL;}
        if (system) {level = ConfigLevel.SYSTEM;}
        String subsection=null;
        String name=null;
        String[] parts = key.split("\\.");
        switch (parts.length){
            case 1:
                subsection = null;
                name = parts[0];
                break;
            case 2:
                subsection = parts[0];
                name = parts[1];
                break;
            default:
                Utils.error("The variable to set must be of the form 'subsection.name' or 'name'.", ExitCode.RUNTIME_ERROR);
        }
        if (get){
            Utils.success(configCtrl.get(level,"docascode", subsection,name));
        } else
        {
            if (add){
                configCtrl.add(level,"docascode", subsection,name,value);
            }
            else {
                configCtrl.set(level,"docascode",subsection,name,value);
            }
        }
    }
}