Run action for success after cake's DoesForEach

85 Views Asked by At

I'm using the DoesForEach alias to run a task for a collection.

I want to report/act on success.

I cannot do this because it would run after every item in the collection:

Task("A")
  .DoesForEach(GetFiles("**/*.txt"), (file) => {
    //...
    DoSomething();           // <---
  });

I cannot do this because it would run for failures too:

Task("A")
  .DoesForEach(GetFiles("**/*.txt"), (file) => {
    //...
  })
  .Finally(() => {
    DoSomething();           // <---
  });

How can I do this?

(A workaround is to run a dependent task after this one - i.e. B->A - but that is a messy way to do it... unless it's the only way?)

2

There are 2 best solutions below

3
Nils On BEST ANSWER

Additionally to what devlead said, you could also add multiple actions to a task, like this:

Task("Default")
.Does(() => 
{
   Information("This action runs first.");
}).DoesForEach(GetFiles("./**/*"), f => 
{
   Information("Found file: "+f);
}).Does(() => {
   Information("This action runs last.");
});

And then there is also the finally block:

Task("Default")
    .Does(() =>
{
   Information("This action runs...");
})
.Finally(() =>
{
    Information("This action runs at the end, regardless of errors...");
});
3
devlead On

TaskSetup / TaskTeardown probably what you're looking for.

https://cakebuild.net/docs/writing-builds/setup-and-teardown#task-lifetime

TaskSetup(setupContext =>
{
    var message = string.Format("Task: {0}", setupContext.Task.Name);
    // custom logging
});

TaskTeardown(teardownContext =>
{
    var message = string.Format("Task: {0}", teardownContext.Task.Name);
    // custom logging
});

An example to group tasks in GitHub Actions

if (BuildSystem.GitHubActions.IsRunningOnGitHubActions)
{
    TaskSetup(context=> System.Console.WriteLine($"::group::{context.Task.Name.Quote()}"));
    TaskTeardown(context=>System.Console.WriteLine("::endgroup::"));
}

Documentation on task setup context definition here https://cakebuild.net/api/Cake.Core/ITaskSetupContext/

and teardown here https://cakebuild.net/api/Cake.Core/ITaskTeardownContext/