Created
January 6, 2016 13:07
-
-
Save anonymous/843af34cad38bd7e2007 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
package Mojo::DOM::YAML; | |
use Mojo::Base qw(Mojo::DOM::HTML); | |
use XML::Simple qw(:strict); | |
use YAML::Tiny; | |
sub parse { | |
my ($self, $string) = @_; | |
my $yaml = YAML::Tiny->read_string($string); | |
my $xml = XMLout( | |
$yaml->[0], | |
KeyAttr => [], | |
RootName => 'container', | |
); | |
return bless Mojo::DOM::HTML->new(xml => 1)->parse($xml), __PACKAGE__; | |
} | |
package Mojolicious::Command::grep; | |
use Mojo::Base 'Mojolicious::Command'; | |
use Mojo::Loader qw(data_section); | |
use XML::Simple qw(XMLin); | |
use YAML::Tiny; | |
has description => 'Grep.. FOR SCIENCE'; | |
has usage => "Usage: APPLICATION grep SELECTOR\n"; | |
sub grep_path { | |
my ($self, $path, $selector) = @_; | |
my $file = data_section 'main', $path; | |
my $xml = Mojo::DOM::YAML->new->parse($file); | |
my $dom = Mojo::DOM->new->tree($xml->tree); | |
my $results = $dom->find($selector); | |
return if $results->size < 1; | |
$results->each(sub { | |
$self->mark_parents($_); | |
$_->child_nodes->each(sub { $_->{'MATCH'} = 1 }); | |
}); | |
$dom->find('*')->each(sub { | |
$_->remove if !$_->{'MATCH'}; | |
delete $_->{'MATCH'}; | |
}); | |
my $pruned = XMLin($dom->to_string); | |
say YAML::Tiny->new($pruned)->write_string; | |
} | |
sub mark_parents { | |
my ($self, $dom) = @_; | |
while ($dom) { | |
$dom->{'MATCH'} = 1; | |
$dom = $dom->parent; | |
} | |
} | |
sub run { | |
my $self = shift; | |
die $self->usage if @_ < 1; | |
foreach my $path (sort keys %{data_section 'main'}) { | |
$self->grep_path($path, @_) if $path =~ m![.] yml \z!msx; | |
} | |
} | |
package main; | |
use Mojolicious::Lite; | |
app->start; | |
__DATA__ | |
@@ AAAA.yml | |
--- | |
uuid: AAAA | |
description: drop box | |
items: | |
item: | |
- | |
type: HDD | |
capacity: 1TB | |
serial: 01234 | |
- | |
type: HDD | |
capacity: 200GB | |
serial: 0A1B2C | |
- | |
type: SSD | |
capacity: 32GB | |
serial: AAAA | |
@@ BBBB.yml | |
--- | |
uuid: BBBB | |
description: to use | |
items: | |
item: | |
- | |
type: HDD | |
capacity: 500GB | |
serial: 98765 | |
- | |
type: HDD | |
capacity: 128GB | |
serial: Z2Y1X0 | |
- | |
type: SSD | |
capacity: 128GB | |
serial: ZZZZ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment