<commit_before>/*
 * The MIT License
 *
 * Copyright (c) 2014, <NAME>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.jenkinsci.plugins.SemanticVersioning;

import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.TaskListener;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.util.FormValidation;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jenkinsci.plugins.SemanticVersioning.parsing.*;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

public class SemanticVersionBuildWrapper extends BuildWrapper {
    private static final String DEFAULT_ENVIRONMENT_VARIABLE_NAME = "SEMANTIC_APP_VERSION";
    private static final String MISSING_BUILD_NUMBER = "-1";
    private String environmentVariableName = DEFAULT_ENVIRONMENT_VARIABLE_NAME;
    private static Logger logger = LogManager.getLogger(AppVersion.class);

    @DataBoundConstructor
    public SemanticVersionBuildWrapper(String environmentVariableName) {
        logger.info("### SemanticVersionBuildWrapper");
        this.environmentVariableName = environmentVariableName;
    }

    /**
     * Used from <tt>config.jelly</tt>.
     * @return the value of the environment variable name to be used.
     */
    public String getEnvironmentVariableName() {
        logger.info("### SemanticVersionBuildWrapper::getEnvironmentVariableName");
        return this.environmentVariableName;
    }

    /**
     * Used from <tt>config.jelly</tt>.
     * @return the name of the file in which the semantic version will be stored.
     */
    public String getSemanticVersionFilename() {
        return ".semanticVersion";
    }

    @Override
    public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) {
        logger.debug("### SemanticVersionBuildWrapper::setUp");
        AppVersion appVersion = getAppVersion(build);
        String buildNumber = getJenkinsBuildNumber(build);

        appVersion.setBuild(Integer.parseInt(buildNumber));

        logger.debug("### SemanticVersionBuildWrapper::setUp -> appVersion found to be: {" + getEnvironmentVariableName() + ": " + appVersion.getOriginal() + ", buildNumber: " + buildNumber + ", combined: " + appVersion.toString() + "}\n");

        final String reportedVersion = appVersion.toString();

        writeVersionToFile(build, reportedVersion);

        return new Environment() {
            @Override
            public void buildEnvVars(Map<String, String> env) {
                env.put(getEnvironmentVariableName(), reportedVersion);
            }
        };
    }

    private void writeVersionToFile(AbstractBuild build, String reportedVersion) {
        String filename = getSemanticVersionFilename();
        if(filename != null && filename.length() > 0) {
            File file = new File(build.getArtifactsDir() + "/" + filename);
            logger.info(build.getArtifactsDir() + "/" + filename);
            try {
                FileUtils.writeStringToFile(file, reportedVersion + "\n");
            } catch (IOException e) {
                logger.debug("Exception writing version to file: " + e);
            }
        }
    }

    private AppVersion getAppVersion(AbstractBuild build) {
        logger.debug("### SemanticVersionBuildWrapper::getAppVersion");
        AppVersion appVersion = AppVersion.EmptyVersion;
        FilePath workspace = build.getWorkspace();

        Collection<BuildDefinitionParser> parsers = new ArrayList<BuildDefinitionParser>();
        parsers.add(new PomParser(workspace + "/pom.xml"));
        parsers.add(new BuildScalaParser(workspace + "/project/Build.scala"));
        parsers.add(new SbtParser(workspace + "/build.sbt"));

        for(BuildDefinitionParser parser : parsers) {
            try {
                logger.debug("### SemanticVersionBuildWrapper::getAppVersion -> attempting to parse using " + parser.getClass().getSimpleName());
                appVersion = parser.extractAppVersion();
                return appVersion;
            } catch (IOException e) {
                logger.error("EXCEPTION: " + e);
            } catch (InvalidBuildFileFormatException e) {
                logger.error("EXCEPTION: " + e);
            }
        }

        return appVersion;
    }

    private String getJenkinsBuildNumber(AbstractBuild build) {
        logger.debug("### SemanticVersionBuildWrapper::getJenkinsBuildNumber");
        EnvVars environmentVariables = null;
        try {
            environmentVariables = build.getEnvironment(TaskListener.NULL);
        } catch (IOException e) {
            logger.error("EXCEPTION: " + e);
        } catch (InterruptedException e) {
            logger.error("EXCEPTION: " + e);
        }
        return environmentVariables != null ? environmentVariables.get("BUILD_NUMBER", MISSING_BUILD_NUMBER) : MISSING_BUILD_NUMBER;
    }

    public static final DescriptorImpl descriptor = new DescriptorImpl();

    @Override
    public BuildWrapperDescriptor getDescriptor() {
        return descriptor;
    }

    /**
     * descriptor for {@link SemanticVersionBuildWrapper}. Used as a singleton.
     * The class is marked as public so that it can be accessed from views.
     * See <tt>src/main/resources/hudson/plugins/hello_world/SbtVersionExtracter/*.jelly</tt>
     * for the actual HTML fragment for the configuration screen.
     */
    @Extension // This indicates to Jenkins that this is an implementation of an extension point.
    public static final class DescriptorImpl extends BuildWrapperDescriptor {

        /**
         * In order to load the persisted global configuration, you have to
         * call load() in the constructor.
         */
        public DescriptorImpl() {
            super(SemanticVersionBuildWrapper.class);
            logger.debug("### DescriptorImpl");
            load();
        }

        /**
         * This human readable name is used in the configuration screen.
         * @return the display name for the plugin
         */
        public String getDisplayName() {
            logger.debug("### DescriptorImpl::getDisplayName");
            return "Determine Semantic Version for project.";
        }
<commit_msg>Fixing a problem of the property value not being stored the way it should be<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2014, <NAME>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.jenkinsci.plugins.SemanticVersioning;

import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.TaskListener;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.util.FormValidation;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jenkinsci.plugins.SemanticVersioning.parsing.*;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

public class SemanticVersionBuildWrapper extends BuildWrapper {
    private static final String DEFAULT_ENVIRONMENT_VARIABLE_NAME = "SEMANTIC_APP_VERSION";
    private static final String MISSING_BUILD_NUMBER = "-1";
    private String environmentVariableName = DEFAULT_ENVIRONMENT_VARIABLE_NAME;
    private static Logger logger = LogManager.getLogger(AppVersion.class);

    @DataBoundConstructor
    public SemanticVersionBuildWrapper(String environmentVariableName) {
        logger.info("### SemanticVersionBuildWrapper");
        this.environmentVariableName = environmentVariableName;
    }

    /**
     * Used from <tt>config.jelly</tt>.
     * @return the value of the environment variable name to be used.
     */
    public String getEnvironmentVariableName() {
        logger.info("### SemanticVersionBuildWrapper::getEnvironmentVariableName");
        return this.environmentVariableName;
    }

    /**
     * Used from <tt>config.jelly</tt>.
     * @return the name of the file in which the semantic version will be stored.
     */
    public String getSemanticVersionFilename() {
        return ".semanticVersion";
    }

    @Override
    public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) {
        logger.debug("### SemanticVersionBuildWrapper::setUp");
        AppVersion appVersion = getAppVersion(build);
        String buildNumber = getJenkinsBuildNumber(build);

        appVersion.setBuild(Integer.parseInt(buildNumber));

        logger.debug("### SemanticVersionBuildWrapper::setUp -> appVersion found to be: {" + getEnvironmentVariableName() + ": " + appVersion.getOriginal() + ", buildNumber: " + buildNumber + ", combined: " + appVersion.toString() + "}\n");

        final String reportedVersion = appVersion.toString();

        writeVersionToFile(build, reportedVersion);

        return new Environment() {
            @Override
            public void buildEnvVars(Map<String, String> env) {
                env.put(getEnvironmentVariableName(), reportedVersion);
            }
        };
    }

    private void writeVersionToFile(AbstractBuild build, String reportedVersion) {
        String filename = getSemanticVersionFilename();
        if(filename != null && filename.length() > 0) {
            File file = new File(build.getArtifactsDir() + "/" + filename);
            logger.info(build.getArtifactsDir() + "/" + filename);
            try {
                FileUtils.writeStringToFile(file, reportedVersion + "\n");
            } catch (IOException e) {
                logger.debug("Exception writing version to file: " + e);
            }
        }
    }

    private AppVersion getAppVersion(AbstractBuild build) {
        logger.debug("### SemanticVersionBuildWrapper::getAppVersion");
        AppVersion appVersion = AppVersion.EmptyVersion;
        FilePath workspace = build.getWorkspace();

        Collection<BuildDefinitionParser> parsers = new ArrayList<BuildDefinitionParser>();
        parsers.add(new PomParser(workspace + "/pom.xml"));
        parsers.add(new BuildScalaParser(workspace + "/project/Build.scala"));
        parsers.add(new SbtParser(workspace + "/build.sbt"));

        for(BuildDefinitionParser parser : parsers) {
            try {
                logger.debug("### SemanticVersionBuildWrapper::getAppVersion -> attempting to parse using " + parser.getClass().getSimpleName());
                appVersion = parser.extractAppVersion();
                return appVersion;
            } catch (IOException e) {
                logger.error("EXCEPTION: " + e);
            } catch (InvalidBuildFileFormatException e) {
                logger.error("EXCEPTION: " + e);
            }
        }

        return appVersion;
    }

    private String getJenkinsBuildNumber(AbstractBuild build) {
        logger.debug("### SemanticVersionBuildWrapper::getJenkinsBuildNumber");
        EnvVars environmentVariables = null;
        try {
            environmentVariables = build.getEnvironment(TaskListener.NULL);
        } catch (IOException e) {
            logger.error("EXCEPTION: " + e);
        } catch (InterruptedException e) {
            logger.error("EXCEPTION: " + e);
        }
        return environmentVariables != null ? environmentVariables.get("BUILD_NUMBER", MISSING_BUILD_NUMBER) : MISSING_BUILD_NUMBER;
    }

    @Extension
    public static final DescriptorImpl descriptor = new DescriptorImpl();

    @Override
    public BuildWrapperDescriptor getDescriptor() {
        return descriptor;
    }

    /**
     * descriptor for {@link SemanticVersionBuildWrapper}. Used as a singleton.
     * The class is marked as public so that it can be accessed from views.
     * See <tt>src/main/resources/hudson/plugins/hello_world/SbtVersionExtracter/*.jelly</tt>
     * for the actual HTML fragment for the configuration screen.
     */
    public static final class DescriptorImpl extends BuildWrapperDescriptor {

        /**
         * In order to load the persisted global configuration, you have to
         * call load() in the constructor.
         */
        public DescriptorImpl() {
            super(SemanticVersionBuildWrapper.class);
            logger.debug("### DescriptorImpl");
            load();
        }

        /**
         * This human readable name is used in the configuration screen.
         * @return the display name for the plugin
         */
        public String getDisplayName() {
            logger.debug("### DescriptorImpl::getDisplayName");
            return "Determine Semantic Version for project";
        }

{'fraction_non_alphanumeric': 0.09170731707317073, 'fraction_numerical': 0.001040650406504065, 'mean_word_length': 3.1478284326949018, 'pattern_counts': {'":': 2, '<': 23, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5221532', 'n_tokens_mistral': 3980, 'n_tokens_neox': 3818, 'n_words': 1151}