Skip to content

Commit

Permalink
Fix traceback when not passing file to -o option (#698)
Browse files Browse the repository at this point in the history
If precli-init is run without an argument for the -o, it will fail with
a traceback due to the argparse.FileType not allowing a default of a str
for a file name.

This change does the logic of detecting and opening files manually on
its own. It will present an error if the file already exists to prevent
overwriting. Except in the case where the file is pyproject.toml and the
settings will be appended to it.

Signed-off-by: Eric Brown <eric.brown@securesauce.dev>
  • Loading branch information
ericwb authored Nov 13, 2024
1 parent 8905f37 commit 0d609cb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 11 deletions.
12 changes: 10 additions & 2 deletions precli/cli/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,20 @@ def setup_arg_parser() -> Namespace:
"--output",
dest="output",
action="store",
type=argparse.FileType("x", encoding="utf-8"),
type=str,
default=".precli.toml",
help="output the config to given file",
help="output the config to given file (default: .precli.toml)",
)
args = parser.parse_args()

# Prevent overwriting output files except appending to pyproject.toml
path = pathlib.Path(args.output)
if path.exists() and path.name != "pyproject.toml":
parser.error(
f"argument -o/--output: can't open '{args.output}': [Errno 17] "
f"File exists: '{args.output}'"
)

return args


Expand Down
9 changes: 0 additions & 9 deletions tests/unit/cli/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@

class TestInit:
@classmethod
def test_main_invalid_output(self, monkeypatch):
monkeypatch.setattr(
"sys.argv",
["precli-init", "-o", "../does/not/exist"],
)
with pytest.raises(SystemExit) as excinfo:
init.main()
assert excinfo.value.code == 2

def test_main_output_already_exists(self, monkeypatch, capsys):
temp_dir = tempfile.mkdtemp()
output_path = os.path.join(temp_dir, "output.txt")
Expand Down

0 comments on commit 0d609cb

Please sign in to comment.