-
Notifications
You must be signed in to change notification settings - Fork 10
/
gateway_generate_docs.py
1579 lines (1264 loc) · 63.3 KB
/
gateway_generate_docs.py
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 -*-
# This file is part of Enphase-API <https://github.com/Matthew1471/Enphase-API>
# Copyright (C) 2023 Matthew1471!
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# 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, see <https://www.gnu.org/licenses/>.
"""
Enphase® API Documentation Generator
This module is responsible for generating documentation for the Enphase® API in AsciiDoc format.
It processes endpoint metadata, attempts to call undocumented endpoints to determine their schema,
and writes the resulting documentation to disk.
Usage:
1. The module loads endpoint metadata from a JSON file containing API details.
2. It processes each endpoint by calling the API to obtain example data and schema information.
3. The generated documentation includes information about endpoints, their URIs, descriptions,
request and response schemas, and example usage.
4. The resulting AsciiDoc files are organized into sub-directories based on the API's structure.
5. An index file summarizing all endpoints and their descriptions is also generated.
Note:
- The module requires valid API credentials to authenticate requests.
- The generated documentation can be used for reference by developers using the Enphase® API.
"""
import json # This script makes heavy use of JSON parsing.
import os.path # We check whether a file exists and manipulate filepaths.
import urllib.parse # We URL encode URLs.
# All the shared Enphase® functions are in these packages.
from enphase_api.cloud.authentication import Authentication
from enphase_api.local.gateway import Gateway
# Enable this mode to perform no actual requests.
TEST_ONLY = False
# This script's version.
VERSION = 0.1
class JSONSchema:
"""
A utility class for deriving JSON schemas from sample JSON data.
This class provides static methods for determining the JSON schema structure
and types based on given sample JSON data.
"""
@staticmethod
# pylint: disable=unidiomatic-typecheck
def get_type_string(json_value):
"""
Determine the JSON type of the given value and return it as a string.
"""
if type(json_value) in (int, float):
return 'Number'
# In Python, a bool is a sub-class of int.
if type(json_value) is bool:
return 'Boolean'
if type(json_value) is str:
return 'String'
if json_value is None:
return 'Null'
return 'Unknown'
@staticmethod
# pylint: disable=unidiomatic-typecheck
def get_table_name(table_field_map, original_table_name, json_key):
"""
Determine the appropriate table name based on mappings and original names.
"""
# We can override some object names (and merge metadata).
if (table_field_map
and (key_metadata := table_field_map.get(json_key))
and type(key_metadata) is dict
and (value_name := key_metadata.get('value_name'))):
# This name has been overridden.
return value_name
# Otherwise, is this not the root table?
if original_table_name and original_table_name != '.':
# Get a sensible default name for this table (that preserves its JSON scope).
return f'{original_table_name}.{json_key.capitalize()}'
# Return just the capitalised JSON key.
return json_key.capitalize()
@staticmethod
# pylint: disable=unidiomatic-typecheck
# pylint: disable-next=invalid-name
def merge_dictionaries(a, b, path=None, mark_optional_at_depth=None):
"""
Recursively merges 'b' into 'a' and then returns 'a'.
If mark_optional_at_depth is set then any additions,
result in a "optional" key being set at that path.
If at a current path one side is a dictionary but the other is a string,
then the string is merged into the dictionary as a description.
If it is unsafe to merge a path it will return an error.
Inspired by:
https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries
"""
# What path is currently being inspected.
if path is None:
path = []
# Take each of the keys in dictionary 'b'.
for key in b:
# Does the same key exist in 'a'?
if key in a:
# Are both dictionaries?
if type(a[key]) is dict and type(b[key]) is dict:
# Merge the child dictionaries by invoking this recursively.
JSONSchema.merge_dictionaries(
a=a[key],
b=b[key],
path=path + [str(key)],
mark_optional_at_depth=mark_optional_at_depth
)
# Are they otherwise the same values.
elif a[key] == b[key]:
# Same values do not require copying.
pass
# If 'a' is a dictionary but 'b' is a string.
elif type(a[key]) is dict and type(b[key]) is str:
# Set the description in the 'a' dictionary to include the 'b' string.
a[key]['description'] = b[key]
# If 'b' is a dictionary but 'a' is a string.
elif type(b[key]) is dict and type(a[key]) is str:
# Set the description in the 'b' dictionary to include the 'a' string.
b[key]['description'] = a[key]
# Replace the 'a' value with the recently updated 'b' dictionary.
a[key] = b[key]
# If 'a' is an array of unknown but 'b' is defined.
elif ((key == 'type' and (a[key] == 'Array(Unknown)'))
or (key == 'value' and (a[key] == 'Array of Unknown'))):
# Unknown type and another type are compatible.
a[key] = b[key]
# If 'b' is an array of unknown but 'a' is defined.
elif ((key == 'type' and (b[key] == 'Array(Unknown)'))
or (key == 'value' and (b[key] == 'Array of Unknown'))):
# Do not require copying.
pass
# Do the types not otherwise match?
else:
# Error as data loss could occur.
raise ValueError(f'Conflict at {".".join(path + [key])}')
# It doesn't exist in 'a', so just add it.
else:
# We can record where a value was optional.
if len(path) == mark_optional_at_depth:
if type(b[key]) is dict and 'type' in b[key]:
b[key]['optional'] = True
a[key] = b[key]
# Do a sweeping check for keys that were in 'a' but not in 'b'.
if len(path) == mark_optional_at_depth:
# Take each of the keys in dictionary 'a'.
for key in a:
# Was this only in 'a' and not added as a result of a merge of 'b'
# (but 'a' had a valid 'type' and was not just a description)?
if key not in b and 'type' in a[key]:
a[key]['optional'] = True
return a
@staticmethod
# pylint: disable=unidiomatic-typecheck
def get_schema(json_object, table_name='.', table_field_map=None):
"""
Recursively generate the schema for the given JSON data.
Args:
json_object: The JSON data for which to generate the schema.
table_name: The name of the current table (default is '.').
table_field_map: A mapping of fields to override table names and metadata (optional).
Returns:
A dictionary representing the schema of the JSON data.
Note:
This method is designed to help in automatically deriving JSON schemas.
"""
# The fields in the current table.
current_table_fields = {}
# Store any discovered nested tables in this dictionary.
child_tables = None
# A field_map contains all the table metadata both static and learnt.
# Does this table already exist in the field map?
# Get a reference to just this table's field_map outside the loop.
current_table_field_map = (table_field_map.get(table_name) if table_field_map else None)
# If there is no root element (anonymous array) we must add one.
if type(json_object) is list:
json_object = {'.': json_object}
# Take each key and value of the current table.
for json_key, json_value in json_object.items():
# Is this itself another object?
if type(json_value) is dict:
# We can override some object names (and merge metadata).
child_table_name = JSONSchema.get_table_name(
table_field_map=current_table_field_map,
original_table_name=table_name,
json_key=json_key
)
# This could return multiple tables if there are nested types.
new_dict_schema = JSONSchema.get_schema(
json_object=json_value,
table_name=child_table_name,
table_field_map=table_field_map
)
# Merge this table list.
if child_tables:
child_tables = JSONSchema.merge_dictionaries(
a=child_tables,
b=new_dict_schema,
mark_optional_at_depth=1
)
else:
child_tables = new_dict_schema
# Add the type of this key.
current_table_fields[json_key] = {
'type': 'Object',
'value': f'`{child_table_name}` object'
}
# Is this a list of values?
elif type(json_value) is list:
# Are there any values.
if len(json_value) > 0:
# Is the first value an object?
if type(json_value[0]) is dict:
# We can override some object names (and merge metadata).
child_table_name = JSONSchema.get_table_name(
table_field_map=current_table_field_map,
original_table_name=table_name,
json_key=json_key
)
# As this is a list each item could have different metadata;
# take each of the items in the list
# and combine all the keys and their metadata.
for list_item in json_value:
# This could return multiple tables if there are nested types.
new_list_schema = JSONSchema.get_schema(
json_object=list_item,
table_name=child_table_name,
table_field_map=table_field_map
)
# Merge this table list.
if child_tables:
child_tables = JSONSchema.merge_dictionaries(
a=child_tables,
b=new_list_schema,
mark_optional_at_depth=1
)
else:
child_tables = new_list_schema
# Add the type of this key.
current_table_fields[json_key] = {
'type': 'Array(Object)',
'value': f'Array of `{child_table_name}`'
}
# The first value must be a primitive type.
else:
# Add the type of the key.
type_string = JSONSchema.get_type_string(json_value[0])
current_table_fields[json_key] = {
'type': f'Array({type_string})',
'value': f'Array of {type_string}'
}
# This is just an array of standard JSON types.
else:
# Add the type of this key.
type_string = JSONSchema.get_type_string(json_value)
current_table_fields[json_key] = {
'type': f'Array({type_string})',
'value': f'Array of {type_string}'
}
# This is just a standard JSON type.
else:
# Add the type of this key.
current_table_fields[json_key] = {'type': JSONSchema.get_type_string(json_value)}
# Prepend this parent table (all its fields have been explored for nested objects).
tables = {}
tables[table_name] = current_table_fields
# Not all tables will have child tables.
if child_tables:
# Add any child tables to the list of tables.
tables.update(child_tables)
return tables
class DocumentationGenerator:
"""
A class to generate generic documentation.
This class can be used by other documentation generators.
"""
@staticmethod
def get_header_settings_and_variables():
"""
Generates a header containing reference information, document settings, and variables.
This function constructs a header with reference information, document settings,
and variables for documentation generation.
Returns:
str: The AsciiDoc generated header content.
"""
# Reference.
result = 'Matthew1471 <https://github.com/matthew1471[@Matthew1471]>;\n\n'
# Document Settings.
result += '// Document Settings:\n\n'
# Set the autogenerated section IDs to be in GitHub format,
# so links work consistently across both platforms.
result += '// Set the ID Prefix and ID Separators to be consistent with GitHub so links '
result += 'work irrespective of rendering platform.'
result += ' (https://docs.asciidoctor.org/asciidoc/latest/sections/id-prefix-and-separator/)\n'
result += ':idprefix:\n'
result += ':idseparator: -\n\n'
# This project uses JSON code highlighting by default.
result += '// Any code blocks will be in JSON by default.\n'
result += ':source-language: json\n\n'
# This will convert the admonitions to be icons rather than text (in and out of GitHub).
result += 'ifndef::env-github[:icons: font]\n\n'
result += '// Set the admonitions to have icons (Github Emojis) if rendered on GitHub'
result += ' (https://blog.mrhaki.com/2016/06/awesome-asciidoctor-using-admonition.html).\n'
result += 'ifdef::env-github[]\n'
result += ':status:\n'
result += ':caution-caption: :fire:\n'
result += ':important-caption: :exclamation:\n'
result += ':note-caption: :paperclip:\n'
result += ':tip-caption: :bulb:\n'
result += ':warning-caption: :warning:\n'
result += 'endif::[]\n\n'
# The document's metadata.
result += '// Document Variables:\n'
result += ':release-version: 1.0\n'
result += ':url-org: https://github.com/Matthew1471\n'
result += ':url-repo: {url-org}/Enphase-API\n'
result += ':url-contributors: {url-repo}/graphs/contributors\n\n'
return result
@staticmethod
def get_introduction_section(description=None, file_depth=0):
"""
Generate the introduction section for Enphase-API documentation.
This function constructs the introduction section for the Enphase-API documentation.
It includes a heading, an optional description, and details about the project.
Args:
description (str, optional): An optional description to be included in the introduction.
file_depth (int, optional): The depth of the file in the directory structure.
Returns:
str: The AsciiDoc content for the introduction section.
"""
# Heading.
result = '== Introduction\n\n'
if description:
result += f'{description}\n\n'
result += 'Enphase-API is an unofficial project providing an API wrapper and the '
result += 'documentation for Enphase(R)\'s products and services.\n\n'
result += 'More details on the project are available from the xref:'
result += f'{"../" * (file_depth + 1)}README.adoc[project\'s homepage].\n'
return result
class EndpointDocumentationGenerator:
"""
A class to generate documentation for a specific API endpoint.
"""
@staticmethod
def get_header_section(name, endpoint, file_depth=0):
"""
Generate the AsciiDoc heading and introductory section for documentation.
Args:
name (str): The name of the section.
endpoint (dict): Information about the endpoint.
file_depth (int, optional): How many sub-directories deep the file will be stored in.
Returns:
str: A string containing the AsciiDoc heading and introductory section.
Note:
This function constructs the heading, table of contents, shared settings, and
introductory content for the AsciiDoc documentation of an API endpoint.
"""
# Heading.
result = f'= {name}\n'
# Table of Contents.
result += ':toc: preamble\n'
# Shared block of data.
result += DocumentationGenerator.get_header_settings_and_variables()
# Page Description.
long_description = None
if 'description' in endpoint:
description = endpoint['description']
result += f'{description["short"]}\n\n'
# We can add the long description later.
if 'long' in description:
long_description = description['long']
else:
print(f'Warning : "{name}" does not have a description.')
result += 'This endpoint and its purpose has not been fully documented yet.\n\n'
# Introduction.
result += DocumentationGenerator.get_introduction_section(
description=long_description,
file_depth=file_depth
)
# Some endpoints require some hardcoded explanatory details to be included.
if 'details' in endpoint:
result += EndpointDocumentationGenerator.get_details_section(endpoint['details'])
return result
@staticmethod
def get_details_section(details):
"""
Generate the details section for Enphase-API documentation.
This function constructs the details section for the Enphase-API documentation.
It includes a heading and details about the endpoint.
Args:
details (str): The details to be included in the documentation.
Returns:
str: The AsciiDoc content for the details section.
"""
# Heading.
result = '\n== Details\n\n'
# Add details.
result += f'{details}\n\n'
return result
@staticmethod
def get_request_section(request_json, file_depth=0, type_map=None):
"""
Generate the AsciiDoc section for the request details of an API endpoint.
Args:
request_json (dict): Information about the request of the API endpoint.
file_depth (int, optional): How many sub-directories deep the file will be stored in.
type_map (dict, optional): A type map listing different data types.
Returns:
tuple: A tuple containing a string with the AsciiDoc request section and a list of used
custom types.
Note:
This function constructs the request section of the AsciiDoc documentation for an API
endpoint, including methods, authorization requirements, querystring table, and request
data tables.
"""
# Any used custom types are collected then output after the tables.
used_custom_types = []
# Heading.
result = '\n== Request\n\n'
# List available methods.
if 'methods' in request_json:
# Whether authentication and authorisation are required.
auth_required = False
# Get a reference to the methods.
methods = request_json['methods']
# Check if anything requires authorisation.
for method, value in methods.items():
# Does at least one method require authentication?
if 'auth_level' in value and value['auth_level'] is not None:
auth_required = True
break
result += f'The `/{request_json["uri"]}` endpoint supports the following:\n'
result += EndpointDocumentationGenerator.get_methods_section(
methods=methods,
file_depth=file_depth
)
else:
# Whether authentication and authorisation are required.
auth_required = True
result += f'A HTTP `GET` to the `/{request_json["uri"]}` endpoint provides the following response data.\n\n'
# Some IQ Gateway API requests now require authentication.
if auth_required:
result += 'As of recent Gateway software versions this request requires user '
result += 'authentication and authorisation, see xref:'
result += f'{"../" * file_depth}Authentication.adoc[Authentication].\n'
# Get the request querystring table.
if 'query' in request_json:
# Get the table section but also any used and referenced custom types.
table_section, used_custom_types = EndpointDocumentationGenerator.get_table_section(
table_name='Querystring',
table=request_json['query'],
type_map=type_map,
short_booleans=True,
level=3
)
# Add the table section to the output.
result += table_section
# Get the request data table.
if (field_map := request_json.get('field_map')):
# Ouput all the request content tables.
result += '\n=== Message Body\n'
# Some API endpoints may not have all available methods declared yet.
if 'methods' in request_json:
result += '\nWhen making a '
already_output_method = False
for method in request_json['methods']:
if method == 'GET':
continue
if already_output_method:
result += ' or '
result += f'`{method}`'
already_output_method = True
result += ' request:\n'
# Add each of the tables from the derived json_schema.
for table_name, table in field_map.items():
# Format the table_name.
if table_name and table_name != '.':
table_name = f'`{table_name}` Object'
else:
table_name = 'Root'
# Get the table section but also any used and referenced custom types.
table_section, table_used_custom_types = (
EndpointDocumentationGenerator.get_table_section(
table_name=table_name,
table=table,
type_map=type_map,
short_booleans=True,
level=4
)
)
# Collect any used custom_types, ignoring any duplicates.
for custom_type in table_used_custom_types:
if custom_type not in used_custom_types:
used_custom_types.append(custom_type)
# Add the table section to the output.
result += table_section
return result, used_custom_types
@staticmethod
def get_methods_section(methods, file_depth=0):
"""
Generate the AsciiDoc section for the supported methods of an API endpoint.
Args:
methods (dict):
A dictionary of supported methods and their descriptions.
file_depth (int, optional):
How many sub-directories deep the file will be stored in.
Returns:
str:
A string containing the AsciiDoc methods section with a table of methods and
descriptions.
Note:
This method constructs the methods section of the AsciiDoc documentation for an API
endpoint, listing the supported HTTP methods and their descriptions.
"""
# Sub Heading.
result = '\n=== Methods\n'
# Method Table Header.
result += '[cols=\"1,1,2\", options=\"header\"]\n'
result += '|===\n'
result += '|Method\n'
result += f'|xref:{"../" * file_depth}Authentication.adoc#roles[Required Authorisation Level]\n'
result += '|Description\n\n'
# Take each method.
for method, value in methods.items():
# Method Name.
result += f'|`{method}`\n'
# Authorisation Level.
result += f'|{value["auth_level"]}\n'
# Method Description.
result += f'|{value["description"]}\n\n'
# End of Table.
result += '|===\n'
return result
@staticmethod
def get_example_section(example_item):
"""
Generate the AsciiDoc example section for an API endpoint using the provided URI and
example data.
Args:
example_item (dict):
Information about the example, including request and response details.
Returns:
str:
A string containing the AsciiDoc example section with request and response details.
Note:
This method constructs the example section of the AsciiDoc documentation for an API
endpoint, showcasing example requests and responses, including JSON formatting and raw
text.
"""
# Sub Heading.
result = f'\n\n=== {example_item["name"]}\n'
# We use a dictionary to store requests and/or responses for output as part of a loop.
example_output = {}
# Was there request details?
if 'request_form' in example_item:
example_output['Request'] = example_item['request_form']
elif 'request_json' in example_item:
example_output['Request'] = json.dumps(example_item['request_json'])
# Add the response.
if not 'response_raw' in example_item:
if example_item['response'] is not None:
example_output['Response'] = json.dumps(example_item['response'])
else:
example_item['response_raw'] = 'No data was returned.'
example_output['Response'] = example_item['response_raw']
else:
# We allow the raw value to opt-out of displaying anything.
if example_item['response_raw']:
example_output['Response'] = example_item['response_raw']
# Add the example_output Request, Response or both.
for example_type, example_content in example_output.items():
# List the example request/response details.
result += f'\n.{example_item.get("method", "GET")} *{example_item["uri"]}*'
result += f' {example_type}\n'
# We can override JSON responses and present raw text instead.
if (example_type == 'Request' and 'request_form' in example_item):
result += '[source,http]'
elif (example_type == 'Response' and 'response_raw' in example_item):
result += '[listing]'
else:
result += '[source,json,subs="+quotes"]'
# Add the example content (JSON or raw).
result += '\n----\n'
result += f'{example_content}\n'
result += '----'
return result
@staticmethod
def get_type_section(used_custom_types, type_map):
"""
Generate the AsciiDoc section for custom data types based on the provided information.
Args:
used_custom_types (list): A list of custom types referenced in the documentation.
type_map (dict): A dictionary containing definitions of custom data types.
Returns:
str: A string containing the AsciiDoc types section with details about
custom data types.
Note:
This method constructs the types section of the AsciiDoc documentation for custom data
types, including values, names, and descriptions of each type's fields.
"""
# Heading.
result = '\n== Types\n'
# Take each used custom type.
for used_custom_type in used_custom_types:
# Check the custom_type is defined.
if custom_type := type_map.get(used_custom_type):
# Type Sub Heading.
result += f'\n=== `{used_custom_type}` Type\n\n'
# Type Table Header.
result += '[cols=\"1,1,2\", options=\"header\"]\n'
result += '|===\n'
result += '|Value\n'
result += '|Name\n'
result += '|Description\n\n'
# Type Table Rows.
for current_field in custom_type:
# Field Value.
result += f'|`{current_field["value"]}`'
if 'uncertain' in current_field:
result += '?'
result += '\n'
# Field Name.
result += f'|{current_field["name"]}\n'
# Field Description.
result += f'|{current_field["description"]}\n\n'
# End of Table.
result += '|===\n'
return result
@staticmethod
# pylint: disable=unidiomatic-typecheck
def get_table_row(field_name, field_metadata=None, type_map=None, short_booleans=False):
"""
Generate a single AsciiDoc table row containing field details
(Name, Type, Value, Description).
Args:
field_name (str): The name of the field.
field_metadata (dict, optional):
Metadata for the field, including type, value, description, etc.
type_map (dict, optional):
A map of custom data types.
short_booleans (bool, optional):
If True, represent booleans as 0 or 1 instead of true or false.
Returns:
str: A string containing the AsciiDoc table row with field details.
Note:
This method constructs a table row in AsciiDoc format, presenting field information
including name, type, value, and description. It is used to create tables of fields in
API documentation.
"""
# Field Name.
result = f'|`{field_name}`'
if field_metadata and 'optional' in field_metadata and field_metadata['optional']:
result += ' (Optional)'
result += '\n'
# Field Type.
if type(field_metadata) is dict and 'type' in field_metadata:
field_type = (field_metadata['type'] if 'type' in field_metadata else 'Unknown')
else:
field_type = 'Unknown'
result += f'|{field_type}\n'
# Field Value.
result += '|'
if type(field_metadata) is dict and 'value' in field_metadata:
result += field_metadata['value']
# Did the user provide further details about this field in the field map?
elif (type(field_metadata) is dict
and field_type not in ('Object','Array(Object)','Array(Unknown)')
and (value_name := field_metadata.get('value_name'))):
result += f'`{value_name}`'
# Add an example value if available.
if type_map and value_name in type_map and len(type_map[value_name]) > 0:
result += f' (e.g. `{type_map[value_name][0]["value"]}`)'
else:
result += field_type
# Did the user provide further details about this number field in the field map?
if field_type == 'Number' and field_metadata.get('allow_negative') is False:
result += ' (> 0)'
# Booleans will always be 0 or 1.
elif field_type == 'Boolean':
result += f' (e.g. `{"0` or `1" if short_booleans else "true` or `false"}`)'
result += '\n'
# Field Description. Did the user provide further details about this field in the field map?
result += '|'
# Is "Description" one of the things the user has declared.
if field_metadata and 'description' in field_metadata:
# Add the description.
result += field_metadata['description']
# Is this a field that has a custom type?
if (field_type not in ('Object','Array(Object)','Array(Unknown)')
and (field_value_name:= field_metadata.get('value_name'))):
# Update the description to mark the type.
result += f' In the format `{field_value_name}`.'
else:
# This field is not currently documented.
result += '???'
result += '\n\n'
# Return the result but also any custom types that we referenced.
return result
@staticmethod
def get_table_section(table_name, table, type_map, short_booleans=False, level=3):
"""
Generate an AsciiDoc table section containing field details for the provided table.
Args:
table_name (str): The name of the table.
table (dict): A dictionary of field metadata for the table.
type_map (dict): A map of custom data types.
short_booleans (bool, optional): If True, represent booleans as 0 or 1 instead of true
or false.
level (int, optional): The heading level for the section.
Returns:
tuple: A tuple containing a string of the AsciiDoc table section and a list of used
custom types.
Note:
This method constructs an AsciiDoc table section with field details including name,
type, values and descriptions. The level parameter determines the depth of the heading.
Used custom types are collected and returned as a list.
"""
# Sub Heading.
result = f'\n{"=" * level} {table_name}\n\n'
# Table Header.
result += '[cols=\"1,1,1,2\", options=\"header\"]\n'
result += '|===\n'
result += '|Name\n'
result += '|Type\n'
result += '|Values\n'
result += '|Description\n\n'
# Any used custom types are collected then output after the tables.
used_custom_types = []
# Table Rows (and collect any referenced custom types).
for field_name, field_metadata in table.items():
# Add this row.
result += EndpointDocumentationGenerator.get_table_row(
field_name=field_name,
field_metadata=field_metadata,
type_map=type_map,
short_booleans=short_booleans
)
# Was this a custom type?
# pylint: disable-next=unidiomatic-typecheck
if (type(field_metadata) is dict
and field_metadata.get('type') not in ('Object','Array(Object)','Array(Unknown)')
and (field_value_name:= field_metadata.get('value_name'))):
# We do not want to collect duplicates.
if field_value_name not in used_custom_types:
# Mark that we need to ouput this custom type after this table.
used_custom_types.append(field_value_name)
# End of Table.
result += '|===\n'
return result, used_custom_types
@staticmethod
def get_not_yet_documented():
"""
Generate an AsciiDoc section for endpoints that are not yet documented.
Returns:
str: A string containing the AsciiDoc "Not Yet Documented" section.
Note:
This section serves as a placeholder for endpoints that are currently not documented.
The section informs readers that the documentation is pending.
"""
# Heading.
result = '\n== Request & Response\n\n'
# Placeholder Text.
result += 'This has not yet been documented. Please check back later.\n'
return result
@staticmethod
def process_endpoint(gateway, key, endpoint):
"""
Generate Enphase-API documentation in AsciiDoc format for a specific endpoint.
Args:
gateway (Gateway): An instance of the gateway wrapper.
key (str): The metadata key for the endpoint.
endpoint (dict): A dictionary containing the metadata of the endpoint.
Returns:
bool: True if the documentation was successfully generated, False otherwise.
Note:
This method processes the metadata of a specific API endpoint to generate AsciiDoc
documentation. It handles generating sections for requests, responses, examples,
custom types, and more.
"""
# Skip if the endpoint is not meant to be documented.
if not 'documentation' in endpoint:
print(f'Warning : Skipping \'{key}\' due to lack of \'documentation\' filepath.')
return False
# Count how many sub-folders this file will be under (including the "IQ Gateway API/").
file_depth = endpoint['documentation'].count('/') + 1
# Add the documentation header.
output = EndpointDocumentationGenerator.get_header_section(
name=key.replace('/','-'),
endpoint=endpoint,
file_depth=file_depth
)
# We can specify the custom types of some values.
type_map = (endpoint['type_map'] if 'type_map' in endpoint else None)
# Any used custom types are collected then output after the tables.
used_custom_types = []
# Check this documentation file supports making requests to the endpoint.
if 'request' in endpoint:
# Get a reference to the current endpoint's request details.
endpoint_request = endpoint['request']
# Get a reference to the current endpoint's response details.
endpoint_response = endpoint['response'] if 'response' in endpoint else {}
# Are there any examples?
if 'examples' in endpoint_request:
previous_request_schema = None