Module.pm 30.5 KB
Newer Older
1
package ksb::Module 0.20;
2

3
4
5
6
7
# Class: Module
#
# Represents a source code module of some sort, which can be updated, built,
# and installed. Includes a stringifying overload and can be sorted amongst
# other ksb::Modules.
8

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

13
use parent qw(ksb::OptionsBase);
14

15
16
17
18
19
20
21
22
23
24
25
use ksb::IPC;
use ksb::Debug;
use ksb::Util;

use ksb::l10nSystem;

use ksb::Updater::Svn;
use ksb::Updater::Git;
use ksb::Updater::Bzr;
use ksb::Updater::KDEProject;
use ksb::Updater::KDEProjectMetadata;
26
use ksb::Updater::Qt5;
27

28
29
use ksb::BuildException 0.20;

30
use ksb::BuildSystem 0.30;
31
32
33
use ksb::BuildSystem::Autotools;
use ksb::BuildSystem::QMake;
use ksb::BuildSystem::Qt4;
34
use ksb::BuildSystem::Qt5;
35
36
use ksb::BuildSystem::KDE4;
use ksb::BuildSystem::CMakeBootstrap;
37
use ksb::BuildSystem::Meson;
38

39
40
use ksb::ModuleSet::Null;

41
42
43
44
45
46
47
48
49
50
51
52
use Storable 'dclone';
use Carp 'confess';
use Scalar::Util 'blessed';
use overload
    '""' => 'toString', # Add stringify operator.
    '<=>' => 'compare',
    ;

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

53
54
55
    croak_internal ("Empty ksb::Module constructed") unless $name;

    my $self = ksb::OptionsBase::new($class);
56
57
58
59
60
61
62

    # If building a BuildContext instead of a ksb::Module, then the context
    # can't have been setup yet...
    my $contextClass = 'ksb::BuildContext';
    if ($class ne $contextClass &&
        (!blessed($ctx) || !$ctx->isa($contextClass)))
    {
63
        croak_internal ("Invalid context $ctx");
64
65
66
    }

    # Clone the passed-in phases so we can be different.
67
    my $phases = dclone($ctx->phases()) if $ctx;
68

69
    my %newOptions = (
70
71
72
73
74
75
        name         => $name,
        scm_obj      => undef,
        build_obj    => undef,
        phases       => $phases,
        context      => $ctx,
        'module-set' => undef,
76
        post_build_msgs => [ ],
77
    );
78

79
80
81
    @{$self}{keys %newOptions} = values %newOptions;

    return $self;
82
83
84
85
86
87
88
89
90
91
92
}

sub phases
{
    my $self = shift;
    return $self->{phases};
}

sub moduleSet
{
    my ($self) = @_;
93
94
    $self->{'module-set'} //= ksb::ModuleSet::Null->new();
    return $self->{'module-set'};
95
96
97
98
}

sub setModuleSet
{
99
100
101
    my ($self, $moduleSet) = @_;
    assert_isa($moduleSet, 'ksb::ModuleSet');
    $self->{'module-set'} = $moduleSet;
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
}

# Subroutine to retrieve a subdirectory path with tilde-expansion and
# relative path handling.
# The parameter is the option key (e.g. build-dir or log-dir) to read and
# interpret.
sub getSubdirPath
{
    my ($self, $subdirOption) = @_;
    my $dir = $self->getOption($subdirOption);

    # If build-dir starts with a slash, it is an absolute path.
    return $dir if $dir =~ /^\//;

    # Make sure we got a valid option result.
    if (!$dir) {
        confess ("Reading option for $subdirOption gave empty \$dir!");
    }

    # If it starts with a tilde, expand it out.
    if ($dir =~ /^~/)
    {
        $dir =~ s/^~/$ENV{'HOME'}/;
    }
    else
    {
        # Relative directory, tack it on to the end of $kdesrcdir.
        my $kdesrcdir = $self->getOption('source-dir');
        $dir = "$kdesrcdir/$dir";
    }

    return $dir;
}

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# Method: getInstallPathComponents
#
# Returns the directory that a module should be installed in.
#
# NOTE: The return value is a hash. The key 'module' will return the final
# module name, the key 'path' will return the full path to the module. The
# key 'fullpath' will return their concatenation.
#
# For example, with $module == 'KDE/kdelibs', and no change in the dest-dir
# option, you'd get something like:
#
# > {
# >   'path'     => '/home/user/kdesrc/KDE',
# >   'module'   => 'kdelibs',
# >   'fullpath' => '/home/user/kdesrc/KDE/kdelibs'
# > }
#
# If dest-dir were changed to e.g. extragear-multimedia, you'd get:
#
# > {
# >   'path'     => '/home/user/kdesrc',
# >   'module'   => 'extragear-multimedia',
# >   'fullpath' => '/home/user/kdesrc/extragear-multimedia'
# > }
#
# Parameters:
#   pathType - Either 'source' or 'build'.
#
# Returns:
#   hash (Not a hashref; See description).
sub getInstallPathComponents
{
    my $module = assert_isa(shift, 'ksb::Module');
    my $type = shift;
    my $destdir = $module->destDir();
    my $srcbase = $module->getSourceDir();
    $srcbase = $module->getSubdirPath('build-dir') if $type eq 'build';

    my $combined = "$srcbase/$destdir";

    # Remove dup //
    $combined =~ s/\/+/\//;

    my @parts = split(/\//, $combined);
    my %result = ();
    $result{'module'} = pop @parts;
    $result{'path'} = join('/', @parts);
    $result{'fullpath'} = "$result{path}/$result{module}";

    my $compatDestDir = $module->destDir($module->name());
    my $fullCompatPath = "$srcbase/$compatDestDir";

    # We used to have code here to migrate very old directory layouts. It was
    # removed as of about 2013-09-29.

    return %result;
}

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# Do note that this returns the *base* path to the source directory,
# without the module name or kde_projects stuff appended. If you want that
# use subroutine fullpath().
sub getSourceDir
{
    my $self = shift;
    return $self->getSubdirPath('source-dir');
}

sub name
{
    my $self = shift;
    return $self->{name};
}

sub scm
{
    my $self = shift;

    return $self->{scm_obj} if $self->{scm_obj};

    # Look for specific setting of repository and svn-server. If both is
    # set it's a bug, if one is set, that's the type (because the user says
    # so...). Don't use getOption($key) as it will try to fallback to
    # global options.

    my $svn_status = $self->getOption('svn-server', 'module');
    my $repository = $self->getOption('repository', 'module') // '';
    my $rcfile = $self->buildContext()->rcFile();

    if ($svn_status && $repository) {
        error (<<EOF);
You have specified both y[b[svn-server] and y[b[repository] options for the
b[$self] module in $rcfile.

You should only specify one or the other -- a module cannot be both types
- svn-server uses Subversion.
- repository uses git.
EOF
        die (make_exception('Config', 'svn-server and repository both set'));
    }

    # Overload repository to allow bzr URLs?
    if ($repository =~ /^bzr:\/\//) {
        $self->{scm_obj} = ksb::Updater::Bzr->new($self);
    }

    # If it needs a repo it's git. Everything else is svn for now.
    $self->{scm_obj} //=
        $repository
            ? ksb::Updater::Git->new($self)
            : ksb::Updater::Svn->new($self);

    return $self->{scm_obj};
}

sub setScmType
{
    my ($self, $scmType) = @_;

    my $newType;

    given($scmType) {
        when('git')  { $newType = ksb::Updater::Git->new($self); }
        when('proj') { $newType = ksb::Updater::KDEProject->new($self); }
        when('metadata') { $newType = ksb::Updater::KDEProjectMetadata->new($self); }
        when('l10n') { $newType = ksb::l10nSystem->new($self); }
        when('svn')  { $newType = ksb::Updater::Svn->new($self); }
        when('bzr')  { $newType = ksb::Updater::Bzr->new($self); }
263
        when('qt5')  { $newType = ksb::Updater::Qt5->new($self); }
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
        default      { $newType = undef; }
    }

    $self->{scm_obj} = $newType;
}

# Returns a string describing the scm platform of the given module.
# Return value: 'git' or 'svn' at this point, as appropriate.
sub scmType
{
    my $self = shift;
    return $self->scm()->name();
}

sub currentScmRevision
{
    my $self = shift;

    return $self->scm()->currentRevisionInternal();
}

# Returns a new build system object, given the appropriate name.
# This is a sub-optimal way to fix the problem of allowing users to override
# the detected build system (we could instead use introspection to figure out
# available build systems at runtime). However, KISS...
sub buildSystemFromName
{
    my ($self, $name) = @_;
    my %buildSystemClasses = (
        'generic'         => 'ksb::BuildSystem',
        'qmake'           => 'ksb::BuildSystem::QMake',
        'cmake-bootstrap' => 'ksb::BuildSystem::CMakeBootstrap',
        'kde'             => 'ksb::BuildSystem::KDE4',
        'qt'              => 'ksb::BuildSystem::Qt4',
298
        'qt5'             => 'ksb::BuildSystem::Qt5',
299
        'autotools'       => 'ksb::BuildSystem::Autotools',
300
        'meson'           => 'ksb::BuildSystem::Meson',
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    );

    my $class = $buildSystemClasses{lc $name} // undef;
    return $class->new($self) if ($class);

    # Past here, no class found
    croak_runtime("Invalid build system $name requested");
}

sub buildSystem
{
    my $self = shift;

    if ($self->{build_obj} && $self->{build_obj}->name() ne 'generic') {
        return $self->{build_obj};
    }

    if (my $userBuildSystem = $self->getOption('override-build-system')) {
        $self->{build_obj} = $self->buildSystemFromName($userBuildSystem);
        return $self->{build_obj};
    }

    # If not set, let's guess.
    my $buildType;
    my $sourceDir = $self->fullpath('source');

    if (($self->getOption('repository') =~ /gitorious\.org\/qt\//) ||
        ($self->getOption('repository') =~ /^kde:qt$/) ||
        (-e "$sourceDir/bin/syncqt"))
    {
        $buildType = ksb::BuildSystem::Qt4->new($self);
    }

    # This test must come before the KDE buildsystem's as cmake's own
    # bootstrap system also has CMakeLists.txt
    if (!$buildType && (-e "$sourceDir/CMakeLists.txt") &&
        (-e "$sourceDir/bootstrap"))
    {
        $buildType = ksb::BuildSystem::CMakeBootstrap->new($self);
    }

    if (!$buildType && (-e "$sourceDir/CMakeLists.txt" ||
            $self->getOption('#xml-full-path')))
    {
        $buildType = ksb::BuildSystem::KDE4->new($self);
    }

348
349
350
351
    # We have to assign to an array to force glob to return all results,
    # otherwise it acts like a non-reentrant generator whose output depends on
    # how many times it's been called...
    if (!$buildType && (my @files = glob ("$sourceDir/*.pro"))) {
352
353
354
355
356
357
358
359
360
361
362
        $buildType = ksb::BuildSystem::QMake->new($self);
    }

    # 'configure' is a popular fall-back option even for other build
    # systems so ensure we check last for autotools.
    if (!$buildType &&
        (-e "$sourceDir/configure" || -e "$sourceDir/autogen.sh"))
    {
        $buildType = ksb::BuildSystem::Autotools->new($self);
    }

363
364
365
366
367
368
    # Someday move this up, but for now ensure that Meson happens after
    # configure/autotools support is checked for.
    if (!$buildType && -e "$sourceDir/meson.build") {
        $buildType = ksb::BuildSystem::Meson->new($self);
    }

369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    # Don't just assume the build system is KDE-based...
    $buildType //= ksb::BuildSystem->new($self);

    $self->{build_obj} = $buildType;

    return $self->{build_obj};
}

# Sets the build system **object**, although you can find the build system
# type afterwards (see buildSystemType).
sub setBuildSystem
{
    my ($self, $obj) = @_;

    assert_isa($obj, 'ksb::BuildSystem');
    $self->{build_obj} = $obj;
}

# Current possible build system types:
# KDE (i.e. cmake), Qt, l10n (KDE language buildsystem), autotools (either
# configure or autogen.sh). A final possibility is 'pendingSource' which
# simply means that we don't know yet.
#
# If the build system type is not set ('pendingSource' counts as being
# set!) when this function is called then it will be autodetected if
# possible, but note that not all possible types will be detected this way.
# If in doubt use setBuildSystemType
sub buildSystemType
{
    my $self = shift;
    return $self->buildSystem()->name();
}

# Subroutine to build this module.
# Returns boolean false on failure, boolean true on success.
sub build
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $moduleName = $self->name();
408
409
    my %pathinfo = $self->getInstallPathComponents('build');
    my $builddir = $pathinfo{'fullpath'};
410
411
412
413
414
415
416
    my $buildSystem = $self->buildSystem();

    if ($buildSystem->name() eq 'generic' && !pretending()) {
        error ("\tr[b[$self] does not seem to have a build system to use.");
        return 0;
    }

417
418
    # Ensure we're in a known directory before we start; some options remove
    # the old build directory that a previous module might have been using.
419
    super_mkdir($pathinfo{'path'});
420
421
    p_chdir($pathinfo{'path'});

422
423
424
425
426
    return 0 if !$self->setupBuildSystem();
    return 1 if $self->getOption('build-system-only');

    if (!$buildSystem->buildInternal())
    {
427
428
        return 0;
    }
429

430
431
    $self->setPersistentOption('last-build-rev', $self->currentScmRevision());

432
433
434
435
436
    # TODO: This should be a simple phase to run.
    if ($self->getOption('run-tests'))
    {
        $self->buildSystem()->runTestsuite();
    }
437

438
439
440
441
    # TODO: Likewise this should be a phase to run.
    if ($self->getOption('install-after-build'))
    {
        return 0 if !$self->install();
442
443
444
    }
    else
    {
445
        info ("\tSkipping install for y[$self]");
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
    }

    return 1;
}

# Subroutine to setup the build system in a directory.
# Returns boolean true on success, boolean false (0) on failure.
sub setupBuildSystem
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $moduleName = $self->name();

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

    if ($buildSystem->name() eq 'generic' && !pretending()) {
        croak_internal('Build system determination still pending when build attempted.');
    }

464
465
    my $refreshReason = $buildSystem->needsRefreshed();
    if ($refreshReason ne "")
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    {
        # The build system needs created, either because it doesn't exist, or
        # because the user has asked that it be completely rebuilt.
        info ("\tPreparing build system for y[$self].");

        # Check to see if we're actually supposed to go through the
        # cleaning process.
        if (!$self->getOption('#cancel-clean') &&
            !$buildSystem->cleanBuildSystem())
        {
            warning ("\tUnable to clean r[$self]!");
            return 0;
        }
    }

    if (!$buildSystem->createBuildSystem()) {
        error ("\tError creating r[$self]'s build system!");
        return 0;
    }

    # Now we're in the checkout directory
    # So, switch to the build dir.
    # builddir is automatically set to the right value for qt
    p_chdir ($self->fullpath('build'));

    if (!$buildSystem->configureInternal()) {
        error ("\tUnable to configure r[$self] with " . $self->buildSystemType());

        # Add undocumented ".refresh-me" file to build directory to flag
        # for --refresh-build for this module on next run. See also the
        # "needsRefreshed" subroutine.
        if (open my $fh, '>', '.refresh-me') {
            say $fh "# Build directory will be re-generated next kdesrc-build run";
            say $fh "# due to failing to complete configuration on the last run";
            close $fh;
        };

        return 0;
    }

    return 1;
}

# Responsible for installing the module (no update, build, etc.)
# Return value: Boolean flag indicating whether module installed successfully or
# not.
# Exceptions may be thrown for abnormal conditions (e.g. no build dir exists)
sub install
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $builddir = $self->fullpath('build');
    my $buildSysFile = $self->buildSystem()->configuredModuleFileName();

    if (!pretending() && ! -e "$builddir/$buildSysFile")
    {
        warning ("\tThe build system doesn't exist for r[$self].");
        warning ("\tTherefore, we can't install it. y[:-(].");
        return 0;
    }

    $self->setupEnvironment();

    my @makeInstallOpts = split(' ', $self->getOption('make-install-prefix'));

    # We can optionally uninstall prior to installing
    # to weed out old unused files.
    if ($self->getOption('use-clean-install') &&
        $self->getPersistentOption('last-install-rev'))
    {
        if (!$self->buildSystem()->uninstallInternal(@makeInstallOpts)) {
            warning ("\tUnable to uninstall r[$self] before installing the new build.");
            warning ("\tContinuing anyways...");
        }
        else {
            $self->unsetPersistentOption('last-install-rev');
        }
    }

    if (!$self->buildSystem()->installInternal(@makeInstallOpts))
    {
        error ("\tUnable to install r[$self]!");
        $self->buildContext()->markModulePhaseFailed('install', $self);
        return 0;
    }

    if (pretending())
    {
        pretend ("\tWould have installed g[$self]");
        return 1;
    }

    # Past this point we know we've successfully installed, for real.

    $self->setPersistentOption('last-install-rev', $self->currentScmRevision());

    my $remove_setting = $self->getOption('remove-after-install');

    # Possibly remove the srcdir and builddir after install for users with
    # a little bit of HD space.
    if($remove_setting eq 'all')
    {
        # Remove srcdir
        my $srcdir = $self->fullpath('source');
        note ("\tRemoving b[r[$self source].");
570
        safe_rmtree($srcdir);
571
572
573
574
575
576
    }

    if($remove_setting eq 'builddir' || $remove_setting eq 'all')
    {
        # Remove builddir
        note ("\tRemoving b[r[$self build directory].");
577
        safe_rmtree($builddir);
578
579
580

        # We're likely already in the builddir, so chdir back to the root
        p_chdir('/');
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    }

    return 1;
}

# Handles uninstalling this module (or its sub-directories as given by the checkout-only
# option).
#
# Returns boolean false on failure, boolean true otherwise.
sub uninstall
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $builddir = $self->fullpath('build');
    my $buildSysFile = $self->buildSystem()->configuredModuleFileName();

    if (!pretending() && ! -e "$builddir/$buildSysFile")
    {
        warning ("\tThe build system doesn't exist for r[$self].");
        warning ("\tTherefore, we can't uninstall it.");
        return 0;
    }

    $self->setupEnvironment();

    my @makeInstallOpts = split(' ', $self->getOption('make-install-prefix'));

    if (!$self->buildSystem()->uninstallInternal(@makeInstallOpts))
    {
        error ("\tUnable to uninstall r[$self]!");
        $self->buildContext()->markModulePhaseFailed('install', $self);
        return 0;
    }

    if (pretending())
    {
        pretend ("\tWould have uninstalled g[$self]");
        return 1;
    }

    $self->unsetPersistentOption('last-install-rev');
    return 1;
}

sub buildContext
{
    my $self = shift;
    return $self->{context};
}

# Integrates 'set-env' option to the build context environment
sub applyUserEnvironment
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $ctx = $self->buildContext();

    # Let's see if the user has set env vars to be set.
    # Note the global set-env must be checked separately anyways, so
    # we limit inheritance when searching.
    my $env_hash_ref = $self->getOption('set-env', 'module');

    while (my ($key, $value) = each %{$env_hash_ref})
    {
        $ctx->queueEnvironmentVariable($key, $value);
    }
}

# Establishes proper build environment in the build context. Should be run
# before forking off commands for e.g. updates, builds, installs, etc.
sub setupEnvironment
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $ctx = $self->buildContext();
    my $prefix = $self->installationPath();

655
    # Add global set-envs and context
656
657
    $self->buildContext()->applyUserEnvironment();

658
659
    # Build system's environment injection
    my $buildSystem = $self->buildSystem();
660

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    #
    # Suppress injecting qtdir/kdedir related environment variables if a toolchain is also set
    # Let the toolchain files/definitions take care of themselves.
    #
    if ($buildSystem->hasToolchain()) {
        note ("\tNot setting environment variables for b[$self]: a custom toolchain is used");
    } else {
        my $kdedir = $self->getOption('kdedir');
        my $qtdir  = $self->getOption('qtdir');

        # Ensure the platform libraries we're building can be found, as long as they
        # are not the system's own libraries.
        for my $platformDir ($qtdir, $kdedir) {
            next unless $platformDir;       # OK, assume system platform is usable
            next if $platformDir eq '/usr'; # Don't 'fix' things if system platform
                                            # manually set

            $ctx->prependEnvironmentValue('PKG_CONFIG_PATH', "$platformDir/lib/pkgconfig");
            $ctx->prependEnvironmentValue('LD_LIBRARY_PATH', "$platformDir/lib");
            $ctx->prependEnvironmentValue('PATH', "$platformDir/bin");
        }
682
    }
683

684
    $buildSystem->prepareModuleBuildEnvironment($ctx, $self, $prefix);
685
686

    # Read in user environment defines
687
    $self->applyUserEnvironment() unless $self == $ctx;
688
689
690
}

# Returns the path to the log directory used during this run for this
691
692
# ksb::Module, based on an autogenerated unique id. The id doesn't change
# once generated within a single run of the script.
693
694
695
696
697
698
sub getLogDir
{
    my ($self) = @_;
    return $self->buildContext()->getLogDirFor($self);
}

699
700
701
702
703
704
705
706
707
708
# Returns a full path that can be open()'d to write a log
# file, based on the given basename (with extension).
# Updates the 'latest' symlink as well, unlike getLogDir
# Use when you know you're going to create a new log
sub getLogPath
{
    my ($self, $path) = @_;
    return $self->buildContext()->getLogPathFor($self, $path);
}

709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
sub toString
{
    my $self = shift;
    return $self->name();
}

sub compare
{
    my ($self, $other) = @_;
    return $self->name() cmp $other->name();
}

sub update
{
    my ($self, $ipc, $ctx) = @_;

    my $moduleName = $self->name();
    my $module_src_dir = $self->getSourceDir();
    my $kdesrc = $ctx->getSourceDir();

    if ($kdesrc ne $module_src_dir)
    {
        # This module has a different source directory, ensure it exists.
        if (!super_mkdir($module_src_dir))
        {
            error ("Unable to create separate source directory for r[$self]: $module_src_dir");
            $ipc->sendIPCMessage(ksb::IPC::MODULE_FAILURE, $moduleName);
            next;
        }
    }

    my $fullpath = $self->fullpath('source');
    my $count;
    my $returnValue;

744
    eval { $count = $self->scm()->updateInternal($ipc) };
745
746
747
748
749

    if ($@)
    {
        my $reason = ksb::IPC::MODULE_FAILURE;

750
        if (had_an_exception()) {
751
752
753
754
755
756
757
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
            if ($@->{'exception_type'} eq 'ConflictPresent') {
                $reason = ksb::IPC::MODULE_CONFLICT;
            }
            else {
                $ctx->markModulePhaseFailed('build', $self);
            }

            $@ = $@->{'message'};
        }

        error ("Error updating r[$self], removing from list of packages to build.");
        error (" > y[$@]");

        $ipc->sendIPCMessage($reason, $moduleName);
        $self->phases()->filterOutPhase('build');
        $returnValue = 0;
    }
    else
    {
        my $message;
        if (not defined $count)
        {
            $message = ksb::Debug::colorize ("b[y[Unknown changes].");
            $ipc->notifyUpdateSuccess($moduleName, $message);
        }
        elsif ($count)
        {
            $message = "1 file affected." if $count == 1;
            $message = "$count files affected." if $count != 1;
            $ipc->notifyUpdateSuccess($moduleName, $message);
        }
        else
        {
            $message = "0 files affected.";
785
            my $refreshReason = $self->buildSystem()->needsRefreshed();
786

787
            $ipc->sendIPCMessage(ksb::IPC::MODULE_UPTODATE, "$moduleName,$refreshReason");
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
        }

        # We doing e.g. --src-only, the build phase that normally outputs
        # number of files updated doesn't get run, so manually mention it
        # here.
        if (!$ipc->supportsConcurrency()) {
            info ("\t$self update complete, $message");
        }

        $returnValue = 1;
    }

    info (""); # Print empty line.
    return $returnValue;
}

804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# OVERRIDE
#
# This calls OptionsBase::setOption and performs any Module-specific
# handling.
sub setOption
{
    my ($self, %options) = @_;

    # Ensure we don't accidentally get fed module-set options
    for (qw(git-repository-base use-modules ignore-modules)) {
        if (exists $options{$_}) {
            error (" r[b[*] module b[$self] should be declared as module-set to use b[$_]");
            die ksb::BuildException::Config->new($_, "Option $_ can only be used in module-set");
        };
    }

    # Special case handling.
    if (exists $options{'filter-out-phases'}) {
        for my $phase (split(' ', $options{'filter-out-phases'})) {
            $self->phases()->filterOutPhase($phase);
        }
        delete $options{'filter-out-phases'};
    }

    $self->SUPER::setOption(%options);
}

831
832
# OVERRIDE
#
833
834
835
836
837
838
839
840
841
842
843
844
845
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
# This subroutine returns an option value for a given module.  Some globals
# can't be overridden by a module's choice (but see 2nd parameter below).
# If so, the module's choice will be ignored, and a warning will be issued.
#
# Option names are case-sensitive!
#
# Some options (e.g. cmake-options, configure-flags) have the global value
# and then the module's own value appended together. To get the actual
# module setting you must use the level limit parameter set to 'module'.
#
# Likewise, some qt module options do not obey the previous proviso since
# Qt options are not likely to agree nicely with generic KDE buildsystem
# options.
#
# 1st parameter: Name of option
# 2nd parameter: Level limit (optional). If not present, then the value
# 'allow-inherit' is used. Options:
#   - allow-inherit: Module value is used if present (with exceptions),
#     otherwise global is used.
#   - module: Only module value is used (if you want only global then use the
#     buildContext) NOTE: This overrides global "sticky" options as well!
sub getOption
{
    my ($self, $key, $levelLimit) = @_;
    my $ctx = $self->buildContext();
    $levelLimit //= 'allow-inherit';

    # Some global options would probably make no sense applied to Qt.
    my @qtCopyOverrides = qw(branch configure-flags tag cxxflags);
    if (list_has(\@qtCopyOverrides, $key) && $self->buildSystemType() eq 'Qt') {
        $levelLimit = 'module';
    }

    assert_in($levelLimit, [qw(allow-inherit module)]);

    # If module-only, check that first.
    return $self->{options}{$key} if $levelLimit eq 'module';

871
872
    my $ctxValue = $ctx->getOption($key); # we'll use this a lot from here

873
    # Some global options always override module options.
874
    return $ctxValue if $ctx->hasStickyOption($key);
875
876
877

    # Some options append to the global (e.g. conf flags)
    my @confFlags = qw(cmake-options configure-flags cxxflags);
878
879
    if (list_has(\@confFlags, $key) && $ctxValue) {
        return trimmed("$ctxValue " . ($self->{options}{$key} || ''));
880
881
882
883
    }

    # Everything else overrides the global option, unless it's simply not
    # set at all.
884
    return $self->{options}{$key} // $ctxValue;
885
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
}

# Gets persistent options set for this module. First parameter is the name
# of the option to lookup. Undef is returned if the option is not set,
# although even if the option is set, the value returned might be empty.
# Note that ksb::BuildContext also has this function, with a slightly
# different signature, which OVERRIDEs this function since Perl does not
# have parameter-based method overloading.
sub getPersistentOption
{
    my ($self, $key) = @_;
    return $self->buildContext()->getPersistentOption($self->name(), $key);
}

# Sets a persistent option (i.e. survives between processes) for this module.
# First parameter is the name of the persistent option.
# Second parameter is its actual value.
# See the warning for getPersistentOption above, it also applies for this
# method vs. ksb::BuildContext::setPersistentOption
sub setPersistentOption
{
    my ($self, $key, $value) = @_;
    return $self->buildContext()->setPersistentOption($self->name(), $key, $value);
}

# Unsets a persistent option for this module.
# Only parameter is the name of the option to unset.
sub unsetPersistentOption
{
    my ($self, $key) = @_;
    $self->buildContext()->unsetPersistentOption($self->name(), $key);
}

# Returns the path to the desired directory type (source or build),
# including the module destination directory itself.
sub fullpath
{
    my ($self, $type) = @_;
    assert_in($type, [qw/build source/]);

925
    my %pathinfo = $self->getInstallPathComponents($type);
926
927
928
    return $pathinfo{'fullpath'};
}

929
930
# Returns the "full kde-projects path" for the module. As should be obvious by
# the description, this only works for modules with an scm type that is a
931
932
# Updater::KDEProject (or its subclasses), but modules that don't fall into this
# hierarchy will just return the module name (with no path components) anyways.
933
934
935
sub fullProjectPath
{
    my $self = shift;
936
    return ($self->getOption('#xml-full-path', 'module') || $self->name());
937
938
}

939
940
941
942
943
944
# Returns true if this module is (or was derived from) a kde-projects module.
sub isKDEProject
{
    my $self = shift;
    return $self->hasOption('#xml-full-path');
}
945

946
947
948
949
950
951
952
953
954
955
956
957
# Subroutine to return the name of the destination directory for the
# checkout and build routines.  Based on the dest-dir option.  The return
# value will be relative to the src/build dir.  The user may use the
# '$MODULE' or '${MODULE}' sequences, which will be replaced by the name of
# the module in question.
#
# The first parameter is optional, but if provided will be used as the base
# path to replace $MODULE entries in dest-dir.
sub destDir
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $destDir = $self->getOption('dest-dir');
958
959
960
961
962
963

    my $basePath = "";

    if ($self->getOption('ignore-kde-structure')) {
        $basePath = $self->name();
    } else {
964
965
966
967
968
969
970
971
972
        if ($self->getOption('use-invent-structure')) {
            my $repo = $self->getOption('repository');
            if ($repo =~ m/kde:(.*)\.git/) {
                $basePath = $1;
            }
        }
    }

    if (!$basePath) {
973
        $basePath = shift // $self->getOption('#xml-full-path');
974
        $basePath ||= $self->name(); # Default if not provided in repo-metadata
975
    }
976

977
    $destDir =~ s/(\$\{MODULE})|(\$MODULE\b)/$basePath/g;
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997

    return $destDir;
}

# Subroutine to return the installation path of a given module (the value
# that is passed to the CMAKE_INSTALL_PREFIX CMake option).
# It is based on the "prefix" and, if it is not set, the "kdedir" option.
# The user may use '$MODULE' or '${MODULE}' in the "prefix" option to have
# them replaced by the name of the module in question.
sub installationPath
{
    my $self = assert_isa(shift, 'ksb::Module');
    my $path = $self->getOption('prefix');

    if (!$path)
    {
        return $self->getOption('kdedir');
    }

    my $moduleName = $self->name();
998
    $path =~ s/(\$\{MODULE})|(\$MODULE\b)/$moduleName/g;
999
1000
1001
1002

    return $path;
}

1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
# Returns a list of any 'post-build' messages that have been set for the module
# to show after the build has ended. These may be messages such as warning of a
# local source conflict that may have scrolled past or similar things the user
# needs to know about.
#
# Each entry in the list will be a text message that should be shown (perhaps
# with additional formatting).
sub getPostBuildMessages
{
    my $self = assert_isa(shift, 'ksb::Module');
    return @{$self->{post_build_msgs}};
}

# Adds the given message to the list of post-build messages to show to the user
sub addPostBuildMessage
{
    my ($self, $new_msg) = @_;

    push @{$self->{post_build_msgs}}, $new_msg;
    return;
}

1025
1;