示例#1
0
  public SlackService newSlackService(AbstractBuild r, BuildListener listener) {
    String teamDomain = this.teamDomain;
    if (StringUtils.isEmpty(teamDomain)) {
      teamDomain = getDescriptor().getTeamDomain();
    }
    String authToken = this.authToken;
    if (StringUtils.isEmpty(authToken)) {
      authToken = getDescriptor().getToken();
    }
    String room = this.room;
    if (StringUtils.isEmpty(room)) {
      room = getDescriptor().getRoom();
    }

    EnvVars env = null;
    try {
      env = r.getEnvironment(listener);
    } catch (Exception e) {
      listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
      env = new EnvVars();
    }
    teamDomain = env.expand(teamDomain);
    authToken = env.expand(authToken);
    room = env.expand(room);

    return new StandardSlackService(teamDomain, authToken, room);
  }
  private void addArgsTo(
      ArgumentListBuilder args,
      SonarInstallation sonarInst,
      EnvVars env,
      Map<String, String> props) {
    args.add("begin");

    args.add("/k:" + env.expand(projectKey) + "");
    args.add("/n:" + env.expand(projectName) + "");
    args.add("/v:" + env.expand(projectVersion) + "");

    // expand macros using itself
    EnvVars.resolve(props);

    for (Map.Entry<String, String> e : props.entrySet()) {
      if (!StringUtils.isEmpty(e.getValue())) {
        // expand macros using environment variables and hide passwords/tokens
        boolean hide =
            e.getKey().contains("password")
                || (!StringUtils.isEmpty(sonarInst.getServerAuthenticationToken())
                    && e.getKey().contains("login"));
        args.addKeyValuePair("/d:", e.getKey(), env.expand(e.getValue()), hide);
      }
    }

    args.add(sonarInst.getAdditionalAnalysisPropertiesWindows());
    args.addTokenized(sonarInst.getAdditionalProperties());
    args.addTokenized(additionalArguments);
  }
示例#3
0
 public HygieiaService newHygieiaService(AbstractBuild r, BuildListener listener) {
   String hygieiaAPIUrl = getDescriptor().getHygieiaAPIUrl();
   String hygieiaToken = getDescriptor().getHygieiaToken();
   String hygieiaJenkinsName = getDescriptor().getHygieiaJenkinsName();
   boolean useProxy = getDescriptor().isUseProxy();
   EnvVars env;
   try {
     env = r.getEnvironment(listener);
   } catch (Exception e) {
     listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
     env = new EnvVars();
   }
   hygieiaAPIUrl = env.expand(hygieiaAPIUrl);
   hygieiaToken = env.expand(hygieiaToken);
   hygieiaJenkinsName = env.expand(hygieiaJenkinsName);
   return new DefaultHygieiaService(hygieiaAPIUrl, hygieiaToken, hygieiaJenkinsName, useProxy);
 }
  @Test
  public void shouldExpandSha() throws Exception {
    when(run.getEnvironment(listener)).thenReturn(env);
    when(env.expand(Matchers.anyString())).thenReturn(EXPANDED);

    String context = new ManuallyEnteredShaSource("").get(run, listener);
    assertThat(context, equalTo(EXPANDED));
  }
  @Override
  public boolean perform(
      AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) {
    if (build.getResult().isWorseOrEqualTo(Result.FAILURE)) return false;

    listener.getLogger().println(Messages.TestflightRecorder_InfoUploading());

    try {
      EnvVars vars = build.getEnvironment(listener);

      String workspace = vars.expand("$WORKSPACE");

      List<TestflightUploader.UploadRequest> urList =
          new ArrayList<TestflightUploader.UploadRequest>();

      for (TestflightTeam team : createDefaultPlusAdditionalTeams()) {
        try {
          TestflightUploader.UploadRequest ur = createPartialUploadRequest(team, vars, build);
          urList.add(ur);
        } catch (MisconfiguredJobException mje) {
          listener.getLogger().println(mje.getConfigurationMessage());
          return false;
        }
      }

      for (TestflightUploader.UploadRequest ur : urList) {
        TestflightRemoteRecorder remoteRecorder =
            new TestflightRemoteRecorder(workspace, ur, listener);

        final List<Map> parsedMaps;

        try {
          Object result = launcher.getChannel().call(remoteRecorder);
          parsedMaps = (List<Map>) result;
        } catch (UploadException ue) {
          listener
              .getLogger()
              .println(Messages.TestflightRecorder_IncorrectResponseCode(ue.getStatusCode()));
          listener.getLogger().println(ue.getResponseBody());
          return false;
        }

        if (parsedMaps.size() == 0) {
          listener.getLogger().println(Messages.TestflightRecorder_NoUploadedFile(ur.filePaths));
          return false;
        }
        for (Map parsedMap : parsedMaps) {
          addTestflightLinks(build, listener, parsedMap);
        }
      }
    } catch (Throwable e) {
      listener.getLogger().println(e);
      e.printStackTrace(listener.getLogger());
      return false;
    }

    return true;
  }
  @Override
  public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    EnvVars env = build.getEnvironment(listener);
    env.overrideAll(build.getBuildVariables());

    if (Computer.currentComputer() instanceof SlaveComputer) {
      FilePath destinationFilePath;
      if (isOverrideDestinationFolder() && StringUtils.isNotBlank(getDestinationFolder())) {
        destinationFilePath = new FilePath(new File(env.expand(getDestinationFolder())));
      } else {
        destinationFilePath =
            CopyToSlaveUtils.getProjectWorkspaceOnMaster(build, listener.getLogger());
      }

      FilePath projectWorkspaceOnSlave = build.getProject().getWorkspace();

      String includes = env.expand(getIncludes());
      String excludes = env.expand(getExcludes());

      listener
          .getLogger()
          .printf(
              "[copy-to-slave] Copying '%s', excluding %s, from '%s' on '%s' to '%s' on the master.\n",
              includes,
              StringUtils.isBlank(excludes) ? "nothing" : '\'' + excludes + '\'',
              projectWorkspaceOnSlave.toURI(),
              Computer.currentComputer().getNode(),
              destinationFilePath.toURI());

      projectWorkspaceOnSlave.copyRecursiveTo(includes, excludes, destinationFilePath);
    } else if (Computer.currentComputer() instanceof MasterComputer) {
      listener
          .getLogger()
          .println(
              "[copy-to-slave] The build is taking place on the master node, no copy back to the master will take place.");
    }

    return true;
  }
  public ConfigurationItem toConfigurationItem(
      DeployitDescriptorRegistry registry,
      FilePath workspace,
      EnvVars envVars,
      JenkinsDeploymentListener listener) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(getName()), "Name is required.");
    ConfigurationItem deployable = registry.newInstance(type, envVars.expand(getName()));
    if (!isNullOrEmpty(tags)) {
      String resolvedTags = envVars.expand(tags);
      deployable.setProperty("tags", newHashSet(commaSeparatedListToList(resolvedTags)));
    }

    if (properties != null) {
      for (NameValuePair pair : properties) {
        String value = stripEnclosingQuotes(nullToEmpty(pair.propertyValue));
        value = envVars.expand(value);
        registry.setProperty(deployable, pair.propertyName, value);
      }
    }

    return deployable;
  }
  public boolean perform(
      final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
      throws VSphereException {

    PrintStream jLogger = listener.getLogger();
    EnvVars env;
    try {
      env = build.getEnvironment(listener);
    } catch (Exception e) {
      throw new VSphereException(e);
    }
    env.overrideAll(build.getBuildVariables());
    String expandedMemorySize = env.expand(memorySize);

    VSphereLogger.vsLogger(jLogger, "Preparing reconfigure: Memory");
    spec.setMemoryMB(Long.valueOf(expandedMemorySize));
    VSphereLogger.vsLogger(jLogger, "Finished!");
    return true;
  }
  /** @param env Environment variables from which to expand project names; Might be {@code null}. */
  public List<AbstractProject> getProjectList(EnvVars env) {
    if (projectList == null) {
      projectList = new ArrayList<AbstractProject>();

      // expand variables if applicable
      StringBuilder projectNames = new StringBuilder();
      StringTokenizer tokens = new StringTokenizer(projects, ",");
      while (tokens.hasMoreTokens()) {
        if (projectNames.length() > 0) {
          projectNames.append(',');
        }
        projectNames.append(
            env != null ? env.expand(tokens.nextToken().trim()) : tokens.nextToken().trim());
      }

      projectList.addAll(Items.fromNameList(projectNames.toString(), AbstractProject.class));
    }
    return projectList;
  }
  private Collection<String> lookupCommitSha1s(
      @SuppressWarnings("rawtypes") AbstractBuild build, BuildListener listener) {

    if (commitSha1 != null && commitSha1.trim().length() > 0) {
      PrintStream logger = listener.getLogger();
      try {
        EnvVars environment = build.getEnvironment(listener);
        return Arrays.asList(environment.expand(commitSha1));
      } catch (IOException e) {
        logger.println("Unable to expand commit SHA value");
        e.printStackTrace(logger);
        return Arrays.asList();
      } catch (InterruptedException e) {
        logger.println("Unable to expand commit SHA value");
        e.printStackTrace(logger);
        return Arrays.asList();
      }
    }

    // Use a set to remove duplicates
    Collection<String> sha1s = new HashSet<String>();
    // MultiSCM may add multiple BuildData actions for each SCM, but we are covered in any case
    for (BuildData buildData : build.getActions(BuildData.class)) {
      // get the sha1 of the commit that was built

      String lastBuiltSha1 = buildData.getLastBuiltRevision().getSha1String();

      // Should never be null, but may be blank
      if (!lastBuiltSha1.isEmpty()) {
        sha1s.add(lastBuiltSha1);
      }

      // This might be different than the lastBuiltSha1 if using "Merge before build"
      String markedSha1 = buildData.lastBuild.getMarked().getSha1String();

      // Should never be null, but may be blank
      if (!markedSha1.isEmpty()) {
        sha1s.add(markedSha1);
      }
    }
    return sha1s;
  }
示例#11
0
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws IOException, InterruptedException {
    if (debug) listener.getLogger().println("Running mailer");
    // substitute build parameters
    EnvVars env = build.getEnvironment(listener);
    String recip = env.expand(recipients);

    return new MailSender(
        recip, dontNotifyEveryUnstableBuild, sendToIndividuals, descriptor().getCharset()) {
      /** Check whether a path (/-separated) will be archived. */
      @Override
      public boolean artifactMatches(String path, AbstractBuild<?, ?> build) {
        ArtifactArchiver aa = build.getProject().getPublishersList().get(ArtifactArchiver.class);
        if (aa == null) {
          LOGGER.finer("No ArtifactArchiver found");
          return false;
        }
        String artifacts = aa.getArtifacts();
        for (String include : artifacts.split("[, ]+")) {
          String pattern = include.replace(File.separatorChar, '/');
          if (pattern.endsWith("/")) {
            pattern += "**";
          }
          if (SelectorUtils.matchPath(pattern, path)) {
            LOGGER.log(
                Level.FINER,
                "DescriptorImpl.artifactMatches true for {0} against {1}",
                new Object[] {path, pattern});
            return true;
          }
        }
        LOGGER.log(
            Level.FINER,
            "DescriptorImpl.artifactMatches for {0} matched none of {1}",
            new Object[] {path, artifacts});
        return false;
      }
    }.execute(build, listener);
  }
  @Override
  public String evaluate(AbstractBuild<?, ?> context, TaskListener listener, String macroName)
      throws MacroEvaluationException, IOException, InterruptedException {
    if (!context.getWorkspace().child(path).exists()) {
      return StringUtils.isNotBlank(fileNotFoundMessage)
          ? String.format(fileNotFoundMessage, path)
          : "ERROR: File '" + path + "' does not exist";
    }

    // do some environment variable substitution
    try {
      EnvVars env = context.getEnvironment(listener);
      path = env.expand(path);
    } catch (Exception e) {
      listener.error("Error retrieving environment");
    }

    try {
      return context.getWorkspace().child(path).readToString();
    } catch (IOException e) {
      return "ERROR: File '" + path + "' could not be read";
    }
  }
示例#13
0
  /* (non-Javadoc)
   * @see hudson.tasks.BuildWrapper#setUp(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.BuildListener)
   */
  private boolean markVm(
      final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
      throws VSphereException {
    PrintStream jLogger = listener.getLogger();
    VSphereLogger.vsLogger(jLogger, "Converting template to VM. Please wait ...");

    EnvVars env;
    try {
      env = build.getEnvironment(listener);
    } catch (Exception e) {
      throw new VSphereException(e);
    }

    // TODO:  take in a comma delimited list and convert all
    env.overrideAll(build.getBuildVariables()); // Add in matrix axes..
    String expandedTemplate = env.expand(template);

    VirtualMachine vm = vsphere.markAsVm(expandedTemplate);
    VSphereLogger.vsLogger(jLogger, "\"" + expandedTemplate + "\" is a VM!");

    if (powerOn) {
      vsphere.startVm(expandedTemplate);
      String vmIP = vsphere.getIp(vm);
      if (vmIP != null) {
        VSphereLogger.vsLogger(jLogger, "Got IP for \"" + expandedTemplate + "\" ");
        VSphereEnvAction envAction = new VSphereEnvAction();
        envAction.add("VSPHERE_IP", vmIP);
        build.addAction(envAction);
        return true;
      }

      VSphereLogger.vsLogger(jLogger, "Error: Could not get IP for \"" + expandedTemplate + "\" ");
      return false;
    }

    return true;
  }
 private TestflightUploader.UploadRequest createPartialUploadRequest(
     TestflightTeam team, EnvVars vars, AbstractBuild<?, ?> build) {
   TestflightUploader.UploadRequest ur = new TestflightUploader.UploadRequest();
   TokenPair tokenPair = getTokenPair(team.getTokenPairName());
   ur.filePaths = vars.expand(StringUtils.trim(team.getFilePath()));
   ur.dsymPath = vars.expand(StringUtils.trim(team.getDsymPath()));
   ur.apiToken = vars.expand(Secret.toString(tokenPair.getApiToken()));
   ur.buildNotes = createBuildNotes(vars.expand(buildNotes), build.getChangeSet());
   ur.lists = vars.expand(lists);
   ur.notifyTeam = notifyTeam;
   ProxyConfiguration proxy = getProxy();
   ur.proxyHost = proxy.name;
   ur.proxyPass = proxy.getPassword();
   ur.proxyPort = proxy.port;
   ur.proxyUser = proxy.getUserName();
   ur.replace = replace;
   ur.teamToken = vars.expand(Secret.toString(tokenPair.getTeamToken()));
   ur.debug = debug;
   return ur;
 }
示例#15
0
 public String getMavenOpts(TaskListener listener, EnvVars envVars) {
   return envVars.expand(expandTokens(listener, getProject().getParent().getMavenOpts()));
 }
示例#16
0
 public SbtInstallation forEnvironment(EnvVars environment) {
   return new SbtInstallation(
       getName(), environment.expand(getHome()), getProperties().toList());
 }
示例#17
0
  /** {@inheritDoc} * */
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher l, BuildListener listener)
      throws InterruptedException, IOException {

    if (build.getProject().getScm() instanceof ClearCaseUcmSCM) {
      try {
        File ctLogFile = ClearToolLogFile.getCleartoolLogFile(build);
        ClearCaseLogger logger = new ClearCaseLogger(listener, ctLogFile);
        logger.log("### Begin Baseline creation/promotion ###");
        boolean buildOK =
            build.getResult().equals(Result.SUCCESS) || build.getResult().equals(Result.UNSTABLE);

        if (!buildOK && this.skipOnBuildFailure) {
          logger.log(
              "Build result is "
                  + build.getResult()
                  + ". "
                  + "Skipping the baseline creation/promotion step.");
          return false;
        }

        ///// init variables //////////////////////////////////////////////////////////////
        ClearCaseUcmSCM scm = (ClearCaseUcmSCM) build.getProject().getScm();
        EnvVars env = build.getEnvironment(listener);
        String nodeName = Computer.currentComputer().getName();
        ClearCaseConfiguration ccConfig = scm.fetchClearCaseConfig(nodeName);
        FilePath workspace;
        StringParameterValue wsParam =
            CCParametersAction.getBuildParameter(build, ORIGINAL_WORKSPACE_ENVSTR);
        if (wsParam != null) {
          workspace = new FilePath(build.getWorkspace().getChannel(), wsParam.value);
        } else {
          workspace = build.getWorkspace();
        }
        ClearTool ct =
            scm.createClearTool(
                ccConfig.getCleartoolExe(),
                workspace,
                build.getBuiltOn().getRootPath(),
                env,
                ctLogFile,
                null);

        View view = ClearCaseUcmSCM.getBuildView(build);

        Stream stream = view.getStream();

        ///// check stream lock state /////////////////////////////////////////////////////
        LockState state = ct.getStreamLockState(stream);
        stream.setLockState(state);
        switch (state) {
          case NONE:
          case UNLOCKED:
            break;
          default:
            logger.log(
                "WARNING: building on a '" + state + "' stream. No baseline will be created.");
            return false;
        }

        ///// resolve variables in baseline name //////////////////////////////////////////
        String baseName = env.expand(this.namePattern);
        String comment = env.expand(this.commentPattern);

        /* illegal characters removal */
        baseName = baseName.replaceAll("[\\s\\\\\\/:\\?\\*\\|]+", "_");
        Pattern p = Pattern.compile("(\\$\\{.+?\\})");
        Matcher match = p.matcher(baseName);
        if (match.find()) {
          throw new ClearToolError(
              String.format(
                  "Illegal characters found "
                      + "in baseline name : %s. "
                      + "An environment variable may not have been resolved.",
                  match.group()));
        }

        ///// main process ////////////////////////////////////////////////////////////////
        logger.log("Retrieving components details...");
        List<Component> components = resolveComponents(stream, ct);

        logger.log("Creating new baselines...");
        List<Baseline> createdBls = createBaselines(baseName, comment, ct, view, components);

        logger.log("Retrieving latest baselines...");
        /* retrieval of the full names of the baselines */
        List<Baseline> latestBls = ct.getLatestBaselines(stream);

        /* get every component attached to the latest baselines */
        matchComponentsToBaselines(ct, stream, latestBls);
        /* resolve created baselines */
        markCreatedBaselines(createdBls, latestBls);

        printUsedBaselines(logger, latestBls);

        if (createdBls.isEmpty()) {
          logger.log("No baseline was created.");
        } else {
          /* get vob dependent promotion levels */
          ct.fetchPromotionLevels(stream.getPvob());

          if (buildOK) {
            logger.log("Promoting created baselines...");

            /* On success, promote all the baselines that hudson created to "BUILT" */
            for (Baseline bl : createdBls) {
              ct.changeBaselinePromotionLevel(bl, PromotionLevel.BUILT);
              logger.log(printPromotedBl(bl, ct.print(PromotionLevel.BUILT)));
            }

            /* recommend all baselines that meet the stream's promotion level requirements */
            if (this.recommend) {
              logger.log("Recommending created baselines...");
              ct.recommendAllEligibleBaselines(stream);
            }
            /* Rebase a dynamic view */
            if (this.rebaseDynamicView) {
              logger.log(
                  String.format("Rebasing view: %s with created baselines...", dynamicViewName));

              View dynView = new View(dynamicViewName, stream, true);
              ct.rebaseDynamicView(dynView, createdBls);
            }
          } else {
            /* On failure, demote all the baselines that hudson created to "REJECTED" */
            logger.log("Rejecting created baselines...");
            for (Baseline bl : createdBls) {
              ct.changeBaselinePromotionLevel(bl, PromotionLevel.REJECTED);
              logger.log(printPromotedBl(bl, ct.print(PromotionLevel.REJECTED)));
            }
          }
        }

        publishBaselinesAsParams(build, latestBls);

        logger.log("~~~ End Baseline creation/promotion ~~~");

      } catch (ClearToolError ctError) {
        listener.getLogger().println(ctError.toString());
        build.setResult(Result.FAILURE);
        return false;
      } catch (Exception e) {
        e.printStackTrace(listener.getLogger());
        build.setResult(Result.FAILURE);
        return false;
      }
    } else {
      listener.getLogger().println("ERROR: Baselines are only handled by Clearcase UCM.");
      return false;
    }
    return true;
  } // perform()
 public String replaceBuildParamWithValue(String paramValue) {
   return fixEmptyAndTrim(environment.expand(paramValue));
 }
  @Override
  public BuildWrapper.Environment setUp(
      AbstractBuild build, Launcher launcher, BuildListener listener)
      throws IOException, InterruptedException {
    final PrintStream logger = listener.getLogger();

    final DeviceFarmApi api = new DeviceFarmApiImpl();
    long start = System.currentTimeMillis();

    try {
      EnvVars environment = build.getEnvironment(listener);
      String expendedTag = environment.expand(tag);

      log(logger, Messages.TRYING_TO_CONNECT_API_SERVER(deviceApiUrl, expendedTag));
      api.connectApiServer(
          logger,
          deviceApiUrl,
          expendedTag,
          build.getProject().getAbsoluteUrl() + build.getNumber());

      final RemoteDevice reserved =
          api.waitApiResponse(
              logger, DEVICE_WAIT_TIMEOUT_IN_MILLIS, DEVICE_READY_CHECK_INTERVAL_IN_MS);
      log(
          logger,
          Messages.DEVICE_IS_READY(passedSeconds(start), reserved.ip, reserved.port, reserved.url));

      if (descriptor == null) {
        descriptor = Hudson.getInstance().getDescriptorByType(DescriptorImpl.class);
      }

      // Substitute environment and build variables into config
      final String androidHome = discoverAndroidSdkHome(build, launcher, listener);
      log(logger, Messages.USING_SDK(androidHome));

      AndroidSdk sdk = new AndroidSdk(androidHome, androidHome);
      final AndroidDeviceContext device =
          new AndroidDeviceContext(build, launcher, listener, sdk, reserved.ip, reserved.port);
      // disconnect first to workaround previous error
      device.disconnect();

      // connect device with adb
      device.connect(DEVICE_CONNECT_TIMEOUT_IN_MILLIS);

      device.waitDeviceReady(logger, DEVICE_CONNECT_TIMEOUT_IN_MILLIS, 1000);
      // check availability
      device.devices();

      // unlock screen
      device.unlockScreen();

      // Start dumping logcat to temporary file
      final LogcatCollector logcatCollector = new LogcatCollector(build, device);
      logcatCollector.start();

      return new BuildWrapper.Environment() {
        @Override
        public void buildEnvVars(Map<String, String> env) {
          env.put("ANDROID_IP", device.ip());
          env.put("ANDROID_HOME", androidHome);
          env.put("ANDROID_SDK_HOME", androidHome);
          env.put("ANDROID_PORT", Integer.toString(device.port()));
          env.put("ANDROID_SERIAL", device.serial());
        }

        @Override
        public boolean tearDown(AbstractBuild build, BuildListener listener)
            throws IOException, InterruptedException {
          cleanUp(build, device, api, logcatCollector);

          return true;
        }
      };

    } catch (FailedToConnectApiServerException e) {
      log(logger, Messages.FAILED_TO_CONNECT_API_SERVER());
    } catch (MalformedResponseException e) {
      log(logger, Messages.FAILED_TO_PARSE_DEVICE_FARM_RESPONSE());
    } catch (TimeoutException e) {
      log(logger, Messages.DEVICE_WAIT_TIMEOUT(passedSeconds(start)));
    } catch (NoDeviceAvailableException e) {
      log(logger, Messages.NO_SUCH_DEVICE());
    }

    build.setResult(Result.NOT_BUILT);
    cleanUp(null, null, api, null);
    return null;
  }
示例#20
0
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener)
      throws InterruptedException {

    // during matrix build, the push back would happen at the very end only once for the whole
    // matrix,
    // not for individual configuration build.
    if (build instanceof MatrixRun) {
      return true;
    }

    SCM scm = build.getProject().getScm();

    if (!(scm instanceof GitSCM)) {
      return false;
    }

    final GitSCM gitSCM = (GitSCM) scm;

    if (gitSCM.getUseShallowClone()) {
      listener.getLogger().println("GitPublisher disabled while using shallow clone.");
      return true;
    }

    final String projectName = build.getProject().getName();
    final FilePath workspacePath = build.getWorkspace();
    final int buildNumber = build.getNumber();
    final Result buildResult = build.getResult();

    // If pushOnlyIfSuccess is selected and the build is not a success, don't push.
    if (pushOnlyIfSuccess && buildResult.isWorseThan(Result.SUCCESS)) {
      listener
          .getLogger()
          .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) {
        e.printStackTrace(listener.error("Failed to build up environment"));
        tempEnvironment = new EnvVars();
      }

      String confName = gitSCM.getGitConfigNameToUse();
      if ((confName != null) && (!confName.equals(""))) {
        tempEnvironment.put("GIT_COMMITTER_NAME", confName);
        tempEnvironment.put("GIT_AUTHOR_NAME", confName);
      }
      String confEmail = gitSCM.getGitConfigEmailToUse();
      if ((confEmail != null) && (!confEmail.equals(""))) {
        tempEnvironment.put("GIT_COMMITTER_EMAIL", confEmail);
        tempEnvironment.put("GIT_AUTHOR_EMAIL", confEmail);
      }

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

      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 buildnumber = "jenkins-" + projectName + "-" + buildNumber;
                      git.deleteTag(buildnumber);

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

                      git.tag(buildnumber, "Jenkins Build #" + buildNumber);

                      PreBuildMergeOptions mergeOptions = gitSCM.getMergeOptions();

                      if (mergeOptions.doMerge() && buildResult.isBetterOrEqualTo(Result.SUCCESS)) {
                        RemoteConfig remote = mergeOptions.getMergeRemote();
                        listener
                            .getLogger()
                            .println(
                                "Pushing HEAD to branch "
                                    + mergeOptions.getMergeTarget()
                                    + " of "
                                    + remote.getName()
                                    + " repository");

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

                      return true;
                    }
                  });
        } catch (Throwable e) {
          e.printStackTrace(listener.error("Failed to push merge to origin repository"));
          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, "Jenkins 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) {
              e.printStackTrace(
                  listener.error("Failed to push tag " + tagName + " to " + targetRepo));
              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;

                        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;
                          }

                          listener
                              .getLogger()
                              .println(
                                  "Pushing HEAD to branch "
                                      + branchName
                                      + " at repo "
                                      + targetRepo);
                          git.push(remote, "HEAD:" + branchName);

                          return true;
                        }
                      });
            } catch (Throwable e) {
              e.printStackTrace(
                  listener.error("Failed to push branch " + branchName + " to " + targetRepo));
              build.setResult(Result.FAILURE);
              branchResult = false;
            }
          }

          if (!branchResult) {
            allBranchesResult = false;
          }
        }
        if (!allBranchesResult) {
          pushResult = false;
        }
      }

      if (isPushNotes()) {
        boolean allNotesResult = true;
        for (final NoteToPush b : notesToPush) {
          boolean noteResult = true;
          if (b.getnoteMsg() == null) {
            listener.getLogger().println("No note to push defined");
            return false;
          }

          b.setEmptyTargetRepoToOrigin();
          final String noteMsg = environment.expand(b.getnoteMsg());
          final String noteNamespace = environment.expand(b.getnoteNamespace());
          final String targetRepo = environment.expand(b.getTargetRepoName());
          final boolean noteReplace = b.getnoteReplace();

          if (noteResult) {
            try {
              noteResult =
                  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;
                          }

                          listener
                              .getLogger()
                              .println(
                                  "Adding note \""
                                      + noteMsg
                                      + "\" to namespace \""
                                      + noteNamespace
                                      + "\"");

                          if (noteReplace) git.addNote(noteMsg, noteNamespace);
                          else git.appendNote(noteMsg, noteNamespace);

                          git.push(remote, "refs/notes/*");

                          return true;
                        }
                      });
            } catch (Throwable e) {
              e.printStackTrace(
                  listener.error(
                      "Failed to add note \"" + noteMsg + "\" to \"" + noteNamespace + "\""));
              build.setResult(Result.FAILURE);
              noteResult = false;
            }
          }

          if (!noteResult) {
            allNotesResult = false;
          }
        }
        if (!allNotesResult) {
          pushResult = false;
        }
      }

      return pushResult;
    }
  }