Application.pm 87.5 KB
Newer Older
1
package ksb::Application 0.20;
2 3 4 5 6 7 8 9

# Class: Application
#
# Contains the application-layer logic (i.e. creating a build context, reading
# options, parsing command-line, etc.)

use strict;
use warnings;
10
use 5.014;
11 12 13 14
no if $] >= 5.018, 'warnings', 'experimental::smartmatch';

use ksb::Debug;
use ksb::Util;
15
use ksb::BuildContext 0.35;
16
use ksb::BuildSystem::QMake;
17
use ksb::BuildException 0.20;
18
use ksb::FirstRun;
19
use ksb::Module;
20
use ksb::ModuleResolver 0.20;
21
use ksb::ModuleSet 0.20;
22
use ksb::ModuleSet::KDEProjects;
23
use ksb::OSSupport;
24
use ksb::RecursiveFH;
25 26 27 28
use ksb::DependencyResolver 0.20;
use ksb::IPC::Pipe 0.20;
use ksb::IPC::Null;
use ksb::Updater::Git;
29 30 31
use ksb::Version qw(scriptVersion);

use List::Util qw(first min);
32
use File::Basename; # basename, dirname
33
use File::Glob ':glob';
Michael Pyne's avatar
Michael Pyne committed
34
use POSIX qw(:sys_wait_h _exit :errno_h);
35
use Getopt::Long qw(GetOptionsFromArray :config gnu_getopt nobundling);
36 37
use IO::Handle;
use IO::Select;
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

### Package-specific variables (not shared outside this file).

use constant {
    # We use a named remote to make some git commands work that don't accept the
    # full path.
    KDE_PROJECT_ID   => 'kde-projects',          # git-repository-base for kde_projects.xml
};

### Package methods

sub new
{
    my ($class, @options) = @_;

    my $self = bless {
        context         => ksb::BuildContext->new(),
        metadata_module => undef,
        run_mode        => 'build',
        modules         => undef,
58 59
        module_factory  => undef, # ref to sub that makes a new Module.
                                  # See generateModuleList
60
        _base_pid       => $$, # See finish()
61 62 63 64 65 66 67 68
    }, $class;

    # Default to colorized output if sending to TTY
    ksb::Debug::setColorfulOutput(-t STDOUT);

    my @moduleList = $self->generateModuleList(@options);
    $self->{modules} = \@moduleList;

69 70 71 72 73
    if (!@moduleList) {
        print "No modules to build, exiting.\n";
        exit 0;
    }

74 75 76 77 78 79 80 81 82 83
    $self->context()->setupOperatingEnvironment(); # i.e. niceness, ulimits, etc.

    # After this call, we must run the finish() method
    # to cleanly complete process execution.
    if (!pretending() && !$self->context()->takeLock())
    {
        print "$0 is already running!\n";
        exit 1; # Don't finish(), it's not our lockfile!!
    }

84 85 86 87 88 89 90
    # Install signal handlers to ensure that the lockfile gets closed.
    _installSignalHandlers(sub {
        note ("Signal received, terminating.");
        @main::atexit_subs = (); # Remove their finish, doin' it manually
        $self->finish(5);
    });

91 92 93
    return $self;
}

94 95 96 97 98 99 100 101 102 103 104 105 106
# Method: _readCommandLineOptionsAndSelectors
#
# Returns a list of module/module-set selectors, selected module/module-set
# options, and global options, based on the command-line arguments passed to
# this function.
#
# This is a package method, should be called as
# $app->_readCommandLineOptionsAndSelectors
#
# Phase:
#  initialization - Do not call <finish> from this function.
#
# Parameters:
107
#  cmdlineOptions - hashref to hold parsed modules options to be applied later.
108
#    *Note* this must be done separately, it is not handled by this subroutine.
109
#    Global options will be stored in a hashref at $cmdlineOptions->{global}.
110
#    Module or module-set options will be stored in a hashref at
111
#    $cmdlineOptions->{$moduleName} (it will be necessary to disambiguate
112 113
#    later in the run whether it is a module set or a single module).
#
114 115 116
#    If the global option 'start-program' is set, then the program to start and
#    its options will be found in a listref pointed to under the
#    'start-program' option.
117 118 119 120 121
#
#  selectors - listref to hold the list of module or module-set selectors to
#    build, in the order desired by the user. These will just be strings, the
#    caller will have to figure out whether the selector is a module or
#    module-set, and create any needed objects, and then set the recommended
122
#    options as listed in cmdlineOptions.
123
#
124
#  ctx - <BuildContext> to hold the global build state.
125 126 127 128 129 130 131 132 133 134
#
#  @options - The remainder of the arguments are treated as command line
#    arguments to process.
#
# Returns:
#  Nothing. An exception will be raised on failure, or this function may quit
#  the program directly (e.g. to handle --help, --usage).
sub _readCommandLineOptionsAndSelectors
{
    my $self = shift;
135
    my ($cmdlineOptionsRef, $selectorsRef, $ctx, @options) = @_;
136
    my $phases = $ctx->phases();
137
    my @savedOptions = @options; # Copied for use in debugging.
138
    my $os = ksb::OSSupport->new;
139
    my $version = "kdesrc-build " . scriptVersion();
140 141 142 143 144 145
    my $author = <<DONE;
$version was written (mostly) by:
  Michael Pyne <mpyne\@kde.org>

Many people have contributed code, bugfixes, and documentation.

146
Please report bugs using the KDE Bugzilla, at https://bugs.kde.org/
147 148
DONE

149 150 151 152 153 154
    # Getopt::Long will store options in %foundOptions, since that is what we
    # pass in. To allow for custom subroutines to handle an option it is
    # required that the sub *also* be in %foundOptions... whereupon it will
    # promptly be overwritten if we're not careful. Instead we let the custom
    # subs save to %auxOptions, and read those in back over it later.
    my (%foundOptions, %auxOptions);
155
    %foundOptions = (
156
        'show-info' => sub { say $version; say "OS: ", $os->vendorID(); exit },
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        version => sub { say $version; exit },
        author  => sub { say $author;  exit },
        help    => sub { _showHelpMessage(); exit 0 },
        install => sub {
            $self->{run_mode} = 'install';
            $phases->phases('install');
        },
        uninstall => sub {
            $self->{run_mode} = 'uninstall';
            $phases->phases('uninstall');
        },
        'no-src' => sub {
            $phases->filterOutPhase('update');
        },
        'no-install' => sub {
            $phases->filterOutPhase('install');
        },
174 175 176 177
        'no-snapshots' => sub {
            # The documented form of disable-snapshots
            $auxOptions{'disable-snapshots'} = 1;
        },
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        'no-tests' => sub {
            # The "right thing" to do
            $phases->filterOutPhase('test');

            # What actually works at this point.
            $foundOptions{'run-tests'} = 0;
        },
        'no-build' => sub {
            $phases->filterOutPhase('build');
        },
        # Mostly equivalent to the above
        'src-only' => sub {
            $phases->phases('update');

            # We have an auto-switching function that we only want to run
            # if --src-only was passed to the command line, so we still
            # need to set a flag for it.
            $foundOptions{'allow-auto-repo-move'} = 1;
        },
        'build-only' => sub {
            $phases->phases('build');
        },
200 201 202 203
        'install-only' => sub {
            $self->{run_mode} = 'install';
            $phases->phases('install');
        },
204 205
        prefix => sub {
            my ($optName, $arg) = @_;
206
            $auxOptions{prefix} = $arg;
207 208 209
            $foundOptions{kdedir} = $arg; #TODO: Still needed for compat?
            $foundOptions{reconfigure} = 1;
        },
210 211 212 213 214 215 216 217 218 219 220 221 222 223
        query => sub {
            my (undef, $arg) = @_;

            my $validMode = qr/^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/;
            die("Invalid query mode $arg")
                unless $arg =~ $validMode;

            # Add useful aliases
            $arg = 'source-dir'  if $arg =~ /^src-?dir$/;
            $arg = 'build-dir'   if $arg =~ /^build-?dir$/;
            $arg = 'install-dir' if $arg eq 'prefix';

            $self->{run_mode} = 'query';
            $auxOptions{query} = $arg;
224
            $auxOptions{pretend} = 1; # Implied pretend mode
225
        },
226 227
        pretend => sub {
            # Set pretend mode but also force the build process to run.
228
            $auxOptions{pretend} = 1;
229 230
            $foundOptions{'build-when-unchanged'} = 1;
        },
231 232 233 234 235
        resume => sub {
            $auxOptions{resume} = 1;
            $phases->filterOutPhase('update'); # Implied --no-src
            $foundOptions{'no-metadata'} = 1;  # Implied --no-metadata
        },
236 237 238 239 240 241 242 243 244 245 246 247 248
        verbose => sub { $foundOptions{'debug-level'} = ksb::Debug::WHISPER },
        quiet => sub { $foundOptions{'debug-level'} = ksb::Debug::NOTE },
        'really-quiet' => sub { $foundOptions{'debug-level'} = ksb::Debug::WARNING },
        debug => sub {
            $foundOptions{'debug-level'} = ksb::Debug::DEBUG;
            debug ("Commandline was: ", join(', ', @savedOptions));
        },

        # Hack to set module options
        'set-module-option-value' => sub {
            my ($optName, $arg) = @_;
            my ($module, $option, $value) = split (',', $arg, 3);
            if ($module && $option) {
249 250
                $cmdlineOptionsRef->{$module} //= { };
                $cmdlineOptionsRef->{$module}->{$option} = $value;
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
            }
        },

        # Getopt::Long doesn't set these up for us even though we specify an
        # array. Set them up ourselves.
        'start-program' => [ ],
        'ignore-modules' => [ ],

        # Module selectors, the <> is Getopt::Long shortcut for an
        # unrecognized non-option value (i.e. an actual argument)
        '<>' => sub {
            my $arg = shift;
            push @{$selectorsRef}, $arg;
        },
    );

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    # Handle any "cmdline-eligible" options not already covered.
    my $flagHandler = sub {
        my ($optName, $optValue) = @_;

        # Assume to set if nothing provided.
        $optValue = 1 if (!defined $optValue or $optValue eq '');
        $optValue = 0 if lc($optValue) eq 'false';
        $optValue = 0 if !$optValue;

        $auxOptions{$optName} = $optValue;
    };

    foreach my $option (keys %ksb::BuildContext::defaultGlobalFlags) {
        if (!exists $foundOptions{$option}) {
            $foundOptions{$option} = $flagHandler; # A ref to a sub here!
        }
    }

    # Actually read the options.
286
    my $optsSuccess = GetOptionsFromArray(\@options, \%foundOptions,
287 288
        # Options here should not duplicate the flags and options defined below
        # from ksb::BuildContext!
289
        'version|v', 'author', 'help', 'show-info',
290
        'install', 'uninstall', 'no-src|no-svn', 'no-install', 'no-build',
291
        'no-tests', 'build-when-unchanged|force-build', 'no-metadata',
292
        'verbose', 'quiet|quite|q', 'really-quiet', 'debug',
293
        'reconfigure', 'colorful-output|color!', 'async!',
294
        'src-only|svn-only', 'build-only', 'install-only', 'build-system-only',
295
        'rc-file=s', 'prefix=s', 'niceness|nice:10', 'ignore-modules=s{,}',
296
        'print-modules', 'pretend|dry-run|p', 'refresh-build',
297
        'query=s', 'start-program|run=s{,}',
298
        'revision=i', 'resume-from=s', 'resume-after=s',
299
        'rebuild-failures', 'resume',
300
        'stop-after=s', 'stop-before=s', 'set-module-option-value=s',
301
        'metadata-only', 'include-dependencies',
302 303

        # Special sub used (see above), but have to tell Getopt::Long to look
304 305
        # for negatable boolean flags
        (map { "$_!" } (keys %ksb::BuildContext::defaultGlobalFlags)),
306 307 308 309

        # Default handling fine, still have to ask for strings.
        (map { "$_:s" } (keys %ksb::BuildContext::defaultGlobalOptions)),

310 311 312
        '<>', # Required to read non-option args
        );

313 314 315 316
    if (!$optsSuccess) {
        croak_runtime("Error reading command-line options.");
    }

317 318 319 320 321 322 323 324 325 326
    # To store the values we found, need to strip out the values that are
    # subroutines, as those are the ones we created. Alternately, place the
    # subs inline as an argument to the appropriate option in the
    # GetOptionsFromArray call above, but that's ugly too.
    my @readOptionNames = grep {
        ref($foundOptions{$_}) ne 'CODE'
    } (keys %foundOptions);

    # Slice assignment: $left{$key} = $right{$key} foreach $key (@keys), but
    # with hashref syntax everywhere.
327
    @{ $cmdlineOptionsRef->{'global'} }{@readOptionNames}
328
        = @foundOptions{@readOptionNames};
329

330
    @{ $cmdlineOptionsRef->{'global'} }{keys %auxOptions}
331
        = values %auxOptions;
332 333
}

334
# Generates the build context and module list based on the command line options
335 336
# and module selectors provided, resolves dependencies on those modules if needed,
# filters out ignored or skipped modules, and sets up the module factory.
337 338
#
# After this function is called all module set selectors will have been
339
# expanded, and we will have downloaded kde-projects metadata.
340 341
#
# Returns: List of Modules to build.
342 343 344 345 346 347 348 349 350
sub generateModuleList
{
    my $self = shift;
    my @argv = @_;

    # Note: Don't change the order around unless you're sure of what you're
    # doing.

    my $ctx = $self->context();
351 352
    my $cmdlineOptions = { global => { }, };
    my $cmdlineGlobalOptions = $cmdlineOptions->{global};
353
    my $deferredOptions = { }; # 'options' blocks
354 355

    # Process --help, --install, etc. first.
356
    my @selectors;
357
    $self->_readCommandLineOptionsAndSelectors($cmdlineOptions, \@selectors,
358
        $ctx, @argv);
359

360 361 362
    # Convert list to hash for lookup
    my %ignoredSelectors =
        map { $_, 1 } @{$cmdlineGlobalOptions->{'ignore-modules'}};
363

364 365
    my @startProgramAndArgs = @{$cmdlineGlobalOptions->{'start-program'}};
    delete @{$cmdlineGlobalOptions}{qw/ignore-modules start-program/};
366

367
    # rc-file needs special handling.
368 369
    if (exists $cmdlineGlobalOptions->{'rc-file'} && $cmdlineGlobalOptions->{'rc-file'}) {
        $ctx->setRcFile($cmdlineGlobalOptions->{'rc-file'});
370 371 372
    }

    # disable async if only running a single phase.
373
    $cmdlineGlobalOptions->{async} = 0 if (scalar $ctx->phases()->phases() == 1);
374 375

    my $fh = $ctx->loadRcFile();
376 377
    $ctx->loadPersistentOptions();

378
    if (exists $cmdlineGlobalOptions->{'resume'}) {
379 380 381 382 383 384 385 386 387
        my $moduleList = $ctx->getPersistentOption('global', 'resume-list');
        if (!$moduleList) {
            error ("b[--resume] specified, but unable to find resume point!");
            error ("Perhaps try b[--resume-from] or b[--resume-after]?");
            croak_runtime("Invalid --resume flag");
        }

        unshift @selectors, split(/,\s*/, $moduleList);
    }
388

389
    if (exists $cmdlineGlobalOptions->{'rebuild-failures'}) {
390 391 392 393 394 395 396 397 398 399
        my $moduleList = $ctx->getPersistentOption('global', 'last-failed-module-list');
        if (!$moduleList) {
            error ("b[y[--rebuild-failures] was specified, but unable to determine");
            error ("which modules have previously failed to build.");
            croak_runtime("Invalid --rebuild-failures flag");
        }

        unshift @selectors, split(/,\s*/, $moduleList);
    }

400 401 402
    # _readConfigurationOptions will add pending global opts to ctx while ensuring
    # returned modules/sets have any such options stripped out. It will also add
    # module-specific options to any returned modules/sets.
403
    my @optionModulesAndSets = _readConfigurationOptions($ctx, $fh, $deferredOptions);
404 405 406 407 408
    close $fh;

    # Check if we're supposed to drop into an interactive shell instead.  If so,
    # here's the stop off point.

409
    if (@startProgramAndArgs) {
410 411 412
        $ctx->setupEnvironment(); # Read options from set-env
        $ctx->commitEnvironmentChanges(); # Apply env options to environment
        _executeCommandLineProgram(@startProgramAndArgs); # noreturn
413 414
    }

415 416 417 418
    # Everything else in cmdlineOptions should be OK to apply directly as a module
    # or context option.
    $ctx->setOption(%{$cmdlineGlobalOptions});

419 420 421
    # Selecting modules or module sets would requires having the KDE
    # build metadata (kde-build-metadata and sysadmin/repo-metadata)
    # available.
422
    $ctx->setKDEDependenciesMetadataModuleNeeded();
423
    $ctx->setKDEProjectsMetadataModuleNeeded();
424 425 426 427 428 429 430

    if (!exists $ENV{HARNESS_ACTIVE}) {
        # Running in a test harness, avoid downloading metadata which will be
        # ignored in the test or making changes to git config
        ksb::Updater::Git::verifyGitConfig();
        $self->_downloadKDEProjectMetadata();
    }
431 432 433

    # The user might only want metadata to update to allow for a later
    # --pretend run, check for that here.
434
    if (exists $cmdlineGlobalOptions->{'metadata-only'}) {
435 436 437
        return;
    }

438 439 440 441 442
    # At this point we have our list of candidate modules / module-sets (as read in
    # from rc-file). The module sets have not been expanded into modules.
    # We also might have cmdline "selectors" to determine which modules or
    # module-sets to choose. First let's select module sets, and expand them.

443
    my @globalCmdlineArgs = keys %{$cmdlineGlobalOptions};
444
    my $commandLineModules = scalar @selectors;
445

446
    my $moduleResolver = ksb::ModuleResolver->new($ctx);
447
    $moduleResolver->setCmdlineOptions($cmdlineOptions);
448
    $moduleResolver->setDeferredOptions($deferredOptions);
449
    $moduleResolver->setInputModulesAndOptions(\@optionModulesAndSets);
450
    $moduleResolver->setIgnoredSelectors([keys %ignoredSelectors]);
451

452
    $self->_defineNewModuleFactory($moduleResolver);
453

454
    my @modules;
455
    if ($commandLineModules) {
456
        @modules = $moduleResolver->resolveSelectorsIntoModules(@selectors);
457 458 459
    }
    else {
        # Build everything in the rc-file, in the order specified.
460
        @modules = $moduleResolver->expandModuleSets(@optionModulesAndSets);
461 462

        if ($ctx->getOption('kde-languages')) {
463
            @modules = _expandl10nModules($ctx, @modules);
464 465 466 467 468 469 470 471 472
        }
    }

    # If modules were on the command line then they are effectively forced to
    # process unless overridden by command line options as well. If phases
    # *were* overridden on the command line, then no update pass is required
    # (all modules already have correct phases)
    @modules = _updateModulePhases(@modules) unless $commandLineModules;

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
    # TODO: Verify this does anything still
    my $metadataModule = $ctx->getKDEDependenciesMetadataModule();
    $ctx->addToIgnoreList($metadataModule->scm()->ignoredModules());

    # Remove modules that are explicitly blanked out in their branch-group
    # i.e. those modules where they *have* a branch-group, and it's set to
    # be empty ("").
    my $resolver = $ctx->moduleBranchGroupResolver();
    my $branchGroup = $ctx->effectiveBranchGroup();

    @modules = grep {
        my $branch = $_->isKDEProject()
            ? $resolver->findModuleBranch($_->fullProjectPath(), $branchGroup)
            : 1; # Just a placeholder truthy value
        whisper ("Removing ", $_->fullProjectPath(), " due to branch-group") if (defined $branch and !$branch);
        (!defined $branch or $branch); # This is the actual test
    } (@modules);

    @modules = $self->_resolveModuleDependencies(@modules);

    # Filter --resume-foo options. This might be a second pass, but that should
    # be OK since there's nothing different going on from the first pass (in
    # resolveSelectorsIntoModules) in that event.
    @modules = _applyModuleFilters($ctx, @modules);

    # Check for ignored modules (post-expansion)
    @modules = grep { ! exists $ignoredSelectors{$_->name()} } @modules;

501 502 503
    return @modules;
}

504 505 506
# Causes kde-projects metadata to be downloaded (unless --pretend, --no-src, or
# --no-metadata is in effect, although we'll download even in --pretend if
# nothing is available).
507 508 509
#
# No return value.
sub _downloadKDEProjectMetadata
510 511 512
{
    my $self = shift;
    my $ctx = $self->context();
513 514 515
    my $updateStillNeeded = 0;

    my $wasPretending = pretending();
516

517
    eval {
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
        for my $metadataModule (
            $ctx->getKDEDependenciesMetadataModule(),
            $ctx->getKDEProjectsMetadataModule())
        {
            my $sourceDir = $metadataModule->getSourceDir();
            super_mkdir($sourceDir);

            my $moduleSource = $metadataModule->fullpath('source');
            my $updateDesired = !$ctx->getOption('no-metadata') && $ctx->phases()->has('update');
            my $updateNeeded = (! -e $moduleSource) || is_dir_empty($moduleSource);
            my $lastUpdate = $ctx->getPersistentOption('global', 'last-metadata-update') // 0;

            $updateStillNeeded ||= $updateNeeded;

            if (!$updateDesired && $updateNeeded && (time - ($lastUpdate)) >= 7200) {
                warning (" r[b[*] Skipping build metadata update, but it hasn't been updated recently!");
            }
535

536 537 538 539 540
            if ($updateNeeded && pretending()) {
                warning (" y[b[*] Ignoring y[b[--pretend] option to download required metadata\n" .
                         " y[b[*] --pretend mode will resume after metadata is available.");
                ksb::Debug::setPretending(0);
            }
541

542 543 544 545
            if ($updateDesired && (!pretending() || $updateNeeded)) {
                $metadataModule->scm()->updateInternal();
                $ctx->setPersistentOption('global', 'last-metadata-update', time);
            }
546

547
            ksb::Debug::setPretending($wasPretending);
548
        }
549
    };
550

551
    my $err = $@;
552

553
    ksb::Debug::setPretending($wasPretending);
554

555 556
    if ($err) {
        die $err if $updateStillNeeded;
557 558 559 560 561

        # Assume previously-updated metadata will work if not updating
        warning (" b[r[*] Unable to download required metadata for build process");
        warning (" b[r[*] Will attempt to press onward...");
        warning (" b[r[*] Exception message: $@");
562 563 564 565 566 567
    }
}

# Returns a list of Modules in the proper build order according to the
# kde-build-metadata dependency information.
#
568 569 570
# The kde-build-metadata repository must have already been updated, and the
# module factory must be setup. The Modules to reorder must be passed as
# arguments.
571 572 573 574
sub _resolveModuleDependencies
{
    my $self = shift;
    my $ctx = $self->context();
575
    my $metadataModule = $ctx->getKDEDependenciesMetadataModule();
576 577 578
    my @modules = @_;

    @modules = eval {
579
        my $dependencyResolver = ksb::DependencyResolver->new($self->{module_factory});
580
        my $branchGroup = $ctx->effectiveBranchGroup();
581

582 583 584 585 586 587 588 589 590
        for my $file ('dependency-data-common', "dependency-data-$branchGroup")
        {
            my $dependencyFile = $metadataModule->fullpath('source') . "/$file";
            my $dependencies = pretend_open($dependencyFile)
                or die "Unable to open $dependencyFile: $!";

            debug (" -- Reading dependencies from $dependencyFile");
            $dependencyResolver->readDependencyData($dependencies);
            close $dependencies;
591
        }
592 593 594 595 596 597 598 599 600

        my @reorderedModules = $dependencyResolver->resolveDependencies(@modules);
        return @reorderedModules;
    };

    if ($@) {
        warning (" r[b[*] Problems encountered trying to sort modules into correct order:");
        warning (" r[b[*] $@");
        warning (" r[b[*] Will attempt to continue.");
601 602
    }

603 604
    return @modules;
}
605

606 607
# Runs all update, build, install, etc. phases. Basically this *is* the
# script.
608
# The metadata module must already have performed its update by this point.
609 610 611 612 613
sub runAllModulePhases
{
    my $self = shift;
    my $ctx = $self->context();
    my @modules = $self->modules();
614

615
    if ($ctx->getOption('print-modules')) {
616 617 618
        for my $m (@modules) {
            say ((" " x ($m->getOption('#dependency-level', 'module') // 0)), "$m");
        }
619 620 621
        return 0; # Abort execution early!
    }

622 623 624 625 626
    # Add to global module list now that we've filtered everything.
    $ctx->addModule($_) foreach @modules;

    my $runMode = $self->runMode();

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    if ($runMode eq 'query') {
        my $queryMode = $ctx->getOption('query', 'module');

        # Default to ->getOption as query method.
        # $_[0] is short name for first param.
        my $query = sub { $_[0]->getOption($queryMode) };
        $query = sub { $_[0]->fullpath('source') } if $queryMode eq 'source-dir';
        $query = sub { $_[0]->fullpath('build') }  if $queryMode eq 'build-dir';
        $query = sub { $_[0]->installationPath() } if $queryMode eq 'install-dir';
        $query = sub { $_[0]->fullProjectPath() }  if $queryMode eq 'project-path';
        $query = sub { ($_[0]->scm()->_determinePreferredCheckoutSource())[0] // '' }
            if $queryMode eq 'branch';

        if (@modules == 1) {
            # No leading module name, just the value
            say $query->($modules[0]);
        }
        else {
            for my $m (@modules) {
                say "$m: ", $query->($m);
            }
        }
649

650 651 652 653
        return 0;
    }

    my $result;
654 655 656 657 658 659 660 661 662

    if ($runMode eq 'build')
    {
        # No packages to install, we're in build mode

        # What we're going to do is fork another child to perform the source
        # updates while we build.  Setup for this first by initializing some
        # shared memory.
        my $ipc = 0;
663 664 665 666
        my $updateOptsSub = sub {
            my ($k, $v) = @_;
            $ctx->setPersistentOption($k, $v);
        };
667 668 669 670

        if ($ctx->getOption('async'))
        {
            $ipc = ksb::IPC::Pipe->new();
671
            $ipc->setPersistentOptionHandler($updateOptsSub);
672 673 674 675 676
        }

        if (!$ipc)
        {
            $ipc = ksb::IPC::Null->new();
677 678
            $ipc->setPersistentOptionHandler($updateOptsSub);

679 680 681 682 683 684 685 686 687 688 689
            whisper ("Using no IPC mechanism\n");

            note ("\n b[<<<  Update Process  >>>]\n");
            $result = _handle_updates ($ipc, $ctx);

            note (" b[<<<  Build Process  >>>]\n");
            $result = _handle_build ($ipc, $ctx) || $result;
        }
        else
        {
            $result = _handle_async_build ($ipc, $ctx);
690
            $ipc->outputPendingLoggedMessages() if debugging();
691 692 693 694 695 696 697 698 699 700 701 702 703
        }
    }
    elsif ($runMode eq 'install')
    {
        $result = _handle_install ($ctx);
    }
    elsif ($runMode eq 'uninstall')
    {
        $result = _handle_uninstall ($ctx);
    }

    _cleanup_log_directory($ctx) if $ctx->getOption('purge-old-logs');
    _output_failed_module_lists($ctx);
704 705 706 707 708 709 710 711 712 713 714

    # Record all failed modules. Unlike the 'resume-list' option this doesn't
    # include any successfully-built modules in between failures.
    my $failedModules = join(',', map { "$_" } $ctx->listFailedModules());
    if ($failedModules) {
        # We don't clear the list of failed modules on success so that
        # someone can build one or two modules and still use
        # --rebuild-failures
        $ctx->setPersistentOption('global', 'last-failed-module-list', $failedModules);
    }

715 716 717 718 719 720
    # env driver is just the ~/.config/kde-env-*.sh, session driver is that + ~/.xsession
    if ($ctx->getOption('install-environment-driver') ||
        $ctx->getOption('install-session-driver'))
    {
        _installCustomSessionDriver($ctx);
    }
721

Michael Pyne's avatar
Michael Pyne committed
722 723
    my $color = 'g[b[';
    $color = 'r[b[' if $result;
724

Michael Pyne's avatar
Michael Pyne committed
725
    info ("${color}", $result ? ":-(" : ":-)") unless pretending();
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

    return $result;
}

# Method: finish
#
# Exits the script cleanly, including removing any lock files created.
#
# Parameters:
#  ctx - Required; BuildContext to use.
#  [exit] - Optional; if passed, is used as the exit code, otherwise 0 is used.
sub finish
{
    my $self = shift;
    my $ctx = $self->context();
    my $exitcode = shift // 0;

    if (pretending() || $self->{_base_pid} != $$) {
        # Abort early if pretending or if we're not the same process
        # that was started by the user (e.g. async mode, forked pipe-opens
        exit $exitcode;
    }

    $ctx->closeLock();
    $ctx->storePersistentOptions();

    my $logdir = $ctx->getLogDir();
    note ("Your logs are saved in y[$logdir]");

    exit $exitcode;
}

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
### Package-internal helper functions.

# Reads a "line" from a file. This line is stripped of comments and extraneous
# whitespace. Also, backslash-continued multiple lines are merged into a single
# line.
#
# First parameter is the reference to the filehandle to read from.
# Returns the text of the line.
sub _readNextLogicalLine
{
    my $fileReader = shift;

    while($_ = $fileReader->readLine()) {
        # Remove trailing newline
        chomp;

        # Replace \ followed by optional space at EOL and try again.
        if(s/\\\s*$//)
        {
            $_ .= $fileReader->readLine();
            redo;
        }

        s/#.*$//;        # Remove comments
        next if /^\s*$/; # Skip blank lines

        return $_;
    }

    return undef;
}

# Takes an input line, and extracts it into an option name, and simplified
# value. The value has "false" converted to 0, white space simplified (like in
# Qt), and tildes (~) in what appear to be path-like entries are converted to
# the home directory path.
#
# First parameter is the build context (used for translating option values).
# Second parameter is the line to split.
# Return value is (option-name, option-value)
sub _splitOptionAndValue
{
    my $ctx = assert_isa(shift, 'ksb::BuildContext');
    my $input = shift;
    my $optionRE = qr/\$\{([a-zA-Z0-9-]+)\}/;

    # The option is the first word, followed by the
    # flags on the rest of the line.  The interpretation
806
    # of the flags is dependent on the option.
807 808 809 810 811 812
    my ($option, $value) = ($input =~ /^\s*     # Find all spaces
                            ([-\w]+) # First match, alphanumeric, -, and _
                            # (?: ) means non-capturing group, so (.*) is $value
                            # So, skip spaces and pick up the rest of the line.
                            (?:\s+(.*))?$/x);

813
    $value = trimmed($value // '');
814 815 816 817 818 819 820 821 822 823 824 825 826

    # Simplify whitespace.
    $value =~ s/\s+/ /g;

    # Check for false keyword and convert it to Perl false.
    $value = 0 if lc($value) eq 'false';

    # Replace reference to global option with their value.
    # The regex basically just matches ${option-name}.
    my ($sub_var_name) = ($value =~ $optionRE);
    while ($sub_var_name)
    {
        my $sub_var_value = $ctx->getOption($sub_var_name) || '';
827
        if(!$ctx->hasOption($sub_var_name)) {
828
            warning (" *\n * WARNING: $sub_var_name is not set at line y[$.]\n *");   ## TODO: filename is missing
829 830 831 832
        }

        debug ("Substituting \${$sub_var_name} with $sub_var_value");

833
        $value =~ s/\$\{$sub_var_name\}/$sub_var_value/g;
834 835 836 837 838 839 840 841 842 843 844 845

        # Replace other references as well.  Keep this RE up to date with
        # the other one.
        ($sub_var_name) = ($value =~ $optionRE);
    }

    # Replace tildes with home directory.
    1 while ($value =~ s"(^|:|=)~/"$1$ENV{'HOME'}/");

    return ($option, $value);
}

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
# Ensures that the given ModuleSet has at least a valid repository and
# use-modules setting based on the given BuildContext.
sub _validateModuleSet
{
    my ($ctx, $moduleSet) = @_;
    my $name = $moduleSet->name() || 'unnamed';
    my $rcSources = _getModuleSources($moduleSet);

    # re-read option from module set since it may be pre-set
    my $selectedRepo = $moduleSet->getOption('repository');
    if (!$selectedRepo) {
        error (<<EOF);

There was no repository selected for the y[b[$name] module-set declared at
    $rcSources

A repository is needed to determine where to download the source code from.

Most will want to use the b[g[kde-projects] repository. See also
https://docs.kde.org/trunk5/en/extragear-utils/kdesrc-build/kde-modules-and-selection.html#module-sets
EOF
        die make_exception('Config', 'Missing repository option');
    }

    my $repoSet = $ctx->getOption('git-repository-base');
    if ($selectedRepo ne KDE_PROJECT_ID &&
        not exists $repoSet->{$selectedRepo})
    {
        my $projectID = KDE_PROJECT_ID;
        my $moduleSetName = $moduleSet->name();
        my $moduleSetId = $moduleSetName ? "module-set ($moduleSetName)"
                                         : "module-set";

        error (<<EOF);
There is no repository assigned to y[b[$selectedRepo] when assigning a
$moduleSetId at $rcSources.

These repositories are defined by g[b[git-repository-base] in the global
section of your configuration.

Make sure you spelled your repository name right, but you probably meant
to use the magic b[$projectID] repository for your module-set instead.
EOF

        die make_exception('Config', 'Unknown repository base');
    }
}

894 895 896 897
# Reads in the options from the config file and adds them to the option store.
# The first parameter is a BuildContext object to use for creating the returned
#     ksb::Module under.
# The second parameter is a reference to the file handle to read from.
898 899
# The third parameter is the ksb::OptionsBase to use (module, module-set, ctx,
#     etc.)
900
#     For global options, just pass in the BuildContext for this param.
901 902
# The fourth parameter is optional, if provided it should be a regexp for the
#     terminator to use for the block being parsed in the rc file.
903
#
904 905
# The return value is the ksb::OptionsBase provided, with options set as given in
# the configuration file section being processed.
906 907
sub _parseModuleOptions
{
908
    my ($ctx, $fileReader, $module, $endRE) = @_;
909
    assert_isa($ctx, 'ksb::BuildContext');
910
    assert_isa($module, 'ksb::OptionsBase');
911

912 913 914 915
    my $endWord = $module->isa('ksb::BuildContext') ? 'global'     :
                  $module->isa('ksb::ModuleSet')    ? 'module-set' :
                  $module->isa('ksb::Module')       ? 'module'     :
                                                      'options';
916

917 918 919 920
    # Just look for an end marker if terminator not provided.
    $endRE //= qr/^end[\w\s]*$/;

    _markModuleSource($module, $fileReader->currentFilename() . ":$.");
921 922

    # Read in each option
923
    while (($_ = _readNextLogicalLine($fileReader)) && ($_ !~ $endRE))
924
    {
925 926
        my $current_file = $fileReader->currentFilename();

927
        # Sanity check, make sure the section is correctly terminated
928
        if(/^(module\b|options\b)/)
929
        {
930
            error ("Invalid configuration file $current_file at line $.\nAdd an 'end $endWord' before " .
931
                   "starting a new module.\n");
932
            die make_exception('Config', "Invalid file $current_file");
933 934 935 936
        }

        my ($option, $value) = _splitOptionAndValue($ctx, $_);

937 938 939 940 941 942 943 944
        eval { $module->setOption($option, $value); };
        if (my $err = $@) {
            if (blessed($err) && $err->isa('ksb::BuildException::Config'))
            {
                my $msg = "$current_file:$.: " . $err->message();
                my $explanation = $err->optionUsageExplanation();
                $msg = $msg . "\n" . $explanation if $explanation;
                $err->setMessage($msg);
945 946
            }

947
            die; # re-throw
948 949 950 951 952 953
        }
    }

    return $module;
}

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
# Marks the given OptionsBase subclass (i.e. Module or ModuleSet) as being
# read in from the given string (filename:line). An OptionsBase can be
# tagged under multiple files.
sub _markModuleSource
{
    my ($optionsBase, $configSource) = @_;
    my $key = '#defined-at';

    my $sourcesRef = $optionsBase->hasOption($key)
        ? $optionsBase->getOption($key)
        : [];

    push @$sourcesRef, $configSource;
    $optionsBase->setOption($key, $sourcesRef);
}

# Returns rcfile sources for given OptionsBase (comma-separated).
sub _getModuleSources
{
    my $optionsBase = shift;
    my $key = '#defined-at';

    my $sourcesRef = $optionsBase->getOption($key) || [];

    return join(', ', @$sourcesRef);
}

981 982 983 984
# Reads in a "moduleset".
#
# First parameter is the build context.
# Second parameter is the filehandle to the config file to read from.
985
# Third parameter is the ksb::ModuleSet to use.
986
#
987 988
# Returns the ksb::ModuleSet passed in with read-in options set, which may need
# to be further expanded (see ksb::ModuleSet::convertToModules).
989 990
sub _parseModuleSetOptions
{
991
    my ($ctx, $fileReader, $moduleSet) = @_;
992

993
    $moduleSet = _parseModuleOptions($ctx, $fileReader, $moduleSet, qr/^end\s+module(-?set)?$/);
994

995 996
    if ($moduleSet->getOption('repository') eq KDE_PROJECT_ID &&
        !$moduleSet->isa('ksb::ModuleSet::KDEProjects'))
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    {
        # Perl-specific note! re-blessing the module set into the right 'class'
        # You'd probably have to construct an entirely new object and copy the
        # members over in other languages.
        bless $moduleSet, 'ksb::ModuleSet::KDEProjects';
    }

    return $moduleSet;
}

# Function: _readConfigurationOptions
#
# Reads in the settings from the configuration, passed in as an open
# filehandle.
#
# Phase:
#  initialization - Do not call <finish> from this function.
#
# Parameters:
1016
#  ctx - The <BuildContext> to update based on the configuration read and
1017
#  any pending command-line options (see cmdlineGlobalOptions).
1018
#
1019 1020 1021
#  filehandle - The I/O object to read from. Must handle _eof_ and _readline_
#  methods (e.g. <IO::Handle> subclass).
#
Yuri Chornoivan's avatar
Yuri Chornoivan committed
1022
#  deferredOptions - An out parameter: a hashref holding the options set by any
1023 1024 1025
#  'options' blocks read in by this function. Each key (identified by the name
#  of the 'options' block) will point to a hashref value holding the options to
#  apply.
1026
#
1027
# Returns:
1028
#  @module - Heterogeneous list of <Modules> and <ModuleSets> defined in the
1029 1030 1031 1032 1033 1034 1035 1036 1037
#  configuration file. No module sets will have been expanded out (either
#  kde-projects or standard sets).
#
# Throws:
#  - Config exceptions.
sub _readConfigurationOptions
{
    my $ctx = assert_isa(shift, 'ksb::BuildContext');
    my $fh = shift;
1038
    my $deferredOptionsRef = shift;
1039 1040
    my @module_list;
    my $rcfile = $ctx->rcFile();
1041
    my ($option, %readModules);
1042

1043 1044
    my $fileReader = ksb::RecursiveFH->new($rcfile);
    $fileReader->addFile($fh, $rcfile);
1045 1046 1047 1048

    # Read in global settings
    while ($_ = $fileReader->readLine())
    {
1049 1050 1051
        s/#.*$//; # Remove comments
        s/^\s+//; # Remove leading whitespace
        next unless $_; # Skip blank lines
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062

        # First command in .kdesrc-buildrc should be a global
        # options declaration, even if none are defined.
        if (not /^global\s*$/)
        {
            error ("Invalid configuration file: $rcfile.");
            error ("Expecting global settings section at b[r[line $.]!");
            die make_exception('Config', 'Missing global section');
        }

        # Now read in each global option.
1063
        _parseModuleOptions($ctx, $fileReader, $ctx);
1064

1065 1066 1067 1068
        last;
    }

    my $using_default = 1;
1069
    my %seenModules; # NOTE! *not* module-sets, *just* modules.
1070
    my %seenModuleSets; # and vice versa -- named sets only though!
1071
    my %seenModuleSetItems; # To track option override modules.
1072 1073 1074 1075 1076 1077 1078 1079 1080

    # Now read in module settings
    while ($_ = $fileReader->readLine())
    {
        s/#.*$//;          # Remove comments
        s/^\s*//;          # Remove leading whitespace
        next if (/^\s*$/); # Skip blank lines

        # Get modulename (has dash, dots, slashes, or letters/numbers)
1081
        my ($type, $modulename) = /^(options|module)\s+([-\/\.\w]+)\s*$/;
1082
        my $newModule;
1083

1084 1085 1086
        # 'include' directives can change the current file, so check where we're at
        $rcfile = $fileReader->currentFilename();

1087 1088
        # Module-set?
        if (not $modulename) {
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
            my $moduleSetRE = qr/^module-set\s*([-\/\.\w]+)?\s*$/;
            ($modulename) = m/$moduleSetRE/;

            # modulename may be blank -- use the regex directly to match
            if (not /$moduleSetRE/) {
                error ("Invalid configuration file $rcfile!");
                error ("Expecting a start of module section at r[b[line $.].");
                die make_exception('Config', 'Ungrouped/Unknown option');
            }

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
            if ($modulename && exists $seenModuleSets{$modulename}) {
                error ("Duplicate module-set $modulename at $rcfile:$.");
                die make_exception('Config', "Duplicate module-set $modulename defined at $rcfile:$.");
            }

            if ($modulename && exists $seenModules{$modulename}) {
                error ("Name $modulename for module-set at $rcfile:$. is already in use on a module");
                die make_exception('Config', "Can't re-use name $modulename for module-set defined at $rcfile:$.");
            }

1109
            # A moduleset can give us more than one module to add.
1110 1111
            $newModule = _parseModuleSetOptions($ctx, $fileReader,
                ksb::ModuleSet->new($ctx, $modulename || "<module-set at line $.>"));
1112 1113 1114 1115 1116

            # Save 'use-modules' entries so we can see if later module decls
            # are overriding/overlaying their options.
            my @moduleSetItems = $newModule->moduleNamesToFind();
            @seenModuleSetItems{@moduleSetItems} = ($newModule) x scalar @moduleSetItems;
1117 1118

            $seenModuleSets{$modulename} = $newModule if $modulename;
1119
        }
1120 1121
        # Duplicate module entry? (Note, this must be checked before the check
        # below for 'options' sets)
1122
        elsif (exists $seenModules{$modulename} && $type ne 'options') {
1123 1124
            error ("Duplicate module declaration b[r[$modulename] on line $. of $rcfile");
            die make_exception('Config', "Duplicate module $modulename declared at $rcfile:$.");
1125
        }
1126
        # Module/module-set options overrides
1127
        elsif ($type eq 'options') {
1128 1129 1130 1131
            my $options = _parseModuleOptions($ctx, $fileReader,
                ksb::OptionsBase->new());

            $deferredOptionsRef->{$modulename} = $options->{options};
1132

1133
            next; # Don't add to module list
1134
        }
1135 1136 1137 1138 1139
        # Must follow 'options' handling
        elsif (exists $seenModuleSets{$modulename}) {
            error ("Name $modulename for module at $rcfile:$. is already in use on a module-set");
            die make_exception('Config', "Can't re-use name $modulename for module defined at $rcfile:$.");
        }
1140
        else {
1141 1142
            $newModule = _parseModuleOptions($ctx, $fileReader,
                ksb::Module->new($ctx, $modulename));
1143 1144 1145 1146
            $seenModules{$modulename} = $newModule;
        }

        push @module_list, $newModule;
1147 1148 1149 1150

        $using_default = 0;
    }

1151 1152 1153 1154
    while (my ($name, $moduleSet) = each %seenModuleSets) {
        _validateModuleSet($ctx, $moduleSet);
    }

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    # If the user doesn't ask to build any modules, build a default set.
    # The good question is what exactly should be built, but oh well.
    if ($using_default) {
        warning (" b[y[*] There do not seem to be any modules to build in your configuration.");
        return ();
    }

    return @module_list;
}

# Exits out of kdesrc-build, executing the user's preferred shell instead.  The
# difference is that the environment variables should be as set in kdesrc-build
# instead of as read from .bashrc and friends.
#
# You should pass in the options to run the program with as a list.
#
# Meant to implement the --run command line option.
sub _executeCommandLineProgram
{
    my ($program, @args) = @_;

    if (!$program)
    {
        error ("You need to specify a program with the --run option.");
        exit 1; # Can't use finish here.
    }

    if (($< != $>) && ($> == 0))
    {
        error ("kdesrc-build will not run a program as root unless you really are root.");
        exit 1;
    }

    debug ("Executing b[r[$program] ", join(' ', @args));

    exit 0 if pretending();

    exec $program, @args or do {
        # If we get to here, that sucks, but don't continue.
        error ("Error executing $program: $!");
        exit 1;
    };
}

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
# Function: _split_url
#
# Subroutine to split a url into a protocol and host
sub _split_url
{
    my $url = shift;
    my ($proto, $host) = ($url =~ m|([^:]*)://([^/]*)/|);

    return ($proto, $host);
}

# Function: _check_for_ssh_agent
#
# Checks if we are supposed to use ssh agent by examining the environment, and
# if so checks if ssh-agent has a list of identities.  If it doesn't, we run
# ssh-add (with no arguments) and inform the user.  This can be controlled with
# the disable-agent-check parameter.
#
# Parameters:
# 1. Build context
sub _check_for_ssh_agent
{
    my $ctx = assert_isa(shift, 'ksb::BuildContext');

    # Don't bother with all this if the user isn't even using SSH.
    return 1 if pretending();

    my @svnServers = grep {
        $_->scmType() eq 'svn'
    } ($ctx->modulesInPhase('update'));

    my @gitServers = grep {
        $_->scmType() eq 'git'
    } ($ctx->modulesInPhase('update'));

    my @sshServers = grep {
        my ($proto, $host) = _split_url($_->getOption('svn-server'));

        # Check if ssh is explicitly used in the proto, or if the host is the
        # developer main svn.
        (defined $proto && $proto =~ /ssh/) || (defined $host && $host =~ /^svn\.kde\.org/);
    } @svnServers;

    push @sshServers, grep {
        # Check for git+ssh:// or git@git.kde.org:/path/etc.
        my $repo = $_->getOption('repository');
        ($repo =~ /^git\+ssh:\/\//) || ($repo =~ /^[a-zA-Z0-9_.]+@.*:\//);
    } @gitServers;

    return 1 if (not @sshServers) or $ctx->getOption('disable-agent-check');
1249
    whisper ("\tChecking for SSH Agent") if (scalar @sshServers);
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

    # We're using ssh to download, see if ssh-agent is running.
    return 1 unless exists $ENV{'SSH_AGENT_PID'};

    my $pid = $ENV{'SSH_AGENT_PID'};

    # It's supposed to be running, let's see if there exists the program with
    # that pid (this check is linux-specific at the moment).
    if (-d "/proc" and not -e "/proc/$pid")
    {
        warning ("r[ *] SSH Agent is enabled, but y[doesn't seem to be running].");
        warning ("Since SSH is used to download from Subversion you may want to see why");
        warning ("SSH Agent is not working, or correct the environment variable settings.");

        return 0;
    }

    # The agent is running, but does it have any keys?  We can't be more specific
    # with this check because we don't know what key is required.
    my $noKeys = 0;

    filter_program_output(sub { $noKeys ||= /no identities/ }, 'ssh-add', '-l');

    if ($noKeys)
    {
        # Use print so user can't inadvertently keep us quiet about this.
        print ksb::Debug::colorize (<<EOF);
b[y[*] SSH Agent does not appear to be managing any keys.  This will lead to you
  being prompted for every module update for your SSH passphrase.  So, we're
  running g[ssh-add] for you.  Please type your passphrase at the prompt when
  requested, (or simply Ctrl-C to abort the script).
EOF
        my @commandLine = ('ssh-add');
        my $identFile = $ctx->getOption('ssh-identity-file');
        push (@commandLine, $identFile) if $identFile;

        my $result = system (@commandLine);
        if ($result) # Run this code for both death-by-signal and nonzero return
        {
            my $rcfile = $ctx->rcFile();

            print "\nUnable to add SSH identity, aborting.\n";
            print "If you don't want kdesrc-build to check in the future,\n";
            print ksb::Debug::colorize ("Set the g[disable-agent-check] option to g[true] in your $rcfile.\n\n");

            return 0;
        }
    }

    return 1;
}

# Function: _handle_updates
#
# Subroutine to update a list of modules.
#
# Parameters:
# 1. IPC module to pass results to.
# 2. Build Context, which will be used to determine the module update list.
#
# The ipc parameter contains an object that is responsible for communicating
# the status of building the modules.  This function must account for every
# module in $ctx's update phase to the ipc object before returning.
#
# Returns 0 on success, non-zero on error.
sub _handle_updates
{
    my ($ipc, $ctx) = @_;
    my $kdesrc = $ctx->getSourceDir();
    my @update_list = $ctx->modulesInPhase('update');

    # No reason to print out the text if we're not doing anything.
    if (!@update_list)
    {
        $ipc->sendIPCMessage(ksb::IPC::ALL_UPDATING, "update-list-empty");
1325
        $ipc->sendIPCMessage(ksb::IPC::ALL_DONE,     "update-list-empty");
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        return 0;
    }

    if (not _check_for_ssh_agent($ctx))
    {
        $ipc->sendIPCMessage(ksb::IPC::ALL_FAILURE, "ssh-failure");
        return 1;
    }

    if (not -e $kdesrc)
    {
        whisper ("KDE source download directory doesn't exist, creating.\n");
        if (not super_mkdir ($kdesrc))
        {
            error ("Unable to make directory r[$kdesrc]!");
            $ipc->sendIPCMessage(ksb::IPC::ALL_FAILURE, "no-source-dir");

            return 1;
        }
    }

    # Once at this point, any errors we get should be limited to a module,
    # which means we can tell the build thread to start.
    $ipc->sendIPCMessage(ksb::IPC::ALL_UPDATING, "starting-updates");

    my $hadError = 0;
    foreach my $module (@update_list)
    {
        $ipc->setLoggedModule($module->name());

        # Note that this must be in this order to avoid accidentally not
        # running ->update() from short-circuiting if an error is noted.
        $hadError = !$module->update($ipc, $ctx) || $hadError;
    }

1361 1362
    $ipc->sendIPCMessage(ksb::IPC::ALL_DONE, "had_errors: $hadError");

1363 1364 1365
    return $hadError;
}

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
# Builds the given module.
#
# Return value is the failure phase, or 0 on success.
sub _buildSingleModule
{
    my ($ipc, $ctx, $module, $startTimeRef) = @_;

    $ctx->resetEnvironment();
    $module->setupEnvironment();

    my $fail_count = $module->getPersistentOption('failure-count') // 0;
    my ($resultStatus, $message) = $ipc->waitForModule($module);
1378 1379
    $ipc->forgetModule($module);

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    if ($resultStatus eq 'failed') {
        error ("\tUnable to update r[$module], build canceled.");
        $module->setPersistentOption('failure-count', ++$fail_count);
        return 'update';
    }
    elsif ($resultStatus eq 'success') {
        note ("\tSource update complete for g[$module]: $message");
    }
    # Skip actually building a module if the user has selected to skip
    # builds when the source code was not actually updated. But, don't skip
    # if we didn't successfully build last time.
    elsif ($resultStatus eq 'skipped' &&
        !$module->getOption('build-when-unchanged') &&
        $fail_count == 0)
    {
        note ("\tSkipping g[$module], its source code has not changed.");
        return 0;
    }
    elsif ($resultStatus eq 'skipped') {
        note ("\tNo changes to g[$module] source, proceeding to build.");
    }

    $$startTimeRef = time;
1403 1404
    $fail_count = $module->build() ? 0 : $fail_count + 1;
    $module->setPersistentOption('failure-count', $fail_count);
1405 1406 1407 1408

    return $fail_count > 0 ? 'build' : 0;
}

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
# Function: _handle_build
#
# Subroutine to handle the build process.
#
# Parameters:
# 1. IPC object to receive results from.
# 2. Build Context, which is used to determine list of modules to build.
#
# If the packages are not already checked-out and/or updated, this
# subroutine WILL NOT do so for you.
#
# This subroutine assumes that the source directory has already been set up.
# It will create the build directory if it doesn't already exist.
#
# If $builddir/$module/.refresh-me exists, the subroutine will
# completely rebuild the module (as if --refresh-build were passed for that
# module).
#
# Returns 0 for success, non-zero for failure.
sub _handle_build
{
    my ($ipc, $ctx) = @_;
    my @build_done;
    my @modules = $ctx->modulesInPhase('build');
    my $result = 0;

    # No reason to print building messages if we're not building.
    return 0 if scalar @modules == 0;

    # Check for absolutely essential programs now.
    if (!_checkForEssentialBuildPrograms($ctx) &&
        !exists $ENV{KDESRC_BUILD_IGNORE_MISSING_PROGRAMS})
    {
        error (" r[b[*] Aborting now to save a lot of wasted time.");
        error (" y[b[*] export KDESRC_BUILD_IGNORE_MISSING_PROGRAMS=1 and re-run (perhaps with --no-src)");
        error (" r[b[*] to continue anyways. If this check was in error please report a bug against");
        error (" y[b[*] kdesrc-build at https://bugs.kde.org/");

        return 1;
    }

    # IPC queue should have a message saying whether or not to bother with the
    # build.
    $ipc->waitForStreamStart();

1454 1455
    $ctx->unsetPersistentOption('global', 'resume-list');

1456
    my $outfile = pretending() ? '/dev/null'
1457 1458
                               : $ctx->getLogDir() . '/build-status';

1459
    open (STATUS_FILE, '>', $outfile) or do {
1460 1461 1462 1463 1464 1465 1466 1467
        error (<<EOF);
	Unable to open output status file r[b[$outfile]
	You won't be able to use the g[--resume] switch next run.\n";
EOF
        $outfile = undef;
    };

    my $num_modules = scalar @modules;
1468
    my $statusViewer = $ctx->statusViewer();
1469 1470
    my $i = 1;

1471 1472
    $statusViewer->numberModulesTotal(scalar @modules);

1473 1474 1475 1476
    while (my $module = shift @modules)
    {
        my $moduleName = $module->name();
        my $moduleSet = $module->moduleSet()->name();
1477
        my $modOutput = $moduleName;
1478 1479 1480 1481 1482

        if (debugging(ksb::Debug::WHISPER)) {
            $modOutput .= " (build system " . $module->buildSystemType() . ")"
        }

1483 1484
        $moduleSet = " from g[$moduleSet]" if $moduleSet;
        note ("Building g[$modOutput]$moduleSet ($i/$num_modules)");
1485

1486
        my $start_time = time;
1487
        my $failedPhase = _buildSingleModule($ipc, $ctx, $module, \$start_time);
1488
        my $elapsed = prettify_seconds(time - $start_time);
1489

1490
        if ($failedPhase)
1491
        {
1492 1493 1494
            # FAILURE
            $ctx->markModulePhaseFailed($failedPhase, $module);
            print STATUS_FILE "$module: Failed on $failedPhase after $elapsed.\n";
1495 1496 1497 1498 1499 1500

            if ($result == 0) {
                # No failures yet, mark this as resume point
                my $moduleList = join(', ', map { "$_" } ($module, @modules));
                $ctx->setPersistentOption('global', 'resume-list', $moduleList);
            }
1501 1502 1503 1504 1505 1506 1507
            $result = 1;

            if ($module->getOption('stop-on-failure'))
            {
                note ("\n$module didn't build, stopping here.");
                return 1; # Error
            }
1508 1509

            $statusViewer->numberModulesFailed(1 + $statusViewer->numberModulesFailed);
1510
        }
1511 1512 1513 1514 1515
        else {
            # Success
            print STATUS_FILE "$module: Succeeded after $elapsed.\n";

            push @build_done, $moduleName; # Make it show up as a success
1516 1517

            $statusViewer->numberModulesSucceeded(1 + $statusViewer->numberModulesSucceeded);
1518
        }
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540

        $i++;
    }
    continue # Happens at the end of each loop and on next
    {
        print "\n"; # Space things out
    }

    if ($outfile)
    {
        close STATUS_FILE;

        # Update the symlink in latest to point to this file.
        my $logdir = $ctx->getSubdirPath('log-dir');
        if (-l "$logdir/latest/build-status") {
            safe_unlink("$logdir/latest/build-status");
        }
        symlink($outfile, "$logdir/latest/build-status");
    }

    info ("<<<  g[PACKAGES SUCCESSFULLY BUILT]  >>>") if scalar @build_done > 0;

Michael Pyne's avatar