/
nut-ddl.py.in
1581 lines (1345 loc) · 55 KB
/
nut-ddl.py.in
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 - Daniele Pezzini <hyouko@gmail.com>
# Copyright (C) 2022 - 2023 - Jim Klimov <jimklimov+nut@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import re
import os
import pathlib
import argparse
###
# NOTE: Detailed documentation is in nut-ddl repo README file
# Path to NUT's manpages directory, relative to the working directory
manDir = "nut/docs/man/"
# Path to manpage directory in website
webManDir = "../../docs/man/"
# Currently not configurable, but maybe in the future we can make use of
# the difference of the two renderer projects with different features...
WITH_ASCIIDOCTOR = False
# Also not configurable externally now, but toggles rendering markup
# below as we experiment with it:
DEV_COMMENT_BLOCKS_AS_LIST = False #True
# Should we warn or fail when we see unique entries like comments twice, etc.?
PEDANTIC_DECLARATIONS = os.getenv("NUT_DDL_PEDANTIC_DECLARATIONS", "False")
# Booleanize this:
PEDANTIC_DECLARATIONS = (PEDANTIC_DECLARATIONS in ["True", "true", "TRUE", "Yes", "yes", "YES", "1"])
# This is not fatal, some documents do have layman comments,
# notably "# :; upsc output" before the data dump (such pattern
# is ignored to reduce noise when reviewing content). This feature
# just allows to track down comments that could be structured
# but were overlooked previously. Note however that this may
# also see issues with mis-typed structured comments if their
# lines are excluded by initial regex filter, e.g. like this one:
# DEVICE:URL:REPORT: http://some.site/ and more text
# where the filter requires a single token or it is a plain comment.
# The important thing here is that such entries would not be rendered!
PEDANTIC_TRACK_UNSTRUCTURED_COMMENTS = os.getenv("NUT_DDL_PEDANTIC_TRACK_UNSTRUCTURED_COMMENTS", "False")
PEDANTIC_TRACK_UNSTRUCTURED_COMMENTS = (PEDANTIC_TRACK_UNSTRUCTURED_COMMENTS in ["True", "true", "TRUE", "Yes", "yes", "YES", "1"])
###
# Old (no longer available in NUT) -> new (currently available) drivers map
nutDriversUpdateMap = {
# "old": "new",
"blazer": "blazer_ser",
"cpsups": "powerpanel",
"cyberpower": "powerpanel",
"esupssmart": "blazer_ser",
"fentonups": "blazer_ser",
"hidups": "usbhid-ups",
"ippon": "blazer_ser",
"liebertgxt2": "liebert-esp2",
"megatec": "blazer_ser",
"megatec_usb": "blazer_usb",
"mustek": "blazer_ser",
"newhidups": "usbhid-ups",
"newmge-shut": "mge-shut",
"nitram": "powerpanel",
"powermust": "blazer_ser",
"sms": "blazer_ser",
}
# Actually reported (yet available in NUT) -> new suggested drivers map
nutDriversHintsMap = {
# "reported": "suggested",
"apcsmart-old": "apcsmart",
"bestups": "nutdrv_qx",
"blazer_ser": "nutdrv_qx",
"blazer_usb": "nutdrv_qx",
}
###
# Global vars
ndsVersion = "-1"
ndsSL = -1
varCmdComments = {}
devComment = []
devCommentBlocks = []
devURLs_vendor = []
devURLs_report = []
devURLs = []
nutVars = {}
nutRWs = {}
nutCommands = {}
manPages = []
fromFileName = {}
commentsMap = {}
nonCommentsMap = {}
###
# Command line arguments
parser = argparse.ArgumentParser(description="Parse a NUT's .dev/.nds file to AsciiDoc")
parser.add_argument("infile", help="Input file to parse (either .dev or .nds)")
parser.add_argument("outfile", help="Output file where the resulting page should be stored")
parser.add_argument("-v", "--verbose", action="store_true", help="Be pedantic about what's going on")
args = parser.parse_args()
inputFile = args.infile
outputFile = args.outfile
verbose = args.verbose
###
# Comments parsing
def nds_version(raw):
"""
Parse NDS file version.
"""
# '# NDS:VERSION:<version>\n'
global ndsVersion
if ndsVersion != "-1":
msg = "Redeclaration of NDS version"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove '# NDS:VERSION:'
ndsVersion = raw[0][14:]
def nds_sl(raw):
"""
Parse user-provided support-level for the device.
"""
# '# DEVICE:SUPPORT-LEVEL:<support-level>\n'
global ndsSL
if ndsSL != -1:
msg = "Redeclaration of NDS support-level"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove '# DEVICE:SUPPORT-LEVEL:'
sl = int(raw[0][23:])
if not 1 <= sl <= 10:
msg = ("NDS support-level: '%d' out of range [1..10]" % sl)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
ndsSL = sl
def nds_dev_url_vendor(raw):
"""
Parse the URL for more device information
(manufacturer/vendor/brander site or product page).
May be present more than once, one URL per line.
"""
# '# DEVICE:URL:VENDOR: *...\n'
# Remove leading 'start' of the line ('# DEVICE:URL:VENDOR: *')
line = str(raw[0][20:]).strip()
# Empty comment
if not len(line):
msg = "Empty device vendor URL"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Too eager a copy-paste from asciidoc?
if line.startswith("link:"):
line = line.replace("link:", "", 1)
if not "://" in line:
msg = ("Device vendor URL does not contain a schema, ignored: %s" % line)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
devURLs_vendor.append(line)
def nds_dev_url_report(raw):
"""
Parse the URL for more device information (mailing list, blog, NUT issue...)
where the report originated, driver was implemented, etc.
May be present more than once, one URL per line.
"""
# '# DEVICE:URL:REPORT: *...\n'
# Remove leading 'start' of the line ('# DEVICE:URL:REPORT: *')
line = str(raw[0][20:]).strip()
# Empty comment
if not len(line):
msg = "Empty device report URL"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Too eager a copy-paste from asciidoc?
if line.startswith("link:"):
line = line.replace("link:", "", 1)
if not "://" in line:
msg = ("Device report URL does not contain a schema, ignored: %s" % line)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
devURLs_report.append(line)
def nds_dev_url(raw):
"""
Parse the URL for more device information (vendor site, NUT issue...)
if not converted or suited to the more specific VENDOR or REPORT types.
May be present more than once, one URL per line.
"""
# '# DEVICE:URL: *...\n'
# Remove leading 'start' of the line ('# DEVICE:URL: *')
line = str(raw[0][13:]).strip()
# Empty comment
if not len(line):
msg = "Empty device URL"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Too eager a copy-paste from asciidoc?
if line.startswith("link:"):
line = line.replace("link:", "", 1)
if not "://" in line:
msg = ("Device URL does not contain a schema, ignored: %s" % line)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
devURLs.append(line)
def nds_dev_comment(raw):
"""
Parse device comment. Note that only one per device may be defined.
See also DEVICE:COMMENT-BLOCK<:type>?: <title> which may be repeated
for tool output "screenshots".
"""
# '# DEVICE:COMMENT[:]\n'
# '# <comment>\n'
# '# <comment>\n'
# ...
# '# DEVICE:EOC\n'
if len(devComment):
msg = "Redeclaration of device comment (only one un-typed block is allowed)"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove leading 'start' line ('# DEVICE:COMMENT[:]\n')
raw = raw[1:]
# Not a valid device comment, don't do anything with it
if not len(raw) or (raw[-1] != "# DEVICE:EOC" and raw[-1] != "# DEVICE:EOC:"):
msg = ("Invalid device comment: %s" % ("seems empty" if not len(raw) else "does not end with DEVICE:EOC (blank non-comment lines mid-block?)"))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove the 'close' line
raw = raw[:-1]
# Empty comment
if not len(raw):
msg = "Empty device comment"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove hash and leading space
for line in raw:
devComment.append(line[2:])
def nds_dev_comment_block(raw):
"""
Parse device block-comment(s) with pre-formatted text (tool "screenshots").
"""
# '# DEVICE:COMMENT-BLOCK:UPSCONF: *<single-token title may be UPS name if no section in text, otherwise pasted as a starting comment>\n'
# '# DEVICE:COMMENT-BLOCK:LSUSB: *<title with lsusb cmdline>\n'
# '# DEVICE:COMMENT-BLOCK:LOGS: *<optional title>\n'
# '# DEVICE:COMMENT-BLOCK:FIXME:UPSCMD: *<single-token title is UPS name for example command, multi-token is pasted as a starting comment>\n'
# '# DEVICE:COMMENT-BLOCK:FIXME:UPSRW: *<single-token title is UPS name for example command, multi-token is pasted as a starting comment>\n'
# '# DEVICE:COMMENT-BLOCK: *<title of unstructured info>\n'
# '# <content-to-become-pre-formatted>\n'
# '# <content-to-become-pre-formatted>\n'
# ...
# '# DEVICE:EOC\n'
# Preferably titled like "Configuration section" or "lsusb listing",
# or specifying the content type, or both in some cases. The cut-off
# point is the colon char (comment_type_title starts with either type
# or possible space and title right away):
comment_type_title = str(raw[0][23:])
try:
# Variants of the remaining "type +/- title" to consider:
# " *<empty>"
# " *Some title (unstructured)"
# "TYPE: *<empty>"
# "TYPE: *Some title"
# For regex below, currently the "TYPE:" is all-caps letters and colon
# (may be inside, e.g. "FIXME:SOMETHING"); not adding more match chars
# until needed by a syntax extension.
matcher = re.match(r'^([A-Z:]+:)? *(.*)$', comment_type_title)
if matcher:
comment_type = matcher.group(1)
title = matcher.group(2)
if title is None:
# Be sure it is a string type
title = ""
else:
# Report below and use it all as title if not in pedantic mode
raise ValueError("regular expression did not match expected pattern")
except ValueError as exc:
msg = ("Could not parse tag '%s' => tail '%s' further into a type and title: %s" % (str(raw[0]), comment_type_title, str(exc)))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
comment_type = None
title = comment_type_title
title = title.strip()
# NOTE: Title validation continued after general content sanity check and trim
# Remove leading 'start' line ('# DEVICE:COMMENT-BLOCK<:TYPE>: *<title>\n')
raw = raw[1:]
# Not a valid device block comment, don't do anything with it
if not len(raw) or (raw[-1] != "# DEVICE:EOC" and raw[-1] != "# DEVICE:EOC:"):
msg = ("Invalid device block comment: %s" % ("seems empty" if not len(raw) else "does not end with DEVICE:EOC (blank non-comment lines mid-block?)"))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove the 'close' line
raw = raw[:-1]
# Empty comment block
if not len(raw):
msg = "Empty device block comment"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Collect stripped and prepared contents here:
blk = []
upsname = None
# Pre-populate contents (and default title sometimes), as
# based on caller-specified type and/or title of the entry:
if comment_type == "UPSCONF:":
# single-token title is UPS name, multi-token is pasted as a starting comment
bGotSection = False
bTitleComment = True
upsname = None
if len(title):
if not " " in title:
# ...else: multi-token, use as comment anyway
# Below, we strip possible markup (so far don't care about proper nesting)
upsname = re.sub(r"(^[\"'`[]*|[\"'`[]*$)", '', title)
if not len(upsname):
upsname = None
for line in raw:
line = line[2:].strip()
# No dollar, trailing comment syntactically possible:
matcher = re.match(r'^\[([^ ]+)\]', line)
if matcher:
bGotSection = True
if upsname is not None and matcher.group(1) == upsname:
bTitleComment = False
break
if not bGotSection:
if upsname is None:
msg = "Driver configuraton example lacks a section name for the device"
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
# else: ugh, whatever
blk.append("[ups]")
else:
blk.append("[%s]" % upsname)
bTitleComment = False
if len(title) and bTitleComment:
blk.append("# %s" % title)
# if not len(title):
title = "Driver configuration"
elif comment_type == "LSUSB:":
if len(title):
# Title assumed to be e.g. `lsusb -vvv` or `lsusb -s 007:002` (bus:dev)
# or `lsusb -d 1234:5678` (vid:pid) or even `lsusb | grep Liebert`
blk.append(":; %s" % title)
title = "`%s` listing"
else:
if "lsusb" in raw[0]:
title = "`lsusb` listing"
else:
# Assume the content starts with desired command, if posted
title = "`lsusb` or similar tool listing"
elif comment_type == "LOGS:":
if not len(title):
title = "Logs of NUT service startup"
elif comment_type == "FIXME:UPSCMD:":
# single-token title is UPS name for example command, multi-token is pasted as a starting comment
bTitleComment = True
upsname = "ups"
if len(title):
if not " " in title:
# ...else: multi-token, use as comment anyway
# Below, we strip possible markup (so far don't care about proper nesting)
upsname = re.sub(r"(^[\"'`[]*|[\"'`[]*$)", '', title)
if len(upsname):
bTitleComment = False
if bTitleComment:
blk.append("# %s" % title)
# else: TODO: extract upsname from example command and/or
# > Instant commands supported on UPS [myupsname]:
# line, if any.
if not "@" in upsname:
upsname = upsname + "@localhost"
# if not len(title):
title = "Commands per `upscmd -l %s` listing" % upsname
if "TODO" not in raw[0] and "FIXME" not in raw[0] \
and (len(raw) < 2 or ("TODO" not in raw[1] and "FIXME" not in raw[1])):
blk.append("# TODO: Convert to CMD:... markup")
if "upscmd -l" not in raw[0] \
and (len(raw) < 2 or "upscmd -l" not in raw[1]):
blk.append(":; upscmd -l %s" % upsname)
# else: TODO: rewrite upsname in example command and/or
# > Instant commands supported on UPS [myupsname]:
# line, if any? Perhaps to address below in the loop.
elif comment_type == "FIXME:UPSRW:":
# single-token title is UPS name for example command, multi-token is pasted as a starting comment
bTitleComment = True
upsname = "ups"
if len(title):
if not " " in title:
# ...else: multi-token, use as comment anyway
# Below, we strip possible markup (so far don't care about proper nesting)
upsname = re.sub(r"(^[\"'`[]*|[\"'`[]*$)", '', title)
if len(upsname):
bTitleComment = False
if bTitleComment:
blk.append("# %s" % title)
# else: TODO: extract upsname from example command, if any
if not "@" in upsname:
upsname = upsname + "@localhost"
# if not len(title):
title = "Variables per `upsrw %s` listing" % upsname
if "TODO" not in raw[0] and "FIXME" not in raw[0] \
and (len(raw) < 2 or ("TODO" not in raw[1] and "FIXME" not in raw[1])):
blk.append("# TODO: Convert to RW:... and RO:... markup")
if ("upsrw" not in raw[0] or "upsrw output" in raw[0]) \
and (len(raw) < 2 or ("upsrw" not in raw[1] or "upsrw output" in raw[1])):
blk.append(":; upsrw %s" % upsname)
# else: TODO: rewrite upsname in example command, if any?
# Perhaps to address below in the loop.
elif comment_type is not None:
msg = ("Invalid device block comment type: '%s'" % str(comment_type))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
comment_type = None
if not len(title):
title = "Data sample"
msg = ("Invalid device block comment title, using default: '%s'" % title)
if verbose:
print (msg)
# if PEDANTIC_DECLARATIONS:
# raise RuntimeWarning (msg)
# Loop to populate the rest of ultimately published contents, finally:
for line in raw:
# Remove hash and one leading space
line = line[2:]
lineStrip = line.strip()
if comment_type == "FIXME:UPSRW:" and re.match(r'^upsrw output:*$', lineStrip):
continue
elif comment_type == "FIXME:UPSCMD:" and re.match(r'^upscmd output:*$', lineStrip):
continue
blk.append(line)
devCommentBlocks.append({'title': title, 'content': blk})
def nds_var_cmd_comments(raw):
"""
Parse comments of variables/commands.
"""
# '# var.name[.suffix[. ...]]/command.name[.suffix[. ...]]:COMMENT[:]\n'
# '# <comment>\n'
# '# <comment>\n'
# ...
# '# var.name[.suffix[. ...]]/command.name[.suffix[. ...]]:EOC\n'
# Get var/command name
itemName = re.sub(":COMMENT:?.*$", "", raw[0][2:])
if varCmdComments.get(itemName):
msg = ("Redeclaration of comment for '%s'" % itemName)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove leading 'start' line
raw = raw[1:]
# Not a valid comment, don't do anything with it
if not len(raw) or (raw[-1] != "# %s:EOC" % itemName and raw[-1] != "# %s:EOC:" % itemName):
msg = ("Invalid comment for '%s': %s" % (itemName, "seems empty" if not len(raw) else "does not end with DEVICE:EOC (blank non-comment lines mid-block?)"))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
# Remove the 'close' line
raw = raw[:-1]
# Empty comment
if not len(raw):
msg = ("Empty comment for '%s'" % itemName)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
varCmdComments[itemName] = []
# Remove hash and leading space
for line in raw:
varCmdComments[itemName].append(line[2:])
# Comments 'Pattern => parsing function' map for .nds files
ndsCommentsMap = {
# N[UT]D[evice]S[imulation] version
# '# NDS:VERSION:<value>\n'
"^# NDS:VERSION:\S+$": nds_version,
# Vars/commands - Start of comment:
# '# var.name[.suffix[. ...]]/command.name[.suffix[. ...]]:COMMENT[:]\n'
"^# ([\w\-]+\.)+[\w\-]+:COMMENT:?$": nds_var_cmd_comments,
# Device - Start of comment block
# '# DEVICE:COMMENT-BLOCK: *<title>\n'
"^# DEVICE:COMMENT-BLOCK:UPSCONF: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:LSUSB: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:LOGS: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:FIXME:UPSCMD: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:FIXME:UPSRW: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK: *.*$": nds_dev_comment_block,
# Device - Start of comment
# '# DEVICE:COMMENT[:]\n'
"^# DEVICE:COMMENT:?$": nds_dev_comment,
# Further information about the device (vendor/mfr, issue/blog/mailing list, unclassified)
# '# DEVICE:URL:VENDOR:<link>\n'
"^# DEVICE:URL:VENDOR: *[^ ]+://[^ ]+$": nds_dev_url_vendor,
# '# DEVICE:URL:REPORT:<link>\n'
"^# DEVICE:URL:REPORT: *[^ ]+://[^ ]+$": nds_dev_url_report,
# '# DEVICE:URL:<link>\n'
"^# DEVICE:URL: *[^ ]+://[^ ]+$": nds_dev_url,
# Support level
# '# DEVICE:SUPPORT-LEVEL:<value>\n'
"^# DEVICE:SUPPORT-LEVEL:\d\d?$": nds_sl
}
# Comments 'Pattern => parsing function' map for .dev files
devCommentsMap = {
# Vars/commands - Start of comment:
# '# var.name[.suffix[. ...]]/command.name[.suffix[. ...]]:COMMENT[:]\n'
"^# ([\w\-]+\.)+[\w\-]+:COMMENT:?$": nds_var_cmd_comments,
# Device - Start of comment block
# '# DEVICE:COMMENT-BLOCK: *<title>\n'
"^# DEVICE:COMMENT-BLOCK:UPSCONF: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:LSUSB: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:LOGS: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:FIXME:UPSCMD: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK:FIXME:UPSRW: *.*$": nds_dev_comment_block,
"^# DEVICE:COMMENT-BLOCK: *.*$": nds_dev_comment_block,
# Device - Start of comment
# '# DEVICE:COMMENT[:]\n'
"^# DEVICE:COMMENT:?$": nds_dev_comment,
# Further information about the device (vendor/mfr, issue/blog/mailing list, unclassified)
# '# DEVICE:URL:VENDOR:<link>\n'
"^# DEVICE:URL:VENDOR: *[^ ]+://[^ ]+$": nds_dev_url_vendor,
# '# DEVICE:URL:REPORT:<link>\n'
"^# DEVICE:URL:REPORT: *[^ ]+://[^ ]+$": nds_dev_url_report,
# '# DEVICE:URL:<link>\n'
"^# DEVICE:URL: *[^ ]+://[^ ]+$": nds_dev_url,
# Support level
# '# DEVICE:SUPPORT-LEVEL:<value>\n'
"^# DEVICE:SUPPORT-LEVEL:\d\d?$": nds_sl
}
###
# End Of Comments patterns
EOCPatterns = [
# Vars/commands comments
# '# var.name[.suffix[. ...]]/command.name[.suffix[. ...]]:EOC\n'
"^# ([\w\-]+\.)+[\w\-]+:EOC:?$",
# Device comment
# '# DEVICE:EOC\n'
"^# DEVICE:EOC:?$"
]
###
# Non-comments parsing
def nds_vars(raw):
"""
Parse NUT's vars.
"""
# 'var.name[.suffix[. ...]]: <value>\n'
# Check for End Of Line comments
eol = None
if len(raw["eol"]):
for EOLType in EOLComments:
if re.match(EOLComments[EOLType]["pattern"], raw["eol"]):
eol = {
"type": EOLType,
"comment": EOLComments[EOLType]["function"](raw["eol"])
}
raw["eol"] = ""
break
varName = re.sub(":.*$", "", raw["line"])
if nutVars.get(varName):
msg = ("Redeclaration of variable '%s'" % varName)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
nutVars[varName] = {}
nutVars[varName]["value"] = raw["line"].replace("%s:" % varName, "", 1)[1:]
if eol is not None:
nutVars[varName][eol["type"]] = eol["comment"]
def nds_rw_vars(raw):
"""
Parse NUT's RW vars.
"""
# For .nds files:
# 'RW:var.name[.suffix[. ...]]:<type>:<options>\n'
# For .dev files:
# '#RW:var.name[.suffix[. ...]]:<type>:<options>\n'
# '#RW:var.name[.suffix[. ...]]:STRING[:<len>]\n'
# Check for End Of Line comments
eol = None
if len(raw["eol"]):
for EOLType in EOLComments:
if re.match(EOLComments[EOLType]["pattern"], raw["eol"]):
eol = {
"type": EOLType,
"comment": EOLComments[EOLType]["function"](raw["eol"])
}
raw["eol"] = ""
break
buf = raw["line"].split(":", 4)
varName = buf[1]
varType = buf[2]
if not nutRWs.get(varName):
nutRWs[varName] = {}
nutRWs[varName]["type"] = varType
elif not nutRWs[varName].get("type") or nutRWs[varName]["type"] != varType:
msg = ("Redeclaration of RW variable '%s' with mismatching types (%s != %s)" % (varName, varType, nutRWs[varName]["type"]))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
if varType == "STRING":
# 'RW:var.name[.suffix[. ...]]:STRING:<len>\n'
# '#RW:var.name[.suffix[. ...]]:STRING[:<len>]\n'
if fromFileName["fileType"] == "dev":
if len(buf) < 4:
buf.append("0")
elif len(buf) < 4:
msg = ("Declaration of RW variable '%s' of type 'STRING' without a length" % varName)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
if not nutRWs[varName].get("opts"):
del nutRWs[varName]
if not buf[3].isdigit():
msg = ("Declaration of RW variable '%s' of type 'STRING' with an invalid length (%s)" % (varName, buf[3]))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
if not nutRWs[varName].get("opts"):
del nutRWs[varName]
return
length = int(buf[3])
if nutRWs[varName].get("opts"):
if length != nutRWs[varName]["opts"]:
msg = ("Redeclaration of variable '%s' of type 'STRING' with different length (%d != %d)" % (varName, length, nutRWs[varName]["opts"]))
else:
msg = ("Redeclaration of variable '%s' of type 'STRING'" % varName)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
nutRWs[varName]["opts"] = length
if eol is not None:
nutRWs[varName][eol["type"]] = eol["comment"]
elif varType == "ENUM":
# 'RW:var.name[.suffix[. ...]]:ENUM:"<enumerated value>"\n'
if not re.match("^\".+\"$", buf[3]):
msg = ("Declaration of RW variable '%s' of type 'ENUM' with an invalid format." % varName) + \
("\texpected: 'RW:var.name[.suffix[. ...]]:ENUM:\"<enumerated value>\"'") + \
("\tgot: '%s'" % raw["line"])
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
if not nutRWs[varName].get("opts"):
del nutRWs[varName]
return
if not nutRWs[varName].get("opts"):
nutRWs[varName]["opts"] = []
opts = { "enum": buf[3][1:-1] }
if eol is not None:
opts[eol["type"]] = eol["comment"]
nutRWs[varName]["opts"].append(opts)
elif varType == "RANGE":
# 'RW:var.name[.suffix[. ...]]:RANGE:"<min>" "<max>"\n'
if not re.match("^\"\d+\" \"\d+\"$", buf[3]):
msg = ("Declaration of RW variable '%s' of type 'RANGE' with an invalid range." % varName) + \
("\texpected: 'RW:var.name[.suffix[. ...]]:RANGE:\"<min>\" \"<max>\"'") + \
("\tgot: '%s'" % raw["line"])
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
if not nutRWs[varName].get("opts"):
del nutRWs[varName]
return
rwRange = buf[3].split("\"")
if not len(rwRange[1]) or not rwRange[1].isdigit() or not len(rwRange[3]) or not rwRange[3].isdigit():
msg = ("Declaration of RW variable '%s' of type 'RANGE' with a non-numerical range (%s..%s)" % (varName, rwRange[1], rwRange[3]))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
if not nutRWs[varName].get("opts"):
del nutRWs[varName]
return
rangeMin = int(rwRange[1])
rangeMax = int(rwRange[3])
if not rangeMin < rangeMax:
msg = ("Declaration of RW variable '%s' of type 'RANGE' with an invalid range (%d..%d)" % (varName, rangeMin, rangeMax))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
if not nutRWs[varName].get("opts"):
del nutRWs[varName]
return
if not nutRWs[varName].get("opts"):
nutRWs[varName]["opts"] = []
opts = {
"min": rangeMin,
"max": rangeMax
}
if eol is not None:
opts[eol["type"]] = eol["comment"]
nutRWs[varName]["opts"].append(opts)
else:
if not nutRWs[varName].get("opts"):
del nutRWs[varName]
msg = ("Declaration of RW variable '%s' of unknown type '%s'." % (varName, varType))
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
def nds_commands(raw):
"""
Parse NUT's instant commands.
"""
# For .nds files:
# 'CMD:command.name[.suffix[. ...]]\n'
# For .dev files:
# '#CMD:command.name[.suffix[. ...]]\n'
# Check for End Of Line comments
eol = None
if len(raw["eol"]):
for EOLType in EOLComments:
if re.match(EOLComments[EOLType]["pattern"], raw["eol"]):
eol = {
"type": EOLType,
"comment": EOLComments[EOLType]["function"](raw["eol"])
}
raw["eol"] = ""
break
command = re.sub("^#?CMD:", "", raw["line"])
if nutCommands.get(command):
msg = ("Redeclaration of command '%s'" % command)
if verbose:
print (msg)
if PEDANTIC_DECLARATIONS:
raise RuntimeWarning (msg)
return
nutCommands[command] = {};
if eol is not None:
nutCommands[command][eol["type"]] = eol["comment"]
# Non-comments 'Pattern => parsing function' map for .nds files
ndsNonCommentsMap = {
# Vars
# 'var.name[.suffix[. ...]]: <value>\n'
"^([\w\-]+\.)+[\w\-]+: .*$": nds_vars,
# Empty vars
# 'var.name[.suffix[. ...]]:\n'
"^([\w\-]+\.)+[\w\-]+:$": nds_vars,
# RW Vars
# 'RW:var.name[.suffix[. ...]]:<type>:<options>\n'
"^RW:([\w\-]+\.)+[\w\-]+:\w+:\S.*$": nds_rw_vars,
# Commands
# 'CMD:command.name[.suffix[. ...]]\n'
"^CMD:(\w+\.)+\w+$": nds_commands
}
# Non-comments 'Pattern => parsing function' map for .dev files
devNonCommentsMap = {
# Vars
# 'var.name[.suffix[. ...]]: <value>\n'
"^([\w\-]+\.)+[\w\-]+: .*$": nds_vars,
# Empty vars
# 'var.name[.suffix[. ...]]:\n'
"^([\w\-]+\.)+[\w\-]+:$": nds_vars,
# RW Vars
# '#RW:var.name[.suffix[. ...]]:<type>:<options>\n'
# '#RW:var.name[.suffix[. ...]]:STRING[:<len>]\n'
"^#RW:([\w\-]+\.)+[\w\-]+:(STRING|\w+:\S.*)$": nds_rw_vars,
# Commands
# '#CMD:command.name[.suffix[. ...]]\n'
"^#CMD:(\w+\.)+\w+$": nds_commands
}
###
# End Of File patterns
EOFPatterns = [
# Beginning of a sequence of [recorded] events
"TIMER \d+"
]
###
# End Of Line parsing
def nds_bad(raw):
"""
Parse bad vars/commands comments/flags.
"""
# '#BAD[: <comment>]\n'
return re.sub("^[ \t]*#BAD:?\s*", "", raw)
def nds_comment(raw):
"""
Parse End Of Line vars/commands comments.
"""
# '#COMMENT[: <comment>]\n'
return re.sub("^[ \t]*#COMMENT:?\s*", "", raw)
# End Of Line 'Pattern => parsing function' map