Tuesday, June 24, 2014

Add failed test results to Jenkins build descriptions with Groovy

// Set description of all builds to result of failed tests
def whichJob = "myJob";
def job = hudson.model.Hudson.instance.getItem(whichJob);
def builds = job.getBuilds();
def bldRptStub = "<b>Failed Tests</b><ul>";
builds.each
{
  build ->
    build.setDescription('');
    if (build.testResultAction)
    {
      def bldRpt = bldRptStub;
      def setDescription = false;
      def tra = build.testResultAction;
      def childReports = tra.childReports;
      childReports.each
      {
        rpt ->
          def result = rpt.result;
          if (result.failedTests.size > 0)
          {
            setDescription = true;
          }
          result.failedTests.each
          {
            t ->
              if (t.name != '')
              {
                bldRpt += "<li>" + t.name + "</li>";
              }
          }
      }
      bldRpt += "</ul>";
      if (setDescription)
      {
        build.setDescription(bldRpt);
      }
    }
}

Thursday, December 09, 2010

Alphanumeric sort

Sometimes I have lists that look like:

someThing1
someThing2
..
someThing15

...and I want to sort them numerically, but that doesn't happen because the string part of the scalar makes the compiler think it needs to sort strings which make the items line up like:

someThing1
someThing102093848984
someThing111
someThing2
someThing3

To resolve this, pass the list to sort, which you then pass to substr the second parameter of which you pass to a sub to get the length of the alpha portion of the element, thus giving you the alpha substring within each item to be compared.


my @unsorted = qw(item10 foobar92 item1 doe2 a6 item7);

my @sorted = sort {substr($a, &lengthOfAlpha($a)) <=> substr($b, &lengthOfAlpha($b))} @unsorted;

foreach my $foo(@sorted)
{
  print "$foo\n";
}

sub lengthOfAlpha
{
  my ($input) = @_;
  my ($alpha) = $input =~ /(\D{1,})/;
  my $length = length($alpha);
  print "length of alpha is $length\n";
  return $length;
}