This file is indexed.

/usr/share/lintian/lib/Lintian/Lab.pm is in lintian 2.5.6.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
744
745
746
747
748
749
750
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
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
831
832
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
# Lintian::Lab -- Perl laboratory functions for lintian

# Copyright (C) 2011 Niels Thykier
#   - Based on the work of "Various authors"  (Copyright 1998-2004)
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, you can find it on the World Wide
# Web at http://www.gnu.org/copyleft/gpl.html, or write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.

package Lintian::Lab;

use strict;
use warnings;

use base qw(Class::Accessor Exporter);

use Carp qw(croak);
use Cwd();

use File::Temp qw(tempdir); # For temporary labs

use Scalar::Util qw(blessed);


use constant {
# Lab format Version Number increased whenever incompatible changes
# are done to the lab so that all packages are re-unpacked
    LAB_FORMAT      => 11,
# Constants to avoid semantic errors due to typos in the $lab->{'mode'}
# field values.
    LAB_MODE_STATIC => 'static',
    LAB_MODE_TEMP   => 'temporary',
};


# A private table of suported types.
my %SUPPORTED_TYPES = (
    'binary'  => 1,
    'changes' => 1,
    'source'  => 1,
    'udeb'    => 1,
);

our (@EXPORT, @EXPORT_OK, %EXPORT_TAGS);

BEGIN {
    @EXPORT = ();
    %EXPORT_TAGS = (
        constants => [qw(LAB_FORMAT)],
    );
    @EXPORT_OK = (
        @{ $EXPORT_TAGS{constants} }
    );
};

use Util qw(delete_dir get_dsc_info);

use Lintian::Collect;
use Lintian::Lab::Entry;
use Lintian::Lab::Manifest;

=head1 NAME

Lintian::Lab -- Interface to the Lintian Lab

=head1 SYNOPSIS

 use Lintian::Lab;
 
 # Static lab
 my $lab = Lintian::Lab->new ('/var/lib/lintian/static-lab');

 if (!$lab->exists) {
     $lab->create;
 }
 $lab->open;
 
 # Fetch a package from the lab
 my $pkg = $lab->get_package ('lintian', 'binary', '2.5.4', 'all');
 
 #FIXME: Add more to the synopsis here
 
 $lab->close;

=head1 DESCRIPTION

=head2 Methods

=over 4

=item Lintian::Lab->new([$dir])

Creates a new Lab instance.  If C<$dir> is passed it will be used as
the path to the lab and the lab will be in static mode.  Otherwise the
lab will be in temporary mode and will point to a temporary directory.

=cut


sub new {
    my ($class, $dir) = @_;
    my $absdir;
    my $mode = LAB_MODE_TEMP;
    my $dok = 1;
    if ($dir) {
        $mode = LAB_MODE_STATIC;
        $absdir = Cwd::abs_path ($dir);
        if (!$absdir) {
            if ($dir =~ m,^/,o) {
                $absdir = $dir;
            } else {
                $absdir = Cwd::cwd . '/' . $dir;
            }
            $dok = 0;
        }
    } else {
        $absdir = ''; #Ensure it is defined.
    }
    my $self = {
        # Must be absolute (frontend/lintian depends on it)
        #  - also $self->dir promises this
        #  - it may be the empty string (see $self->dir)
        'dir'         => $absdir,
        'state'       => {},
        'mode'        => $mode,
        'is_open'     => 0,
        'keep-lab'    => 0,
        'lab-info'    => {},
    };
    $self->{'_correct_dir'} = 1 unless $dok;
    bless $self, $class;
    $self->_init ($dir);
    return $self;
}

=item $lab->dir

Returns the absolute path to the base of the lab.

Note: This may return the empty string if either the lab has been
deleted or this is a temporary lab that has not been created yet.  In
the latter case, $lab->create or $lab->open should be run to get a
non-empty value from this method.

=item $lab->is_open

Returns a truth value if this lab is open.

Note: If the lab is open, it also exists.  However, if the lab is
closed then the lab may or may not exist (see L</exists>).

=cut

Lintian::Lab->mk_ro_accessors (qw(dir is_open));

=item $lab->exists

Returns a truth value if B<$lab> points to an existing lab.

Note: This never implies that the lab is open.  Though it may imply
the lab is closed (see L</is_open>).

=cut

sub exists {
    my ( $self ) = @_;
    my $dir = $self->dir;
    return unless $dir;
    # New style lab?
    return 1 if -d "$dir/info" && -d "$dir/pool";
    # 10-style lab?
    return -d "$dir/binary"
        && -d "$dir/udeb"
        && -d "$dir/source"
        && -d "$dir/info";
}

=item $lab->get_package ($pkg_name, $pkg_type[, @extra]), $lab->get_package ($proc)

Fetches an existing package from the lab.

The first argument can be a L<Lintian::Processable|proccessable>.  In that
case all other arguments are ignored.

If the first calling convention is used then this method will search
for an existing package.  The @extra argument can be used to narrow
the search or even to add a new entry.

@extra consists of (in order):
 - version
 - arch (Ignored if $pkg_type is "source")

If version or arch is omitted (or if it is undef) then that search
parameter is consider a wildcard for "any".  Example:

 # Returns all eclipse-platform packages with architecture i386 regardless
 # of their version (if any)
 @ps  = $lab->get_package ('eclipse-platform', 'binary', undef, 'i386');
 # Returns all eclipse-platform packages with version 3.5.2-11 regardless
 # of their architecture (if any)
 @ps  = $lab->get_package ('eclipse-platform', 'binary', '3.5.2-11');
 # Return the eclipse-platform package with version 3.5.2-11 and architecture
 # i386 (or undef)
 $pkg = $lab->get_package ('eclipse-platform', 'binary', '3.5.2-11', 'i386');


In list context, this returns a list of matches.  In scalar context
this returns the first match (if any).

If the second calling convention is used, then this method will search
for an entry matching the the processable passed.  If such an entry
does not exists, an new "non-existing" L<entry|Lintian::Lab::Entry>
will be returned.  This entry can be created by using the "create"
method on the entry.

=cut

sub get_package {
    my ($self, $pkg, $pkg_type, $pkg_version, $pkg_arch) = @_;
    my $pkg_name;
    my $pkg_path;
    my @entries;
    my $index;
    my $proc;

    croak 'Lab is not open' unless $self->is_open;

    # TODO: Cache and check for existing entries to avoid passing out
    # the same entry twice with different instances.  Problem being
    # circular references (and weaken may be un-available)

    if (blessed $pkg && $pkg->isa ('Lintian::Processable')) {
        $pkg_name = $pkg->pkg_name;
        $pkg_type = $pkg->pkg_type;
        $pkg_version = $pkg->pkg_version;
        $pkg_arch = $pkg->pkg_arch;
        $pkg_path = $pkg->pkg_path;
        $proc = $pkg;
    } else {
        $pkg_name = $pkg;
        croak "Package name and type must be defined" unless $pkg_name && $pkg_type;
    }

    $index = $self->_get_lab_index ($pkg_type);

    if (defined $pkg_version && (defined $pkg_arch || $pkg_type eq 'source')) {
        # We know everything - just do a regular look up
        my $dir;
        my @keys = ($pkg_name, $pkg_version);
        my $e;
        my ($pkg_src, $pkg_src_version);
        push @keys, $pkg_arch if $pkg_type ne 'source';
        if ($proc) {
            $pkg_src = $proc->pkg_src;
            $pkg_src_version = $proc->pkg_src_version;
        } else {
            $e = $index->get (@keys);
            return unless $e;
            $pkg_src = $e->{'source'};
            $pkg_src_version = $e->{'source-version'}//$pkg_version;
        }
        $dir = $self->_pool_path ($pkg_src, $pkg_type, $pkg_name, $pkg_version, $pkg_arch);
        push @entries, Lintian::Lab::Entry->_new ($self, $pkg_name, $pkg_version, $pkg_arch, $pkg_type, $pkg_path, $pkg_src, $pkg_src_version, $dir);
    } else {
        # clear $pkg_arch if it is a source package - it simplifies
        # the search code below
        undef $pkg_arch if $pkg_type eq 'source';
        my $searcher = sub {
            my ($entry, @keys) = @_;
            my ($n, $v, $a) = @keys;
            my $dir;
            my $pp;
            my $pkg_src;
            # We do not have to check version - if we have a specific
            # version, only entries with that version will be visited.
            return if defined $pkg_arch && $a ne $pkg_arch;
            $pp = $entry->{'file'};
            $pkg_src = $entry->{'source'};
            $dir = $self->_pool_path ($pkg_src, $pkg_type, $pkg_name, $v, $a);
            push @entries,  Lintian::Lab::Entry->_new ($self, $pkg_name, $v, $a, $pkg_type, $pp, $pkg_src, $entry->{'source-version'}//$v, $dir);
        };
        my @sk = ($pkg_name);
        push @sk, $pkg_version if defined $pkg_version;
        $index->visit_all ($searcher, @sk);
    }

    return wantarray ? @entries : $entries[0];
}

=item $lab->visit_packages ($visitor[, $pkg_type])

Passes each lab entry to $visitor.  If $pkg_type is passed, then only
entries of that type are passed.

The visitor is given a reference to the L<entry|Lintian::Lab::Entry>,
the package name, the package version and the package architecture
(may be undef for source packages).

=cut

sub visit_packages {
    my ($self, $visitor, $type) = @_;
    my @types;
    push @types, $type if $type;
    @types = keys %SUPPORTED_TYPES unless $type;
    foreach my $pkg_type (@types) {
        my $index = $self->_get_lab_index ($pkg_type);
        my $intv = sub {
            my ($me, $pkg_name, $pkg_version, $pkg_arch) = @_;
            my $pkg_src = $me->{'source'}//$pkg_name;
            my $dir = $self->_pool_path ($pkg_src, $pkg_type, $pkg_name, $pkg_version, $pkg_arch);
            my $pkg_src_version = $me->{'source-version'}//$pkg_version;
            my $lentry = Lintian::Lab::Entry->_new ($self, $pkg_name, $pkg_version, $pkg_arch,
                                                   $pkg_type, undef, $pkg_src, $pkg_src_version, $dir);
            $visitor->($lentry, $pkg_name, $pkg_version, $pkg_arch);
        };
        $index->visit_all ($intv);
    }
}


# Non-API method used by reporting to look up the manifest data via the Lab
# rather than bypassing it.
sub _get_lab_manifest_data {
    my ($self, $pkg_name, $pkg_type, @keys) = @_;
    my $index = $self->_get_lab_index ($pkg_type);
    if (scalar @keys >= 2 || (scalar @keys >= 1 && $pkg_type eq 'source')) {
        # All we need to know
        return $index->get ($pkg_name, @keys);
    } else {
        # Time to guess (or hope)
        my @result = ();
        my $searcher = sub {
            my ($v) = @_;
            push @result, $v;
        }; # end searcher
        $index->visit_all ($searcher, $pkg_name, @keys);
        return $result[0] if @result;
    }
    # Nothing so far, then it does not exist
    return;
}

# Returns the index of packages in the lab of a given type (of packages).
#
# Unlike $lab->_load_lab_index, this uses the cached version if it is
# available.
#
# Note this is also used by reporting/html_reports
sub _get_lab_index {
    my ($self, $pkg_type) = @_;
    croak "Undefined (or empty) package type" unless $pkg_type;
    croak "Unknown package type $pkg_type" unless $SUPPORTED_TYPES{$pkg_type};
    # Fetch (or load) the index of that type
    return $self->{'state'}->{$pkg_type} // $self->_load_lab_index ($pkg_type);
}

# Unconditionally (re-)loads the index of packages in the lab of a
# given type (of packages).
#
# $lab->_get_lab_index is generally faster since it uses the cache if
# available.
sub _load_lab_index {
    my ($self, $pkg_type) = @_;
    my $dir = $self->dir;
    my $manifest = Lintian::Lab::Manifest->new ($pkg_type);
    my $lif = "$dir/info/${pkg_type}-packages";
    $manifest->read_list ($lif);
    $self->{'state'}->{$pkg_type} = $manifest;
    return $manifest;
}

# Given the package meta data (src_name, type, name, version, arch) return the
# path to it in the Lab.  The path returned will be absolute.
sub _pool_path {
    my ($self, $pkg_src, $pkg_type, $pkg_name, $pkg_version, $pkg_arch) = @_;
    my $dir = $self->dir;
    my $p;
    # If it is at least 4 characters and starts with "lib", use "libX"
    # as prefix
    if ($pkg_src =~ m/^lib./o) {
        $p = substr $pkg_src, 0, 4;
    } else {
        $p = substr $pkg_src, 0, 1;
    }
    $p  = "$p/$pkg_src/${pkg_name}_${pkg_version}";
    $p .= "_${pkg_arch}" unless $pkg_type eq 'source';
    $p .= "_${pkg_type}";
    # Turn spaces into dashes - spaces do appear in architectures
    # (i.e. for changes files).
    $p =~ s/\s/-/go;
    # Also replace ":" with "_" as : is usually used for path separator
    $p =~ s/:/_/go;
    return "$dir/pool/$p";
}

=item $lab->generate_diffs(@lists)

Each member of @lists must be a Lintian::Lab::Manifest.

The lab will generate a diff between the given member and its state
for the given package type.

The diffs are valid until the original manifest is modified or a package
is added or removed to the lab.

=cut

sub generate_diffs {
    my ($self, @lists) = @_;
    my $labdir = $self->dir;
    my @diffs;
    croak "$labdir is not a valid lab (run lintian --setup-lab first?).\n"
        unless $self->is_open;
    foreach my $list (@lists) {
        my $type = $list->type;
        my $lab_list;
        $lab_list = $self->_get_lab_index ($type);
        push @diffs, $lab_list->diff ($list);
    }
    return @diffs;
}

=item $lab->repair_lab ()

Checks the lab contents against the current meta-data and syncs them.
The lab must be open and should not be access while this method is
running.

This returns the number of corrections done by this process.  If there
were any corrections, the state files are written before returning.

The method may croak if it is unable to do a full check of the lab or
if it is unable to write the corrected metadata.

Note: This may (and generally will) correct "broken" entries by
removing them.

=cut

sub repair_lab {
    my ($self) = @_;
    my $updates = 0;
    croak "Lab is not open.\n" unless $self->is_open;
    foreach my $pkg_type (keys %SUPPORTED_TYPES) {
        my $index = $self->_get_lab_index ($pkg_type);
        my $visitor = sub {
            my ($metadata, @keys) = @_;
            my ($pkg_name, $pkg_version, $pkg_arch) = @keys;
            my $pkg_src = $metadata->{'source'}//$pkg_name;
            my $pkg_src_version = $metadata->{'source-version'}//$pkg_version;
            my $dir = $self->_pool_path ($pkg_src, $pkg_type, $pkg_name, $pkg_version, $pkg_arch);
            my $entry;
            unless ( -d $dir && -f "$dir/.lintian-status") {
                # The entry is clearly not here, remove it from the metadata
                $index->delete (@keys);
                $updates++;
                -d $dir && rmdir $dir;
                return;
            }
            eval {
                $entry = Lintian::Lab::Entry->_new ($self, $pkg_name, $pkg_version, $pkg_arch,
                                                    $pkg_type, undef, $pkg_src, $pkg_src_version,
                                                    $dir);
            };
            unless ($entry && $entry->exists) {
                # We either cannot load the entry or it does not
                # believe it exists - either way, the metadata is out
                # of date.
                if ($entry) {
                    $entry->remove;
                    # Strictly speaking $entry->remove ought to clean
                    # up the index for us, but fall through and do it
                    # anyway.
                } else {
                    # The entry is not here to clean up, lets purge it
                    # the good old fashioned way.
                    delete_dir ($dir);
                }
                $index->delete (@keys);
                $updates++;
            }
        };

        $index->visit_all ($visitor);
    }

    # FIXME: scan the pool for entries not in the metadata.

    $self->_write_manifests;

    return $updates;
}

=item $lab->create ([$opts])

Creates a new lab.  It will create $lab->dir if it does not exist.
It will also create a basic empty lab.  If this is a temporary
lab, this method will also setup the temporary dir for the lab.

The $lab will I<not> be opened by this method.  This should be done
afterwards by invoking the open method.

B<$opts> (if present) is a hashref containing options.  The following
options are accepted:

=over 4

=item keep-lab

If "keep-lab" points to a truth value the temporary directory will
I<not> be removed by closing the lab (nor exiting the application).
However, explicitly calling $lab->remove will remove the lab.

=item mode

If present, this will be used as mode for creating directories.
Will default to 0777 if not specified.

=back

Note: This will not create parent directories of $lab->dir and will
croak if these does not exist.

Note: This may update the value of $lab->dir as resolving the path
requires it to exist.

Note: This does nothing if the lab appears to already exists.

=cut

sub create {
    my ($self, $opts) = @_;
    my $dir = $self->dir;
    my $mid = 0;
    my $mode = 0777;

    return 1 if $self->exists;

    $opts = {} unless $opts;
    $mode = $opts->{'mode'} if exists $opts->{'mode'};
    if ( !$dir or $self->is_temp) {
        if ($self->is_temp) {
            my $keep = $opts->{'keep-lab'}//0;
            my %topts = ( 'CLEANUP' => !$keep, 'TMPDIR' => 1 );
            my $t = tempdir ('temp-lintian-lab-XXXXXXXXXX', %topts);
            $dir = Cwd::abs_path ($t);
            croak "Could not resolve $t: $!" unless $dir;
            $self->{'dir'} = $dir;
            $self->{'keep-lab'} = $keep;
        } else {
            # This should not be possible - but then again,
            # code should not have any bugs either...
            croak 'Lab path may not be empty for a static lab';
        }
    }
    # Create the top dir if needed - note due to Lintian::Lab->new
    # and the above tempdir creation code, we know that $dir is
    # absolute.
    croak "Cannot create $dir: $!" unless -d $dir or mkdir $dir, $mode;

    if ($self->{'_correct_dir'}) {
        # This happens if $dir has been created in this call.
        # Until now we have been unable to fully resolve the path,
        # so we try now.
        my $absdir = Cwd::abs_path ($dir);
        croak "Cannot resolve $dir: $!" unless $absdir;
        delete $self->{'_correct_dir'};
        $dir = $absdir;
        $self->{'dir'} = $absdir;
    }

    # Top dir exists, time to create the minimal directories.
    unless (-d "$dir/info") {
        mkdir "$dir/info", $mode or croak "mkdir $dir/info: $!";
        $mid = 1; # remember we created the info dir
    }

    unless (-d "$dir/pool") {
        unless (mkdir "$dir/pool", $mode) {
            my $err = $!; # store the error
            # Remove the info dir if we made it.  This attempts to
            # prevent a semi-created lab that the API cannot remove
            # again.
            #
            # ignore the error (if any) - we can only do so much
            rmdir "$dir/info" if $mid;
            $! = $err;
            croak "mkdir $dir/pool: $!";
        }
    }
    # Okay - $dir/info and $dir/pool exists... The subdirs in
    # $dir/pool will be created as needed.

    # Create the meta-data file - note at this point we can use
    # $lab->remove
    my $ok = 0;
    eval {
        open my $lfd, '>', "$dir/info/lab-info" or croak "opening $dir/info/lab-info: $!";

        print $lfd 'Lab-Format: ' . LAB_FORMAT . "\n";
        print $lfd "Layout: pool\n";

        close $lfd or croak "closing $dir/info/lab-info: $!";
        $ok = 1;
    };
    unless ($ok) {
        my $err = $@;
        eval { $self->remove; };
        croak $err;
    }
    return 1;
}

=item $lab->open

Opens the lab and reads the contents into caches.  If the lab is
temporary and does not exists, this method will call create to
initialize the temporary lab.

This will croak if the lab is already open.  It may also croak for
the same reasons as $lab->create if the lab is temporary (see above).

Note: for static labs, $lab->dir must point to an existing consistent
lab or this will croak.  To open a new lab, please use
$lab->create.

Note: It is not possible to pass options to the creation of the
temporary lab.  If special options are required, please use
$lab->create directly.

=cut

sub open {
    my ($self) = @_;
    my $dir;
    my $msg = "Open Lab failed";
    croak ('Lab is already open') if $self->is_open;
    if ($self->is_temp) {
        $self->create unless $self->exists;
        $dir = $self->dir;
    } else {
        $dir = $self->dir;
        unless ($self->exists) {
            croak "$msg: $dir does not exists" unless -e $dir;
            croak "$msg: $dir is not a lab or the lab is corrupt";
        }
    }

    unless ( -e "$dir/info/lab-info") {
        if ( $self->exists ) {
            croak "$msg: The Lab format is not supported";
        }
        croak "$msg: Lab is corrupt - $dir/info/lab-info does not exist";
    }

    # Check the lab-format - this ought to be redundant for temp labs, but
    # it's simpler to do it for them anyway.
    my $header = get_dsc_info ("$dir/info/lab-info");
    my $format = $header->{'lab-format'}//'';
    my $layout = $header->{'layout'}//'pool';
    unless ($format && $format eq LAB_FORMAT) {
        croak "$msg: Lab format $format is not supported ($dir)" if $format;
        croak "$msg: No lab format specification in $dir/info/lab-info";
    }
    unless ($layout && lc($layout) eq 'pool') {
        # Unknown layout style?
        croak "$msg: Layout field present but with no value" unless $layout;
        croak "$msg: Implementation does not support the layout \"$layout\"";
    }

    # Looks decent so far
    $self->{'lab-info'} = $header;
    $self->{'is_open'} = 1;
    return 1;
}

=item $lab->close

Close the lab - all state caches will be flushed to the disk and the
lab can no longer be used.  All references to entries in the lab
should be considered invalid.

Note: if the lab is a temporary one, this will be deleted unless it
was created with "keep-lab" (see $lab->create).

=cut

sub close {
    my ($self) = @_;
    return unless $self->exists;
    if ($self->is_temp && !$self->{'keep-lab'}) {
        # Temporary lab (without "keep-lab" property)
        $self->remove;
    } else {
        $self->_write_manifests;
    }
    $self->{'state'} = {};
    $self->{'is_open'} = 0;
    $self->{'lab-info'} = {};
    return 1;
}

sub _write_manifests {
    my ($self) = @_;
    my $dir = $self->dir;
    while ( my ($pkg_type, $plist) = (each %{ $self->{'state'} }) ) {
        # write_list croaks on error, so no need for "or croak/die"
        $plist->write_list ("$dir/info/${pkg_type}-packages");
    }
}

=item $lab->remove

Removes the lab and everything in it.  Any reference to an entry
returned from this lab will immediately become invalid.

If this is a temporary lab, the lab root dir (as returned $lab->dir)
will be removed as well on success.  Otherwise the lab root dir will
not be removed by this call.

On success, this will return a truth value.  If the lab is a temporary
lab, the directory path will be set to the empty string (that is,
$lab->dir will return '').

On error, this method will croak.

If the lab has already been removed (or does not exist), this will
return a truth value.

=cut

sub remove {
    my ($self) = @_;
    my $dir = $self->dir;
    my @subdirs = ();
    my $empty = 0;

    return 1 unless $dir && -d $dir;

    # sanity check if $self->{dir} really points to a lab :)
    unless (-d "$dir/info") {
        # info/ subdirectory does not exist--empty directory?
        my @t = glob("$dir/*");
        if ($#t+1 <= 2) {
            # yes, empty directory--skip it
            $empty = 1;
        } else {
            # non-empty directory that does not look like a lintian lab!
            croak "$dir: Does not look like a lab";
        }
    }

    unless ($empty) {
        # looks ok.
        if ( -d "$dir/pool") {
            # New lab style
            @subdirs = qw/pool info/;
        } else {
            # 10-style Lab
            @subdirs = qw/binary source udeb info/;
            push @subdirs, 'changes' if -d "$dir/changes";
        }
        unless (delete_dir( map { "$dir/$_" } @subdirs )) {
            croak "delete_dir (\$contents): $!";
        }
    }

    # dynamic lab?
    if ($self->is_temp) {
        rmdir $dir or croak "rmdir $dir: $!";
        $self->{'dir'} = '';
    }

    $self->{'is_open'} = 0;
    return 1;
}

=item $lab->is_temp

Returns a truth value if $lab is a temporary lab.

Note: This returns a truth value, even if the lab was created with the
"keep-lab" property.

=cut

sub is_temp {
    my ($self) = @_;
    return $self->{'mode'} eq LAB_MODE_TEMP ? 1 : 0;
}

# initialize the instance
#
# May be overriden by a sub-class.
#
# $self->dir may be the empty string if this is a temporary lab.
sub _init {
    my ($self) = @_;
}

# event - triggered by Lintian::Lab::Entry
sub _entry_removed {
    my ($self, $entry) = @_;
    my $pkg_name    = $entry->pkg_name;
    my $pkg_type    = $entry->pkg_type;
    my $pkg_version = $entry->pkg_version;
    my @keys = ($pkg_name, $pkg_version);
    my $pf = $self->_get_lab_index ($pkg_type);

    push @keys, $entry->pkg_arch if $pkg_type ne 'source';

    $pf->delete (@keys);
}

# event - triggered by Lintian::Lab::Entry
sub _entry_created {
    my ($self, $entry) = @_;
    my $pkg_name    = $entry->pkg_name;
    my $pkg_type    = $entry->pkg_type;
    my $pkg_version = $entry->pkg_version;
    my $pkg_path    = $entry->pkg_path;
    my $ts = 0;
    my $pf = $self->_get_lab_index ($pkg_type);
    my %data = (
        'file'    => $pkg_path,
        'version' => $pkg_version,
    );

    if (my @stat = stat $pkg_path) {
        $ts = $stat[9];
    }
    $data{'timestamp'} = $ts;
    if ($pkg_type eq 'source') {
        my $info = $entry->info;
        my $up = $info->field ('uploaders')//'';
        my $maint = $info->field ('maintainer')//'';
        my $bin = $info->field ('binary')//'';

        # Normalize the fields - usually this will be "no-ops", but we
        # do check some really warped packages every now and then...

        if ($up) {
            $up =~ s/\n/ /og;
            $up = join (', ', split (m/\s*,\s*/o, $up));
        }
        if ($bin) {
            $bin   =~ s/\n\s*//og;
            $bin = join (', ', split (m/\s*,\s*/o, $bin));
        }

        $maint =~ s/\n\s*//og if $maint;
        $data{'binary'}     = $bin;
        $data{'source'}     = $pkg_name;
        $data{'area'}       = ''; # just blank this - we do not know it :)
        $data{'maintainer'} = $maint;
        $data{'uploaders'}  = $up;
    } elsif ($pkg_type eq 'changes') {
        $data{'architecture'} = $entry->pkg_arch;
        $data{'source'}       = $pkg_name;
    } elsif ($pkg_type eq 'binary' or $pkg_type eq 'udeb') {
        my $info = $entry->info;
        my $area = 'main';
        my $s = $info->field ('section')//'';
        if ($s && $s =~ m,\s*([a-zA-Z0-9-_]+)/,o) {
            $area = $1;
        }
        $data{'architecture'}   = $entry->pkg_arch;
        $data{'area'}           = $area;
        $data{'package'}        = $pkg_name;
        $data{'source'}         = $entry->pkg_src;
        $data{'source-version'} = $entry->pkg_src_version;
    } else {
        croak "Unknown package type: $pkg_type";
    }

    $pf->set (\%data);
}

=back

=head1 Changes to the lab format.

Lab formats up to (and including) "10" used to store the lab format
with each entry.  The files in $LAB/info/ were used to list packages
from a mirror (dist).

In lab format 11 the lab format is stored in $LAB/info/lab-info.  The
rest of the files in $LAB/info/* have been re-purposed to be a list of
packages in the lab.

The $LAB/info/lab-info is parsed as a debian control file (See Debian
Policy Manual §5.1 for syntax).  The consists of a single paragraph
and only the following fields are allowed:

=over 4

=item Lab-Format (simple, mandatory)

This field contains the lab format of this lab.  Generally this is
simply an integer (though during development non-integers have been
used).

=item Layout (simple, optional)

The layout parameter describes how packages are stored in the lab.
Currently the only accepted value is "pool" and the value is not
case-sensitive.

The pool format dictates that packages are stored in:

 pool/$l/${name}/${name}_${version}[_${arch}]_${type}/

Note that $arch is left out for source packages, $l is the first
letter of the package name (except if the name starts with "lib", then
it is the first 4 letters of the package name).  Whitespaces (i.e. "
") are replaced with dashes ("-") and colons (":") with underscores
("_").

If the field is missing, it defaults to "pool".

=back

It is allowed to use comments in $LAB/info/lab-info as described
in the Debian Policy Manual §5.1.

=head1 AUTHOR

Niels Thykier <niels@thykier.net>

Based on the work of various others.

=cut

1;

# Local Variables:
# indent-tabs-mode: nil
# cperl-indent-level: 4
# End:
# vim: syntax=perl sw=4 sts=4 sr et