Application.pm 93 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::ModuleSet::Qt;
24
use ksb::OSSupport;
25
use ksb::RecursiveFH;
26
use ksb::DependencyResolver 0.20;
27
use ksb::DebugOrderHints;
28 29 30
use ksb::IPC::Pipe 0.20;
use ksb::IPC::Null;
use ksb::Updater::Git;
31 32 33
use ksb::Version qw(scriptVersion);

use List::Util qw(first min);
34
use File::Basename; # basename, dirname
35
use File::Glob ':glob';
Michael Pyne's avatar
Michael Pyne committed
36
use POSIX qw(:sys_wait_h _exit :errno_h);
37
use Getopt::Long qw(GetOptionsFromArray :config gnu_getopt nobundling);
38 39
use IO::Handle;
use IO::Select;
40 41 42 43 44 45

### 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.
46 47
    KDE_PROJECT_ID   => 'kde-projects',  # git-repository-base for sysadmin/repo-metadata
    QT_PROJECT_ID    => 'qt-projects',   # git-repository-base for qt.io Git repo
48 49 50 51 52 53 54 55 56 57 58 59 60
};

### Package methods

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

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

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

69 70
    my $workLoad = $self->generateModuleList(@options);
    if (!$workLoad->{build}) {
71 72 73 74
        print "No modules to build, exiting.\n";
        exit 0;
    }

75 76 77
    $self->{modules} = $workLoad->{selectedModules};
    $self->{workLoad} = $workLoad;

78 79 80 81 82 83 84 85 86 87
    $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!!
    }

88 89 90 91 92 93 94
    # 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);
    });

95 96 97
    return $self;
}

98 99 100 101 102 103 104 105 106 107 108 109 110
# 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:
111
#  cmdlineOptions - hashref to hold parsed modules options to be applied later.
112
#    *Note* this must be done separately, it is not handled by this subroutine.
113
#    Global options will be stored in a hashref at $cmdlineOptions->{global}.
114
#    Module or module-set options will be stored in a hashref at
115
#    $cmdlineOptions->{$moduleName} (it will be necessary to disambiguate
116 117
#    later in the run whether it is a module set or a single module).
#
118 119 120
#    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.
121 122 123 124 125
#
#  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
126
#    options as listed in cmdlineOptions.
127
#
128
#  ctx - <BuildContext> to hold the global build state.
129 130 131 132 133 134 135 136 137 138
#
#  @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;
139
    my ($cmdlineOptionsRef, $selectorsRef, $ctx, @options) = @_;
140
    my $phases = $ctx->phases();
141
    my @savedOptions = @options; # Copied for use in debugging.
142
    my $os = ksb::OSSupport->new;
143
    my $version = "kdesrc-build " . scriptVersion();
144 145 146 147 148 149
    my $author = <<DONE;
$version was written (mostly) by:
  Michael Pyne <mpyne\@kde.org>

Many people have contributed code, bugfixes, and documentation.

150
Please report bugs using the KDE Bugzilla, at https://bugs.kde.org/
151 152
DONE

153 154 155 156 157 158
    # 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);
159
    %foundOptions = (
160
        'show-info' => sub { say $version; say "OS: ", $os->vendorID(); exit },
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        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');
        },
178 179 180 181
        'no-snapshots' => sub {
            # The documented form of disable-snapshots
            $auxOptions{'disable-snapshots'} = 1;
        },
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        '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');
        },
204 205 206 207
        'install-only' => sub {
            $self->{run_mode} = 'install';
            $phases->phases('install');
        },
208 209
        prefix => sub {
            my ($optName, $arg) = @_;
210
            $auxOptions{prefix} = $arg;
211 212 213
            $foundOptions{kdedir} = $arg; #TODO: Still needed for compat?
            $foundOptions{reconfigure} = 1;
        },
214 215 216 217 218 219 220 221 222 223 224 225 226 227
        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;
228
            $auxOptions{pretend} = 1; # Implied pretend mode
229
        },
230 231
        pretend => sub {
            # Set pretend mode but also force the build process to run.
232
            $auxOptions{pretend} = 1;
233 234
            $foundOptions{'build-when-unchanged'} = 1;
        },
235 236 237 238 239
        resume => sub {
            $auxOptions{resume} = 1;
            $phases->filterOutPhase('update'); # Implied --no-src
            $foundOptions{'no-metadata'} = 1;  # Implied --no-metadata
        },
240 241 242 243 244 245 246 247 248 249 250 251 252
        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) {
253 254
                $cmdlineOptionsRef->{$module} //= { };
                $cmdlineOptionsRef->{$module}->{$option} = $value;
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
            }
        },

        # 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;
        },
    );

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    # 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.
290
    my $optsSuccess = GetOptionsFromArray(\@options, \%foundOptions,
291 292
        # Options here should not duplicate the flags and options defined below
        # from ksb::BuildContext!
293
        'version|v', 'author', 'help', 'show-info',
294
        'install', 'uninstall', 'no-src|no-svn', 'no-install', 'no-build',
295
        'no-tests', 'build-when-unchanged|force-build', 'no-metadata',
296
        'verbose', 'quiet|quite|q', 'really-quiet', 'debug',
297
        'reconfigure', 'colorful-output|color!', 'async!',
298
        'src-only|svn-only', 'build-only', 'install-only', 'build-system-only',
299
        'rc-file=s', 'prefix=s', 'niceness|nice:10', 'ignore-modules=s{,}',
300
        'print-modules', 'pretend|dry-run|p', 'refresh-build',
301
        'query=s', 'start-program|run=s{,}',
302
        'revision=i', 'resume-from=s', 'resume-after=s',
303
        'rebuild-failures', 'resume',
304
        'stop-after=s', 'stop-before=s', 'set-module-option-value=s',
305 306
        'metadata-only', 'include-dependencies', 'list-build',
        'dependency-tree',
307 308

        # Special sub used (see above), but have to tell Getopt::Long to look
309 310
        # for negatable boolean flags
        (map { "$_!" } (keys %ksb::BuildContext::defaultGlobalFlags)),
311 312 313 314

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

315 316 317
        '<>', # Required to read non-option args
        );

318 319 320 321
    if (!$optsSuccess) {
        croak_runtime("Error reading command-line options.");
    }

322 323 324 325 326 327 328 329 330 331
    # 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.
332
    @{ $cmdlineOptionsRef->{'global'} }{@readOptionNames}
333
        = @foundOptions{@readOptionNames};
334

335
    @{ $cmdlineOptionsRef->{'global'} }{keys %auxOptions}
336
        = values %auxOptions;
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
sub _yieldModuleDependencyTreeEntry
{
    my ($nodeInfo, $module, $context) = @_;

    my $depth = $nodeInfo->{depth};
    my $index = $nodeInfo->{idx};
    my $count = $nodeInfo->{count};
    my $build = $nodeInfo->{build};
    my $currentItem = $nodeInfo->{currentItem};
    my $currentBranch = $nodeInfo->{currentBranch};
    my $parentItem = $nodeInfo->{parentItem};
    my $parentBranch = $nodeInfo->{parentBranch};

    my $buildStatus = $build ? 'built' : 'not built';
    my $statusInfo = $currentBranch ? "($buildStatus: $currentBranch)" : "($buildStatus)";

    my $connectorStack = $context->{stack};


    my $prefix = pop(@$connectorStack);

    while($context->{depth} > $depth) {
        $prefix = pop(@$connectorStack);
        --($context->{depth});
    }

    push(@$connectorStack, $prefix);

    my $connector;

    if ($depth == 0) {
        $connector = $prefix . ' ── ';
        push(@$connectorStack, $prefix . (' ' x 4));
    }
    else {
        $connector = $prefix . ($index == $count ? '└── ': '├── ');
        push(@$connectorStack, $prefix . ($index == $count ? ' ' x 4: ''));
    }

    $context->{depth} = $depth + 1;
    $context->{report}($connector . $currentItem . ' ' . $statusInfo);
}

382
# Generates the build context and module list based on the command line options
383 384
# and module selectors provided, resolves dependencies on those modules if needed,
# filters out ignored or skipped modules, and sets up the module factory.
385 386
#
# After this function is called all module set selectors will have been
387
# expanded, and we will have downloaded kde-projects metadata.
388
#
389 390 391 392 393 394
# Returns: a hash containing the following entries:
#
#  - selectedModules: the selected modules to build
#  - dependencyInfo: reference to dependency info object as created by ksb::DependencyResolver
#  - build: whether or not to actually perform a build action
#
395 396 397 398 399 400 401 402 403
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();
404 405
    my $cmdlineOptions = { global => { }, };
    my $cmdlineGlobalOptions = $cmdlineOptions->{global};
406
    my $deferredOptions = { }; # 'options' blocks
407 408

    # Process --help, --install, etc. first.
409
    my @selectors;
410
    $self->_readCommandLineOptionsAndSelectors($cmdlineOptions, \@selectors,
411
        $ctx, @argv);
412

413 414 415
    # Convert list to hash for lookup
    my %ignoredSelectors =
        map { $_, 1 } @{$cmdlineGlobalOptions->{'ignore-modules'}};
416

417 418
    my @startProgramAndArgs = @{$cmdlineGlobalOptions->{'start-program'}};
    delete @{$cmdlineGlobalOptions}{qw/ignore-modules start-program/};
419

420
    # rc-file needs special handling.
421 422
    if (exists $cmdlineGlobalOptions->{'rc-file'} && $cmdlineGlobalOptions->{'rc-file'}) {
        $ctx->setRcFile($cmdlineGlobalOptions->{'rc-file'});
423 424 425
    }

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

    my $fh = $ctx->loadRcFile();
429 430
    $ctx->loadPersistentOptions();

431
    if (exists $cmdlineGlobalOptions->{'resume'}) {
432 433 434 435 436 437 438 439 440
        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);
    }
441

442
    if (exists $cmdlineGlobalOptions->{'rebuild-failures'}) {
443 444 445 446 447 448 449 450 451 452
        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);
    }

453 454 455
    # _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.
456
    my @optionModulesAndSets = _readConfigurationOptions($ctx, $fh, $deferredOptions);
457 458 459 460 461
    close $fh;

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

462
    if (@startProgramAndArgs) {
463 464 465
        $ctx->setupEnvironment(); # Read options from set-env
        $ctx->commitEnvironmentChanges(); # Apply env options to environment
        _executeCommandLineProgram(@startProgramAndArgs); # noreturn
466 467
    }

468 469 470 471
    # Everything else in cmdlineOptions should be OK to apply directly as a module
    # or context option.
    $ctx->setOption(%{$cmdlineGlobalOptions});

472 473 474
    # Selecting modules or module sets would requires having the KDE
    # build metadata (kde-build-metadata and sysadmin/repo-metadata)
    # available.
475
    $ctx->setKDEDependenciesMetadataModuleNeeded();
476
    $ctx->setKDEProjectsMetadataModuleNeeded();
477 478 479 480 481 482 483

    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();
    }
484 485 486

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

491 492 493 494 495
    # 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.

496
    my @globalCmdlineArgs = keys %{$cmdlineGlobalOptions};
497
    my $commandLineModules = scalar @selectors;
498

499
    my $moduleResolver = ksb::ModuleResolver->new($ctx);
500
    $moduleResolver->setCmdlineOptions($cmdlineOptions);
501
    $moduleResolver->setDeferredOptions($deferredOptions);
502
    $moduleResolver->setInputModulesAndOptions(\@optionModulesAndSets);
503
    $moduleResolver->setIgnoredSelectors([keys %ignoredSelectors]);
504

505
    $self->_defineNewModuleFactory($moduleResolver);
506

507
    my @modules;
508
    if ($commandLineModules) {
509
        @modules = $moduleResolver->resolveSelectorsIntoModules(@selectors);
510 511 512
    }
    else {
        # Build everything in the rc-file, in the order specified.
513
        @modules = $moduleResolver->expandModuleSets(@optionModulesAndSets);
514 515

        if ($ctx->getOption('kde-languages')) {
516
            @modules = _expandl10nModules($ctx, @modules);
517 518 519 520 521 522 523 524 525
        }
    }

    # 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;

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    # 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);

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    my $moduleGraph = $self->_resolveModuleDependencyGraph(@modules);

    if (!$moduleGraph || !exists $moduleGraph->{graph}) {
        croak_runtime("Failed to resolve dependency graph");
    }

    if (exists $cmdlineGlobalOptions->{'dependency-tree'}) {
        my $depTreeCtx = {
            stack => [''],
            depth => 0,
            report => sub {
                print(@_, "\n");
            }
        };
        ksb::DependencyResolver::walkModuleDependencyTrees(
            $moduleGraph->{graph},
            \&_yieldModuleDependencyTreeEntry,
            $depTreeCtx,
            @modules
        );
564 565 566 567 568 569 570

        my $result = {
            dependencyInfo => $moduleGraph,
            selectedModules => [],
            build => 0
        };
        return $result;
571 572 573 574 575
    }

    @modules = ksb::DependencyResolver::sortModulesIntoBuildOrder(
        $moduleGraph->{graph}
    );
576 577 578 579 580 581 582 583 584

    # 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;

585 586 587 588 589 590 591 592 593
    if(exists $cmdlineGlobalOptions->{'list-build'}) {
        for my $module (@modules) {
            my $branch = ksb::DependencyResolver::_getBranchOf($module);
            print(' ── ', $module->name());
            if($branch) {
                print(' : ', $branch);
            }
            print("\n");
        }
594 595 596 597 598 599 600

        my $result = {
            dependencyInfo => $moduleGraph,
            selectedModules => [],
            build => 0
        };
        return $result;
601 602
    }

603 604 605 606 607 608
    my $result = {
        dependencyInfo => $moduleGraph,
        selectedModules => \@modules,
        build => 1
    };
    return $result;
609 610
}

611 612 613
# 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).
614 615 616
#
# No return value.
sub _downloadKDEProjectMetadata
617 618 619
{
    my $self = shift;
    my $ctx = $self->context();
620 621 622
    my $updateStillNeeded = 0;

    my $wasPretending = pretending();
623

624
    eval {
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
        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!");
            }
642

643 644 645 646 647
            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);
            }
648

649 650 651 652
            if ($updateDesired && (!pretending() || $updateNeeded)) {
                $metadataModule->scm()->updateInternal();
                $ctx->setPersistentOption('global', 'last-metadata-update', time);
            }
653

654
            ksb::Debug::setPretending($wasPretending);
655
        }
656
    };
657

658
    my $err = $@;
659

660
    ksb::Debug::setPretending($wasPretending);
661

662 663
    if ($err) {
        die $err if $updateStillNeeded;
664 665 666 667 668

        # 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: $@");
669 670 671
    }
}

672 673
# Returns a graph of Modules according to the kde-build-metadata dependency
# information.
674
#
675
# The kde-build-metadata repository must have already been updated, and the
676 677 678
# module factory must be setup. The modules for which to calculate the graph
# must be passed in as arguments
sub _resolveModuleDependencyGraph
679 680 681
{
    my $self = shift;
    my $ctx = $self->context();
682
    my $metadataModule = $ctx->getKDEDependenciesMetadataModule();
683 684
    my @modules = @_;

685
    my $graph = eval {
686
        my $dependencyResolver = ksb::DependencyResolver->new($self->{module_factory});
687
        my $branchGroup = $ctx->effectiveBranchGroup();
688

689 690 691 692 693 694 695 696 697
        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;
698
        }
699

700
        return $dependencyResolver->resolveToModuleGraph(@modules);
701 702 703
    };

    if ($@) {
704
        warning (" r[b[*] Problems encountered trying to determing correct module graph:");
705 706
        warning (" r[b[*] $@");
        warning (" r[b[*] Will attempt to continue.");
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

        $graph = {
            graph => undef,
            syntaxErrors  => 0,
            cycles        => 0,
            trivialCycles => 0,
            pathErrors    => 0,
            branchErrors  => 0,
            exception => $@
        };
    }
    else {
        if (!$graph->{graph}) {
            warning (" r[b[*] Unable to determine correct module graph");
            warning (" r[b[*] Will attempt to continue.");
        }
723 724
    }

725 726 727
    $graph->{exception} = undef;

    return $graph;
728
}
729

730 731
# Runs all update, build, install, etc. phases. Basically this *is* the
# script.
732
# The metadata module must already have performed its update by this point.
733 734 735 736 737
sub runAllModulePhases
{
    my $self = shift;
    my $ctx = $self->context();
    my @modules = $self->modules();
738

739
    if ($ctx->getOption('print-modules')) {
740 741 742
        for my $m (@modules) {
            say ((" " x ($m->getOption('#dependency-level', 'module') // 0)), "$m");
        }
743 744 745
        return 0; # Abort execution early!
    }

746 747 748 749 750
    # Add to global module list now that we've filtered everything.
    $ctx->addModule($_) foreach @modules;

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

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    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);
            }
        }
773

774 775 776 777
        return 0;
    }

    my $result;
778 779 780 781 782 783 784 785 786

    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;
787 788 789 790
        my $updateOptsSub = sub {
            my ($k, $v) = @_;
            $ctx->setPersistentOption($k, $v);
        };
791 792 793 794

        if ($ctx->getOption('async'))
        {
            $ipc = ksb::IPC::Pipe->new();
795
            $ipc->setPersistentOptionHandler($updateOptsSub);
796 797 798 799 800
        }

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

803 804 805 806 807 808 809 810 811 812 813
            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);
814
            $ipc->outputPendingLoggedMessages() if debugging();
815 816 817 818 819 820 821 822 823 824 825 826
        }
    }
    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');
827 828 829 830 831

    my $workLoad = $self->workLoad();
    my $dependencyGraph = $workLoad->{dependencyInfo}->{graph};
    _output_failed_module_lists($ctx, $dependencyGraph);

832 833 834 835 836 837 838 839 840 841 842

    # 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);
    }

843 844 845 846 847 848
    # 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);
    }
849

Michael Pyne's avatar
Michael Pyne committed
850 851
    my $color = 'g[b[';
    $color = 'r[b[' if $result;
852

Michael Pyne's avatar
Michael Pyne committed
853
    info ("${color}", $result ? ":-(" : ":-)") unless pretending();
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

    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;
}

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
### 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
934
    # of the flags is dependent on the option.
935 936 937 938 939 940
    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);

941
    $value = trimmed($value // '');
942 943 944 945 946 947 948 949 950 951 952 953 954

    # 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) || '';
955
        if(!$ctx->hasOption($sub_var_name)) {
956
            warning (" *\n * WARNING: $sub_var_name is not set at line y[$.]\n *");   ## TODO: filename is missing
957 958 959 960
        }

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

961
        $value =~ s/\$\{$sub_var_name\}/$sub_var_value/g;
962 963 964 965 966 967 968 969 970 971 972 973

        # 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);
}

974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
# 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');
999
    if ($selectedRepo ne KDE_PROJECT_ID && $selectedRepo ne QT_PROJECT_ID &&
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
        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');
    }
}

1022 1023 1024 1025
# 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.
1026 1027
# The third parameter is the ksb::OptionsBase to use (module, module-set, ctx,
#     etc.)
1028
#     For global options, just pass in the BuildContext for this param.
1029 1030
# 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.
1031
#
1032 1033
# The return value is the ksb::OptionsBase provided, with options set as given in
# the configuration file section being processed.
1034 1035
sub _parseModuleOptions
{
1036
    my ($ctx, $fileReader, $module, $endRE) = @_;
1037
    assert_isa($ctx, 'ksb::BuildContext');
1038
    assert_isa($module, 'ksb::OptionsBase');
1039

1040 1041 1042 1043
    my $endWord = $module->isa('ksb::BuildContext') ? 'global'     :
                  $module->isa('ksb::ModuleSet')    ? 'module-set' :
                  $module->isa('ksb::Module')       ? 'module'     :
                                                      'options';
1044

1045 1046 1047 1048
    # Just look for an end marker if terminator not provided.
    $endRE //= qr/^end[\w\s]*$/;

    _markModuleSource($module, $fileReader->currentFilename() . ":$.");
1049 1050

    # Read in each option
1051
    while (($_ = _readNextLogicalLine($fileReader)) && ($_ !~ $endRE))
1052
    {
1053 1054
        my $current_file = $fileReader->currentFilename();

1055
        # Sanity check, make sure the section is correctly terminated
1056
        if(/^(module\b|options\b)/)
1057
        {
1058
            error ("Invalid configuration file $current_file at line $.\nAdd an 'end $endWord' before " .
1059
                   "starting a new module.\n");
1060
            die make_exception('Config', "Invalid file $current_file");
1061 1062 1063 1064
        }

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

1065 1066 1067 1068 1069 1070 1071 1072
        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);
1073 1074
            }

1075
            die; # re-throw
1076 1077 1078 1079 1080 1081
        }
    }

    return $module;
}

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
# 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);
}

1109 1110 1111 1112
# Reads in a "moduleset".
#
# First parameter is the build context.
# Second parameter is the filehandle to the config file to read from.
1113
# Third parameter is the ksb::ModuleSet to use.
1114
#
1115 1116
# Returns the ksb::ModuleSet passed in with read-in options set, which may need
# to be further expanded (see ksb::ModuleSet::convertToModules).
1117 1118
sub _parseModuleSetOptions
{
1119
    my ($ctx, $fileReader, $moduleSet) = @_;
1120

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

1123 1124 1125 1126
    # 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.
    if ($moduleSet->getOption('repository') eq KDE_PROJECT_ID) {
1127
        bless $moduleSet, 'ksb::ModuleSet::KDEProjects';
1128 1129
    } elsif ($moduleSet->getOption('repository') eq QT_PROJECT_ID) {
        bless $moduleSet, 'ksb::ModuleSet::Qt';
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    }

    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:
1144
#  ctx - The <BuildContext> to update based on the configuration read and
1145
#  any pending command-line options (see cmdlineGlobalOptions).
1146
#
1147 1148 1149
#  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
1150
#  deferredOptions - An out parameter: a hashref holding the options set by any
1151 1152 1153
#  '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.
1154
#
1155
# Returns:
1156
#  @module - Heterogeneous list of <Modules> and <ModuleSets> defined in the
1157 1158 1159 1160 1161 1162 1163 1164 1165
#  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;
1166
    my $deferredOptionsRef = shift;
1167 1168
    my @module_list;
    my $rcfile = $ctx->rcFile();
1169
    my ($option, %readModules);
1170

1171 1172
    my $fileReader = ksb::RecursiveFH->new($rcfile);
    $fileReader->addFile($fh, $rcfile);
1173 1174 1175 1176

    # Read in global settings
    while ($_ = $fileReader->readLine())
    {
1177 1178 1179
        s/#.*$//; # Remove comments
        s/^\s+//; # Remove leading whitespace
        next unless $_; # Skip blank lines
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190

        # 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.
1191
        _parseModuleOptions($ctx, $fileReader, $ctx);
1192

1193 1194 1195 1196
        last;
    }

    my $using_default = 1;
1197
    my %seenModules; # NOTE! *not* module-sets, *just* modules.
1198
    my %seenModuleSets; # and vice versa -- named sets only though!
1199
    my %seenModuleSetItems; # To track option override modules.
1200 1201 1202 1203 1204 1205 1206 1207 1208

    # 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)
1209
        my ($type, $modulename) = /^(options|module)\s+([-\/\.\w]+)\s*$/;
1210
        my $newModule;
1211

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

1215 1216
        # Module-set?
        if (not $modulename) {
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
            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');
            }

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
            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:$.");
            }

1237
            # A moduleset can give us more than one module to add.
1238 1239
            $newModule = _parseModuleSetOptions($ctx, $fileReader,
                ksb::ModuleSet->new($ctx, $modulename || "<module-set at line $.>"));
1240 1241 1242 1243 1244

            # 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;
1245 1246

            $seenModuleSets{$modulename} = $newModule if $modulename;
1247
        }
1248 1249
        # Duplicate module entry? (Note, this must be checked before the check
        # below for 'options' sets)
1250
        elsif (exists $seenModules{$modulename} && $type ne 'options') {
1251 1252
            error ("Duplicate module declaration b[r[$modulename] on line $. of $rcfile");
            die make_exception('Config', "Duplicate module $modulename declared at $rcfile:$.");
1253
        }
1254
        # Module/module-set options overrides
1255
        elsif ($type eq 'options') {
1256 1257 1258 1259
            my $options = _parseModuleOptions($ctx, $fileReader,
                ksb::OptionsBase->new());

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

1261
            next; # Don't add to module list
1262
        }
1263 1264 1265 1266 1267
        # 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:$.");
        }
1268
        else {
1269 1270
            $newModule = _parseModuleOptions($ctx, $fileReader,
                ksb::Module->new($ctx, $modulename));
1271 1272 1273 1274
            $seenModules{$modulename} = $newModule;
        }

        push @module_list, $newModule;
1275 1276 1277 1278

        $using_default = 0;
    }

1279 1280 1281 1282
    while (my ($name, $moduleSet) = each %seenModuleSets) {
        _validateModuleSet($ctx, $moduleSet);
    }

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 1325 1326
    # 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;
    };
}

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 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
# 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');
1377
    whisper ("\tChecking for SSH Agent") if (scalar @sshServers);
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 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

    # 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");
1453
        $ipc->sendIPCMessage(ksb::IPC::ALL_DONE,     "update-list-empty");
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
        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;
    }

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

1491 1492 1493
    return $hadError;
}

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
# 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);
1506 1507
    $ipc->forgetModule($module);

1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    if ($resultStatus