Util.pm 20.1 KB
Newer Older
1
package ksb::Util 0.30;
2 3 4

# Useful utilities, which are exported into the calling module's namespace by default.

5
use 5.014; # Needed for state keyword
6 7 8 9 10
use strict;
use warnings;

use Scalar::Util qw(blessed);
use File::Path qw(make_path);
11
use File::Find;
12 13 14 15 16 17
use Cwd qw(getcwd);
use Errno qw(:POSIX);
use Digest::MD5;

use ksb::Debug;
use ksb::Version qw(scriptVersion);
18
use ksb::BuildException;
19 20

use Exporter qw(import); # Use Exporter's import method
Michael Pyne's avatar
Michael Pyne committed
21
our @EXPORT = qw(list_has assert_isa assert_in any unique_items
22
                 absPathToExecutable
23
                 fileDigestMD5 log_command disable_locale_message_translation
24
                 trimmed
25
                 split_quoted_on_whitespace safe_unlink safe_system p_chdir
26
                 pretend_open safe_rmtree get_list_digest is_dir_empty
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
                 super_mkdir filter_program_output prettify_seconds);

# Function to work around a Perl language limitation.
# First parameter is a reference to the list to search. ALWAYS.
# Second parameter is the value to search for.
# Returns true if the value is in the list
sub list_has
{
    my ($listRef, $value) = @_;
    my @list = @{$listRef};

    return scalar grep { "$_" eq "$value" } (@list);
}

# Subroutine to return the path to the given executable based on the
# current PATH.  e.g. if you pass make you could get '/usr/bin/make'.  If
# the executable is not found undef is returned.
#
# This assumes that the module environment has already been updated since
# binpath doesn't exactly correspond to $ENV{'PATH'}.
sub absPathToExecutable
{
    my $prog = shift;
    my @paths = split(/:/, $ENV{'PATH'});

    # If it starts with a / the path is already absolute.
    return $prog if $prog =~ /^\//;

    for my $path (@paths)
    {
        return "$path/$prog" if (-x "$path/$prog");
    }

    return undef;
}

# Throws an exception if the first parameter is not an object at all, or if
# it is not an object of the type given by the second parameter (which
# should be a string of the class name. There is no return value;
sub assert_isa
{
    my ($obj, $class) = @_;

    if (!blessed($obj) || !$obj->isa($class)) {
71
        croak_internal("$obj is not of type $class, but of type " . ref($obj));
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    }

    return $obj;
}

# Throws an exception if the first parameter is not included in the
# provided list of possible alternatives. The list of alternatives must
# be passed as a reference, as the second parameter.
sub assert_in
{
    my ($val, $listRef) = @_;

    if (!list_has($listRef, $val)) {
        croak_runtime("$val is not a permissible value for its argument");
    }

    return $val;
}

# Subroutine to unlink the given symlink if global-pretend isn't set.
sub safe_unlink
{
    if (pretending())
    {
        pretend ("\tWould have unlinked ", shift, ".");
        return 1; # Return true
    }

    return unlink (shift);
}

# Subroutine to execute the system call on the given list if the pretend
# global option is not set.
#
# Returns the shell error code, so 0 means success, non-zero means failure.
sub safe_system(@)
{
    if (!pretending())
    {
        whisper ("\tExecuting g['", join("' '", @_), "'");
        return system (@_) >> 8;
    }

115
    pretend ("\tWould have run g['" . join("' '", @_) . "'");
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    return 0; # Return true
}

# Is exactly like "chdir", but it will also print out a message saying that
# we're switching to the directory when debugging.
sub p_chdir($)
{
    my $dir = shift;
    debug ("\tcd g[$dir]\n");

    chdir ($dir) or do {
        return 1 if pretending();
        croak_runtime("Could not change to directory $dir: $!");
    };
}

# Helper subroutine to create a directory, including any parent
# directories that may also need created.
# Throws an exception on failure. See File::Path.
sub super_mkdir
{
    my $pathname = shift;
    state %createdPaths;

    if (pretending()) {
        if (!exists $createdPaths{$pathname} && ! -e $pathname) {
            pretend ("\tWould have created g[$pathname]");
        }

        $createdPaths{$pathname} = 1;
        return 1;
    }
    else {
        make_path($pathname);
        return (-e $pathname) ? 1 : 0;
    }
}

# Calculates the MD5 digest of a file already on-disk. The digest is
# returned as a hex string digest as from Digest::MD5::md5_hex
#
# First parameter: File name to read
# Return value: hex string MD5 digest of file.
# An exception is thrown if an error occurs reading the file.
sub fileDigestMD5
{
    my $fileName = shift;
    my $md5 = Digest::MD5->new;

    open my $file, '<', $fileName or croak_runtime(
        "Unable to open $fileName: $!");
    binmode($file);

    $md5->addfile($file);
    return $md5->hexdigest();
}

# This function is intended to disable the message translation catalog
# settings in the program environment, so that any child processes executed
# will have their output untranslated (and therefore scrapeable).
#
# As such this should only be called for a forked child about to exec as
# there is no easy way to undo this within the process.
sub disable_locale_message_translation
{
    # Ensure that program output is untranslated by setting 'C' locale.
    # We're really trying to affect the LC_MESSAGES locale category, but
    # LC_ALL is a catch-all for that (so needs to be unset if set).
    #
    # Note that the ONLY SUPPORTED way to pass file names, command-line
    # args, etc. to commands is under the UTF-8 encoding at this point, as
    # that is the only sane way for this en_US-based developer to handle
    # the task.  Patches (likely using Encode::Locale) are accepted. :P

    $ENV{'LC_MESSAGES'} = 'C';
    if ($ENV{'LC_ALL'}) {
        $ENV{'LANG'} = $ENV{'LC_ALL'}; # This is lower-priority "catch all"
        delete $ENV{'LC_ALL'};
    }
}

# Returns an array of lines output from a program.  Use this only if you
# expect that the output will be short.
#
# Since there is no way to disambiguate no output from an error, this
# function will call die on error, wrap in eval if this bugs you.
#
# First parameter is subroutine reference to use as a filter (this sub will
# be passed a line at a time and should return true if the line should be
# returned).  If no filtering is desired pass 'undef'.
#
# Second parameter is the program to run (either full path or something
# accessible in $PATH).
#
# All remaining arguments are passed to the program.
#
# Return value is an array of lines that were accepted by the filter.
sub filter_program_output
{
    my ($filterRef, $program, @args) = @_;
    $filterRef //= sub { return 1 }; # Default to all lines

    debug ("Slurping '$program' '", join("' '", @args), "'");

220 221 222 223 224 225 226
    # Check early for whether an executable exists since otherwise
    # it is possible for our fork-open below to "succeed" (i.e. fork()
    # happens OK) and then fail when it gets to the exec(2) syscall.
    if (!absPathToExecutable($program)) {
        croak_runtime("Can't find $program in PATH!");
    }

227
    my $execFailedError = "\t - kdesrc-build - exec failed!\n";
228 229 230 231 232 233
    my $pid = open(my $childOutput, '-|');
    croak_internal("Can't fork: $!") if ! defined($pid);

    if ($pid) {
        # parent
        my @lines = grep { &$filterRef; } (<$childOutput>);
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        close $childOutput or do {
            # $! indicates a rather grievous error
            croak_internal("Unable to open pipe to read $program output: $!") if $!;

            # we can pass serious errors back to ourselves too.
            my $exitCode = $? >> 8;
            if ($exitCode == 99 && @lines >= 1 && $lines[0] eq $execFailedError) {
                croak_runtime("Failed to exec $program, is it installed?");
            }

            # other errors might still be serious but don't need a backtrace
            if (pretending()) {
                whisper ("$program gave error exit code $exitCode");
            } else {
                warning ("$program gave error exit code $exitCode");
            }
        };
251 252 253 254 255 256 257 258 259

        return @lines;
    }
    else {
        disable_locale_message_translation();

        # We don't want stderr output on tty.
        open (STDERR, '>', '/dev/null') or close (STDERR);

260 261 262 263 264
        exec { $program } ($program, @args) or do {
            # Send a message back to parent
            print $execFailedError;
            exit 99; # Helper proc, so don't use finish(), just die
        };
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    }
}

# Subroutine to return a string suitable for displaying an elapsed time,
# (like a stopwatch) would.  The first parameter is the number of seconds
# elapsed.
sub prettify_seconds
{
    my $elapsed = $_[0];
    my $str = "";
    my ($days,$hours,$minutes,$seconds,$fraction);

    $fraction = int (100 * ($elapsed - int $elapsed));
    $elapsed = int $elapsed;

    $seconds = $elapsed % 60;
    $elapsed = int $elapsed / 60;

    $minutes = $elapsed % 60;
    $elapsed = int $elapsed / 60;

    $hours = $elapsed % 24;
    $elapsed = int $elapsed / 24;

    $days = $elapsed;

    $seconds = "$seconds.$fraction" if $fraction;

    my @str_list;

    for (qw(days hours minutes seconds))
    {
        # Use a symbolic reference without needing to disable strict refs.
        # I couldn't disable it even if I wanted to because these variables
        # aren't global or localized global variables.
        my $value = eval "return \$$_;";
        my $text = $_;
        $text =~ s/s$// if $value == 1; # Make singular

        push @str_list, "$value $text" if $value or $_ eq 'seconds';
    }

    # Add 'and ' in front of last element if there was more than one.
    push @str_list, ("and " . pop @str_list) if (scalar @str_list > 1);

    $str = join (", ", @str_list);

    return $str;
}

# Subroutine to mark a file as being the error log for a module.  This also
# creates a symlink in the module log directory for easy viewing.
# First parameter is the module in question.
# Second parameter is the filename in the log directory of the error log.
sub _setErrorLogfile
{
321
    my $module = assert_isa(shift, 'ksb::Module');
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    my $logfile = shift;

    return unless $logfile;

    my $logdir = $module->getLogDir();

    $module->setOption('#error-log-file', "$logdir/$logfile");
    debug ("Logfile for $module is $logfile");

    # Setup symlink in the module log directory pointing to the appropriate
    # file.  Make sure to remove it first if it already exists.
    unlink("$logdir/error.log") if -l "$logdir/error.log";

    if(-e "$logdir/error.log")
    {
        # Maybe it was a regular file?
        error ("r[b[ * Unable to create symlink to error log file]");
        return;
    }

    symlink "$logfile", "$logdir/error.log";
}


# Subroutine to run a command, optionally filtering on the output of the child
# command.
#
# First parameter is the module object being built (for logging purposes
#   and such).
# Second parameter is the name of the log file to use (relative to the log
#   directory).
# Third parameter is a reference to an array with the command and its
#   arguments.  i.e. ['command', 'arg1', 'arg2']
#
# After the required three parameters you can pass a hash reference of
# optional features:
#   'callback' => a reference to a subroutine to have each line
#   of child output passed to.  This output is not supposed to be printed
#   to the screen by the subroutine, normally the output is only logged.
#   However this is useful for e.g. munging out the progress of the build.
#   USEFUL: When there is no more output from the child, the callback will be
#     called with an undef string.  (Not just empty, it is also undefined).
#
#   'no_translate' => any true value will cause a flag to be set to request
#   the executed child process to not translate (for locale purposes) its
#   output, so that it can be screen-scraped.
#
# The return value is the shell return code, so 0 is success, and non-zero is
#   failure.
#
# NOTE: This function has a special feature.  If the command passed into the
#   argument reference is 'kdesrc-build', then log_command will, when it
#   forks, execute the subroutine named by the second parameter rather than
#   executing a child process.  The subroutine should include the full package
#   name as well (otherwise the package containing log_command's implementation
#   is used).  The remaining arguments in the list are passed to the
#   subroutine that is called.
sub log_command
{
    my ($module, $filename, $argRef, $optionsRef) = @_;
382
    assert_isa($module, 'ksb::Module');
383 384 385 386 387 388 389
    my @command = @{$argRef};

    $optionsRef //= { };
    my $callbackRef = $optionsRef->{'callback'};

    debug ("log_command(): Module $module, Command: ", join(' ', @command));

390 391 392 393 394 395
    if (pretending())
    {
        pretend ("\tWould have run g['" . join ("' '", @command) . "'");
        return 0;
    }

396 397 398
    # Do this before we fork so we can see errors
    my $logpath = $module->getLogPath("$filename.log");

399 400 401 402 403 404 405
    # Fork a child, with its stdout connected to CHILD.
    my $pid = open(CHILD, '-|');
    if ($pid)
    {
        # Parent
        if (!$callbackRef && debugging()) {
            # If no other callback given, pass to debug() if debug-mode is on.
406
            while (<CHILD>) {
Michael Pyne's avatar
Michael Pyne committed
407
                print ($_) if $_;
408
            }
409 410
        }

411 412
        if ($callbackRef) {
            &{$callbackRef}($_) while (<CHILD>);
413

414 415 416
            # Let callback know there is no more output.
            &{$callbackRef}(undef);
        }
417

Michael Pyne's avatar
Michael Pyne committed
418 419 420 421 422 423
        # This implicitly does a waitpid() as well
        close CHILD or do {
            if ($! == 0) {
                _setErrorLogfile($module, "$filename.log");
                return $?;
            }
424

Michael Pyne's avatar
Michael Pyne committed
425 426
            return 1;
        };
427

Michael Pyne's avatar
Michael Pyne committed
428
        return 0;
429 430 431 432 433 434 435 436 437
    }
    else
    {
        # Child. Note here that we need to avoid running our exit cleanup
        # handlers in here. For that we need POSIX::_exit.

        # Apply altered environment variables.
        $module->buildContext()->commitEnvironmentChanges();

438
        $SIG{PIPE} = "IGNORE";
Michael Pyne's avatar
Michael Pyne committed
439 440 441 442 443
        $SIG{INT} = sub {
            close (STDOUT); # This should be a pipe
            close (STDERR);
            POSIX::_exit(EINTR);
        };
444

445 446 447 448 449
        # Redirect STDIN to /dev/null so that the handle is open but fails when
        # being read from (to avoid waiting forever for e.g. a password prompt
        # that the user can't see.

        open (STDIN, '<', "/dev/null") unless exists $ENV{'KDESRC_BUILD_USE_TTY'};
Michael Pyne's avatar
Michael Pyne committed
450
        if ($callbackRef || debugging()) {
451
            open (STDOUT, "|tee $logpath") or do {
452 453 454 455 456
                error ("Error opening pipe to tee command.");
                # Don't abort, hopefully STDOUT still works.
            };
        }
        else {
457 458 459
            open (STDOUT, '>', $logpath) or do {
                error ("Error $! opening log to $logpath!");
            };
460
        }
461 462

        # Make sure we log everything.
463
        open (STDERR, ">&STDOUT");
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

        # Call internal function, name given by $command[1]
        if ($command[0] eq 'kdesrc-build')
        {
            # No colors!
            ksb::Debug::setColorfulOutput(0);
            debug ("Calling $command[1]");

            my $cmd = $command[1];
            splice (@command, 0, 2); # Remove first two elements.

            no strict 'refs'; # Disable restriction on symbolic subroutines.
            if (! &{$cmd}(@command)) # Call sub
            {
                POSIX::_exit (EINVAL);
            }

            POSIX::_exit (0); # Exit child process successfully.
        }

        # Don't leave empty output files, give an indication of the particular
        # command run. Use print to go to stdout.
        say "# kdesrc-build running: '", join("' '", @command), "'";
        say "# from directory: ", getcwd();

        # If a callback is set assume no translation can be permitted.
        disable_locale_message_translation() if $optionsRef->{'no_translate'};

        # External command.
        exec (@command) or do {
            my $cmd_string = join(' ', @command);
            error (<<EOF);
r[b[Unable to execute "$cmd_string"]!
$!

Please check your binpath setting (it controls the PATH used by kdesrc-build).
Currently it is set to g[$ENV{PATH}].
EOF
            # Don't use return, this is the child still!
            POSIX::_exit (1);
        };
    }
}

508 509 510 511 512 513 514 515 516
# removes leading/trailing whitespace
sub trimmed
{
    my $str = shift;
    $str =~ s/^\s+//;
    $str =~ s/\s+$//;
    return $str;
}

517 518 519 520 521 522 523 524 525
# This subroutine acts like split(' ', $_) except that double-quoted strings
# are not split in the process.
#
# First parameter: String to split on whitespace.
# Return value: A list of the individual words and quoted values in the string.
# The quotes themselves are not returned.
sub split_quoted_on_whitespace
{
    use Text::ParseWords qw(parse_line);
526
    my $line = trimmed(shift);
527 528 529 530 531

    # 0 means not to keep delimiters or quotes
    return parse_line('\s+', 0, $line);
}

532 533 534 535 536 537 538 539 540
# Function: pretend_open
#
# Opens the given file and returns a filehandle to it if the file actually
# exists or the script is not in pretend mode. If the script is in pretend mode
# and the file is not already present then an open filehandle to an empty
# string is returned.
#
# Parameters:
#  filename - Path to the file to open.
541
#  default  - String to use if the file doesn't exist in pretend mode
542 543 544 545 546 547 548 549
#
# Returns:
#  filehandle on success (supports readline() and eof()), can return boolean
#  false if there is an error opening an existing file (or if the file doesn't
#  exist when not in pretend mode)
sub pretend_open
{
    my $path = shift;
550
    my $defaultText = shift // '';
551 552 553
    my $fh;

    if (pretending() && ! -e $path) {
554
        open $fh, '<', \$defaultText or return;
555 556 557 558
    }
    else {
        open $fh, '<', $path or return;
    }
559 560 561 562

    return $fh;
}

563 564 565 566 567 568 569 570
# Returns true if the given sub returns true for any item in the given listref.
sub any(&@)
{
    my ($subRef, $listRef) = @_;
    ($subRef->($_) && return 1) foreach @{$listRef};
    return 0;
}

Michael Pyne's avatar
Michael Pyne committed
571 572 573 574 575 576 577 578 579
# Returns unique items of the list. Order not guaranteed.
sub unique_items
{
    # See perlfaq4
    my %seen;
    my @results = grep { ! $seen{$_}++; } @_;
    return @results;
}

580
# Subroutine to delete a directory and all files and subdirectories within.
Yuri Chornoivan's avatar
Yuri Chornoivan committed
581
# Does nothing in pretend mode.  An analog to "rm -rf" from Linux.
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
# Requires File::Find module.
#
# First parameter: Path to delete
# Returns boolean true on success, boolean false for failure.
sub safe_rmtree
{
    my $path = shift;

    # Pretty user-visible path
    my $user_path = $path;
    $user_path =~ s/^$ENV{HOME}/~/;

    my $delete_file_or_dir = sub {
        # $_ is the filename/dirname.
        return if $_ eq '.' or $_ eq '..';
        if (-f $_ || -l $_)
        {
            unlink ($_) or croak_runtime("Unable to delete $File::Find::name: $!");
        }
        elsif (-d $_)
        {
            rmdir ($File::Find::name) or
                croak_runtime("Unable to remove directory $File::Find::name: $!");
        }
    };

    if (pretending())
    {
        pretend ("Would have removed all files/folders in $user_path");
        return 1;
    }

    # Error out because we probably have a logic error even though it would
    # delete just fine.
    if (not -d $path)
    {
        error ("Cannot recursively remove $user_path, as it is not a directory.");
        return 0;
    }

    eval {
        $@ = '';
        finddepth( # finddepth does a postorder traversal.
        {
            wanted => $delete_file_or_dir,
            no_chdir => 1, # We'll end up deleting directories, so prevent this.
        }, $path);
    };

    if ($@)
    {
        error ("Unable to remove directory $user_path: $@");
        return 0;
    }

    return 1;
}

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
# Returns a hash digest of the given options in the list.  The return value is
# base64-encoded at this time.
#
# Note: Don't be dumb and pass data that depends on execution state as the
# returned hash is almost certainly not useful for whatever you're doing with
# it.  (i.e. passing a reference to a list is not helpful, pass the list itself)
#
# Parameters: List of scalar values to hash.
# Return value: base64-encoded hash value.
sub get_list_digest
{
    use Digest::MD5 "md5_base64"; # Included standard with Perl 5.8

    return md5_base64(@_);
}

656 657 658 659 660
# Utility function to see if a directory path is empty or not
sub is_dir_empty
{
    my $dir = shift;

661
    opendir my $dirh, $dir or return;
662 663 664 665 666 667

    # while-readdir needs Perl 5.12
    while (readdir $dirh) {
        next if ($_ eq '.' || $_ eq '..');

        closedir ($dirh);
668
        return; # not empty
669 670 671 672 673 674
    }

    closedir ($dirh);
    return 1;
}

675 676
1;