hudson.model.Run#addAction ( )源码实例Demo

下面列出了hudson.model.Run#addAction ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public Revision decorateRevisionToBuild(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener, Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
    listener.getLogger().println("Merging " + targetBranch.getName() + " commit " + targetBranch.getRevision().getHash() + " into merge-request head commit " + rev.getSha1String());
    checkout(scm, build, git, listener, rev);
    try {
        git.setAuthor("Jenkins", /* could parse out of JenkinsLocationConfiguration.get().getAdminAddress() but seems overkill */"[email protected]");
        git.setCommitter("Jenkins", "[email protected]");
        MergeCommand cmd = git.merge().setRevisionToMerge(ObjectId.fromString(targetBranch.getRevision().getHash()));
        for (GitSCMExtension ext : scm.getExtensions()) {
            // By default we do a regular merge, allowing it to fast-forward.
            ext.decorateMergeCommand(scm, build, git, listener, cmd);
        }
        cmd.execute();
    } catch (GitException e) {
        // Try to revert merge conflict markers.
        checkout(scm, build, git, listener, rev);
        throw e;
    }
    build.addAction(new MergeRecord(targetBranch.getRefSpec().destinationRef(targetBranch.getName()), targetBranch.getRevision().getHash())); // does not seem to be used, but just in case
    ObjectId mergeRev = git.revParse(Constants.HEAD);
    listener.getLogger().println("Merge succeeded, producing " + mergeRev.name());
    return new Revision(mergeRev, rev.getBranches()); // note that this ensures Build.revision != Build.marked
}
 
源代码2 项目: docker-workflow-plugin   文件: ImageAction.java
/**
 * Records an image name as per {@code Config.Image} in {@code docker inspect $container} or a {@code FROM} instruction.
 * Typically in {@code repository} or {@code user/repository} format, but may include tags {@code repo:latest} or hashes {@code [email protected]}.
 * @see <a href="https://docs.docker.com/reference/api/docker_remote_api_v1.18/#inspect-a-container">this specification which does not really specify anything</a>
 */
static void add(String image, Run<?,?> run) throws IOException {
    synchronized (run) {
        BulkChange bc = new BulkChange(run);
        try {
            ImageAction action = run.getAction(ImageAction.class);
            if (action == null) {
                action = new ImageAction();
                run.addAction(action);
            }
            action.names.add(image);
            bc.commit();
        } finally {
            bc.abort();
        }
    }
}
 
protected static void push(@NonNull Run<?, ?> run, @NonNull Class<? extends AbstractInvisibleRunAction2> clazz,
        @NonNull String item) throws IOException {
    synchronized (run) {
        BulkChange bc = new BulkChange(run);
        try {
            AbstractInvisibleRunAction2 action = run.getAction(clazz);
            if (action == null) {
                action = clazz.newInstance();
                run.addAction(action);
            }
            LOGGER.log(Level.FINEST, "Pushing item {0} to action {1} in run {2}",
                    new Object[] { item, action, run });
            action.stack.push(item);
            bc.commit();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("Can not instantiate class " + clazz, e);
        } finally {
            bc.abort();
        }
    }
}
 
public void perform(LambdaUploadBuildStepVariables lambdaUploadBuildStepVariables,  Run<?, ?>  run, FilePath workspace, Launcher launcher, TaskListener listener) {

        try {
            LambdaUploadBuildStepVariables executionVariables = lambdaUploadBuildStepVariables.getClone();
            executionVariables.expandVariables(run.getEnvironment(listener));
            DeployConfig deployConfig = executionVariables.getUploadConfig();
            LambdaClientConfig lambdaClientConfig = executionVariables.getLambdaClientConfig();

            DeployCallable deployCallable = new DeployCallable(listener, workspace, deployConfig, lambdaClientConfig);
            Boolean lambdaSuccess = launcher.getChannel().call(deployCallable);

            if (!lambdaSuccess) {
                run.setResult(Result.FAILURE);
            }
            run.addAction(new LambdaUploadAction(executionVariables.getFunctionName(), lambdaSuccess));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
public void perform(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) {
    try {
        LambdaPublishBuildStepVariables executionVariables = lambdaPublishBuildStepVariables.getClone();
        executionVariables.expandVariables(run.getEnvironment(listener));
        PublishConfig publishConfig = executionVariables.getPublishConfig();
        LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();

        PublishCallable publishCallable = new PublishCallable(listener, publishConfig, clientConfig);

        LambdaPublishServiceResponse lambdaSuccess = launcher.getChannel().call(publishCallable);

        if(!lambdaSuccess.getSuccess()){
            run.setResult(Result.FAILURE);
        }

        run.addAction(new LambdaPublishAction(lambdaSuccess.getFunctionVersion(), lambdaSuccess.getFunctionAlias(), lambdaSuccess.getSuccess()));
    } catch(Exception exc) {
        throw new RuntimeException(exc);
    }
}
 
public void perform(LambdaInvokeBuildStepVariables lambdaInvokeBuildStepVariables,Run<?, ?> run, Launcher launcher, TaskListener listener) {
    try {
        LambdaInvokeBuildStepVariables executionVariables = lambdaInvokeBuildStepVariables.getClone();
        executionVariables.expandVariables(run.getEnvironment(listener));
        LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
        InvokeConfig invokeConfig = executionVariables.getInvokeConfig();

        InvokeCallable invokeCallable = new InvokeCallable(listener, invokeConfig, clientConfig);

        LambdaInvocationResult invocationResult = launcher.getChannel().call(invokeCallable);
        if(!invocationResult.isSuccess()){
            run.setResult(Result.FAILURE);
        }
        for (Map.Entry<String,String> entry : invocationResult.getInjectables().entrySet()) {
            run.addAction(new LambdaOutputInjectionAction(entry.getKey(), entry.getValue()));
        }
        run.getEnvironment(listener);
        run.addAction(new LambdaInvokeAction(executionVariables.getFunctionName(), invocationResult.isSuccess()));
    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }
}
 
@Override
public void onCompleted(Run run, TaskListener listener) {
  // TODO consider the possibility that there is >1 such action
  TestResultAction testResultAction = run.getAction(TestResultAction.class);

  HistoryAggregatedFlakyTestResultAction historyAction = run.getParent()
      .getAction(HistoryAggregatedFlakyTestResultAction.class);

  // Aggregate test running results
  if (historyAction != null) {
    historyAction.aggregateOneBuild(run);
  }

  if (testResultAction != null && testResultAction.getFailCount() > 0) {
    // Only add deflake action if there are test failures
    run.addAction(
        new DeflakeAction(getFailingTestClassMethodMap(testResultAction.getFailedTests())));
  }
}
 
/**
 * Resets the quality gate for the specified analysis tool.
 *
 * @param selectedBuild
 *         the selected build that will show the action link
 * @param id
 *         the ID of the static analysis tool that should be reset
 */
@VisibleForTesting
public void resetReferenceBuild(final Run<?, ?> selectedBuild, final String id) {
    try {
        selectedBuild.addAction(new ResetReferenceAction(id));
        selectedBuild.save();
    }
    catch (IOException ignore) {
        // ignore
    }
}
 
源代码9 项目: DotCi   文件: ShellScriptRunner.java
private void addExecutionInfoAction(final Run run, final ShellCommands commands) throws IOException {
    final DotCiBuildInfoAction dotCiBuildInfoAction = run.getAction(DotCiBuildInfoAction.class);
    if (dotCiBuildInfoAction == null) {
        run.addAction(new DotCiBuildInfoAction(commands));
    } else {
        dotCiBuildInfoAction.addCommands(commands);
    }
    run.save();
}
 
public void publishStarted(Run<?, ?> build, GitLabSCMHeadMetadataAction metadata, String description) {
    if (build instanceof WorkflowRun && mode == stages) {
        attachGraphListener((WorkflowRun) build, new GitLabSCMGraphListener(build, metadata));
    } else if (mode == result) {
        String context = Messages.GitLabSCMPublishAction_DefaultContext(build.getNumber());
        build.addAction(new RunningContextsAction(context));
        publishBuildStatus(build, metadata, running, context, description);
    }
}
 
源代码11 项目: docker-plugin   文件: DockerBuilderControlOption.java
/**
 * @return first DockerLaunchAction attached to build
 */
protected DockerLaunchAction getLaunchAction(Run<?, ?> build) {
    List<DockerLaunchAction> launchActionList = build.getActions(DockerLaunchAction.class);
    DockerLaunchAction launchAction;
    if (launchActionList.size() > 0 ) {
        launchAction = launchActionList.get(0);
    } else {
        launchAction = new DockerLaunchAction();
        build.addAction(launchAction);
    }
    return launchAction;
}
 
源代码12 项目: docker-plugin   文件: DockerRunListener.java
@Override
public void onStarted(Run<?, ?> run, TaskListener listener) {
    final Computer computer = Computer.currentComputer();
    if (computer instanceof DockerComputer) {
        final DockerComputer dockerComputer = (DockerComputer) computer;
        final DockerTransientNode node = dockerComputer.getNode();
        if (node != null) {
            run.addAction(new DockerBuildAction(node));
        }
    }
}
 
public static void performerPerform(
    final GitChangelogConfig configUnexpanded,
    final Run<?, ?> build,
    final TaskListener listener,
    final FilePath workspace) {
  try {
    final EnvVars env = build.getEnvironment(listener);
    final GitChangelogConfig config = expand(configUnexpanded, env);
    listener.getLogger().println("---");
    listener.getLogger().println("--- Git Changelog ---");
    listener.getLogger().println("---");

    setApiTokenCredentials(config, listener);

    final RemoteCallable remoteTask = new RemoteCallable(workspace.getRemote(), config);
    final RemoteResult remoteResult = workspace.act(remoteTask);
    if (!isNullOrEmpty(remoteResult.getLeftSideTitle())) {
      build.addAction(
          new GitChangelogLeftsideBuildDecorator(
              remoteResult.getLeftSideTitle(), remoteResult.getLeftSideUrl()));
    }
    if (!isNullOrEmpty(remoteResult.getSummary())) {
      build.addAction(new GitChangelogSummaryDecorator(remoteResult.getSummary()));
    }
    doLog(listener, INFO, remoteResult.getLog());
  } catch (final Exception e) {
    doLog(listener, SEVERE, e.getMessage(), e);
  }
}
 
源代码14 项目: phabricator-jenkins-plugin   文件: Differential.java
public void decorate(Run<?, ?> build, String phabricatorURL) {
    // Add a badge next to the build
    build.addAction(PhabricatorPostbuildAction.createShortText(
            getRevisionID(true),
            getPhabricatorLink(phabricatorURL)));
    // Add some long-form text
    PhabricatorPostbuildSummaryAction summary = createSummary(phabricatorURL);
    build.addAction(summary);

}
 
/**
 * Adds an action with a reference to fingerprint if required. It's
 * recommended to call the method from {
 *
 * @BulkChange} transaction to avoid saving the {@link Run} multiple times.
 * @param fp Fingerprint
 * @param imageId ID of the docker image
 * @param run Run to be updated
 * @throws IOException Cannot save the action
 */
static void addToRun(Fingerprint fp, String imageId, Run run) throws IOException {
    synchronized (run) {
        DockerFingerprintAction action = run.getAction(DockerFingerprintAction.class);
        if (action == null) {
            action = new DockerFingerprintAction();
            run.addAction(action);
        }
        
        if (action.imageIDs.add(imageId)) {
            run.save();
        } // else no need to save updates
    }
}
 
@Override
public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
		throws AbortException, java.lang.InterruptedException {
	// This is where you 'build' the project.

	Secret microScannerToken = getDescriptor().getMicroScannerToken();
	boolean caCertificates = getDescriptor().getCaCertificates();

	if (microScannerToken == null || Secret.toString(microScannerToken).trim().equals("")) {
			throw new AbortException("Missing configuration. Please set the global configuration parameters in The \"Aqua Security\" section under  \"Manage Jenkins/Configure System\", before continuing.\n");
	}

	// Support unique names for artifacts when there are multiple steps in the same
	// build
	String artifactSuffix, artifactName;
	if (build.hashCode() != buildId) {
		// New build
		setBuildId(build.hashCode());
		setCount(1);
		artifactSuffix = null; // When there is only one step, there should be no suffix at all
		artifactName = "scanout." + outputFormat;
	} else {
		setCount(count + 1);
		artifactSuffix = Integer.toString(count);
		artifactName = "scanout-" + artifactSuffix + "." + outputFormat;
	}

	int exitCode = ScannerExecuter.execute(build, workspace, launcher, listener, artifactName, microScannerToken, imageName, notCompliesCmd, outputFormat == null ? "html" : outputFormat, onDisallowed == null || !onDisallowed.equals("fail"),caCertificates);
	build.addAction(new AquaScannerAction(build, artifactSuffix, artifactName, imageName));

	archiveArtifacts(build, workspace, launcher, listener);

	System.out.println("exitCode: " + exitCode);
	String failedMessage = "Scanning failed.";
	switch (exitCode) {
	case OK_CODE:
			System.out.println("Scanning success.");
			break;
	case DISALLOWED_CODE:
			throw new AbortException(failedMessage);
	default:
		// This exception causes the message to appear in the Jenkins console
		throw new AbortException(failedMessage);
	}
}
 
源代码17 项目: jenkins-test-harness   文件: FakeChangeLogSCM.java
@Override
public void checkout(Run<?, ?> build, Launcher launcher, FilePath remoteDir, TaskListener listener, File changeLogFile, SCMRevisionState baseline) throws IOException, InterruptedException {
    new FilePath(changeLogFile).touch(0);
    build.addAction(new ChangelogAction(entries, changeLogFile.getName()));
    entries = new ArrayList<EntryImpl>();
}
 
源代码18 项目: jenkins-test-harness   文件: RunLoadCounter.java
static void add(Run<?, ?> build) {
    build.addAction(new Marker(build.getParent().getFullName(), build.getNumber()));
}
 
@Override
public void onStarted(Run<?, ?> build, TaskListener listener) {
	// Skip locking for multiple configuration projects,
	// only the child jobs will actually lock resources.
	if (build instanceof MatrixBuild)
		return;

	if (build instanceof AbstractBuild) {
		Job<?, ?> proj = Utils.getProject(build);
		Set<LockableResource> required = new HashSet<>();
		if (proj != null) {
			LockableResourcesStruct resources = Utils.requiredResources(proj);

			if (resources != null) {
				if (resources.requiredNumber != null || !resources.label.isEmpty() || resources.getResourceMatchScript() != null) {
					required.addAll(LockableResourcesManager.get().
							getResourcesFromProject(proj.getFullName()));
				} else {
					required.addAll(resources.required);
				}

				if (LockableResourcesManager.get().lock(required, build, null)) {
					build.addAction(LockedResourcesBuildAction
							.fromResources(required));
					listener.getLogger().printf("%s acquired lock on %s%n",
							LOG_PREFIX, required);
					LOGGER.fine(build.getFullDisplayName()
							+ " acquired lock on " + required);
					if (resources.requiredVar != null) {
						build.addAction(new ResourceVariableNameAction(new StringParameterValue(
								resources.requiredVar,
								required.toString().replaceAll("[\\]\\[]", ""))));
					}
				} else {
					listener.getLogger().printf("%s failed to lock %s%n",
							LOG_PREFIX, required);
					LOGGER.fine(build.getFullDisplayName() + " failed to lock "
							+ required);
				}
			}
		}
	}
}
 
源代码20 项目: junit-plugin   文件: JUnitResultArchiver.java
public static TestResultAction parseAndAttach(@Nonnull JUnitTask task, PipelineTestDetails pipelineTestDetails,
                                              Run build, FilePath workspace, Launcher launcher, TaskListener listener)
        throws InterruptedException, IOException {
    listener.getLogger().println(Messages.JUnitResultArchiver_Recording());

    final String testResults = build.getEnvironment(listener).expand(task.getTestResults());

    TestResult result = parse(task, pipelineTestDetails, testResults, build, workspace, launcher, listener);

    synchronized (build) {
        // TODO can the build argument be omitted now, or is it used prior to the call to addAction?
        TestResultAction action = build.getAction(TestResultAction.class);
        boolean appending;
        if (action == null) {
            appending = false;
            action = new TestResultAction(build, result, listener);
        } else {
            appending = true;
            result.freeze(action);
            action.mergeResult(result, listener);
        }
        action.setHealthScaleFactor(task.getHealthScaleFactor()); // overwrites previous value if appending
        if (result.isEmpty()) {
            if (build.getResult() == Result.FAILURE) {
                // most likely a build failed before it gets to the test phase.
                // don't report confusing error message.
                return null;
            }
            if (task.isAllowEmptyResults()) {
                // User allow empty results
                listener.getLogger().println(Messages.JUnitResultArchiver_ResultIsEmpty());
                return null;
            }
            // most likely a configuration error in the job - e.g. false pattern to match the JUnit result files
            throw new AbortException(Messages.JUnitResultArchiver_ResultIsEmpty());
        }

        // TODO: Move into JUnitParser [BUG 3123310]
        if (task.getTestDataPublishers() != null) {
            for (TestDataPublisher tdp : task.getTestDataPublishers()) {
                Data d = tdp.contributeTestData(build, workspace, launcher, listener, result);
                if (d != null) {
                    action.addData(d);
                }
            }
        }

        if (appending) {
            build.save();
        } else {
            build.addAction(action);
        }

        return action;
    }
}