Code-TidyAll-Plugin-YAMLFrontMatter
view release on metacpan or search on metacpan
lib/Code/TidyAll/Plugin/YAMLFrontMatter.pm view on Meta::CPAN
package Code::TidyAll::Plugin::YAMLFrontMatter;
use strict;
use warnings;
use namespace::autoclean;
our $VERSION = '1.000003';
use Moo;
use Encode qw( decode encode FB_CROAK );
use Path::Tiny qw( path );
use Try::Tiny qw( catch try );
use YAML::PP 0.006 ();
extends 'Code::TidyAll::Plugin';
# This regular expression is based on the regex
# \A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?) (with the m flag)
# from the Jekyll source code here:
# https://github.com/jekyll/jekyll/blob/c7d98cae2652b2df7ebd3c60b4f8c87950760e47/lib/jekyll/document.rb#L13
# note - The 'm' modifier in ruby is essentially the same as 's' in Perl
# so we need to enable the 's' modifier not 'm'
# - Ruby essentially always treats '^' and '$' the way Perl does when the
# 'm' modifier is enabled, so we need to turn that on too
# - We need to enable the 'x' modifier and space things out so that
# Perl treats '$\n' as '$' and '\n' and not the variable '$\' and 'n'
my $YAML_REGEX = qr{
\A
# the starting ---, and anything up until...
(---\s*\n.*?\n?)
# ...the first --- or ... on their own line
^ (?:---|\.\.\.) \s* $ \n?
}msx;
has encoding => (
is => 'ro',
# By default Jekyll 2.0 and later defaults to utf-8, so this seems
# like a sensible default for us
default => 'UTF-8',
);
has required_top_level_keys => (
is => 'ro',
default => q{},
);
has _req_keys_hash => ( is => 'lazy' );
sub _build__req_keys_hash {
my $self = shift;
return +{
# note use of magical split on space to do automatic trimming
map { $_ => 1 } split q{ }, $self->required_top_level_keys
};
}
sub validate_file {
my ( $self, $filename ) = @_;
my $src = path($filename)->slurp_raw;
# YAML::PP always expects things to be in UTF-8 bytes
my $encoding = $self->encoding;
try {
$src = decode( $encoding, $src, FB_CROAK );
$src = encode( 'UTF-8', $src, FB_CROAK );
}
catch {
die "File does not match encoding '$encoding': $_";
( run in 0.700 second using v1.01-cache-2.11-cpan-39bf76dae61 )