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

io.knowledgelinks.cicd.semantic.versioning.config.ConfigutationWriter Maven / Gradle / Ivy

package io.knowledgelinks.cicd.semantic.versioning.config;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import io.knowledgelinks.cicd.semantic.versioning.api.BuildInfoBuilder;
import io.knowledgelinks.cicd.semantic.versioning.exceptions.SemanticVersioningException;

/**
 * Utility methods to write the configuration information to the ReadMe and configuration files
 * 
 * @author mstabile75
 *
 */
public class ConfigutationWriter {

  private ConfigutationWriter() {
    // static class
  }

  /**
   * Writes the Configuration Documentation to a file. This is used to easily keep the configuration
   * documentation up to date.
   * 
   * @param  config                      the configuration instance to use
   * @throws IOException                 thrown when unable to create the file
   * @throws SemanticVersioningException Thrown when unable to generate the file data
   */
  public static void writeConfigurationDocumentationFile(Configuration config)
      throws IOException, SemanticVersioningException {
    writeFile(createConfigurationDocumentation(config), Globals.CONFIGURATION_DOCUMENTATION_FILE,
        config.getWorkingDirectory(), true);
  }

  /**
   * Creates the configuration documentation markdown contents and returns the data as a string.
   * 
   * @param  config                      the configuration instance to use
   * @return                             the markdown configuration information
   * @throws SemanticVersioningException thrown when unable to create the markdown
   */
  public static String createConfigurationDocumentation(Configuration config)
      throws SemanticVersioningException {
    List data = new ArrayList<>();
    data.add("# Configuration");
    data.add("");
    data.add(String.join(" ",
        new String[] {"The application may be configured at runtime using java system properties,",
            "environment variables, a properties file, or command-line arguments. Below we detail",
            "the available configuration options.", System.lineSeparator()}));
    data.add("## Standard Configuration");
    getBuildInfoFields().forEach(field -> {
      data.add("");
      data.addAll(getFieldDoc(field, false, false));
    });
    data.add("");
    data.add("## Advanced Configuration");
    getConfigurationFields(config).forEach(field -> {
      data.add("");
      data.addAll(getFieldDoc(field, true, true));
    });
    return String.join(System.lineSeparator(), data);
  }

  /**
   * Takes the field and returns the markdown lines to represent the field in the documentation.
   * 
   * @param  field      the ConfigDescriptor of the configurable field
   * @param  withHeader True will add the SEMANTIC_VERSIONING header to the env variable
   * @param  sysProp    True will add the system property as an option
   * @return            list of lines
   */
  private static List getFieldDoc(ConfigDescriptor field, boolean withHeader,
      boolean sysProp) {



    List doc = new ArrayList<>();
    doc.add(String.format("**%s**: *%s*", field.getFieldName(), field.getDescription()));
    doc.add("");
    doc.add(String.format("- ***Default Value***: %s", field.getDefaultValue()));
    String options = field.getOptions();
    if (options != null) {
      doc.add(String.format("- ***Options***: %s", options));
    }
    if (sysProp) {
      doc.add(
          String.format("- ***Property file or System Property***: %s", field.getPropertyName()));
    }
    doc.add(String.format("- ***Env/ConfigMap***: %s", field.getEnvName(withHeader)));

    return doc;
  }

  /**
   * Writes a sample environment file in the working directory. If the file already exists it will
   * throw an SemanticVersioning Exception.
   * 
   * @param  config                      the configuration instance to use
   * @throws IllegalArgumentException    exception
   * @throws IllegalAccessException      exception
   * @throws IOException                 exception
   * @throws SemanticVersioningException exception
   */
  public static void writeEnvironmentFile(Configuration config) throws IllegalArgumentException,
      IllegalAccessException, IOException, SemanticVersioningException {
    List data = new ArrayList<>();
    List allConfigFields = new ArrayList<>();
    allConfigFields.addAll(getBuildInfoFields());
    allConfigFields.addAll(getConfigurationFields(config));

    allConfigFields.stream().forEach(item -> {
      data.add(String.format("# %s", item.getDescription()));
      data.add(item.getEnvFileValue());
      data.add("");
    });
    // remove the last blank line
    data.remove(data.size() - 1);
    String fileData = String.join(System.lineSeparator(), data);
    writeFile(fileData, Globals.ENVIRONMENT_FILE_WRITE_NAME, config.getWorkingDirectory(), false);
  }

  /**
   * Writes a sample environment file in the working directory. If the file already exists it will
   * throw an SemanticVersioning Exception.
   * 
   * @param  config                      the configuration instance to use
   * @throws IllegalArgumentException    exception
   * @throws IllegalAccessException      exception
   * @throws IOException                 exception
   * @throws SemanticVersioningException exception
   */
  public static void writePropertiesFile(Configuration config) throws IllegalArgumentException,
      IllegalAccessException, IOException, SemanticVersioningException {
    List data = new ArrayList<>();
    List allConfigFields = new ArrayList<>();
    allConfigFields.addAll(getBuildInfoFields());
    allConfigFields.addAll(getConfigurationFields(config));

    allConfigFields.stream().forEach(item -> {
      data.add(String.format("# %s", item.getDescription()));
      data.add(item.getPropertiesFileValue());
      data.add("");
    });
    // remove the last blank line
    data.remove(data.size() - 1);
    String fileData = String.join(System.lineSeparator(), data);
    writeFile(fileData, Globals.PROPERTIES_FILE_WRITE_NAME, config.getWorkingDirectory(), false);
  }

  /**
   * Writes the supplied data to a file
   * 
   * @param  data                        The data to write
   * @param  filename                    the name of the file to write
   * @param  directory                   The directory to write the file
   * @param  overwrite                   True will overwrite an existing file, false will throw a
   *                                     {@link SemanticVersioningException}
   * @throws IOException                 exception
   * @throws SemanticVersioningException exception
   */
  public static void writeFile(String data, String filename, String directory, boolean overwrite)
      throws IOException, SemanticVersioningException {
    File writeFile = new File(String.join(File.separator, directory, filename));
    if (!overwrite && writeFile.exists()) {
      throw new SemanticVersioningException(
          String.format("You must remove the existing file prior to writing file: %s", writeFile));
    }
    System.out.println(String.format("Writing file: %s", writeFile)); // NOPMD intended commandline
    try (FileWriter fileWriter = new FileWriter(writeFile)) {
      fileWriter.write(data);
    }
  }

  private static List getBuildInfoFields() throws SemanticVersioningException {
    return Arrays.stream(new BuildInfoBuilder().getConfigurableFieldsArray())
        .collect(Collectors.toList());
  }

  private static List getConfigurationFields(Configuration config) {
    return Arrays.stream(config.configurableFieldsArray).collect(Collectors.toList());
  }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy