Last updated Dec 8, 2017

How do I trigger off a build from my action?

Below is the code for starting a manual build (it'll show the changes since the last build). The buildExecutionManager.tryToDetectAndBuild takes a callback function BuildExecutionManager.BuildDetectionAction that creates the BuildContext. You can get away with not populating the BuildChangesImpl if you don't want to (no changes will be shown for the generated build result)

1
2
buildExecutionManager.tryToDetectAndBuild(buildKey, new BuildExecutionManager.BuildDetectionAction()
{
    public BuildContext process()
    {
        try
        {
            BuildLogger buildLogger = buildPlan.getBuildLogger();
            BuildDefinition buildDefinition = buildPlan.getBuildDefinition();
            Repository repository = buildDefinition.getRepository();

            buildLogger.addBuildLogEntry("Manual build triggered by " + user); // logging to the live activity log
            
            // This block is only required if you care about the changes
            String lastVcsRevisionKey = buildPlan.getLastVcsRevisionKey();
            BuildChanges buildChanges;
            if (lastVcsRevisionKey != null)
            {
                buildChanges = changeDetectionManager.collectChangesSinceLastBuild(buildPlan.getKey(), repository, lastVcsRevisionKey);
            }
            else
            {
                buildChanges = new BuildChangesImpl();
            }

            // Generate a trigger reason
            TriggerReason triggerReason = triggerReasonManager.getTriggerReason(ManualBuildTriggerReason.KEY, buildChanges,
                                                                                EasyMap.build(ManualBuildTriggerReason.TRIGGER_MANUAL_USER, user.getName()));


            BuildContext buildContext = new BuildContextImpl(buildPlan,
                                                             buildManager.retrieveNextBuildNumber(buildPlan.getKey()), // you need this to ensure build numbers are unique
                                                             triggerReason,
                                                             buildDefinition,
                                                             buildChanges);

            return buildContext;
        }
        catch (Exception e)
        {
            String message = "Error encountered while triggering manual build: " + e.getMessage();
            log.error(buildPlan.getBuildLogger().addBuildLogEntry(message), e);
            errorUpdateHandler.recordError(buildPlan.getKey(), message, e);
        }

        return null;
    }
}, true);

Rate this page: