App-JenkinsCli

 view release on metacpan or  search on metacpan

example/rebuild-to-success  view on Meta::CPAN

#!/usr/bin/perl

# Created on: 2016-11-15 11:06:47
# Create by:  Ivan Wills
# $Id$
# $Revision$, $HeadURL$, $Date$
# $Revision$, $Source$, $Date$

use strict;
use warnings;
use Getopt::Alt;
use Data::Dumper qw/Dumper/;
use English qw/ -no_match_vars /;
use FindBin qw/$Bin/;
use Path::Tiny;
use Jenkins::API;

our $VERSION = 0.013;
my ($name)   = $PROGRAM_NAME =~ m{^.*/(.*?)$}mxs;

if ( !@ARGV ) {
    pod2usage( -verbose => 1 );
}

main();
exit 0;

sub main {
    my ($options, $cmd, $opt) = get_options(
        {
            name        => 'jenkins-cli',
            conf_prefix => '.',
            helper      => 1,
            default     => {
                sleep => 10,
            },
        },
        [
            'base_url|base-url|b=s',
            'username|U=s',
            'password|P=s',
            'start',
            'sleep|s=i',
            'verbose|v+',
        ],
    );

    # do stuff here
    my $jenkins = Jenkins::API->new({
        base_url => $options->base_url,
        api_key  => $options->username,
        api_pass => $options->password,
    });

    my $job    = shift @ARGV || die "No job supplied!\n";
    my ($result, $build) = status($jenkins, $job);
    my $number = $result->{nextBuildNumber} - 1;

    while ( $build->{building} || $build->{result} ne 'SUCCESS' ) {

        if ( ! $build->{building} && $build->{number} == $number ) {
            warn "$job : Retrying\n";

            my $ans = $jenkins->trigger_build($job);
            $number = $result->{nextBuildNumber};
        }
        else {
            my $last_status = $result->{builds}[1]{result} || 'NOT RUN';
            printf "%s: Current run time %is, last status was %s\n", $job, time - $build->{timestamp} / 1000, $last_status;

            if ( $build->{building} ) {
                $number = $result->{nextBuildNumber} - 1;
            }
        }

        sleep $options->sleep;

        ($result, $build) = status($jenkins, $job);
    }

    printf "%s: %s\n", $job, $build->{result};

    return;
}

sub status {
    my ($jenkins, $job) = @_;

    my $result = $jenkins->_json_api(['job', $job, 'api', 'json'], { extra_params => { depth => 1 } });
    my $build  = $result->{builds}[0];

    return ($result, $build);
}

__DATA__

=head1 NAME

example/rebuild-to-success - <One-line description of commands purpose>

=head1 VERSION

This documentation refers to example/rebuild-to-success version 0.013

=head1 SYNOPSIS

   example/rebuild-to-success [option]

 OPTIONS:
  -o --other         other option

  -v --verbose       Show more detailed option



( run in 0.690 second using v1.01-cache-2.11-cpan-5a3173703d6 )