summaryrefslogtreecommitdiffstats
path: root/bin/xmlpp
blob: 3de854ab10a9a346d870a8f268f772cf3d826a1b (plain)
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
#!/usr/bin/perl  -w

#
#  Copyright (c) 2002, DecisionSoft Limited All rights reserved.
#  Please see: 
#  http://software.decisionsoft.com/licence.html
#  for more information.
# 

# $Revision: 1.1 $
#
# xmlpp: XML pretty printing
#

# For custom attribute sorting create an attributeOrdering.txt file that
# lists each attributes separated by a newline in the order you would like
# them to be sorted separated by a newline. Then use the -s option.

use FileHandle;
use Fcntl;
use Getopt::Std;

use vars qw($opt_h $opt_H $opt_s $opt_z $opt_t $opt_e $opt_S $opt_c $opt_n);

my $indent=0;
my $textContent='';
my $lastTag=undef;
my $output;
my $inAnnotation = 0;


if (!getopts('nzhHsteSc') or $opt_h) {
    usage();
}

if ($opt_s){

# expect to find attributeOrdering.txt file in same directory
# as xmlpp is being run from
    
  my $scriptDir = $0;
  if ($scriptDir =~ m#/#){
    $scriptDir =~ s#/[^/]+$##;
  }
  else{
    $scriptDir =".";
  }
    
  # get attribute ordering from external file
  if (open(SORTLIST, "<$scriptDir/attributeOrdering.txt")) {
    @sortlist = <SORTLIST>;
    chomp @sortlist;
    close (SORTLIST);
    @specialSort = grep(/^\w+/, @sortlist);
  } 
  else {      
#   print STDERR  "Could not open $scriptDir/attributeOrdering.txt: $!\nWARNING attribute sorting will only be alphabetic\n\n";
  }
}


# set line separator to ">" speeding up parsing of XML files
# with no line breaks 

$/ = ">";


my $sortAttributes = $opt_s;
my $newLineComments = $opt_c;
my $splitAttributes = $opt_t;
my $schemaHackMode = $opt_S;
my $normaliseWhiteSpace = $opt_n;

my $filename = $ARGV[0];
if ($opt_z && (!$filename or $filename eq '-')) {
    print STDERR "Error: I can't edit STDIN in place.\n";
    usage();
}

if (!$opt_z && scalar(@ARGV) > 1) {
    print STDERR "Warning: Multiple files specified without -z option\n"; 
}

my $fh;

my $stdin;

if (!$filename or $filename eq '-') {
    $fh=*STDIN;
    $stdin=1;
} else {
    $fh = open_next_file() or exit(1);
    $stdin=0;
}

do {
    $indent=0;
    $textContent='';
    $lastTag=undef;
    $output = '';
    my $re_name = "(?:[A-Za-z0-9_:][A-Za-z0-9_:.-]*)";
    my $re_attr = "(?:'[^']*'|\"[^\"]*\")";
    my $input;

    while ($input .= <$fh>) {
        while ($input) {
            if ($input =~ s/^<($re_name)((?:\s+$re_name\s*=\s*$re_attr)*\s*)(\/?)>(.*)$/$4/s ) {
                my %attr;
                my ($name,$attr,$selfclose) = ($1,$2,$3);
                while ($attr =~ m/($re_name)\s*=\s*($re_attr)/gs) {
                    my ($name,$value) = ($1,$2);
                    $value =~ s/^["'](.*)["']$/$1/s;
                    $attr{$name} = $value;
                }
                if ($opt_e) {
                    parseStart($name, 0, %attr);
                    if ($selfclose) { parseEnd($name) }
                } else {
                    parseStart($name, $selfclose, %attr);
                }
            } elsif ($input =~ s/^<\/($re_name)\s*>(.*)$/$2/s) {
                parseEnd($1);
            } elsif ($input =~ s/^<!--(.*?)-->(.*)$/$2/s) { 
                parseComment($1);
            } elsif ($input =~ s/^([^<]+)(.*)$/$2/s) {
                parseDefault($1);
            } elsif ($input =~ s/^(<\?[^>]*\?>)(.*)$/$2/s) {
                parsePI("$1\n");
            } elsif ($input =~ s/^(<\!DOCTYPE[^\[>]*(\[[^\]]*\])?[^>]*>)(.*)$/$3/s) {
                parseDoctype("$1");
            } else {
                last;
            }
        }
        if (eof($fh)) {
            last;
        }
    }


    if ($input) {
        $input =~ m/([^\n]+)/gs;
        print STDERR "WARNING: junk remaining on input: $1\n";
    }
    $fh->close();

    if (!$opt_z) {
        if(!$opt_H){ 
            print "$output\n"
        } else {
            print html_escape($output)."\n"
        }
    } else {
        if ($input) { 
            print STDERR "Not overwriting file\n";
        } else {
            open FOUT,"> $filename" or die "Cannot overwrite file: $!";
            if(!$opt_H){
                print FOUT "$output\n"
            } else {
                print FOUT html_escape($output)."\n"
            }
            close FOUT
        }
    }
} while (
    !$stdin && $opt_z && ($fh = open_next_file(\$filename))
  );
  


sub parseStart {
    my $s = shift;
    my $selfclose = shift;
    my %attr = @_;

    $textContent =~ s/\s+$//; 
    printContent($textContent);

    if($inAnnotation) {
        return;
    }

    if($schemaHackMode and $s =~ m/(^|:)annotation$/) {
        $inAnnotation = 1;
        $textContent = '';
        $lastTag = 1;
        return;
    }
    if (length($output)) {
        $output .= "\n";
    }

    $output .= "  " x $indent;
    $output .= "<$s";
    my @k = keys %attr;

    if ($sortAttributes && (scalar(@k) > 1) ){

      my @alphaSorted;
      my @needSpecialSort;
      my @final;
      my $isSpecial;

      # sort attributes alphabetically (default ordering)
      @alphaSorted = sort @k;

      # read through sorted list, if attribute doesn't have specified
      # sort order, push it onto the end of the final array (this maintains
      # alphabetic order). Else create a list that has attributes needing
      # special ordering.
      foreach $attribute (@alphaSorted){
        $isSpecial = 0;
        foreach $sortAttrib (@specialSort){
          if ($attribute eq $sortAttrib){
            push @needSpecialSort, $attribute;
            $isSpecial = 1;
          }
        }
        if (!$isSpecial){
          push @final, $attribute;
        }
      }

      # now read through the specialSort list backwards looking for
      # any match in the needSpecialSort list. Unshift this onto the 
      # front of the final array to maintain proper order.
      foreach my $attribute (reverse @specialSort){
        foreach (@needSpecialSort){
          if ($attribute eq $_){
            unshift @final, $attribute;
          }
        }
      }

      @k = @final;
    }

    foreach my $attr (@k) {
        # 
        # Remove (min|max)Occurs = 1 if schemaHackMode
        #
        if ($schemaHackMode and $attr =~ m/^(minOccurs|maxOccurs)$/ and $attr{$attr} eq "1") {
            next;
        }

        if ($splitAttributes) {
            $output .= "\n"."  " x $indent." ";
        }
        if ($attr{$attr} =~ /'/) {
            $output .= " $attr=\"$attr{$attr}\"";
        } else {
            $output .= " $attr='$attr{$attr}'";
        }
    }
    if ($splitAttributes and @k) {
        $output .= "\n"."  " x $indent;
    }
    if ($selfclose) {
        $output .= " />";
        $lastTag = 0;
    } else {
        $output .= ">";
        $indent++;
        $lastTag = 1;
    }
    $textContent = '';
}

sub parseEnd {
    my $s = shift;

    if($inAnnotation) {
        if($s =~ m/(^|:)annotation$/) {
            $inAnnotation = 0;
        }
        return;
    }

    if($normaliseWhiteSpace) {
        $textContent =~ s/^\s*(.*?)\s*$/$1/;
    }
    $indent--;
    printContent($textContent);
    if ($lastTag == 0) {
        $output .= "\n";
        $output .= "  " x $indent;
    } 
    $output .= "</$s>";
    $textContent = '';
    $lastTag = 0;
}

sub parseDefault {
    my $s = shift;
    if($inAnnotation) { return }
    $textContent .= "$s";
}

sub parsePI {
    my $s = shift;
    $output .= "$s";
}

sub parseDoctype {
    my $s = shift;
    if ($s =~ /^([^\[]*\[)([^\]]*)(\].*)$/ms) {
      $start = $1;
      $DTD = $2;
      $finish = $3;
      $DTD =~ s/\</\n  \</msg;
      $output .= "$start$DTD\n$finish\n";
    } else {
      $output .= "$s";
    }
}

sub parseComment {
    my $s = shift; 
    if($inAnnotation) { return }
    printContent($textContent,1);
    if ($s =~ /([^\<]*)(<.*>)(.*)/ms) {
      $start = $1;
      $xml = $2;
      $finish = $3;
      $xml =~ s/\</\n\</msg;
      $xml =~ s/(\n\s*\n?)+/\n/msg;
      $xml =~ s/^\s*//msg;
      $xml =~ s/\s*$//msg;
      $s = "$start\n$xml\n$finish";
    }
    $s =~ s/\n\s*$/\n  /msg;
    if ($newLineComments) {
        $output .= "\n<!--$s-->\n";
    } else {
        $output .= "<!--$s-->";
    }
    $textContent='';
}

sub printContent {
    my $s = shift;
    my $printLF = shift;
    my ($LF,$ret) = ("","");

    if ($s =~ m/\n\s*$/) {
        $LF = "\n"; 
    }
    if ($s =~ m/^[\s\n]*$/) {
        $ret = undef;
    } else {
        $output .= "$s";
        $ret = 1;
    }
    if ($printLF) {
        $output .= $LF;
    }
}


sub html_escape {
    my $s = shift;
    $s =~ s/&/&amp;/gsm;
    $s =~ s/</&lt;/gsm;
     $s =~ s/>/&gt;/gsm;
    return $s;
}

sub open_next_file {
    my $filename = shift;
    $$filename = shift @ARGV;
    while ($$filename and ! -f $$filename) {
        print STDERR "WARNING: Could not find file: $$filename\n";
        $$filename = shift @ARGV;
    }
    if(!$$filename) {
        return undef;
    }
    my $fh = new FileHandle;
    $fh->open("< $$filename") or die "Can't open $$filename: $!";
    return $fh;
}

sub usage {
    print STDERR <<EOF;
usage: $0 [ options ] [ file.xml ... ]

options:
  -h  display this help message
  -H  escape characters (useful for further processing)
  -t  split attributes, one per line (useful for diff)
  -s  sort attributes (useful for diff)
  -z  in place edit (zap)
  -e  expand self closing tags (useful for diff)
  -S  schema hack mode (used by xmldiff)
  -c  place comments on new line.
  -n  normalise whitespace (remove leading and trailing whitespace from nodes
      with text content.

EOF
    exit 1;
}