openapi-spec-tools 0.15.0__tar.gz → 0.17.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/PKG-INFO +1 -1
  2. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/api_gen/_environment.py +2 -3
  3. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/api_gen/api_generator.py +5 -6
  4. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/base_gen/_logging.py +2 -3
  5. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/base_gen/_requests.py +20 -21
  6. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/base_gen/base_generator.py +8 -9
  7. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/base_gen/utils.py +2 -11
  8. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli/arguments.py +5 -6
  9. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli/cli_gen.py +6 -7
  10. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli/history.py +148 -52
  11. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli/layout.py +8 -0
  12. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli/oas.py +8 -9
  13. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli_gen/_arguments.py +2 -3
  14. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli_gen/_tree.py +10 -11
  15. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli_gen/cli_generator.py +42 -12
  16. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/layout/layout_generator.py +12 -14
  17. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/layout/types.py +42 -10
  18. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/layout/utils.py +62 -3
  19. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/utils.py +6 -8
  20. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/pyproject.toml +1 -1
  21. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/test_cli_generator.py +101 -35
  22. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/LICENSE +0 -0
  23. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/README.md +0 -0
  24. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/__init__.py +0 -0
  25. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/api_gen/files.py +0 -0
  26. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/api_gen/flat_generator.py +0 -0
  27. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/api_gen/opaque_generator.py +0 -0
  28. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/api_gen/property_generator.py +0 -0
  29. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/base_gen/constants.py +0 -0
  30. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/base_gen/files.py +0 -0
  31. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli/api_gen.py +0 -0
  32. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli/utils.py +0 -0
  33. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli_gen/_display.py +0 -0
  34. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli_gen/_exceptions.py +0 -0
  35. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli_gen/constants.py +0 -0
  36. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/cli_gen/files.py +0 -0
  37. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/layout/merge.py +0 -0
  38. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/openapi_spec_tools/types.py +0 -0
  39. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/__init__.py +0 -0
  40. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/helpers.py +0 -0
  41. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/test_display.py +0 -0
  42. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/test_exceptions.py +0 -0
  43. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/test_files.py +0 -0
  44. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/test_main.py +0 -0
  45. {openapi_spec_tools-0.15.0 → openapi_spec_tools-0.17.0}/tests/cli_gen/test_tree.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: openapi-spec-tools
3
- Version: 0.15.0
3
+ Version: 0.17.0
4
4
  Summary: OpenAPI specification tools for analyzing, updating, and generating a CLI.
5
5
  License-File: LICENSE
6
6
  Author: Rick Porter
@@ -1,8 +1,7 @@
1
1
  import os
2
- from typing import Optional
3
2
 
4
3
 
5
- def env_string(varname: str, default: Optional[str] = None, except_missing: bool = False) -> Optional[str]:
4
+ def env_string(varname: str, default: str | None = None, except_missing: bool = False) -> str | None:
6
5
  value = os.environ.get(varname)
7
6
  if value is not None:
8
7
  return value
@@ -11,7 +10,7 @@ def env_string(varname: str, default: Optional[str] = None, except_missing: bool
11
10
  return default
12
11
 
13
12
 
14
- def env_int(varname: str, default: Optional[int] = None, except_missing: bool = False) -> Optional[int]:
13
+ def env_int(varname: str, default: int | None = None, except_missing: bool = False) -> int | None:
15
14
  value = os.environ.get(varname)
16
15
  if value is not None:
17
16
  return int(value)
@@ -95,7 +95,6 @@ from datetime import date # noqa: F401
95
95
  from datetime import datetime # noqa: F401
96
96
  from enum import Enum # noqa: F401
97
97
  from typing import Any
98
- from typing import Optional # noqa: F401
99
98
 
100
99
  from {self.package_name} import _environment as _e # noqa: F401
101
100
  from {self.package_name} import _logging as _l # noqa: F401
@@ -132,10 +131,10 @@ from {self.package_name} import _requests as _r # noqa: F401
132
131
  )
133
132
  log_help = f'log level, read from {self.env_log_level} if not provided, defaults to {self.default_log}'
134
133
  args = [
135
- f'_api_host: Optional[str] = None, # {host_help}',
136
- f'_api_key: Optional[str] = None, # {key_help}',
137
- f'_api_timeout: Optional[int] = None, # {timeout_help}',
138
- f'_log_level: Optional[str] = None, # {log_help}',
134
+ f'_api_host: str | None = None, # {host_help}',
135
+ f'_api_key: str | None = None, # {key_help}',
136
+ f'_api_timeout: int | None = None, # {timeout_help}',
137
+ f'_log_level: str | None = None, # {log_help}',
139
138
  ]
140
139
  return args
141
140
 
@@ -158,7 +157,7 @@ from {self.package_name} import _requests as _r # noqa: F401
158
157
  arg_default = ""
159
158
  else:
160
159
  if not required:
161
- py_type = f"Optional[{py_type}]"
160
+ py_type = f"{py_type} | None"
162
161
  if schema_default is None:
163
162
  arg_default = " = None"
164
163
  elif collection and not isinstance(schema_default, list):
@@ -1,6 +1,5 @@
1
1
  import logging
2
2
  from enum import Enum
3
- from typing import Optional
4
3
 
5
4
  LOG_CLASS = "cli"
6
5
  LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s %(message)s"
@@ -15,11 +14,11 @@ class LogLevel(str, Enum):
15
14
  DEBUG = "debug"
16
15
 
17
16
 
18
- def get_logger(name: Optional[str] = LOG_CLASS) -> logging.Logger:
17
+ def get_logger(name: str | None = LOG_CLASS) -> logging.Logger:
19
18
  return logging.getLogger(name=name)
20
19
 
21
20
 
22
- def init_logging(level: LogLevel, name: Optional[str] = LOG_CLASS) -> logging.Logger:
21
+ def init_logging(level: LogLevel, name: str | None = LOG_CLASS) -> logging.Logger:
23
22
  logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE_FMT)
24
23
  logger = get_logger(name)
25
24
  logger.setLevel(level.upper())
@@ -9,7 +9,6 @@ from copy import deepcopy
9
9
  from datetime import datetime
10
10
  from datetime import timedelta
11
11
  from typing import Any
12
- from typing import Optional
13
12
 
14
13
  import requests
15
14
  import yaml
@@ -65,26 +64,26 @@ class PageParams(BaseModel):
65
64
  """Holds optional pagination parameter names and values."""
66
65
 
67
66
  # page_size_* dictate the limit per request
68
- page_size_value: Optional[int] = None
69
- page_size_name: Optional[str] = None
67
+ page_size_value: int | None = None
68
+ page_size_name: str | None = None
70
69
 
71
70
  # page_start_* dictate the starting point when it is in page increments
72
- page_start_value: Optional[int] = None
73
- page_start_name: Optional[str] = None
71
+ page_start_value: int | None = None
72
+ page_start_name: str | None = None
74
73
 
75
74
  # offset_start_* dictate the starting point when it is specified in item increments
76
- item_start_value: Optional[int] = None
77
- item_start_name: Optional[str] = None
75
+ item_start_value: int | None = None
76
+ item_start_name: str | None = None
78
77
 
79
78
  # max_count specifies the maximim number of items to fetch
80
- max_count: Optional[int] = None
79
+ max_count: int | None = None
81
80
 
82
81
  # items property specifies the property name to pull out the data from
83
- items_property_name: Optional[str] = None
82
+ items_property_name: str | None = None
84
83
 
85
84
  # locations for next url
86
- next_header_name: Optional[str] = None
87
- next_property_name: Optional[str] = None
85
+ next_header_name: str | None = None
86
+ next_property_name: str | None = None
88
87
 
89
88
 
90
89
  def create_url(host_or_base_url: str, *args) -> str:
@@ -104,8 +103,8 @@ def create_url(host_or_base_url: str, *args) -> str:
104
103
 
105
104
 
106
105
  def request_headers(
107
- api_key: Optional[str] = None,
108
- content_type: Optional[str] = None,
106
+ api_key: str | None = None,
107
+ content_type: str | None = None,
109
108
  **kwargs,
110
109
  ) -> dict[str, str]:
111
110
  """Create a set of request headers based on the arguments.
@@ -148,7 +147,7 @@ def raise_for_error(response: requests.Response) -> None:
148
147
  raise requests.HTTPError(message, response=response)
149
148
 
150
149
 
151
- def _pretty_params(params: Optional[dict[str, Any]]) -> str:
150
+ def _pretty_params(params: dict[str, Any] | None) -> str:
152
151
  if not params:
153
152
  return ""
154
153
 
@@ -158,10 +157,10 @@ def _pretty_params(params: Optional[dict[str, Any]]) -> str:
158
157
  def request(
159
158
  method: str,
160
159
  url: str,
161
- headers: Optional[dict[str, Any]] = None,
162
- params: Optional[dict[str, Any]] = None,
163
- body: Optional[dict[str, Any]] = None,
164
- timeout: Optional[int] = None,
160
+ headers: dict[str, Any] | None = None,
161
+ params: dict[str, Any] | None = None,
162
+ body: dict[str, Any] | None = None,
163
+ timeout: int | None = None,
165
164
  **kwargs, # allows passing through additional named parameters
166
165
  ) -> Any:
167
166
  """Perform the specified REST request."""
@@ -213,9 +212,9 @@ def request(
213
212
  def depaginate(
214
213
  page_params: PageParams,
215
214
  url: str,
216
- headers: Optional[dict[str, Any]] = None,
217
- params: Optional[dict[str, Any]] = None,
218
- timeout: Optional[int] = None,
215
+ headers: dict[str, Any] | None = None,
216
+ params: dict[str, Any] | None = None,
217
+ timeout: int | None = None,
219
218
  ) -> Any:
220
219
  """Get a list of items that may be chunked across several pages."""
221
220
  items = []
@@ -3,7 +3,6 @@ import logging
3
3
  import textwrap
4
4
  from copy import deepcopy
5
5
  from typing import Any
6
- from typing import Optional
7
6
 
8
7
  from openapi_spec_tools.base_gen._logging import init_logging
9
8
  from openapi_spec_tools.base_gen.constants import COLLECTIONS
@@ -72,7 +71,7 @@ class BaseGenerator:
72
71
  def __init__(
73
72
  self,
74
73
  oas: dict[str, Any],
75
- logger: Optional[logging.Logger] = None,
74
+ logger: logging.Logger | None = None,
76
75
  supported_content: list[ContentType] = DEFAULT_SUPPORTED_CONTENT,
77
76
  max_help_length: int = DEFAULT_MAX_HELP_LENGTH,
78
77
  reserved: set[str] = DEFAULT_RESERVED,
@@ -277,7 +276,7 @@ class BaseGenerator:
277
276
  """Get the `content` (if any) from the `requestBody`."""
278
277
  return operation.get(OasField.REQ_BODY, {}).get(OasField.CONTENT, {})
279
278
 
280
- def op_get_content_type(self, operation: dict[str, Any]) -> Optional[str]:
279
+ def op_get_content_type(self, operation: dict[str, Any]) -> str | None:
281
280
  """Get the first content-type matching a supported type."""
282
281
  content = self.op_request_content(operation)
283
282
  for ct in self.supported:
@@ -285,7 +284,7 @@ class BaseGenerator:
285
284
  return ct.value
286
285
  return None
287
286
 
288
- def op_request_body(self, operation: dict[str, Any]) -> Optional[dict[str, Any]]:
287
+ def op_request_body(self, operation: dict[str, Any]) -> dict[str, Any] | None:
289
288
  """Get the first request body matching a supported type."""
290
289
  content = self.op_request_content(operation)
291
290
  for ct in self.supported:
@@ -295,7 +294,7 @@ class BaseGenerator:
295
294
 
296
295
  return None
297
296
 
298
- def model_collection_type(self, model: str) -> Optional[str]:
297
+ def model_collection_type(self, model: str) -> str | None:
299
298
  """Determine the collection type (current just an array)."""
300
299
  model_type = self.simplify_type(model.get(OasField.TYPE))
301
300
  if model_type in COLLECTIONS.keys():
@@ -483,7 +482,7 @@ class BaseGenerator:
483
482
 
484
483
  return properties
485
484
 
486
- def schema_to_type(self, schema: str, fmt: Optional[str]) -> Optional[str]:
485
+ def schema_to_type(self, schema: str, fmt: str | None) -> str | None:
487
486
  """Get the base Python type for simple schema types.
488
487
 
489
488
  The fmt is really the "format" field, but renamed to avoid masking builtin.
@@ -528,7 +527,7 @@ class BaseGenerator:
528
527
  return None
529
528
 
530
529
 
531
- def schema_to_pytype(self, schema: dict[str, Any]) -> Optional[str]:
530
+ def schema_to_pytype(self, schema: dict[str, Any]) -> str | None:
532
531
  """Determine the basic Python type from the schema object."""
533
532
  oas_type = self.simplify_type(schema.get(OasField.TYPE))
534
533
  oas_format = schema.get(OasField.FORMAT)
@@ -554,7 +553,7 @@ class BaseGenerator:
554
553
 
555
554
  return None
556
555
 
557
- def get_property_pytype(self, prop_name: str, prop_data: dict[str, Any]) -> Optional[str]:
556
+ def get_property_pytype(self, prop_name: str, prop_data: dict[str, Any]) -> str | None:
558
557
  """Get the "basic" Python type from a property object.
559
558
 
560
559
  Each property potentially has 'type' and 'format' fields.
@@ -577,7 +576,7 @@ class BaseGenerator:
577
576
  if collection:
578
577
  pytype = f"{collection}[{pytype}]"
579
578
  if not prop_data.get(OasField.REQUIRED):
580
- pytype = f"Optional[{pytype}]"
579
+ pytype = f"{pytype} | None"
581
580
 
582
581
  return pytype
583
582
 
@@ -9,14 +9,7 @@ SIMPLE_TRANSLATIONS = str.maketrans(
9
9
  '"': r"\"",
10
10
  },
11
11
  )
12
- SPECIAL_CHARS = [
13
- # mathematical
14
- '/', '*', '+', '-', '^', '%', '&', '|', '~', '<', '>','=',
15
- # operators/punctional
16
- '.', '@', ' ', ':', ';', '#', ',', '!', '`', '?', '\'', '"',
17
- # parenthesis/brackets
18
- '(', ')', '{', '}', '[', ']',
19
- ]
12
+ SPECIAL_CHARS = re.compile(r'([^a-zA-Z0-9])+')
20
13
 
21
14
 
22
15
  def to_snake_case(text: str) -> str:
@@ -47,9 +40,7 @@ def quoted(s: str) -> str:
47
40
  def replace_special(value: str, replacement: str = '_') -> str:
48
41
  """Replace the "special" characters with the replacement."""
49
42
  _replacement = '' if replacement is None else replacement
50
- for v in SPECIAL_CHARS:
51
- value = value.replace(v, _replacement)
52
- return value
43
+ return SPECIAL_CHARS.sub(_replacement, value)
53
44
 
54
45
 
55
46
  def simple_escape(text: str) -> str:
@@ -1,7 +1,6 @@
1
1
  """typer argument definitions to improve consistency amongst CLI commands."""
2
2
  from enum import Enum
3
3
  from typing import Annotated
4
- from typing import Optional
5
4
 
6
5
  import typer
7
6
  from rich_objects import OutputFormat
@@ -21,11 +20,11 @@ class LogLevel(str, Enum):
21
20
 
22
21
 
23
22
  CodeDirectoryOption = Annotated[
24
- Optional[str],
23
+ str | None,
25
24
  typer.Option("--code-dir", metavar=DIRECTORY, show_default=False, help="Directory for code -- overrides default")
26
25
  ]
27
26
  CopyrightFileOption = Annotated[
28
- Optional[str],
27
+ str | None,
29
28
  typer.Option(
30
29
  "--copyright-file",
31
30
  metavar=FILENAME,
@@ -47,7 +46,7 @@ LayoutFilenameArgument = Annotated[
47
46
  typer.Argument(metavar=FILENAME, show_default=False, help="Layout file YAML definition"),
48
47
  ]
49
48
  LayoutFilenameOption = Annotated[
50
- Optional[str],
49
+ str | None,
51
50
  typer.Option(
52
51
  "--layout-file",
53
52
  metavar=FILENAME,
@@ -64,7 +63,7 @@ LogLevelOption = Annotated[
64
63
  ),
65
64
  ]
66
65
  MaxCountOption = Annotated[
67
- Optional[int],
66
+ int | None,
68
67
  typer.Option(
69
68
  "--max",
70
69
  "--max-count",
@@ -98,7 +97,7 @@ PathPrefixOption = Annotated[
98
97
  ]
99
98
  StartPointOption = Annotated[str, typer.Option("--start", metavar="START", help="Start point for CLI in layout file")]
100
99
  UpdatedOpenApiFilenameOption = Annotated[
101
- Optional[str],
100
+ str | None,
102
101
  typer.Option(
103
102
  "--updated-file",
104
103
  metavar=FILENAME,
@@ -5,7 +5,6 @@ from copy import deepcopy
5
5
  from pathlib import Path
6
6
  from typing import Annotated
7
7
  from typing import Any
8
- from typing import Optional
9
8
 
10
9
  import typer
11
10
  import yaml
@@ -80,12 +79,12 @@ def generate_cli(
80
79
  package_name: PackageNameArgument,
81
80
  layout_file: LayoutFilenameOption = None,
82
81
  project_dir: Annotated[
83
- Optional[str],
82
+ str | None,
84
83
  typer.Option(metavar=DIRECTORY, show_default=False, help="Project directory name")
85
84
  ] = None,
86
85
  code_dir: CodeDirectoryOption = None,
87
86
  test_dir: Annotated[
88
- Optional[str],
87
+ str | None,
89
88
  typer.Option(metavar=DIRECTORY, show_default=False, help="Directory for tests -- overrides default")
90
89
  ] = None,
91
90
  copyright_file: CopyrightFileOption = None,
@@ -222,7 +221,7 @@ def find_parent(
222
221
  operations: dict[str, Any],
223
222
  path_parts: list[str],
224
223
  prefix: str,
225
- ) -> Optional[LayoutNode]:
224
+ ) -> LayoutNode | None:
226
225
  """Find the parent node (if any) where an operation matches the path parts.
227
226
 
228
227
  The LayoutNode's only know the operationId (not the path), so the operations are needed to
@@ -247,7 +246,7 @@ def update_layout(
247
246
  layout_file: LayoutFilenameArgument,
248
247
  openapi_file: OpenApiFilenameArgument,
249
248
  new_file: Annotated[
250
- Optional[str],
249
+ str | None,
251
250
  typer.Option(metavar="FILENAME", help="New filename (if different than original)")
252
251
  ] = None,
253
252
  start: StartPointOption = DEFAULT_START,
@@ -299,7 +298,7 @@ def show_cli_tree(
299
298
  ] = TreeDisplay.ALL,
300
299
  max_depth: Annotated[int, typer.Option(metavar="DEPTH", help="Maximum tree depth to show")] = 10,
301
300
  search: Annotated[
302
- Optional[str],
301
+ str | None,
303
302
  typer.Option(metavar="NEEDLE", help="Only show the tree for items with this needle.")
304
303
  ] = None,
305
304
  log_level: LogLevelOption = "info",
@@ -330,7 +329,7 @@ def trim_oas(
330
329
  openapi_file: OpenApiFilenameArgument,
331
330
  updated_file: UpdatedOpenApiFilenameOption = None,
332
331
  remove_properties: Annotated[
333
- Optional[list[str]],
332
+ list[str] | None,
334
333
  typer.Option("--remove", metavar="PROPERTIES", show_default=False, help="List of properties to remove."),
335
334
  ] = None,
336
335
  start: StartPointOption = DEFAULT_START,
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env python3
2
2
  """Implement the 'oas-history' CLI commands."""
3
+ import re
3
4
  from datetime import datetime
4
5
  from datetime import timezone
5
6
  from pathlib import Path
6
7
  from typing import Annotated
7
8
  from typing import Any
8
- from typing import Optional
9
9
 
10
10
  import git
11
11
  import typer
@@ -23,19 +23,28 @@ from openapi_spec_tools.cli.arguments import OutputStyleOption
23
23
  from openapi_spec_tools.cli.utils import error_out
24
24
  from openapi_spec_tools.utils import find_diffs
25
25
 
26
+ MIN_HASH_LENGTH = 4
27
+ NON_HEX_RE = re.compile(r'[^a-fA-F0-9]')
28
+
29
+
26
30
  app = typer.Typer(name="history", no_args_is_help=True, short_help="Git history of OAS file")
27
31
 
28
32
 
29
33
  AuthorOption = Annotated[
30
- Optional[str],
31
- typer.Option("--author", show_default=False, help="Name, or partial name, of author or coauthor (case insensitive)")
34
+ str | None,
35
+ typer.Option(
36
+ "--author",
37
+ metavar="NAME",
38
+ show_default=False,
39
+ help="Name, or partial name, of author or coauthor (case insensitive)",
40
+ )
32
41
  ]
33
42
  EndDateOption = Annotated[
34
- Optional[datetime],
43
+ datetime | None,
35
44
  typer.Option("--end", show_default=False, help="Date/time of latest commit.")
36
45
  ]
37
46
  StartDateOption = Annotated[
38
- Optional[datetime],
47
+ datetime | None,
39
48
  typer.Option("--start", show_default=False, help="Date/time of first commit.")
40
49
  ]
41
50
 
@@ -72,12 +81,30 @@ def _author_match(commit: git.Commit, author: str) -> bool:
72
81
  return False
73
82
 
74
83
 
84
+ def _shorthash(commit: git.Commit) -> str:
85
+ """Get a shortened version of the commit hash."""
86
+ return commit.hexsha[:7]
87
+
88
+
89
+ def _commithash(hash: str) -> str:
90
+ """Perform basic checks on the provided hash.
91
+
92
+ If the hash does NOT meet the standard, an exception is thrown and a meaningful
93
+ message provided.
94
+ """
95
+ if len(hash) < MIN_HASH_LENGTH:
96
+ error_out(f"Hash must be at least {MIN_HASH_LENGTH} characters")
97
+ if NON_HEX_RE.search(hash):
98
+ error_out("Hash must be all hexidecimal characters")
99
+ return hash.lower()
100
+
101
+
75
102
  def _find_commits(
76
103
  oas_file: str,
77
- start: Optional[datetime] = None,
78
- end: Optional[datetime] = None,
79
- author: Optional[str] = None,
80
- max_count: Optional[int] = None,
104
+ start: datetime | None = None,
105
+ end: datetime | None = None,
106
+ author: str | None = None,
107
+ max_count: int | None = None,
81
108
  ) -> list[git.Commit]:
82
109
  """Get a list of commits for the provided file and parameters."""
83
110
  repo = git.Repo(oas_file, search_parent_directories=True)
@@ -95,6 +122,33 @@ def _find_commits(
95
122
  return commits
96
123
 
97
124
 
125
+ def _get_commit(
126
+ oas_file: str,
127
+ commit_id: str,
128
+ ) -> git.Commit | None:
129
+ """Search the commits looking for a match."""
130
+ repo = git.Repo(oas_file, search_parent_directories=True)
131
+ for tag in repo.tags:
132
+ if commit_id == tag.name:
133
+ return tag.commit
134
+
135
+ for branch in repo.branches:
136
+ if commit_id == branch.name:
137
+ # unfortunatley, testing in CI pipeline complicates covering this too much
138
+ return branch.commit # pragma: no cover
139
+
140
+
141
+ for commit in repo.iter_commits(paths=oas_file):
142
+ if not commit_id:
143
+ # gets the latest commit if no commit is specified
144
+ return commit
145
+
146
+ if commit_id.lower() in commit.hexsha:
147
+ return commit
148
+
149
+ error_out(f"Unable to find specified commit for '{commit_id}'")
150
+
151
+
98
152
  def _assert_exists(file: str) -> None:
99
153
  """Assert that the file exists in the git repo, or throw an exception."""
100
154
  try:
@@ -106,46 +160,6 @@ def _assert_exists(file: str) -> None:
106
160
  error_out("Unable to find file")
107
161
 
108
162
 
109
- @app.command("commits", short_help="Show git history of the specified OAS file.")
110
- def commit_history(
111
- oas_file: OpenApiFilenameArgument,
112
- start: StartDateOption = None,
113
- end: EndDateOption = None,
114
- author: AuthorOption = None,
115
- max_count: MaxCountOption = 30,
116
- out_fmt: OutputFormatOption = OutputFormat.TABLE,
117
- out_style: OutputStyleOption = OutputStyle.ALL,
118
- ):
119
- """Show git history of the specific OAS file over with the provided search parameters."""
120
- _assert_exists(oas_file)
121
- start = _with_timezone(start)
122
- end = _with_timezone(end)
123
- commits = _find_commits(
124
- oas_file=oas_file,
125
- start=start,
126
- end=end,
127
- author=author,
128
- max_count=max_count,
129
- )
130
- console = console_factory()
131
- if not commits:
132
- console.print("No commits found.")
133
- return
134
-
135
- columns = ["date", "commit", "*"]
136
- data = [
137
- {
138
- "date": _.authored_datetime.date().isoformat(),
139
- "commit": _.hexsha[:7],
140
- "author": _.author.name,
141
- "message": _.message.strip()[:100],
142
- }
143
- for _ in commits
144
- ]
145
- display(data, fmt=out_fmt, style=out_style, columns=columns, console=console)
146
- return
147
-
148
-
149
163
  @app.command("changes", short_help="Show OAS changes over git history.")
150
164
  def commit_changes(
151
165
  oas_file: OpenApiFilenameArgument,
@@ -180,7 +194,7 @@ def commit_changes(
180
194
  data.append(
181
195
  {
182
196
  "date": prev_comm.authored_datetime.date().isoformat(),
183
- "commit": prev_comm.hexsha[:7],
197
+ "commit": _shorthash(prev_comm),
184
198
  "changes": changes,
185
199
  }
186
200
  )
@@ -202,19 +216,101 @@ def commit_changes(
202
216
  return
203
217
 
204
218
 
219
+ @app.command("commits", short_help="Show git history of the specified OAS file.")
220
+ def commit_history(
221
+ oas_file: OpenApiFilenameArgument,
222
+ start: StartDateOption = None,
223
+ end: EndDateOption = None,
224
+ author: AuthorOption = None,
225
+ max_count: MaxCountOption = 30,
226
+ out_fmt: OutputFormatOption = OutputFormat.TABLE,
227
+ out_style: OutputStyleOption = OutputStyle.ALL,
228
+ ):
229
+ """Show git history of the specific OAS file over with the provided search parameters."""
230
+ _assert_exists(oas_file)
231
+ start = _with_timezone(start)
232
+ end = _with_timezone(end)
233
+ commits = _find_commits(
234
+ oas_file=oas_file,
235
+ start=start,
236
+ end=end,
237
+ author=author,
238
+ max_count=max_count,
239
+ )
240
+ console = console_factory()
241
+ if not commits:
242
+ console.print("No commits found.")
243
+ return
244
+
245
+ columns = ["date", "commit", "*"]
246
+ data = [
247
+ {
248
+ "date": _.authored_datetime.date().isoformat(),
249
+ "commit": _shorthash(_),
250
+ "author": _.author.name,
251
+ "message": _.message.strip()[:100],
252
+ }
253
+ for _ in commits
254
+ ]
255
+ display(data, fmt=out_fmt, style=out_style, columns=columns, console=console)
256
+ return
257
+
258
+
259
+ @app.command("diff", short_help="Show difference between two points in OAS history.")
260
+ def commit_diff(
261
+ oas_file: OpenApiFilenameArgument,
262
+ commit_id: Annotated[
263
+ str,
264
+ typer.Argument(metavar="COMMIT[..COMMIT]", help="Commit hash(es), tag(s), or branch(es)"),
265
+ ],
266
+ out_fmt: OutputFormatOption = OutputFormat.TABLE,
267
+ out_style: OutputStyleOption = OutputStyle.ALL,
268
+ ):
269
+ _assert_exists(oas_file)
270
+
271
+ parts = commit_id.split("..", maxsplit=1)
272
+ start_comm = _get_commit(oas_file, parts[0])
273
+ end_comm = _get_commit(oas_file, parts[1] if len(parts) > 1 else None)
274
+
275
+ console = console_factory()
276
+
277
+ start_data = _read_data(start_comm, oas_file)
278
+ end_data = _read_data(end_comm, oas_file)
279
+ changes = find_diffs(start_data, end_data)
280
+ if not changes:
281
+ console.print("Unable to determine differences.")
282
+ return
283
+
284
+ if out_fmt == OutputFormat.TABLE:
285
+ # YAML format is the best looking format for the diffs in a table, so force it
286
+ changes = yaml.dump(changes).strip()
287
+
288
+ columns = ["commits", "changes"]
289
+ data = [
290
+ {
291
+ "commits": f"{_shorthash(start_comm)}..{_shorthash(end_comm)}",
292
+ "changes": changes,
293
+ }
294
+ ]
295
+
296
+ config = TableConfig(value_max_len=1000)
297
+ display(data, fmt=out_fmt, style=out_style, columns=columns, config=config, console=console)
298
+ return
299
+
300
+
205
301
  @app.command("show", short_help="Show single OAS change in git history.")
206
302
  def commit_show(
207
303
  oas_file: OpenApiFilenameArgument,
208
304
  commit: Annotated[
209
305
  str | None,
210
- typer.Argument(help="Commit hash"),
306
+ typer.Argument(metavar="HASH", help="Commit hash"),
211
307
  ],
212
308
  out_fmt: OutputFormatOption = OutputFormat.TABLE,
213
309
  out_style: OutputStyleOption = OutputStyle.ALL,
214
310
  ):
215
311
  """Show OAS changes over the history of the provided search. The ."""
216
312
  _assert_exists(oas_file)
217
- _commit_id = commit.lower()
313
+ _commit_id = _commithash(commit)
218
314
  # NOTE: do not filter out commits by other authors, or before start, or will get odd comparisons
219
315
  commits = _find_commits(oas_file=oas_file)
220
316
  columns = ["date", "commit", "changes"]