diff --git a/README.md b/README.md index 2a7c3fc..b3679e9 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,9 @@ options: --verbose Display debug information for each request ``` +Set `OPENCAGE_GEOCODING_API_KEY` to avoid passing your API key on the command +line. A supplied `--api-key` takes precedence over the environment variable. + See [`examples/addresses.csv`](examples/addresses.csv) for sample input. diff --git a/opencage_cli/command_line.py b/opencage_cli/command_line.py index 341a438..569ad0d 100644 --- a/opencage_cli/command_line.py +++ b/opencage_cli/command_line.py @@ -1,6 +1,7 @@ import argparse import sys import io +import os from pathlib import Path import re import csv @@ -52,7 +53,12 @@ def parse_args(args): 'reverse', help="Reverse geocode a file (input is coordinates, add full address)") for subparser in [subparser_forward, subparser_reverse]: - subparser.add_argument("--api-key", required=True, type=api_key_type, help="Your OpenCage API key") + subparser.add_argument( + "--api-key", + default=os.environ.get("OPENCAGE_GEOCODING_API_KEY"), + required="OPENCAGE_GEOCODING_API_KEY" not in os.environ, + type=api_key_type, + help="Your OpenCage API key (or OPENCAGE_GEOCODING_API_KEY environment variable)") subparser.add_argument( "--input", required=True, diff --git a/test/cli/test_cli_args.py b/test/cli/test_cli_args.py index 28b7726..339137e 100644 --- a/test/cli/test_cli_args.py +++ b/test/cli/test_cli_args.py @@ -61,6 +61,31 @@ def test_invalid_api_key(capfd): ) +def test_api_key_from_environment(monkeypatch): + monkeypatch.setenv("OPENCAGE_GEOCODING_API_KEY", "oc_gc_12345678901234567890123456789012") + + args = parse_args([ + "forward", + "--input", "test/fixtures/input.txt", + "--output", "test/fixtures/output.csv" + ]) + + assert args.api_key == "oc_gc_12345678901234567890123456789012" + + +def test_command_line_api_key_overrides_environment(monkeypatch): + monkeypatch.setenv("OPENCAGE_GEOCODING_API_KEY", "oc_gc_12345678901234567890123456789012") + + args = parse_args([ + "forward", + "--api-key", "12345678901234567890123456789012", + "--input", "test/fixtures/input.txt", + "--output", "test/fixtures/output.csv" + ]) + + assert args.api_key == "12345678901234567890123456789012" + + def test_existing_output_file(capfd): assert_parse_args_error( [