File: dic2markdown

package info (click to toggle)
cod-tools 3.7.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 154,792 kB
  • sloc: perl: 57,588; sh: 36,842; ansic: 6,402; xml: 1,982; yacc: 1,117; makefile: 727; python: 166
file content (380 lines) | stat: -rwxr-xr-x 12,334 bytes parent folder | download
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
#! /bin/sh
#!perl -w # --*- Perl -*--
eval 'exec perl -x $0 ${1+"$@"}'
    if 0;
#------------------------------------------------------------------------------
#$Author: antanas $
#$Date: 2020-09-29 10:54:47 +0300 (Tue, 29 Sep 2020) $
#$Revision: 8533 $
#$URL: svn+ssh://www.crystallography.net/home/coder/svn-repositories/cod-tools/tags/v3.7.0/scripts/dic2markdown $
#------------------------------------------------------------------------------
#*
#* Generate textual descriptions for DDLm dictionaries.
#*
#* USAGE:
#*    $0 --options input1.dic input*.dic
#**

use strict;
use warnings;
use COD::CIF::DDL qw( cif_to_ddlm ddl1_to_ddlm );
use COD::CIF::DDL::DDLm qw( get_definition_class );
use COD::CIF::Parser qw( parse_cif );
use COD::CIF::Tags::Manage qw( cifversion );
use COD::SOptions qw( getOptions get_value );
use COD::SUsage qw( usage options );
use COD::ErrorHandler qw( process_warnings
                          process_errors
                          process_parser_messages );
use COD::UserMessage qw( sprint_message );
use COD::ToolsVersion qw( get_version_string );
use HTML::Entities qw( encode_entities );

sub unprefix($);
sub escape($);
sub mark_hyperlinks($);

my $use_parser = 'c';
my $additional_head_text;
my $add_anchors = 1;

#* OPTIONS:
#*   --use-perl-parser
#*                     Use Perl parser for CIF parsing.
#*   --use-c-parser
#*                     Use Perl & C parser for CIF parsing (default).
#*
#*   --append-head-text
#*                     Read Markdown text from a file and append it to
#*                     the dictionary overview text, just before
#*                     enumerating the categories in the dictionary.
#*
#*   --add-anchors
#*                     Add HTML anchors for headings (default).
#*   --no-add-anchors
#*   --dont-add-anchors
#*                     Do not add HTML anchors for headings.
#*
#*   --help, --usage
#*                     Output a short usage message (this message) and exit.
#*   --version
#*                     Output version information and exit.
#**
@ARGV = getOptions(
    "--use-perl-parser"  => sub { $use_parser = "perl" },
    "--use-c-parser"     => sub { $use_parser = "c" },
    "--append-head-text" => sub { open( my $inp, get_value() );
                                  $additional_head_text =
                                    join '', <$inp>;
                                  close $inp },
    "--add-anchors"      => sub { $add_anchors = 1 },
    "--no-add-anchors"   => sub { $add_anchors = 0 },
    "--dont-add-anchors" => sub { $add_anchors = 0 },

    '--options'      => sub { options; exit },
    '--help,--usage' => sub { usage; exit },
    '--version'      => sub { print get_version_string(), "\n"; exit }
);

my $die_on_errors    = 1;
my $die_on_warnings  = 0;
my $die_on_notes     = 0;
my $die_on_error_level = {
    ERROR   => $die_on_errors,
    WARNING => $die_on_warnings,
    NOTE    => $die_on_notes
};

@ARGV = ('-') unless @ARGV;

for my $filename (@ARGV) {
    my $options = { 'parser' => $use_parser, 'no_print' => 1 };
    my ( $data, $err_count, $messages ) = parse_cif( $filename, $options );
    process_parser_messages( $messages, $die_on_error_level );

    if ( !@{$data} ) {
        warn sprint_message( {
            'program'   => $0,
            'filename'  => $filename,
            'err_level' => 'WARNING',
            'message'   => 'the file contains no data blocks'
        } );
        next;
    }

    if( !cifversion( $data->[0] ) || cifversion( $data->[0] ) !~ /^2\./ ) {
        if( exists $data->[0]{values}{'_dictionary_name'} ||
            exists $data->[0]{values}{'_dictionary.title'} ) {
            local $SIG{__WARN__} = sub {
                process_warnings( {
                    'message'  => @_,
                    'program'  => $0,
                    'filename' => $filename,
                }, $die_on_error_level );
            };

            $data = [ ddl1_to_ddlm( $data, { keep_original_date => 1 } ) ];
            process_warnings( {
                    message  => 'apparently DDL1 dictionary was encountered, ' .
                                'converting it to DDLm; the conversion is ' .
                                'experimental and may result in corruption ' .
                                'or loss of dictionary data',
                    program  => $0,
                    filename => $filename,
                }, $die_on_error_level );
        } else { # plain CIF file
            local $SIG{__WARN__} = sub {
                process_warnings( {
                    'message'  => @_,
                    'program'  => $0,
                    'filename' => $filename,
                    'add_pos'  => 'data_' . $data->[0]{'name'},
                }, $die_on_error_level );
            };

            $data = [ cif_to_ddlm( $data->[0] ) ];
            process_warnings( {
                    message  => 'apparently a plain CIF file was encountered, ' .
                                'converting it to DDLm; the conversion is ' .
                                'experimental',
                    program  => $0,
                    filename => $filename,
                }, $die_on_error_level );
        }
    }

    for my $datablock (@$data) {
        my $dataname = 'data_' . $datablock->{'name'};

        local $SIG{__WARN__} = sub {
            process_warnings( {
                'message'  => @_,
                'program'  => $0,
                'filename' => $filename,
                'add_pos'  => $dataname
            }, $die_on_error_level )
        };

        eval {
            my $dict = build_dictionary_structure( $datablock );

            printf "# %s\n\n",
                   escape( $datablock->{values}{'_dictionary.title'}[0] );
            printf "Version: %s (%s)\n\n",
                   escape( $datablock->{values}{'_dictionary.version'}[0] ),
                   escape( $datablock->{values}{'_dictionary.date'}[0] );

            print "$additional_head_text\n\n" if $additional_head_text;

            dic_block2markdown( $dict,
                                { indent => 1,
                                  add_anchors => $add_anchors,
                                  save_blocks => $datablock->{save_blocks} } );
        };
        if( $@ ) {
            process_errors( {
              'message'       => $@,
              'program'       => $0,
              'filename'      => $filename,
              'add_pos'       => $dataname
            }, $die_on_errors )
        }
    }
}

# Constructs CIF DDLm dictionary relation tree for easier detection of
# dependencies.
sub build_dictionary_structure
{
    my( $dataset ) = @_;

    my $parents = {};
    for my $save_block (@{$dataset->{save_blocks}}) {

        if( !exists $save_block->{values}{'_name.category_id'} ) {
            if( get_definition_class($save_block) ne 'Head' ) {
                warn "save block '$save_block->{name}' does not contain " .
                     '\'_name.category_id\' data item -- unable to ' .
                     'determine its ancestry, skipping' . "\n";
            }
            next;
        }

        my $parent = lc $save_block->{values}{'_name.category_id'}[0];
        push @{$parents->{$parent}}, $save_block;
    }

    my @heads = grep { get_definition_class($_) eq 'Head' }
                     @{$dataset->{save_blocks}};

    my $dict = {};
    $dict->{content} = $heads[0];
    find_children( $dict, $parents );

    return $dict;
}

sub find_children
{
    my( $node, $parents ) = @_;
    my $children = $parents->{lc $node->{content}{values}{'_definition.id'}[0]};
    return if !$children;

    foreach (@$children) {
        my $new_node = { content => $_ };
        find_children( $new_node, $parents );
        push @{$node->{children}}, $new_node;
    }
}

sub dic_block2markdown
{
    my( $node, $options ) = @_;

    $options = {} unless $options;
    my $indent = $options->{indent};
    $indent = 0 unless defined $indent;
    my $add_anchors = $options->{add_anchors};

    my $values = $node->{content}{values};

    my $definition_class = get_definition_class($node->{content});
    if( $definition_class eq 'Attribute' ||
        $definition_class eq 'Datum' ) {
        $indent++;
    }

    if( $definition_class ne 'Head' ) {

        local $\ = "\n\n";

        my $title = $values->{'_definition.id'}[0];
        my $anchor = '';
        if( $options->{add_anchors} ) {
            $anchor = '<a name="' . encode_entities( $title ) . '"></a>';
        }
        print '#' x ($indent + 1) . ' ', $anchor, escape $title;

        if( exists $values->{'_description.text'} ) {
            my $description = mark_hyperlinks escape unprefix
                                $values->{'_description.text'}[0];
            if( $add_anchors ) {
                $description = mark_internal_links( $description,
                                                 $options->{save_blocks} );
            }
            print $description;
        }

        if( exists $values->{'_units.code'} ) {
            print 'Units: ', escape $values->{'_units.code'}[0];
        }

        local $\ = "\n";

        if( exists $values->{'_enumeration_set.state'} &&
            exists $values->{'_enumeration_set.detail'} ) {
            print "Values:\n\n",
                  "<table>\n  <tr><th>Value</th><th>Description</th></tr>";
            for my $i (0..$#{$values->{'_enumeration_set.state'}}) {
                print '  <tr><td>' . encode_entities(
                      unprefix( $values->{'_enumeration_set.state'}[$i] ) ) .
                      '</td><td>' . encode_entities(
                      mark_hyperlinks unprefix $values->{'_enumeration_set.detail'}[$i] ) .
                      "</td></tr>";
            }
            print '</table>';
        } elsif( exists $values->{'_enumeration_set.state'} ) {
            print "Values:\n\n", map { '* ' . escape( $_ ). "\n" }
                                     @{$values->{'_enumeration_set.state'}};
        }
        if( exists $values->{'_enumeration.default'} ) {
            printf "Default value: '%s'\n\n", $values->{'_enumeration.default'}[0];
        }

        if( exists $values->{'_description_example.case'} &&
            exists $values->{'_description_example.detail'} ) {
            print "Examples:\n\n",
                  "<table>\n  <tr><th>Value</th><th>Description</th></tr>";
            for my $i (0..$#{$values->{'_description_example.case'}}) {
                print '  <tr><td>';
                my $example = encode_entities(
                      unprefix $values->{'_description_example.case'}[$i] );
                print '<pre><code>' if $example =~ /\n/;
                print $example;
                print '</code></pre>' if $example =~ /\n/;
                print '  </td><td>', encode_entities(
                      mark_hyperlinks unprefix $values->{'_description_example.detail'}[$i] );
                print '  </td></tr>';
            }
            print '</table>';
        }
    }

    foreach (@{$node->{children}}) {
        dic_block2markdown( $_,
                            { indent => $indent,
                              add_anchors => $options->{add_anchors},
                              save_blocks => $options->{save_blocks} } );
    }
}

sub unprefix($)
{
    my( $text ) = @_;

    $text =~ s/^\s*\n//;

    my( $prefix ) = $text =~ /^( +)/;
    return $text if !$prefix;

    my $len = length $prefix;

    $text =~ s/^ {$len}//gm;
    return $text;
}

sub escape($)
{
    my( $text ) = @_;

    # Escaping Markdown:
    $text =~ s/([_*])/\\$1/g;

    # Escaping HTML:
    $text = encode_entities( $text );

    return $text;
}

sub mark_hyperlinks($)
{
    my( $text ) = @_;

    $text =~ s/(https?:\/\/[^\s\(\)]+)(\.?)/[$1]($1)$2/g;

    return $text;
}

sub mark_tag_if_found
{
    my( $tag, $save_blocks ) = @_;
    my $clean_tag = $tag;
    $clean_tag =~ s/\\_/_/g;
    my $search_tag = $clean_tag;
    $search_tag =~ s/^_//;

    if( grep { $_->{name} eq $search_tag } @$save_blocks ) {
        return "[$tag](#$clean_tag)";
    } else {
        return $tag;
    }
}

sub mark_internal_links
{
    my( $text, $save_blocks ) = @_;

    $text =~ s/([A-Z]*((\\_|\.)[a-zA-Z\-]+)+)/"" . mark_tag_if_found( $1, $save_blocks )/egx;

    return $text;
}