/
Plan.pm
1393 lines (1105 loc) · 43 KB
/
Plan.pm
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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
999
1000
package App::Sqitch::Plan;
use 5.010;
use utf8;
use App::Sqitch::DateTime;
use App::Sqitch::Plan::Tag;
use App::Sqitch::Plan::Change;
use App::Sqitch::Plan::Blank;
use App::Sqitch::Plan::Pragma;
use App::Sqitch::Plan::Depend;
use Path::Class;
use App::Sqitch::Plan::ChangeList;
use App::Sqitch::Plan::LineList;
use Locale::TextDomain qw(App-Sqitch);
use App::Sqitch::X qw(hurl);
use namespace::autoclean;
use Moose;
use constant SYNTAX_VERSION => '1.0.0-b2';
our $VERSION = '0.939';
# Like [:punct:], but excluding _. Copied from perlrecharclass.
my $punct = q{-!"#$%&'()*+,./:;<=>?@[\\]^`{|}~};
my $name_re = qr{
(?![$punct]) # first character isn't punctuation
(?: # start non-capturing group, repeated once or more ...
(?! # negative look ahead for...
[~/=%^] # symbolic reference punctuation
[[:digit:]]+ # digits
(?:$|[[:blank:]]) # eol or blank
) # ...
[^[:blank:]:@#] # match a valid character
)+ # ... end non-capturing group
(?<![$punct])\b # last character isn't punctuation
}x;
my %reserved = map { $_ => undef } qw(ROOT HEAD FIRST LAST);
sub name_regex { $name_re }
has sqitch => (
is => 'ro',
isa => 'App::Sqitch',
required => 1,
weak_ref => 1,
);
has _plan => (
is => 'ro',
isa => 'HashRef',
builder => 'load',
init_arg => 'plan',
lazy => 1,
required => 1,
);
has _changes => (
is => 'ro',
isa => 'App::Sqitch::Plan::ChangeList',
lazy => 1,
required => 1,
default => sub {
App::Sqitch::Plan::ChangeList->new(@{ shift->_plan->{changes} }),
},
);
has _lines => (
is => 'ro',
isa => 'App::Sqitch::Plan::LineList',
lazy => 1,
required => 1,
default => sub {
App::Sqitch::Plan::LineList->new(@{ shift->_plan->{lines} }),
},
);
has position => (
is => 'rw',
isa => 'Int',
required => 1,
default => -1,
);
has project => (
is => 'ro',
isa => 'Str',
required => 1,
lazy => 1,
default => sub {
shift->_plan->{pragmas}{project};
}
);
has uri => (
is => 'ro',
isa => 'Maybe[URI]',
required => 0,
lazy => 1,
default => sub {
my $uri = shift->_plan->{pragmas}{uri} || return;
require URI;
URI->new($uri);
}
);
sub load {
my $self = shift;
my $file = $self->sqitch->plan_file;
hurl plan => __x('Plan file {file} does not exist', file => $file)
unless -e $file;
hurl plan => __x('Plan file {file} is not a regular file', file => $file)
unless -f $file;
my $fh = $file->open('<:encoding(UTF-8)') or hurl plan => __x(
'Cannot open {file}: {error}',
file => $file,
error => $!
);
return $self->_parse($file, $fh);
}
sub _parse {
my ( $self, $file, $fh ) = @_;
my @lines; # List of lines.
my @changes; # List of changes.
my @curr_changes; # List of changes since last tag.
my %line_no_for; # Maps tags and changes to line numbers.
my %change_named; # Maps change names to change objects.
my %tag_changes; # Maps changes in current tag section to line numbers.
my %pragmas; # Maps pragma names to values.
my $seen_version; # Have we seen a version pragma?
my $prev_tag; # Last seen tag.
my $prev_change; # Last seen change.
# Regex to match timestamps.
my $ts_re = qr/
(?<yr>[[:digit:]]{4}) # year
- # dash
(?<mo>[[:digit:]]{2}) # month
- # dash
(?<dy>[[:digit:]]{2}) # day
T # T
(?<hr>[[:digit:]]{2}) # hour
: # colon
(?<mi>[[:digit:]]{2}) # minute
: # colon
(?<sc>[[:digit:]]{2}) # second
Z # Zulu time
/x;
my $planner_re = qr/
(?<planner_name>[^<]+) # name
[[:blank:]]+ # blanks
<(?<planner_email>[^>]+)> # email
/x;
# Use for raising syntax error exceptions.
my $raise_syntax_error = sub {
hurl plan => __x(
'Syntax error in {file} at line {lineno}: {error}',
file => $file,
lineno => $fh->input_line_number,
error => shift
);
};
# First, find pragmas.
HEADER: while ( my $line = $fh->getline ) {
chomp $line;
# Grab blank lines first.
if ($line =~ /\A(?<lspace>[[:blank:]]*)(?:#[[:blank:]]*(?<note>.+)|$)/) {
my $line = App::Sqitch::Plan::Blank->new( plan => $self, %+ );
push @lines => $line;
last HEADER if @lines && !$line->note;
next HEADER;
}
# Grab inline note.
$line =~ s/(?<rspace>[[:blank:]]*)(?:[#][[:blank:]]*(?<note>.*))?$//;
my %params = %+;
$raise_syntax_error->(
__ 'Invalid pragma; a blank line must come between pragmas and changes'
) unless $line =~ /
\A # Beginning of line
(?<lspace>[[:blank:]]*)? # Optional leading space
[%] # Required %
(?<hspace>[[:blank:]]*)? # Optional space
(?<name> # followed by name consisting of...
[^$punct] # not punct
(?: # followed by...
[^[:blank:]=]*? # any number non-blank, non-=
[^$punct[:blank:]] # one not blank or punct
)? # ... optionally
) # ... required
(?: # followed by value consisting of...
(?<lopspace>[[:blank:]]*) # Optional blanks
(?<operator>=) # Required =
(?<ropspace>[[:blank:]]*) # Optional blanks
(?<value>.+) # String value
)? # ... optionally
\z # end of line
/x;
# XXX Die if the pragma is a dupe?
if ($+{name} eq 'syntax-version') {
# Set explicit version in case we write it out later. In future
# releases, may change parsers depending on the version.
$pragmas{syntax_version} = $params{value} = SYNTAX_VERSION;
} elsif ($+{name} eq 'project') {
my $proj = $+{value};
$raise_syntax_error->(__x(
qq{invalid project name "{project}": project names must not }
. 'begin with punctuation, contain "@", ":", or "#", or end in '
. 'punctuation or digits following punctuation',
project => $proj,
)) unless $proj =~ /\A$name_re\z/;
$pragmas{project} = $proj;
} else {
$pragmas{ $+{name} } = $+{value} // 1;
}
push @lines => App::Sqitch::Plan::Pragma->new(
plan => $self,
%+,
%params
);
next HEADER;
}
# We should have a version pragma.
unless ( $pragmas{syntax_version} ) {
unshift @lines => $self->_version_line;
$pragmas{syntax_version} = SYNTAX_VERSION;
}
# Should have valid project pragma.
hurl plan => __x(
'Missing %project pragma in {file}',
file => $file,
) unless $pragmas{project};
LINE: while ( my $line = $fh->getline ) {
chomp $line;
# Grab blank lines first.
if ($line =~ /\A(?<lspace>[[:blank:]]*)(?:#[[:blank:]]*(?<note>.+)|$)/) {
my $line = App::Sqitch::Plan::Blank->new( plan => $self, %+ );
push @lines => $line;
next LINE;
}
# Grab inline note.
$line =~ s/(?<rspace>[[:blank:]]*)(?:[#][[:blank:]]*(?<note>.*))?$//;
my %params = %+;
# Is it a tag or a change?
my $type = $line =~ /^[[:blank:]]*[@]/ ? 'tag' : 'change';
$line =~ /
^ # Beginning of line
(?<lspace>[[:blank:]]*)? # Optional leading space
(?: # followed by...
[@] # @ for tag
| # ...or...
(?<lopspace>[[:blank:]]*) # Optional blanks
(?<operator>[+-]) # Required + or -
(?<ropspace>[[:blank:]]*) # Optional blanks
)? # ... optionally
(?<name>$name_re) # followed by name
(?<pspace>[[:blank:]]+)? # blanks
(?: # followed by...
[[](?<dependencies>[^]]+)[]] # dependencies
[[:blank:]]* # blanks
)? # ... optionally
(?: # followed by...
$ts_re # timestamp
[[:blank:]]* # blanks
)? # ... optionally
(?: # followed by
$planner_re # planner
)? # ... optionally
$ # end of line
/x;
%params = ( %params, %+ );
# Raise errors for missing data.
$raise_syntax_error->(__(
qq{Invalid name; names must not begin with punctuation, }
. 'contain "@", ":", or "#", or end in punctuation or digits following punctuation',
)) if !$params{name}
|| (!$params{yr} && $line =~ $ts_re);
$raise_syntax_error->(__ 'Missing timestamp and planner name and email')
unless $params{yr} || $params{planner_name};
$raise_syntax_error->(__ 'Missing timestamp') unless $params{yr};
$raise_syntax_error->(__ 'Missing planner name and email')
unless $params{planner_name};
# It must not be a reserved name.
$raise_syntax_error->(__x(
'"{name}" is a reserved name',
name => ($type eq 'tag' ? '@' : '') . $params{name},
)) if exists $reserved{ $params{name} };
# It must not look like a SHA1 hash.
$raise_syntax_error->(__x(
'"{name}" is invalid because it could be confused with a SHA1 ID',
name => $params{name},
)) if $params{name} =~ /^[0-9a-f]{40}/;
# Assemble the timestamp.
$params{timestamp} = App::Sqitch::DateTime->new(
year => delete $params{yr},
month => delete $params{mo},
day => delete $params{dy},
hour => delete $params{hr},
minute => delete $params{mi},
second => delete $params{sc},
time_zone => 'UTC',
);
if ($type eq 'tag') {
# Fail if no changes.
unless ($prev_change) {
$raise_syntax_error->(__x(
'Tag "{tag}" declared without a preceding change',
tag => $params{name},
));
}
# Fail on duplicate tag.
my $key = '@' . $params{name};
if ( my $at = $line_no_for{$key} ) {
$raise_syntax_error->(__x(
'Tag "{tag}" duplicates earlier declaration on line {line}',
tag => $params{name},
line => $at,
));
}
# Fail on dependencies.
$raise_syntax_error->(__x(
__ 'Tags may not specify dependencies'
)) if $params{dependencies};
if (@curr_changes) {
# Sort all changes up to this tag by their dependencies.
push @changes => $self->sort_changes(
$pragmas{project},
\%line_no_for,
@curr_changes,
);
@curr_changes = ();
}
# Create the tag and associate it with the previous change.
$prev_tag = App::Sqitch::Plan::Tag->new(
plan => $self,
change => $prev_change,
%params,
);
# Keep track of everything and clean up.
$prev_change->add_tag($prev_tag);
push @lines => $prev_tag;
%line_no_for = (%line_no_for, %tag_changes, $key => $fh->input_line_number);
%tag_changes = ();
} else {
# Fail on duplicate change since last tag.
if ( my $at = $tag_changes{ $params{name} } ) {
$raise_syntax_error->(__x(
'Change "{change}" duplicates earlier declaration on line {line}',
change => $params{name},
line => $at,
));
}
# Got dependencies?
if (my $deps = $params{dependencies}) {
my (@req, @con);
for my $depstring (split /[[:blank:]]+/, $deps) {
my $dep_params = App::Sqitch::Plan::Depend->parse(
$depstring,
) or $raise_syntax_error->(__x(
'"{dep}" is not a valid dependency specification',
dep => $depstring,
));
my $dep = App::Sqitch::Plan::Depend->new(
plan => $self,
%{ $dep_params },
);
if ($dep->conflicts) {
push @con => $dep;
} else {
push @req => $dep;
}
}
$params{requires} = \@req;
$params{conflicts} = \@con;
}
$tag_changes{ $params{name} } = $fh->input_line_number;
push @curr_changes => $prev_change = App::Sqitch::Plan::Change->new(
plan => $self,
( $prev_tag ? ( since_tag => $prev_tag ) : () ),
%params,
);
push @lines => $prev_change;
if (my $duped = $change_named{ $params{name} }) {
# Mark previously-seen change of same name as duped.
$duped->suffix($prev_tag->format_name);
}
$change_named{ $params{name} } = $prev_change;
}
}
# Sort and store any remaining changes.
push @changes => $self->sort_changes(
$pragmas{project},
\%line_no_for,
@curr_changes,
) if @curr_changes;
return {
changes => \@changes,
lines => \@lines,
pragmas => \%pragmas,
};
}
sub _version_line {
App::Sqitch::Plan::Pragma->new(
plan => shift,
name => 'syntax-version',
operator => '=',
value => SYNTAX_VERSION,
);
}
sub sort_changes {
my ( $self, $proj ) = ( shift, shift );
my $seen = ref $_[0] eq 'HASH' ? shift : {};
my %obj; # maps change names to objects.
my %pairs; # all pairs ($l, $r)
my %npred; # number of predecessors
my %succ; # list of successors
for my $change (@_) {
# Stolen from http://cpansearch.perl.org/src/CWEST/ppt-0.14/bin/tsort.
my $name = $change->name;
$obj{$name} = $change;
my $p = $pairs{$name} = {};
$npred{$name} += 0;
# XXX Ignoring conflicts for now.
for my $dep ( $change->requires ) {
# Ignore dependencies on other projects.
if ($dep->got_project) {
# Skip if parsed project name different from current project.
next if $dep->project ne $proj;
} else {
# Skip if an ID was passed, is it could be internal or external.
next if $dep->got_id;
}
my $key = $dep->key_name;
# Skip it if it's a change from an earlier tag.
if ($key =~ /.@/) {
# Need to look it up before the tag.
my ( $change, $tag ) = split /@/ => $key, 2;
if ( my $tag_at = $seen->{"\@$tag"} ) {
if ( my $change_at = $seen->{$change}) {
next if $change_at < $tag_at;
}
}
} else {
next if exists $seen->{$key};
}
$p->{$key}++;
$npred{$key}++;
push @{ $succ{$name} } => $key;
}
}
# Stolen from http://cpansearch.perl.org/src/CWEST/ppt-0.14/bin/tsort.
# Create a list of changes without predecessors
my @list = grep { !$npred{$_->name} } @_;
my @ret;
while (@list) {
my $change = pop @list;
unshift @ret => $change;
foreach my $child ( @{ $succ{$change->name} } ) {
unless ( $pairs{$child} ) {
my $sqitch = $self->sqitch;
my $name = $change->name;
hurl plan => __x(
'Unknown change "{required}" required by change "{change}"',
required => $child,
change => $name,
);
}
push @list, $obj{$child} unless --$npred{$child};
}
}
if ( my @cycles = map { $_->name } grep { $npred{$_->name} } @_ ) {
my $last = pop @cycles;
hurl plan => __x(
'Dependency cycle detected beween changes {changes}',
changes => join( __ ', ', map {
__x('"{quoted}"', quoted => $_)
} @cycles) . __ ' and ' . __x('"{quoted}"', quoted => $last)
);
}
return @ret;
}
sub open_script {
my ( $self, $file ) = @_;
return $file->open('<:encoding(UTF-8)') or hurl plan => __x(
'Cannot open {file}: {error}',
file => $file,
error => $!,
);
}
sub syntax_version { shift->_plan->{pragmas}{syntax_version} };
sub lines { shift->_lines->items }
sub changes { shift->_changes->changes }
sub tags { shift->_changes->tags }
sub count { shift->_changes->count }
sub index_of { shift->_changes->index_of(shift) }
sub get { shift->_changes->get(shift) }
sub find { shift->_changes->find(shift) }
sub first_index_of { shift->_changes->first_index_of(@_) }
sub change_at { shift->_changes->change_at(shift) }
sub last_tagged_change { shift->_changes->last_tagged_change }
sub seek {
my ( $self, $key ) = @_;
my $index = $self->index_of($key);
hurl plan => __x(
'Cannot find change "{change}" in plan',
change => $key,
) unless defined $index;
$self->position($index);
return $self;
}
sub reset {
my $self = shift;
$self->position(-1);
return $self;
}
sub next {
my $self = shift;
if ( my $next = $self->peek ) {
$self->position( $self->position + 1 );
return $next;
}
$self->position( $self->position + 1 ) if defined $self->current;
return undef;
}
sub current {
my $self = shift;
my $pos = $self->position;
return if $pos < 0;
$self->_changes->change_at( $pos );
}
sub peek {
my $self = shift;
$self->_changes->change_at( $self->position + 1 );
}
sub last {
shift->_changes->change_at( -1 );
}
sub do {
my ( $self, $code ) = @_;
while ( local $_ = $self->next ) {
return unless $code->($_);
}
}
sub tag {
my ( $self, %p ) = @_;
( my $name = $p{name} ) =~ s/^@//;
$self->_is_valid(tag => $name);
my $changes = $self->_changes;
my $key = "\@$name";
hurl plan => __x(
'Tag "{tag}" already exists',
tag => $key
) if defined $changes->index_of($key);
my $change = $changes->last_change or hurl plan => __x(
'Cannot apply tag "{tag}" to a plan with no changes',
tag => $key
);
my $tag = App::Sqitch::Plan::Tag->new(
%p,
plan => $self,
name => $name,
change => $change,
rspace => $p{note} ? ' ' : '',
);
$change->add_tag($tag);
$changes->index_tag( $changes->index_of( $change->id ), $tag );
$self->_lines->append( $tag );
return $tag;
}
sub _parse_deps {
my ( $self, $p ) = @_;
# Dependencies must be parsed into objects.
$p->{requires} = [ map {
my $p = App::Sqitch::Plan::Depend->parse($_) // hurl plan => __x(
'"{dep}" is not a valid dependency specification',
dep => $_,
);
App::Sqitch::Plan::Depend->new(
%{ $p },
plan => $self,
conflicts => 0,
);
} @{ $p->{requires} } ] if $p->{requires};
$p->{conflicts} = [ map {
my $p = App::Sqitch::Plan::Depend->parse("!$_") // hurl plan => __x(
'"{dep}" is not a valid dependency specification',
dep => $_,
);
App::Sqitch::Plan::Depend->new(
%{ $p },
plan => $self,
conflicts => 1,
);
} @{ $p->{conflicts} } ] if $p->{conflicts};
}
sub add {
my ( $self, %p ) = @_;
$self->_is_valid(change => $p{name});
my $changes = $self->_changes;
if ( defined( my $idx = $changes->index_of( $p{name} . '@HEAD' ) ) ) {
my $tag_idx = $changes->index_of_last_tagged;
hurl plan => __x(
qq{Change "{change}" already exists.\n}
. 'Use "sqitch rework" to copy and rework it',
change => $p{name},
);
}
$self->_parse_deps(\%p);
$p{rspace} //= ' ' if $p{note};
my $change = App::Sqitch::Plan::Change->new( %p, plan => $self );
# Make sure dependencies are valid.
$self->_check_dependencies( $change, 'add' );
# We good. Append a blank line if the previous change has a tag.
if ( $changes->count ) {
my $prev = $changes->change_at( $changes->count - 1 );
if ( $prev->tags ) {
$self->_lines->append(
App::Sqitch::Plan::Blank->new( plan => $self )
);
}
}
# Append the change and return.
$changes->append( $change );
$self->_lines->append( $change );
return $change;
}
sub rework {
my ( $self, %p ) = @_;
my $changes = $self->_changes;
my $idx = $changes->index_of( $p{name} . '@HEAD') // hurl plan => __x(
qq{Change "{change}" does not exist.\n}
. 'Use "sqitch add {change}" to add it to the plan',
change => $p{name},
);
my $tag_idx = $changes->index_of_last_tagged;
hurl plan => __x(
qq{Cannot rework "{change}" without an intervening tag.\n}
. 'Use "sqitch tag" to create a tag and try again',
change => $p{name},
) if !defined $tag_idx || $tag_idx < $idx;
$self->_parse_deps(\%p);
my ($tag) = $changes->change_at($tag_idx)->tags;
unshift @{ $p{requires} ||= [] } => App::Sqitch::Plan::Depend->new(
plan => $self,
change => $p{name},
tag => $tag->name,
);
my $orig = $changes->change_at($idx);
my $new = App::Sqitch::Plan::Change->new( %p, plan => $self );
# Make sure dependencies are valid.
$self->_check_dependencies( $new, 'rework' );
# We good.
$orig->suffix( $tag->format_name );
$changes->append( $new );
$self->_lines->append( $new );
return $new;
}
sub _check_dependencies {
my ( $self, $change, $action ) = @_;
my $changes = $self->_changes;
my $project = $self->project;
for my $req ( $change->requires ) {
# use Test::More; diag $req->key_name;
# diag $req->project, ' ne ', $project;
next if $req->project ne $project;
$req = $req->key_name;
next if defined $changes->index_of($req =~ /@/ ? $req : $req . '@HEAD');
my $name = $change->name;
if ($action eq 'add') {
hurl plan => __x(
'Cannot add change "{change}": requires unknown change "{req}"',
change => $name,
req => $req,
);
} else {
hurl plan => __x(
'Cannot rework change "{change}": requires unknown change "{req}"',
change => $name,
req => $req,
);
}
}
return $self;
}
sub _is_valid {
my ( $self, $type, $name ) = @_;
hurl plan => __x(
'"{name}" is a reserved name',
name => $name
) if exists $reserved{$name};
hurl plan => __x(
'"{name}" is invalid because it could be confused with a SHA1 ID',
name => $name,
) if $name =~ /^[0-9a-f]{40}/;
unless ($name =~ /\A$name_re\z/) {
if ($type eq 'change') {
hurl plan => __x(
qq{"{name}" is invalid: changes must not begin with punctuation, }
. 'contain "@", ":", or "#", or end in punctuation or digits following punctuation',
name => $name,
);
} else {
hurl plan => __x(
qq{"{name}" is invalid: tags must not begin with punctuation, }
. 'contain "@", ":", or "#", or end in punctuation or digits following punctuation',
name => $name,
);
}
}
}
sub write_to {
my ( $self, $file, $from, $to ) = @_;
my @lines = $self->lines;
if (defined $from || defined $to) {
my $lines = $self->_lines;
# Where are the pragmas?
my $head_ends_at = do {
my $i = 0;
while ( my $line = $lines[$i] ) {
last if $line->isa('App::Sqitch::Plan::Blank')
&& !length $line->note;
++$i;
}
$i;
};
# Where do we start with the changes?
my $from_idx = defined $from ? do {
my $change = $self->find($from // '@ROOT') // hurl plan => __x(
'Cannot find change {change}',
change => $from,
);
$lines->index_of($change);
} : $head_ends_at + 1;
# Where do we end up?
my $to_idx = defined $to ? do {
my $change = $self->find( $to // '@HEAD' ) // hurl plan => __x(
'Cannot find change {change}',
change => $to,
);
# Include any subsequent tags.
if (my @tags = $change->tags) {
$change = $tags[-1];
}
$lines->index_of($change);
} : $#lines;
# Collect the lines to write.
@lines = (
@lines[ 0 .. $head_ends_at ],
@lines[ $from_idx .. $to_idx ],
);
}
my $fh = $file->open('>:encoding(UTF-8)') or hurl plan => __x(
'Cannot open {file}: {error}',
file => $file,
error => $!
);
$fh->say($_->as_string) for @lines;
$fh->close or hurl plan => __x(
'"Error closing {file}: {error}',
file => $file,
error => $!,
);
return $self;
}
__PACKAGE__->meta->make_immutable;
no Moose;
__END__
=head1 Name
App::Sqitch::Plan - Sqitch Deployment Plan
=head1 Synopsis
my $plan = App::Sqitch::Plan->new( sqitch => $sqitch );
while (my $change = $plan->next) {
say "Deploy ", $change->format_name;
}
=head1 Description
App::Sqitch::Plan provides the interface for a Sqitch plan. It parses a plan
file and provides an iteration interface for working with the plan.
=head1 Interface
=head2 Constants
=head3 C<SYNTAX_VERSION>
Returns the current version of the Sqitch plan syntax. Used for the
C<%sytax-version> pragma.
=head2 Class Methods
=head3 C<name_regex>
die "$this has no name" unless $this =~ App::Sqitch::Plan->name_regex;
Returns a regular expression that matches names. Note that it is not anchored,
so if you need to make sure that a string is a valid name and nothing else,
you will need to anchor it yourself, like so:
my $name_re = App::Sqitch::Plan->name_regex;
die "$this is not a valid name" if $this !~ /\A$name_re\z/;
=head2 Constructors
=head3 C<new>
my $plan = App::Sqitch::Plan->new( sqitch => $sqitch );
Instantiates and returns a App::Sqitch::Plan object. Takes a single parameter:
an L<App::Sqitch> object.
=head2 Accessors
=head3 C<sqitch>
my $sqitch = $cmd->sqitch;
Returns the L<App::Sqitch> object that instantiated the plan.
=head3 C<position>
Returns the current position of the iterator. This is an integer that's used
as an index into plan. If C<next()> has not been called, or if C<reset()> has
been called, the value will be -1, meaning it is outside of the plan. When
C<next> returns C<undef>, the value will be the last index in the plan plus 1.
=head3 C<project>
my $project = $plan->project;
Returns the name of the project as set via the C<%project> pragma in the plan
file.
=head3 C<uri>
my $uri = $plan->uri;
Returns the URI for the project as set via the C<%uri> pragma, which is
optional. If it is not present, C<undef> will be returned.
=head3 C<syntax_version>
my $syntax_version = $plan->syntax_version;
Returns the plan syntax version, which is always the latest version.
=head2 Instance Methods
=head3 C<index_of>
my $index = $plan->index_of('6c2f28d125aff1deea615f8de774599acf39a7a1');
my $foo_index = $plan->index_of('@foo');
my $bar_index = $plan->index_of('bar');
my $bar1_index = $plan->index_of('bar@alpha')
my $bar2_index = $plan->index_of('bar@HEAD');
Returns the index of the specified change. Returns C<undef> if no such change
exists. The argument may be any one of:
=over
=item * An ID
my $index = $plan->index_of('6c2f28d125aff1deea615f8de774599acf39a7a1');
This is the SHA1 hash of a change or tag. Currently, the full 40-character hexed
hash string must be specified.
=item * A change name
my $index = $plan->index_of('users_table');
The name of a change. Will throw an exception if the named change appears more
than once in the list.
=item * A tag name
my $index = $plan->index_of('@beta1');
The name of a tag, including the leading C<@>.
=item * A tag-qualified change name
my $index = $plan->index_of('users_table@beta1');
The named change as it was last seen in the list before the specified tag.
=back
=head3 C<get>
my $change = $plan->get('6c2f28d125aff1deea615f8de774599acf39a7a1');
my $foo = $plan->index_of('@foo');
my $bar = $plan->index_of('bar');
my $bar1 = $plan->index_of('bar@alpha')
my $bar2 = $plan->index_of('bar@HEAD');
Returns the change corresponding to the specified ID or name. The argument may
be in any of the formats described for C<index_of()>.
=head3 C<find>
my $change = $plan->find('6c2f28d125aff1deea615f8de774599acf39a7a1');