Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 272 implement #357

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

We follow semantic versioning.

## Version 1.6.0

### Features

- Adds template variables processing


## Version 1.5.0

Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,26 @@ VALUE=0
VAR=foo
```

You can use template string.

```bash
$ cat template.env
SECRET_ANSWER=42
SECRET_TOKEN=very secret string
SECRET_VALUE=0
SECRET_TEMPLATE=${SECRET_ANSWER}${SECRET_TOKEN}${SECRET_VALUE}
```

Template string must be below the variables that will fill it.

```bash
$ dump-env -t .env.template -p SECRET_
SECRET_ANSWER=42
SECRET_TEMPLATE=42very secret string0
SECRET_TOKEN=very secret string
SECRET_VALUE=0

```
#### Strict Source

Using the `--strict-source` flag has the same effect as defining a `--strict` flag for every variable defined in the source template.
Expand Down
14 changes: 14 additions & 0 deletions dump_env/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ def _create_parser() -> argparse.ArgumentParser:
action='store_true',
help='All source template variables should exist in os envs',
)
parser.add_argument(
'--fill',
action='store_true',
help='Fill variables in .env.template file',
)
return parser


Expand Down Expand Up @@ -95,6 +100,14 @@ def main() -> NoReturn:

$ dump-env -s .env.template --strict-source

This example will fill all variables keys in the source template
from variables in this template file:

.. code:: bash

$ dump-env -s .env.template --fill


"""
args = _create_parser().parse_args()
strict_vars = set(args.strict) if args.strict else None
Expand All @@ -106,6 +119,7 @@ def main() -> NoReturn:
strict_vars,
args.source,
args.strict_source,
args.fill,
)
except StrictEnvError as exc:
sys.stderr.write('{0}\n'.format(str(exc)))
Expand Down
56 changes: 53 additions & 3 deletions dump_env/dumper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Store = Mapping[str, str]

EMPTY_STRING: Final = ''
VAR_TEMPLATE: Final = r'\${([a-zA-Z_]+)}'


def _parse(source: str) -> Store:
Expand All @@ -20,7 +21,7 @@ def _parse(source: str) -> Store:
Store with all keys and values.

"""
parsed_data = {}
parsed_data: Dict[str, str] = {}

with open(source) as env_file:
for line in env_file:
Expand All @@ -35,7 +36,6 @@ def _parse(source: str) -> Store:
env_name = env_name.strip()
env_value = env_value.strip().strip('\'"')
parsed_data[env_name] = env_value

return parsed_data


Expand Down Expand Up @@ -98,12 +98,58 @@ def _source(source: str, strict_source: bool) -> Store:
return sourced


def dump(
def _parse_variable_names(template_var: str) -> List[str]:
"""Parse variables from template string."""
names = []
name_begin_idx: int = -1
name_end_idx: int = -1
for idx in range(len(template_var) - 1):
if template_var[idx] == '$' and template_var[idx + 1] == '{':
name_begin_idx = idx + 2
if template_var[idx + 1] == '}':
name_end_idx = idx + 1
if name_begin_idx < name_end_idx:
names.append(template_var[name_begin_idx: name_end_idx])
name_begin_idx = -1
name_end_idx = -1
return names


def _fill(
store: Dict[str, str],
) -> Dict[str, str]:
"""
Fill template env var if all vars has in store.

Args:
store: Store of env variables

Returns:
Filled store

"""
for key, env_value in store.items():
if '${' in env_value and '}' in env_value:
variables = _parse_variable_names(env_value)
form = {
env_variable: store.get(env_variable)
for env_variable in variables
if store.get(env_variable) is not None
}
if form and len(form.keys()) == len(variables):
filled_value = env_value.format(**form)
filled_value = filled_value.replace('$', '')
store[key] = filled_value
return store


def dump( # noqa: WPS211, C901
template: str = EMPTY_STRING,
prefixes: Optional[List[str]] = None,
strict_keys: Optional[Set[str]] = None,
source: str = EMPTY_STRING,
strict_source: bool = False,
fill: bool = False,
) -> Dict[str, str]:
"""
This function is used to dump ``.env`` files.
Expand All @@ -129,6 +175,8 @@ def dump(
strict_source: Whether all keys in source template must also be
presented in env vars.

fill: Fill all variables in template env file.

Returns:
Ordered key-value pairs of dumped env and template variables.

Expand Down Expand Up @@ -156,5 +204,7 @@ def dump(
for prefix in prefixes:
store.update(_preload_existing_vars(prefix))

if fill:
store.update(_fill(store))
# Sort keys and keep them ordered:
return OrderedDict(sorted(store.items()))
Loading
Loading