Document handling of file objects internally in CLI
Marco Ricci

Marco Ricci commited on 2024-12-19 15:27:08
Zeige 1 geänderte Dateien mit 20 Einfügungen und 4 Löschungen.


The type hints for `click.open_file` are so broad that our file objects,
intended to be typed as `typing.TextIO`, end up getting typed as
`typing.TextIO | typing.IO[typing.Any]` instead.  Fix this by casting,
explicitly, one level higher.  Also document why no further checks for
readability or writablility are actually performed.
... ...
@@ -1962,11 +1962,19 @@ def derivepassphrase_vault(  # noqa: C901,PLR0912,PLR0913,PLR0914,PLR0915
1962 1962
         try:
1963 1963
             # TODO(the-13th-letter): keep track of auto-close; try
1964 1964
             # os.dup if feasible
1965
-            infile = (
1966
-                cast(TextIO, import_settings)
1965
+            infile = cast(
1966
+                TextIO,
1967
+                (
1968
+                    import_settings
1967 1969
                     if hasattr(import_settings, 'close')
1968 1970
                     else click.open_file(os.fspath(import_settings), 'rt')
1971
+                ),
1969 1972
             )
1973
+            # Don't specifically catch TypeError or ValueError here if
1974
+            # the passed-in fileobj is not a readable text stream.  This
1975
+            # will never happen on the command-line (thanks to `click`),
1976
+            # and for programmatic use, our caller may want accurate
1977
+            # error information.
1970 1978
             with infile:
1971 1979
                 maybe_config = json.load(infile)
1972 1980
         except json.JSONDecodeError as e:
... ...
@@ -2050,11 +2058,19 @@ def derivepassphrase_vault(  # noqa: C901,PLR0912,PLR0913,PLR0914,PLR0915
2050 2058
         try:
2051 2059
             # TODO(the-13th-letter): keep track of auto-close; try
2052 2060
             # os.dup if feasible
2053
-            outfile = (
2054
-                cast(TextIO, export_settings)
2061
+            outfile = cast(
2062
+                TextIO,
2063
+                (
2064
+                    export_settings
2055 2065
                     if hasattr(export_settings, 'close')
2056 2066
                     else click.open_file(os.fspath(export_settings), 'wt')
2067
+                ),
2057 2068
             )
2069
+            # Don't specifically catch TypeError or ValueError here if
2070
+            # the passed-in fileobj is not a writable text stream.  This
2071
+            # will never happen on the command-line (thanks to `click`),
2072
+            # and for programmatic use, our caller may want accurate
2073
+            # error information.
2058 2074
             with outfile:
2059 2075
                 json.dump(configuration, outfile)
2060 2076
         except OSError as e:
2061 2077