summaryrefslogtreecommitdiff
path: root/lib/SlackBuild/Request.pm
blob: 8fa831b6b7a6b09e2d40a5bb7ff0225f68dbe0ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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
263
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
298
299
300
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
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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
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
# This file is part of slackbuilder
# Copyright (C) 2017-2021 Sergey Poznyakoff
#
# Slackbuilder is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# Slackbuilder is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with slackbuilder.  If not, see <http://www.gnu.org/licenses/>. */

package SlackBuild::Request;
use strict;
use warnings;
use Carp;
use SlackBuild::URI;
use Text::ParseWords;
use JSON;
use File::Basename;
use Safe;
use feature 'state';
use SlackBuild::Request::Loader;

=head1 NAME

SlackBuild::Request - slackbuild request object

=head1 DESCRIPTION

A request object contains the information necessary for building a
package: the package name, version, URLs of the SlackBuild archive,
etc.

=cut    

=head1 ATTRIBUTES

The following attributes are defined:

=over 4    
    
=item package

Package name (string)

=item version

Package version

=item build

Package build number.

=item slackbuild_uri

URI of the slackbuild archive. It can be a remote URL, a local disk file (tar
archive), or a local directory.

=item source_uri

Array of URIs of the source packages.

=item prereq

Array of prerequisites. Each element is either the package name, or
a hash:

    { package => NAME, [version=>X], [arch=>Y], [build=>Z]) }

See SlackBuild::Registry->lookup.

=item rc

Additional shell code to be run before starting the B<I<package>.SlackBuild>
script.    

=item environ

Shell environment variables for the B<I<package>.SlackBuild> script. Variables
VERSION and BUILD are set from the corresponding attributes.    

=item local_name

A perl expression for obtaining local file name from the URL of the source
archive. By default, the last directory component of the URL pathname is
taken as the local file name for download.    

=item strategy

A hash defining merging strategy for certain attributes. See the section
B<MERGING WITH INFO OBJECTS> below for a detailed discussion.    

=item string_full

A boolean value indicating whether the string representation of the object
should include attributes with B<null> value.    
    
=back
    
=cut    

# Hash of attributes this object has. Keys are attribute names. Values
# are hashrefs, that can have the following keys:
#   type - Type of the attribute - 'SCALAR', 'ARRAY' or 'HASH'. Mandatory.
#   info - Name of the SlackBuild::Info attribute corresponding to that
#          attribute.
#   strategy - default merge strategy for this attribute.

my %attributes = (
    package => {
	type => 'SCALAR',
	info => 'PRGNAM',
	strategy => 'keep'
    },
    version => {
	type => 'SCALAR',
	info => 'VERSION',
	strategy => 'keep'
    },
    build => {
	type => 'SCALAR',
    },
    slackbuild_uri => {
	type => 'SCALAR',
    },
    source_uri => {
	type => 'ARRAY',
	info => 'DOWNLOAD',
	strategy => 'keep'
    },
    md5sum => {
	type => 'ARRAY',
	info => 'MD5SUM',
	strategy => 'keep'
    },
    prereq => {
	info => 'REQUIRES',
	type => 'ARRAY',
	strategy => 'merge'
    },
    rc => {
	type => 'ARRAY',
    },
    environ => {
	type => 'HASH'
    },
    local_name => {
	type => 'ARRAY'
    },
    strategy => {
	type => 'HASH'
    },
    tty => {
	type => 'BOOL'
    },
    unconfined => {
	type => 'BOOL'
    },
);

# Values for STRATEGY:
#   overwrite   New value always overrides the old one
#   keep        Old value takes precedence
#   merge       old and new values are merged.

my %generics = (
    'SCALAR' => {
	get => sub {
	           my ($self, $attr) = @_;
		   return $self->{$attr};
	},
	set => sub {
	           my ($self, $attr, $value, $strat) = @_;
		   if (defined($self->{$attr}) && defined($strat)
		       && $strat ne 'overwrite') {
		       ; # Nothing
		   } else {
		       $self->{$attr} = $value;
		   }
	}
    },
    'BOOL' => {
	get => sub {
	           my ($self, $attr) = @_;
		   return $self->{$attr};
	},
	set => sub {
	           my ($self, $attr, $value, $strat) = @_;
		   unless ($value =~ m/^(false|no?|o(ff|n)|true|y(es)?|[01])$/) {
		       croak "$attr=$value: not a valid boolean value";
		   }
		   if (defined($self->{$attr}) && defined($strat)
		       && $strat ne 'overwrite') {
		       ; # Nothing
		   } else {
		       $self->{$attr} = ($value =~ m/^(on|true|y(es)?|1)$/i);
		   }
	}
    },
    'HASH' => {
	get => sub {
	           my ($self, $attr) = @_;
	           return $self->{$attr};
	},
 	set => sub {
	           my ($self, $attr, $value, $strat) = @_;
		   croak "hashref expected when setting $attr" unless ref($value) eq 'HASH';
		   if (defined($self->{$attr}) && defined($strat)
		       && $strat ne 'keep') {
		       if ($strat eq 'merge') {
			   $self->{attr} = [ %{$self->{attr}}, %{$value} ];
		       }
		   } else {
		       $self->{$attr} = $value;
		   }
	}
    }, 
    'ARRAY' => {
	get => sub {
	           my ($self, $attr) = @_;
	           return $self->{$attr};
	},
 	set => sub {
	           my ($self, $attr, $value, $strat) = @_;
		   my $t = ref($value);
		   if ($t eq '') {
		       $value = [ $value ];
		   } elsif ($t ne 'ARRAY') {
		       croak "arrayref or scalar expected";
		   }
		   if (defined($self->{$attr}) && defined($strat)) {
		       if ($strat eq 'overwrite') {
			   $self->{$attr} = $value;
		       } elsif ($strat eq 'merge') {
			   push @{$self->{$attr}}, @{$value};
		       }
		   } else {
		       $self->{$attr} = $value;
		   }
	}
    }
);

sub strategy {
    my ($self, $attr) = @_;
    if ($attr) {
	if (exists($self->{strategy}) && exists($self->{strategy}{$attr})) {
	    return $self->{strategy}{$attr};
	}
	return $attributes{$attr}{strategy} || 'keep';
    }
    return $self->{strategy}
}

sub set_strategy {
    my ($self, $value) = @_;
    croak "hashref expected" unless ref($value) eq 'HASH';
    foreach my $key (keys %$value) {
	croak "$key: undefined attribute"
	    unless exists $attributes{$key};
	unless (grep { $value->{$key} eq $_ } qw{overwrite keep merge}) {
	    croak $value->{key} . ": unknown merge strategy";
	}
    }
    $self->{strategy} = $value;
}

=head1 CONSTRUCTOR

    new SlackBuild::Request(ATTR => VALUE,...)

Build the request from the supplied attribute/value pairs. Allowed attributes
are discussed in detail in the B<ATTRIBUTES> section. Empty argument list
is OK.

    new SlackBuild::Request($URL)

Loads request from the $URL. This is equivalent to

    load SlackBuild::Request($URL)

See the description of B<load>, below.
    
=cut

sub new {
    my $class = shift;
    my %a;
    if (@_ == 1) {
	my $file = shift;
	if (ref($file) eq 'HASH') {
	    %a = %$file;
	} else {
	    %a = return $class->load($file);
	}
    } elsif (@_ % 2) {
	croak "bad number of arguments";
    } else {
	%a = @_;
    }
    
    my $self = bless {}, $class;
    while (my ($k,$v) = each %a) {
	$self->${\ "set_$k"}($v);
    }
    return $self;
}

=head2 load

    $req = load SlackBuild::Request($URL)

Loads request from the supplied $URL. Allowed arguments are:

=over 4     

=item Local file name

If $URL is the name of an existing local file, the file is loaded to the
memory and parsed as JSON object (if it begins with a curly brace), or as
YAML document.    
    
=item Local directory name

If $URL is the name of an existing local directory, it is searched for
any files matching the shell globbing pattern C<*.SlackBuild>. If any
such file is found, its base name is taken as the name of the package,
and the full pathname of the directory itself as the B<slackbuild_uri>.

=item URL of the remote tarball

If $URL begins with any of C<http://>, C<https://>, C<ftp://>, C<ftps://>,
and its path name component ends in C<.tar> with optional compression
suffix (C<.gz>, C<.xz>, C<.lz>, or C<.bz2>), the file name part of the
URL is taken as the package name and the $URL itself as B<slackbuild_uri>.

=item SBo URL

    sbo:///COMMIT/CATEGORY/PACKAGE

This URL refers the definition of C<PACKAGE> in B<slackbuild.org> repository.
For example:

    sbo://HEAD/system/cronie

=item Package name

Unqualified package name is looked up in the B<slackbuild.org> repository.
If it is found, the retrieved data are used to build the request.    

=back

=cut    

sub load {
    my ($class, $reqname) = @_;

    my $ldpack = __PACKAGE__ . '::Loader';
    my @comp = split /::/, $ldpack;

    my $bias = $SlackBuild::Request::Loader::MAX_PRIORITY;

    my $logger = Log::Log4perl::get_logger($class);
    $logger->debug("Looking for request $reqname");
    
    # Current (as of perl 5.28.0) implementation of "state" only permits
    # the initialization of scalar variables in scalar context. Therefore
    # this variable is an array ref.
    state $loaders //=
	[map { $_->[1] }
	    sort { $a->[0] <=> $b->[0] }
	    map {
		my ($modname) = $ldpack . '::' . fileparse($_, '.pm');
		eval {
		    no strict 'refs';
		    unless (scalar %{ $modname.'::' }) {
			require $_;
		    }
		    my $prio = ${$modname.'::PRIORITY'};
		    die unless defined($prio) && $modname->can('Load');
		    [ $bias + $prio, $modname ]
		}
	    }
	    map { glob File::Spec->catfile($_, '*.pm') }
	    grep { -d $_ }
	    map { File::Spec->catfile($_, @comp) } @INC];
    
    foreach my $ld (@$loaders) {
	$logger->debug("trying module $ld");
	if (my $param = $ld->Load($reqname)) {
	    my $req = $class->new($param);
	    $logger->info("request $reqname resoved as $req using module $ld");
	    return $req;
	}
    }

    croak "unrecognized request type";
}

sub merge {
    my ($self, $other) = @_;
    foreach my $attr (keys %attributes) {
	unless (defined($self->{$attr})) {
	    $self->${\ "set_$attr"}($other->${\ $attr});
	}
    }
}

=head1 STRING REPRESENTATION

When used is string context, objects of this class are represented as
JSON objects with attribute names sorted in lexical order. The same
representation is returned by the B<as_string> method.

If the B<string_full> attribute is set, the string representation
includes all attributes, including the ones with B<null> value. Otherwise,
only non-null attributes are returned (the default).

=cut    
    
sub as_string {
    my $self = shift;
    my %h;
    my @k;
    if ($self->string_full) {
	@k = keys %attributes;
    } else {
	@k = grep { defined $self->${\$_} } keys %attributes;
    }
    @h{@k} = map { $self->${\$_} } @k;
    JSON->new->canonical(1)->encode(\%h);
}

sub string_full {
    my $self = shift;
    if (my $v = shift) {
	croak "too many arguments" if @_;
	$self->{string_full} = $v;
    }
    return $self->{string_full};
}

sub set_string_full {
    my ($self, $value) = @_;
    $self->{string_full} = $value;
}

use overload '""' => sub { shift->as_string };

=head1 MERGING WITH INFO OBJECTS

    $req->addinfo($info)

Merges B<$info> (an instance of B<SlackBuild::Info>) with the request
object B<$req>.

If an attribute is unset in B<$req>, it will be set from the corresponding
field in B<$req>.

Otherwise, the behavior depends on the merging strategy set for that
attribute:

=over 4

=item overwrite

The value from B<$info> always overwrites the B<$req> attribute.

=item keep

If the attribute is set, its value is retained and the B<$info> field
is ignored.

=item merge

If the attribute is C<HASH> or C<ARRAY>, the B<$info> field is merged in
the attribute.

=back    

The default strategy is B<merge> for B<prereq>, and B<keep> for the rest
of attributes.    
    
=cut

sub addinfo {
    my ($self, $info) = @_;
    while (my ($attr,$descr) = each %attributes) {
	if ($descr->{info} && (my $v = $info->${ \$descr->{info} })) {
	    $self->${\ "set_$attr"}($v);
	}
    }
}

sub set_prereq {
    my ($self, $value) = @_;
    my $meth = $generics{ARRAY}{set};
    $value = [ $value ] unless ref($value) eq 'ARRAY';
    $value = [ grep { $_ ne '%README%' } @$value ];
    $self->${\$meth}('prereq', $value, $self->strategy('prereq'));
}

{
    no strict 'refs';
    use feature 'state';
    while (my ($attr,$descr) = each %attributes) {
	unless (__PACKAGE__->can($attr)) {
	    *{ __PACKAGE__ . '::' . $attr } = sub {
		my $self = shift;
		return $self->${ \ $generics{$descr->{type}}{get} }($attr)
		    || $descr->{default};
	    }
	}
	unless (__PACKAGE__->can("set_$attr")) {
	    *{ __PACKAGE__ . '::set_' . $attr } = sub {
		my ($self, $value) = @_;
		$self->${\$generics{$descr->{type}}{set}}
                       ($attr, $value, $self->strategy($attr));
	    }
	}
    }
}

sub extract_local_name {
    my ($self, $path) = @_;
    my $result;

    if (my $codelist = $self->local_name) { 
	my $s = new Safe;
	my $package = $self->package;
	my $version = $self->version;
        ${$s->varglob('package')} = $package;
        ${$s->varglob('version')} = $version;
	foreach my $code (@$codelist) {
	    $_ = $path;
	    if (defined(my $r = $s->reval($code))) {
		$result = $_;
		last;
	    } else {
		croak "failed to eval \"$code\" on \"$path\": \n$@\n";
	    }
	}
    }
    return $result || basename($path)
}

1;

Return to:

Send suggestions and report system problems to the System administrator.