Package hudson

Examples of hudson.EnvVars


     */
    public Map<String,String> getEnvVars() {
        try {
            return getEnvironment();
        } catch (IOException e) {
            return new EnvVars();
        } catch (InterruptedException e) {
            return new EnvVars();
        }
    }
View Full Code Here


     *
     * @return the map with the environmental variables. Never <code>null</code>.
     * @since 1.305
     */
    public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
        EnvVars env = getCharacteristicEnvVars();
        Computer c = Computer.currentComputer();
        if (c!=null)
            env = c.getEnvironment().overrideAll(env);
        String rootUrl = Jenkins.getInstance().getRootUrl();
        if(rootUrl!=null) {
            env.put("JENKINS_URL", rootUrl);
            env.put("HUDSON_URL", rootUrl); // Legacy compatibility
            env.put("BUILD_URL", rootUrl+getUrl());
            env.put("JOB_URL", rootUrl+getParent().getUrl());
        }
       
        env.put("JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath() );
        env.put("HUDSON_HOME", Jenkins.getInstance().getRootDir().getPath() );   // legacy compatibility

        Thread t = Thread.currentThread();
        if (t instanceof Executor) {
            Executor e = (Executor) t;
            env.put("EXECUTOR_NUMBER",String.valueOf(e.getNumber()));
      if(e.getOwner() instanceof MasterComputer) {
    env.put("NODE_NAME", "master");
      } else {
        env.put("NODE_NAME",e.getOwner().getName());
      }
            Node n = e.getOwner().getNode();
            if (n!=null)
                env.put("NODE_LABELS",Util.join(n.getAssignedLabels()," "));
        }

        for (EnvironmentContributor ec : EnvironmentContributor.all())
            ec.buildEnvironmentFor(this,env,log);

View Full Code Here

    /**
     * Builds up the environment variable map that's sufficient to identify a process
     * as ours. This is used to kill run-away processes via {@link ProcessTree#killAll(Map)}.
     */
    public final EnvVars getCharacteristicEnvVars() {
        EnvVars env = new EnvVars();
        env.put("JENKINS_SERVER_COOKIE",Util.getDigestOf("ServerID:"+ Jenkins.getInstance().getSecretKey()));
        env.put("HUDSON_SERVER_COOKIE",Util.getDigestOf("ServerID:"+ Jenkins.getInstance().getSecretKey())); // Legacy compatibility
        env.put("BUILD_NUMBER",String.valueOf(number));
        env.put("BUILD_ID",getId());
        env.put("BUILD_TAG","jenkins-"+getParent().getFullName().replace('/', '-')+"-"+number);
        env.put("JOB_NAME",getParent().getFullName());
        return env;
    }
View Full Code Here

                .println(
                    "Build did not succeed and the project is configured to only push after a successful build, so no pushing will occur.");
            return true;
        } else {
            final String gitExe = gitSCM.getGitExe(build.getBuiltOn(), listener);
            EnvVars tempEnvironment;
            try {
                tempEnvironment = build.getEnvironment(listener);
            } catch (IOException e) {
                listener.error("IOException publishing in git plugin");
                tempEnvironment = new EnvVars();
            }

            String confName = gitSCM.getGitConfigNameToUse();
            if (StringUtils.isNotBlank(confName)) {
                tempEnvironment.put(GitConstants.GIT_COMMITTER_NAME_ENV_VAR, confName);
                tempEnvironment.put(GitConstants.GIT_AUTHOR_NAME_ENV_VAR, confName);
            }
            String confEmail = gitSCM.getGitConfigEmailToUse();
            if (StringUtils.isNotBlank(confEmail)) {
                tempEnvironment.put(GitConstants.GIT_COMMITTER_EMAIL_ENV_VAR, confEmail);
                tempEnvironment.put(GitConstants.GIT_AUTHOR_EMAIL_ENV_VAR, confEmail);
            }

            final EnvVars environment = tempEnvironment;
            final FilePath workingDirectory = gitSCM.workingDirectory(workspacePath);

            boolean pushResult = true;
            // If we're pushing the merge back...
            if (pushMerge) {
                boolean mergeResult;
                try {
                    mergeResult = workingDirectory.act(new FileCallable<Boolean>() {
                        private static final long serialVersionUID = 1L;

                        public Boolean invoke(File workspace,
                                              VirtualChannel channel) throws IOException {

                            IGitAPI git = new GitAPI(
                                gitExe, new FilePath(workspace),
                                listener, environment);
                            // We delete the old tag generated by the SCM plugin
                            String tagName = new StringBuilder()
                                .append(GitConstants.INTERNAL_TAG_NAME_PREFIX)
                                .append(GitConstants.HYPHEN_SYMBOL)
                                .append(projectName)
                                .append(GitConstants.HYPHEN_SYMBOL)
                                .append(buildNumber)
                                .toString();

                            git.deleteTag(tagName);

                            // And add the success / fail state into the tag.
                            tagName += "-" + buildResult.toString();

                            git.tag(tagName, GitConstants.INTERNAL_TAG_COMMENT_PREFIX + buildNumber);

                            PreBuildMergeOptions mergeOptions = gitSCM.getMergeOptions();

                            if (mergeOptions.doMerge() && buildResult.isBetterOrEqualTo(
                                Result.SUCCESS)) {
                                RemoteConfig remote = mergeOptions.getMergeRemote();
                                listener.getLogger().println(new StringBuilder().append("Pushing result ")
                                    .append(tagName)
                                    .append(" to ")
                                    .append(mergeOptions.getMergeTarget())
                                    .append(" branch of ")
                                    .append(remote.getName())
                                    .append(" repository")
                                    .toString());

                                git.push(remote, "HEAD:" + mergeOptions.getMergeTarget());
//                            } else {
                                //listener.getLogger().println("Pushing result " + buildnumber + " to origin repository");
                                //git.push(null);
                            }

                            return true;
                        }
                    });
                } catch (Throwable e) {
                    listener.error("Failed to push merge to origin repository: " + e.getMessage());
                    build.setResult(Result.FAILURE);
                    mergeResult = false;

                }

                if (!mergeResult) {
                    pushResult = false;
                }
            }
            if (isPushTags()) {
                boolean allTagsResult = true;
                for (final TagToPush t : tagsToPush) {
                    boolean tagResult = true;
                    if (t.getTagName() == null) {
                        listener.getLogger().println("No tag to push defined");
                        tagResult = false;
                    }
                    if (t.getTargetRepoName() == null) {
                        listener.getLogger().println("No target repo to push to defined");
                        tagResult = false;
                    }
                    if (tagResult) {
                        final String tagName = environment.expand(t.getTagName());
                        final String targetRepo = environment.expand(t.getTargetRepoName());

                        try {
                            tagResult = workingDirectory.act(new FileCallable<Boolean>() {
                                private static final long serialVersionUID = 1L;

                                public Boolean invoke(File workspace,
                                                      VirtualChannel channel) throws IOException {

                                    IGitAPI git = new GitAPI(gitExe, new FilePath(workspace),
                                        listener, environment);

                                    RemoteConfig remote = gitSCM.getRepositoryByName(targetRepo);

                                    if (remote == null) {
                                        listener.getLogger()
                                            .println("No repository found for target repo name " + targetRepo);
                                        return false;
                                    }

                                    if (t.isCreateTag()) {
                                        if (git.tagExists(tagName)) {
                                            listener.getLogger()
                                                .println("Tag " + tagName
                                                    + " already exists and Create Tag is specified, so failing.");
                                            return false;
                                        }
                                        git.tag(tagName, "Hudson Git plugin tagging with " + tagName);
                                    } else if (!git.tagExists(tagName)) {
                                        listener.getLogger()
                                            .println("Tag " + tagName
                                                + " does not exist and Create Tag is not specified, so failing.");
                                        return false;
                                    }

                                    listener.getLogger().println("Pushing tag " + tagName + " to repo "
                                        + targetRepo);
                                    git.push(remote, tagName);

                                    return true;
                                }
                            });
                        } catch (Throwable e) {
                            listener.error("Failed to push tag " + tagName + " to " + targetRepo
                                + ": " + e.getMessage());
                            build.setResult(Result.FAILURE);
                            tagResult = false;
                        }
                    }

                    if (!tagResult) {
                        allTagsResult = false;
                    }
                }
                if (!allTagsResult) {
                    pushResult = false;
                }
            }

            if (isPushBranches()) {
                boolean allBranchesResult = true;
                for (final BranchToPush b : branchesToPush) {
                    boolean branchResult = true;
                    if (b.getBranchName() == null) {
                        listener.getLogger().println("No branch to push defined");
                        return false;
                    }
                    if (b.getTargetRepoName() == null) {
                        listener.getLogger().println("No branch repo to push to defined");
                        return false;
                    }
                    final String branchName = environment.expand(b.getBranchName());
                    final String targetRepo = environment.expand(b.getTargetRepoName());

                    if (branchResult) {
                        try {
                            branchResult = workingDirectory.act(new FileCallable<Boolean>() {
                                private static final long serialVersionUID = 1L;
View Full Code Here

     * An attempt to generate at least semi-useful EnvVars for polling calls, based on previous build.
     * Cribbed from various places.
     */
    public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener)
        throws IOException, InterruptedException {
        EnvVars env;

        AbstractBuild b = (AbstractBuild) p.getLastBuild();

        if (b != null) {
            Node lastBuiltOn = b.getBuiltOn();

            if (lastBuiltOn != null) {
                env = lastBuiltOn.toComputer().getEnvironment().overrideAll(b.getCharacteristicEnvVars());
            } else {
                env = new EnvVars(System.getenv());
            }

            String rootUrl = Hudson.getInstance().getRootUrl();
            if (rootUrl != null) {
                env.put("HUDSON_URL", rootUrl);
                env.put("BUILD_URL", rootUrl + b.getUrl());
                env.put("JOB_URL", rootUrl + p.getUrl());
            }

            if (!env.containsKey("HUDSON_HOME")) {
                env.put("HUDSON_HOME", Hudson.getInstance().getRootDir().getPath());
            }

            if (ws != null) {
                env.put("WORKSPACE", ws.getRemote());
            }


            p.getScm().buildEnvVars(b, env);

            StreamBuildListener buildListener = new StreamBuildListener((OutputStream) listener.getLogger());

            for (NodeProperty nodeProperty : Hudson.getInstance().getGlobalNodeProperties()) {
                Environment environment = nodeProperty.setUp(b, launcher, (BuildListener) buildListener);
                if (environment != null) {
                    environment.buildEnvVars(env);
                }
            }

            if (lastBuiltOn != null) {
                for (NodeProperty nodeProperty : lastBuiltOn.getNodeProperties()) {
                    Environment environment = nodeProperty.setUp(b, launcher, buildListener);
                    if (environment != null) {
                        environment.buildEnvVars(env);
                    }
                }
            }

            EnvVars.resolve(env);
        } else {
            env = new EnvVars(System.getenv());
        }

        return env;
    }
View Full Code Here

        if (buildData.lastBuild != null) {
            listener.getLogger().println("Last Built Revision: " + buildData.lastBuild.revision);
        }

        EnvVars environment = build.getEnvironment(listener);

        String confName = getGitConfigNameToUse();
        if (StringUtils.isNotBlank(confName)) {
            environment.put(GitConstants.GIT_COMMITTER_NAME_ENV_VAR, confName);
            environment.put(GitConstants.GIT_AUTHOR_NAME_ENV_VAR, confName);
        }
        String confEmail = getGitConfigEmailToUse();
        if (StringUtils.isNotBlank(confEmail)) {
            environment.put(GitConstants.GIT_COMMITTER_EMAIL_ENV_VAR, confEmail);
            environment.put(GitConstants.GIT_AUTHOR_EMAIL_ENV_VAR, confEmail);
        }

        final String singleBranch = GitUtils.getSingleBranch(build, getRepositories(), getBranches());
        final String paramLocalBranch = getParamLocalBranch(build);
        Revision tempParentLastBuiltRev = null;

        if (build instanceof MatrixRun) {
            MatrixBuild parentBuild = ((MatrixRun) build).getParentBuild();
            if (parentBuild != null) {
                BuildData parentBuildData = parentBuild.getAction(BuildData.class);
                if (parentBuildData != null) {
                    tempParentLastBuiltRev = parentBuildData.getLastBuiltRevision();
                }
            }
        }

        final List<RemoteConfig> paramRepos = getParamExpandedRepos(build);

        final Revision parentLastBuiltRev = tempParentLastBuiltRev;

        final RevisionParameterAction rpa = build.getAction(RevisionParameterAction.class);

        Map<String, List<RemoteConfig>> repoMap = getRemoteConfigMap(paramRepos);

        boolean result = true;
        boolean hasChanges = false;
        for (Map.Entry<String, List<RemoteConfig>> entry : repoMap.entrySet()) {
            FilePath workingDirectory = workingDirectory(workspace);

            if (StringUtils.isNotEmpty(entry.getKey()) && !entry.getKey().equals(".")) {
                workingDirectory = workingDirectory.child(entry.getKey());
            }

            if (!workingDirectory.exists()) {
                workingDirectory.mkdirs();
            }

            List<RemoteConfig> repos = entry.getValue();
            final Revision revToBuild = gerRevisionToBuild(listener, workingDirectory, gitExe, buildData, environment,
                singleBranch, repos,
                parentLastBuiltRev, rpa);

            if (revToBuild == null) {
                // getBuildCandidates should make the last item the last build, so a re-build
                // will build the last built thing.
                listener.getLogger().println("Nothing to do");
                continue;
            }
            hasChanges = true;

            listener.getLogger().println("Commencing build of " + revToBuild);
            //TODO find how to set git commit for each repository
            environment.put(GIT_COMMIT, revToBuild.getSha1String());

            if (mergeOptions.doMerge() && !revToBuild.containsBranchName(mergeOptions.getRemoteBranchName())) {
                buildConfig = getMergedBuildConfig(listener, workingDirectory, buildNumber, gitExe, buildData,
                    environment, paramLocalBranch, revToBuild, internalTagName, internalTagComment);
                result = result && changeLogResult(buildConfig.getChangeLog(), changelogFile);
View Full Code Here

        // for whether we'd ever been built before. But I'm fixing that right now anyway.
        if (!workingDirectory.exists()) {
            return PollingResult.BUILD_NOW;
        }

        final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener);
        final List<RemoteConfig> paramRepos = getParamExpandedRepos(lastBuild);
        final String singleBranch = GitUtils.getSingleBranch(lastBuild, getRepositories(), getBranches());

        boolean pollChangesResult = workingDirectory.act(new FileCallable<Boolean>() {
            private static final long serialVersionUID = 1L;
View Full Code Here

    protected void setUp() throws Exception {
        System.setProperty("hudson.PluginStrategy", "hudson.ClassicPluginStrategy");
        super.setUp();
        workDir = createTmpDir();
        listener = new StreamTaskListener();
        envVars = new EnvVars();
        setAuthor(johnDoe);
        setCommitter(johnDoe);
        workspace = new FilePath(workDir);
        GitTool.onLoaded();
        initGit();
View Full Code Here

        for (hudson.tasks.Builder b : project.getBuilders()) {
            if (b instanceof CaptureEnvironmentBuilder) {
                return ((CaptureEnvironmentBuilder) b).getEnvVars();
            }
        }
        return new EnvVars();
    }
View Full Code Here

      JDK jdk,
      SettingsProvider settings,
      GlobalSettingsProvider globalSettings,
      boolean usesLocalRepository) throws IOException, InterruptedException {
    MavenModuleSet mavenModuleProject = sonarPublisher.getMavenProject(build);
    EnvVars envVars = build.getEnvironment(listener);
    /**
     * MAVEN_OPTS
     */
    String mvnOptions = sonarPublisher.getMavenOpts();
    if (StringUtils.isEmpty(mvnOptions)
      && mavenModuleProject != null
      && StringUtils.isNotEmpty(mavenModuleProject.getMavenOpts())) {
      mvnOptions = mavenModuleProject.getMavenOpts();
    }
    // Private Repository and Alternate Settings
    LocalRepositoryLocator locaRepositoryToUse = usesLocalRepository ? new PerJobLocalRepositoryLocator() : new DefaultLocalRepositoryLocator();
    SettingsProvider settingsToUse = settings;
    GlobalSettingsProvider globalSettingsToUse = globalSettings;
    if (mavenModuleProject != null) {
      // If we are on a Maven job then take values from the job itself
      locaRepositoryToUse = mavenModuleProject.getLocalRepository();
      settingsToUse = mavenModuleProject.getSettings();
      globalSettingsToUse = mavenModuleProject.getGlobalSettings();
    }
    // Other properties
    String installationProperties = sonarInstallation.getAdditionalProperties();
    String jobProperties = envVars.expand(sonarPublisher.getJobAdditionalProperties());
    String aditionalProperties = ""
      + (StringUtils.isNotBlank(installationProperties) ? installationProperties : "") + " "
      + (StringUtils.isNotBlank(jobProperties) ? jobProperties : "");
    // Execute Maven
    // SONARPLUGINS-487
View Full Code Here

TOP

Related Classes of hudson.EnvVars

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.