File: HasEntries.pm

package info (click to toggle)
libcpan-changes-perl 0.500005-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,964 kB
  • sloc: perl: 988; makefile: 2
file content (93 lines) | stat: -rw-r--r-- 2,086 bytes parent folder | download
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
package CPAN::Changes::HasEntries;
use strict;
use warnings;

our $VERSION = '0.500005';
$VERSION =~ tr/_//d;

use Sub::Quote qw(qsub);
use Types::Standard qw(ArrayRef InstanceOf Str);

use Moo::Role;

my $entry_type = (InstanceOf['CPAN::Changes::Entry'])->plus_coercions(
  Str ,=> qsub q{ CPAN::Changes::Entry->new(text => $_[0]) },
);

has entries => (
  is => 'rw',
  default => sub { [] },
  isa => ArrayRef[$entry_type],
  coerce => 1,
);

sub clone {
  my $self = shift;
  my %attrs = %$self;
  $attrs{entries} = [ map $_->clone, @{$self->entries} ];
  (ref $self)->new(%attrs, @_);
}

sub has_entries {
  my $self = shift;
  !!($self->entries && @{$self->entries});
}

sub find_entry {
  my ($self, $find) = @_;
  return undef
    unless $self->has_entries;
  if (ref $find ne 'Regexp') {
    $find = qr/\A\Q$find\E\z/;
  }
  my ($entry) = grep { $_->text =~ $find } @{ $self->entries };
  return $entry;
}

around serialize => sub {
  my ($orig, $self, %args) = @_;
  my $indents = $args{indents} || [];
  my $styles = $args{styles} || [];
  my $width = $args{width} || 75;
  $indents = [ @{$indents}[1 .. $#$indents], '  '],
  $styles = [ @{$styles}[1 .. $#$styles], '-'],
  my $out = $self->$orig(@_);
  my $entries = $self->entries || [];
  for my $entry ( @$entries ) {
    my $sub = $entry->serialize(
      indents => $indents,
      styles => $styles,
      width => $width - length $indents->[0],
    );
    $sub =~ s/^(.)/$indents->[0]$1/mg;
    $sub .= "\n"
      if $entry->has_entries;
    $out .= $sub;
  }
  $out =~ s/\n\n+\z/\n/;
  return $out;
};

sub add_entry {
  my ($self, @entries) = @_;
  $_ = $entry_type->coerce($_)
    for @entries;
  push @{ $self->entries }, @entries;
  return wantarray ? @entries : $entries[-1];
}

sub remove_entry {
  my ($self, $entry) = @_;
  $entry
    = ref $entry && $entry->isa('CPAN::Changes::Entry') ? $entry
    : $self->find_entry($entry);
  return unless $entry;
  my @entries = grep { $_ != $entry } @{ $self->entries };
  $self->entries(\@entries);
}

require CPAN::Changes::Entry;
1;
__END__

=for Pod::Coverage .*