Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. #!/usr/bin/perl -w
  2.  
  3. use strict;
  4. use Config::Augeas;
  5. use XML::LibXML;
  6. use Getopt::Long;
  7.  
  8. my $file;
  9. my $root = '/';
  10. my $verbose;
  11. my $debug;
  12.  
  13. my $result = GetOptions (
  14. "file=s" => \$file,
  15. "root=s" => \$root,
  16. "verbose" => \$verbose,
  17. "debug" => \$debug,
  18. );
  19.  
  20.  
  21. $verbose ||= $debug;
  22.  
  23.  
  24. unless (defined($file)) {
  25. die "E: You must specify a filename\n";
  26. }
  27.  
  28. open (my $fh, "<$file") or die "E: Could not open $file: $!\n" ;
  29. my $doc = XML::LibXML->load_xml(IO => $fh);
  30. close $fh;
  31.  
  32. my $aug = Config::Augeas->new(root => $root);
  33. # we want to replace everything
  34. $aug->rm('/files/*');
  35. my @top_nodes = $doc->find('/*/node[@label != "files"]')->get_nodelist();
  36.  
  37. for my $node (@top_nodes) {
  38. xml2aug($node, '/files');
  39. }
  40.  
  41. $aug->print('/files') if $debug;
  42. $aug->save();
  43. $aug->print('/augeas//error');
  44.  
  45.  
  46. ########
  47. # Subs
  48. ########
  49.  
  50. sub xml2aug {
  51. my ($elem, $path) = @_;
  52.  
  53. my $type = $elem->nodeType;
  54.  
  55. my $label = $elem->getAttribute('label');
  56.  
  57. my $matchpath = "$path/*[last()]";
  58. $matchpath =~ s| |\\ |g;
  59. my $lastpath = $aug->match("$path/*[last()]");
  60.  
  61. if(defined($lastpath)) {
  62. print "V: Inserting $label after $lastpath\n" if $verbose;
  63.  
  64. # Insert last node
  65. $aug->insert($label, "after", $lastpath);
  66. } else {
  67. $aug->set("$path/$label", '');
  68. }
  69.  
  70. $matchpath = "$path/${label}[last()]";
  71. $matchpath =~ s| |\\ |g;
  72. my $newpath = $aug->match($matchpath);
  73.  
  74.  
  75. my $value;
  76.  
  77. for my $child ($elem->childNodes()) {
  78. if ($child->nodeType == XML_TEXT_NODE) {
  79. # Text node
  80. $value = $child->nodeValue;
  81. } else {
  82. xml2aug($child, $newpath);
  83. }
  84. }
  85.  
  86. if (defined($value)) {
  87. print "V: Setting value of $newpath to $value\n" if $verbose;
  88. $aug->set($newpath, $value);
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement