zenv-cli 0.4.3__tar.gz → 0.5.1__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.
@@ -1,3 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: zenv-cli
3
+ Version: 0.5.1
4
+ Summary:
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: cli,docker,developer,environment
8
+ Author: evegny.zuev
9
+ Author-email: zueves@gmail.com
10
+ Requires-Python: >=3.7,<4.0
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.7
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Requires-Dist: click
23
+ Requires-Dist: python-dotenv (>=0.21,<2)
24
+ Requires-Dist: toml (>=0.10.0,<0.11.0)
25
+ Project-URL: Documentation, https://github.com/zueve/zenv
26
+ Project-URL: Homepage, https://github.com/zueve/zenv
27
+ Project-URL: Repository, https://github.com/zueve/zenv
28
+ Description-Content-Type: text/markdown
29
+
1
30
  Zenv
2
31
  ====
3
32
 
@@ -95,6 +124,73 @@ Command `zenv exec <COMMAND>` or it shot alias `ze <COMMAND>` run `<COMMAND>` in
95
124
  ```
96
125
  To avoid conflicts between host and container variables, all installed system variables are placed in the blacklist when Zenvfile is created, from which editing can be removed
97
126
 
127
+ ### Configuration changes
128
+
129
+ Zenv records a fingerprint of the container creation settings in the Docker label
130
+ `zenv.config-hash`. It covers the image, run options, startup command and init
131
+ commands, including the aliases and execution settings used by initialization.
132
+
133
+ If these settings change, Zenv prints a warning to stderr and asks whether to
134
+ recreate the container (default: no). Answering `y` removes the existing
135
+ container, creates it with the updated configuration, runs initialization and
136
+ retries the original command. Answering `n` or pressing Enter continues using
137
+ the existing container. The same check applies to containers created before
138
+ fingerprint tracking. Confirmation happens before starting the container or
139
+ executing the command and preserves the command's stdout and exit code. With
140
+ piped or noninteractive stdin, a mismatch stops execution without reading input.
141
+
142
+ Fingerprint checking is enabled by default and can be disabled:
143
+
144
+ ```toml
145
+ [run]
146
+ check_zenvfile_changes = false
147
+ ```
148
+
149
+ This disables comparison, warnings and confirmation, including for scripts and
150
+ pipes. New containers still receive a fingerprint so checking can be re-enabled
151
+ later. Changing this flag does not require recreating the container.
152
+
153
+ To apply updated creation settings, run `zenv rm` and retry. The next execution
154
+ creates a container with the updated configuration. Files in the mounted project
155
+ directory remain; changes made only inside the removed container are discarded.
156
+
157
+ Changing ordinary exec settings, host environment variables, UID/GID, TTY or the
158
+ current subdirectory does not require recreating the container. Comments, TOML
159
+ key order, alias descriptions and unused aliases do not affect the fingerprint.
160
+ The fingerprint tracks configuration declarations, not changes inside image tags
161
+ or files referenced by init commands.
162
+
163
+ ### Networks
164
+
165
+ Set a named network in the existing run options:
166
+
167
+ ```toml
168
+ [run]
169
+ manage_network = true
170
+
171
+ [run.options]
172
+ network = "project-dev"
173
+ ```
174
+
175
+ `run.manage_network` defaults to `true`. Set it to `false` to disable automatic
176
+ network creation and deletion. The configured network is still passed to Docker
177
+ and must already exist. This switch takes effect immediately and does not
178
+ require recreating the container.
179
+
180
+ Before creating the container, Zenv attempts `docker network create` for each
181
+ configured network, with the label `zenv.managed-network=true`. A list of names
182
+ is also supported. Existing networks are reused; network command errors and
183
+ output are ignored.
184
+
185
+ On `zenv rm`, Zenv attempts `docker network rm` for the networks explicitly
186
+ listed in the current `run.options.network`, even if the container is already
187
+ absent. It does not check labels or ownership: unused networks created manually
188
+ or through Compose can also be removed. Docker decides whether removal is
189
+ allowed; errors are ignored. No networks are managed when the setting is absent.
190
+
191
+ Set `manage_network = false` when automatic creation and deletion are unwanted,
192
+ including when using system network modes or extended Docker network syntax.
193
+
98
194
  ### Other commands
99
195
 
100
196
  ```shell
@@ -179,3 +275,4 @@ __sleep__ = [ "sleep", "365d",]
179
275
  __create_user__ = [ "useradd", "-m", "-r", "-u", "{uid}", "-g", "{gid}", "zenv",]
180
276
  ```
181
277
 
278
+
@@ -1,25 +1,3 @@
1
- Metadata-Version: 2.1
2
- Name: zenv-cli
3
- Version: 0.4.3
4
- Summary:
5
- Home-page: https://github.com/zueve/zenv
6
- License: MIT
7
- Keywords: cli,docker,developer,environment
8
- Author: evegny.zuev
9
- Author-email: zueves@gmail.com
10
- Requires-Python: >=3.7,<4.0
11
- Classifier: License :: OSI Approved :: MIT License
12
- Classifier: Programming Language :: Python :: 3
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.7
15
- Classifier: Programming Language :: Python :: 3.8
16
- Classifier: Programming Language :: Python :: 3.9
17
- Requires-Dist: click
18
- Requires-Dist: toml (>=0.10.0,<0.11.0)
19
- Project-URL: Documentation, https://github.com/zueve/zenv
20
- Project-URL: Repository, https://github.com/zueve/zenv
21
- Description-Content-Type: text/markdown
22
-
23
1
  Zenv
24
2
  ====
25
3
 
@@ -117,6 +95,73 @@ Command `zenv exec <COMMAND>` or it shot alias `ze <COMMAND>` run `<COMMAND>` in
117
95
  ```
118
96
  To avoid conflicts between host and container variables, all installed system variables are placed in the blacklist when Zenvfile is created, from which editing can be removed
119
97
 
98
+ ### Configuration changes
99
+
100
+ Zenv records a fingerprint of the container creation settings in the Docker label
101
+ `zenv.config-hash`. It covers the image, run options, startup command and init
102
+ commands, including the aliases and execution settings used by initialization.
103
+
104
+ If these settings change, Zenv prints a warning to stderr and asks whether to
105
+ recreate the container (default: no). Answering `y` removes the existing
106
+ container, creates it with the updated configuration, runs initialization and
107
+ retries the original command. Answering `n` or pressing Enter continues using
108
+ the existing container. The same check applies to containers created before
109
+ fingerprint tracking. Confirmation happens before starting the container or
110
+ executing the command and preserves the command's stdout and exit code. With
111
+ piped or noninteractive stdin, a mismatch stops execution without reading input.
112
+
113
+ Fingerprint checking is enabled by default and can be disabled:
114
+
115
+ ```toml
116
+ [run]
117
+ check_zenvfile_changes = false
118
+ ```
119
+
120
+ This disables comparison, warnings and confirmation, including for scripts and
121
+ pipes. New containers still receive a fingerprint so checking can be re-enabled
122
+ later. Changing this flag does not require recreating the container.
123
+
124
+ To apply updated creation settings, run `zenv rm` and retry. The next execution
125
+ creates a container with the updated configuration. Files in the mounted project
126
+ directory remain; changes made only inside the removed container are discarded.
127
+
128
+ Changing ordinary exec settings, host environment variables, UID/GID, TTY or the
129
+ current subdirectory does not require recreating the container. Comments, TOML
130
+ key order, alias descriptions and unused aliases do not affect the fingerprint.
131
+ The fingerprint tracks configuration declarations, not changes inside image tags
132
+ or files referenced by init commands.
133
+
134
+ ### Networks
135
+
136
+ Set a named network in the existing run options:
137
+
138
+ ```toml
139
+ [run]
140
+ manage_network = true
141
+
142
+ [run.options]
143
+ network = "project-dev"
144
+ ```
145
+
146
+ `run.manage_network` defaults to `true`. Set it to `false` to disable automatic
147
+ network creation and deletion. The configured network is still passed to Docker
148
+ and must already exist. This switch takes effect immediately and does not
149
+ require recreating the container.
150
+
151
+ Before creating the container, Zenv attempts `docker network create` for each
152
+ configured network, with the label `zenv.managed-network=true`. A list of names
153
+ is also supported. Existing networks are reused; network command errors and
154
+ output are ignored.
155
+
156
+ On `zenv rm`, Zenv attempts `docker network rm` for the networks explicitly
157
+ listed in the current `run.options.network`, even if the container is already
158
+ absent. It does not check labels or ownership: unused networks created manually
159
+ or through Compose can also be removed. Docker decides whether removal is
160
+ allowed; errors are ignored. No networks are managed when the setting is absent.
161
+
162
+ Set `manage_network = false` when automatic creation and deletion are unwanted,
163
+ including when using system network modes or extended Docker network syntax.
164
+
120
165
  ### Other commands
121
166
 
122
167
  ```shell
@@ -201,4 +246,3 @@ __sleep__ = [ "sleep", "365d",]
201
246
  __create_user__ = [ "useradd", "-m", "-r", "-u", "{uid}", "-g", "{gid}", "zenv",]
202
247
  ```
203
248
 
204
-
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "zenv-cli"
3
- version = "0.4.3"
3
+ version = "0.5.1"
4
4
  description = ""
5
5
  authors = ["evegny.zuev <zueves@gmail.com>"]
6
6
  license = "MIT"
@@ -17,6 +17,7 @@ packages = [
17
17
  python = "^3.7"
18
18
  toml = "^0.10.0"
19
19
  click = "*"
20
+ python-dotenv = ">=0.21,<2"
20
21
 
21
22
  [tool.poetry.dev-dependencies]
22
23
  pytest = "*"
@@ -26,3 +27,7 @@ bpython = "^0.22.1"
26
27
  [tool.poetry.scripts]
27
28
  zenv = 'zenv.cli:cli'
28
29
  ze = 'zenv.cli:exec'
30
+
31
+ [build-system]
32
+ requires = ["poetry-core>=1.0.0"]
33
+ build-backend = "poetry.core.masonry.api"
@@ -117,7 +117,7 @@ def rm(zenvfile):
117
117
  """Remove container (will stop the container, if need)"""
118
118
 
119
119
  config = utils.get_config(zenvfile)
120
- core.rm(config['main']['name'])
120
+ core.remove_environment(config)
121
121
 
122
122
 
123
123
  @cli.command(name='stop-all')
@@ -6,6 +6,8 @@ STATUS_STOPED = 'Stoped'
6
6
  STATUS_NOT_EXIST = 'Not_exist'
7
7
 
8
8
  CONTAINER_PREFIX = 'zenv'
9
+ CONFIG_HASH_LABEL = 'zenv.config-hash'
10
+ MANAGED_NETWORK_LABEL = 'zenv.managed-network'
9
11
  TEMPLATE_FILENAME = 'template.Zenvfile'
10
12
 
11
13
  INIT_TEMPLATE = """# Zenvfile - state file for zenv-cli
@@ -18,6 +20,8 @@ name = "{id}-{container_name}"
18
20
  debug = false
19
21
 
20
22
  [run]
23
+ manage_network = true
24
+ check_zenvfile_changes = true
21
25
  command = ["__sleep__"]
22
26
  init_commands = [["__create_group__"], ["__create_user__"]]
23
27
 
@@ -0,0 +1,205 @@
1
+ import subprocess
2
+ import logging as logger
3
+ import json
4
+ import sys
5
+ from copy import deepcopy
6
+
7
+ import click
8
+ from . import const, networks, utils
9
+
10
+
11
+ def get_command_with_options(command, aliases, exec_params):
12
+ """Prepare docker exec arguments with alias settings overriding defaults."""
13
+ resolved = utils.resolve_alias(command, aliases)
14
+ exec_params = utils.merge_config(deepcopy(resolved['exec']), exec_params)
15
+ env_file = exec_params.get('env_file')
16
+ dotenv_env = utils.load_dotenv(env_file) if env_file else []
17
+ exec_options = dict(exec_params.get('options', {}))
18
+ exec_options['env'] = utils.composit_environment(
19
+ dotenv_env=dotenv_env,
20
+ zenvfile_env=exec_options.get('env', {}),
21
+ blacklist=exec_params.get('env_excludes', ())
22
+ )
23
+ return resolved['command'], utils.build_docker_options(exec_options)
24
+
25
+
26
+ def remove_environment(config):
27
+ """Remove the project container and clean up its configured networks."""
28
+ rm(
29
+ config['main']['name'],
30
+ config['run']['options'].get('network'),
31
+ config['run'].get('manage_network', True),
32
+ )
33
+
34
+
35
+ def _container_for_command(config):
36
+ """Offer to remove an outdated container. Return None when absent."""
37
+ container_name = config['main']['name']
38
+ check_changes = config['run'].get('check_zenvfile_changes', True)
39
+ while True:
40
+ container = inspect_container(container_name)
41
+ if container is None or not check_changes:
42
+ return container
43
+ labels = container['Config'].get('Labels') or {}
44
+ if labels.get(const.CONFIG_HASH_LABEL) == config['main']['config_hash']:
45
+ return container
46
+
47
+ click.echo(
48
+ 'Warning: container creation settings do not match Zenvfile.',
49
+ err=True,
50
+ )
51
+ if not sys.stdin.isatty():
52
+ raise click.ClickException(
53
+ 'Cannot confirm recreation without interactive stdin. '
54
+ 'Set run.check_zenvfile_changes = false for noninteractive use.'
55
+ )
56
+ if not click.confirm(
57
+ 'Recreate the container with the updated settings?',
58
+ default=False, err=True,
59
+ ):
60
+ return container
61
+
62
+ # Another invocation may create a replacement before our next inspect.
63
+ remove_environment(config)
64
+
65
+
66
+ def _create_container(config):
67
+ """Launch the configured container and run its initialization commands."""
68
+ main = config['main']
69
+ setup = config['run']
70
+ aliases = config['aliases']
71
+ options = {'name': main['name'], **setup['options']}
72
+ labels = options.get('label', [])
73
+ if isinstance(labels, str):
74
+ labels = [labels]
75
+ options['label'] = list(labels) + [
76
+ '{}={}'.format(const.CONFIG_HASH_LABEL, main['config_hash'])
77
+ ]
78
+ command = utils.resolve_alias(setup['command'], aliases)['command']
79
+ if setup.get('manage_network', True):
80
+ networks.create(options.get('network'))
81
+ exit_code = run(
82
+ image=main['image'], command=command,
83
+ options=utils.build_docker_options(options), path=main['zenvfilepath'],
84
+ )
85
+ if exit_code:
86
+ return exit_code
87
+
88
+ for init_command in setup['init_commands']:
89
+ command, exec_options = get_command_with_options(
90
+ init_command, aliases, {}
91
+ )
92
+ exec_(main['name'], command, exec_options)
93
+ return exit_code
94
+
95
+
96
+ def call(config, command):
97
+ container_name = config['main']['name']
98
+ container = _container_for_command(config)
99
+ command, exec_options = get_command_with_options(
100
+ command, config['aliases'], config['exec']
101
+ )
102
+
103
+ if container is None:
104
+ exit_code = _create_container(config)
105
+ if exit_code:
106
+ return exit_code
107
+ elif container['State']['Status'] in ('exited', 'created'):
108
+ cmd = ['docker', 'start', container_name]
109
+ logger.debug(cmd)
110
+ result = subprocess.run(cmd)
111
+ if result.returncode:
112
+ return result.returncode
113
+
114
+ return exec_(container_name, command, exec_options)
115
+
116
+
117
+ def run(image, command, options, path):
118
+ cmd = ['docker', 'run', *options, image, *command]
119
+
120
+ with utils.in_directory(path):
121
+ logger.debug(cmd)
122
+ result = subprocess.run(cmd)
123
+ return result.returncode
124
+
125
+
126
+ def exec_(container_name, command, options):
127
+ cmd = ('docker', 'exec', *options, container_name, *command)
128
+ logger.debug(cmd)
129
+ return subprocess.run(cmd).returncode
130
+
131
+
132
+ def inspect_container(container_name):
133
+ cmd = ['docker', 'container', 'inspect', '--', container_name]
134
+ logger.debug(cmd)
135
+ result = subprocess.run(cmd, capture_output=True)
136
+ if result.returncode == 0:
137
+ return json.loads(result.stdout)[0]
138
+
139
+ # Verify absence with a daemon query, without parsing error text.
140
+ names = subprocess.run(
141
+ ['docker', 'ps', '--all', '--format', '{{.Names}}'],
142
+ capture_output=True,
143
+ )
144
+ if names.returncode:
145
+ raise click.ClickException(names.stderr.decode().strip())
146
+ if container_name not in names.stdout.decode().splitlines():
147
+ return None
148
+ raise click.ClickException(result.stderr.decode().strip())
149
+
150
+
151
+ def status(container_name):
152
+ container = inspect_container(container_name)
153
+ if container is None:
154
+ return const.STATUS_NOT_EXIST
155
+ state = container['State']['Status']
156
+ return {
157
+ 'running': const.STATUS_RUNNING,
158
+ 'exited': const.STATUS_STOPED,
159
+ }.get(state, state)
160
+
161
+
162
+ def version():
163
+ cmd = 'docker version'
164
+ subprocess.run(cmd, shell=True)
165
+
166
+
167
+ def stop(container_name):
168
+ cmd = f'docker stop {container_name}'
169
+ subprocess.run(cmd, shell=True)
170
+
171
+
172
+ def rm(container_name, network=None, manage_network=True):
173
+ container = inspect_container(container_name)
174
+ if container is not None:
175
+ container_id = container['Id']
176
+ if container['State']['Status'] == 'running':
177
+ cmd = ['docker', 'stop', '--', container_id]
178
+ logger.debug(cmd)
179
+ if subprocess.run(cmd).returncode:
180
+ raise click.ClickException('Could not stop the container.')
181
+ cmd = ['docker', 'rm', '--', container_id]
182
+ logger.debug(cmd)
183
+ if subprocess.run(cmd).returncode:
184
+ raise click.ClickException('Could not remove the container.')
185
+ if manage_network:
186
+ networks.remove(network)
187
+
188
+
189
+ def stop_all(exclude_containers=()):
190
+ """
191
+ Stop all containers started with `zenv-`
192
+
193
+ """
194
+
195
+ cmd = (
196
+ "docker ps --format='{{.Names}}'"
197
+ )
198
+ result = subprocess.run(cmd, shell=True, check=True, capture_output=True)
199
+
200
+ for container_name in result.stdout.decode().split('\n'):
201
+ if (
202
+ container_name.startswith(const.CONTAINER_PREFIX + '-')
203
+ and container_name not in exclude_containers
204
+ ):
205
+ stop(container_name)
@@ -0,0 +1,24 @@
1
+ """Fingerprint declared container setup before invocation substitutions."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+
7
+ from .utils import resolve_alias
8
+
9
+
10
+ def config_hash(config, project_directory):
11
+ aliases = config['aliases']
12
+
13
+ setup = {
14
+ 'project_directory': os.path.abspath(project_directory),
15
+ 'image': config['main']['image'],
16
+ 'command': resolve_alias(config['run']['command'], aliases)['command'],
17
+ 'options': config['run']['options'],
18
+ 'init_commands': [
19
+ resolve_alias(command, aliases)
20
+ for command in config['run']['init_commands']
21
+ ],
22
+ }
23
+ content = json.dumps(setup, sort_keys=True, separators=(',', ':'))
24
+ return hashlib.sha256(content.encode('utf-8')).hexdigest()
@@ -0,0 +1,27 @@
1
+ """Attempt configured network operations and let Docker handle conflicts."""
2
+
3
+ import logging as logger
4
+ import subprocess
5
+
6
+ from . import const
7
+
8
+
9
+ def _run(options, network):
10
+ names = [network] if isinstance(network, str) else network or []
11
+ for name in names:
12
+ command = ['docker', 'network', *options, '--', name]
13
+ logger.debug(command)
14
+ subprocess.run(
15
+ command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
16
+ check=False,
17
+ )
18
+
19
+
20
+ def create(network):
21
+ _run([
22
+ 'create', '--label', '{}=true'.format(const.MANAGED_NETWORK_LABEL),
23
+ ], network)
24
+
25
+
26
+ def remove(network):
27
+ _run(['rm'], network)
@@ -15,13 +15,25 @@ class Default(dict):
15
15
  return '{' + key + '}'
16
16
 
17
17
 
18
+ def resolve_alias(command, aliases):
19
+ """Expand the first word once and return the declared exec overrides."""
20
+ alias = aliases.get(command[0])
21
+ if alias is None:
22
+ return {'command': command, 'exec': {}}
23
+ return {
24
+ 'command': alias['command'] + list(command[1:]),
25
+ 'exec': alias.get('exec', {}),
26
+ }
27
+
28
+
18
29
  def load_dotenv(dotenvfile):
19
30
  try:
20
31
  with open(dotenvfile) as file:
21
32
  environments = [
22
- bind.original.string.strip()
33
+ f'{bind.key}={bind.value}'
34
+ if bind.value is not None else bind.key
23
35
  for bind in parser.parse_stream(file)
24
- if not bind.error
36
+ if not bind.error and bind.key is not None
25
37
  ]
26
38
  except FileNotFoundError:
27
39
  raise click.ClickException(f'Env file not found {dotenvfile}')
@@ -29,11 +41,30 @@ def load_dotenv(dotenvfile):
29
41
 
30
42
 
31
43
  def get_config(zenvfile=None):
44
+ from .fingerprint import config_hash
45
+
32
46
  if not zenvfile:
33
47
  zenvfile = find_file(os.getcwd(), fname=const.DEFAULT_FILENAME)
34
48
  if not zenvfile:
35
49
  raise click.ClickException('Zenvfile don\'t find. Make `zenv init`')
36
50
 
51
+ zenvfile = os.path.abspath(zenvfile)
52
+ source = Path(zenvfile).read_text()
53
+
54
+ # Distinct symbols retain active placeholders while unescaping TOML braces.
55
+ symbolic_params = Default(
56
+ uid='__zenv_runtime_uid__', gid='__zenv_runtime_gid__',
57
+ pwd='__zenv_runtime_pwd__', tty='__zenv_runtime_tty__',
58
+ zenvfilepath='__zenv_project_directory__', env_excludes='[]',
59
+ )
60
+ declared_config = merge_config(
61
+ toml.loads(source.format_map(symbolic_params)),
62
+ toml.loads(const.CONFIG_TEMPLATE.format_map(symbolic_params)),
63
+ )
64
+ creation_hash = config_hash(
65
+ declared_config, os.path.dirname(zenvfile)
66
+ )
67
+
37
68
  params = Default(
38
69
  zenvfilepath=os.path.dirname(zenvfile),
39
70
  pwd=os.getcwd(),
@@ -43,7 +74,7 @@ def get_config(zenvfile=None):
43
74
  env_excludes='[]'
44
75
  )
45
76
 
46
- content = Path(zenvfile).read_text().format_map(params)
77
+ content = source.format_map(params)
47
78
 
48
79
  config = toml.loads(content)
49
80
 
@@ -52,6 +83,10 @@ def get_config(zenvfile=None):
52
83
  merge_config(origin_config, origin_config['hidden'])
53
84
 
54
85
  config = merge_config(config, origin_config)
86
+ for flag in ('manage_network', 'check_zenvfile_changes'):
87
+ if not isinstance(config['run'][flag], bool):
88
+ raise click.ClickException('run.{} must be a boolean'.format(flag))
89
+ config['main']['config_hash'] = creation_hash
55
90
 
56
91
  # init logging
57
92
  if 'debug' in config['main'] and config['main']['debug']:
zenv-cli-0.4.3/setup.py DELETED
@@ -1,34 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- from setuptools import setup
3
-
4
- packages = \
5
- ['zenv']
6
-
7
- package_data = \
8
- {'': ['*']}
9
-
10
- install_requires = \
11
- ['click', 'toml>=0.10.0,<0.11.0']
12
-
13
- entry_points = \
14
- {'console_scripts': ['ze = zenv.cli:exec', 'zenv = zenv.cli:cli']}
15
-
16
- setup_kwargs = {
17
- 'name': 'zenv-cli',
18
- 'version': '0.4.3',
19
- 'description': '',
20
- 'long_description': 'Zenv\n====\n\nZenv is container based virtual environments.\nThe main goal of Zenv is to simplify access to applications inside container, making it seamless in use like native (host-machine) applications\n\n## Usage\n```shell\n> zenv init\nZenv created!\n\n> # run `ls` command inside contaner\n> ze ls\n```\n\n## Motivation\n\nAs a developer, when set up a project locally, I usually need to install additional applications on the system. Of course, modern package managers such as poetry, pipenv, npm, cargo, ext, perfectly solve for us most of the problems with dependencies within a single stack of technologies. But they do not allow to solve the problem with the installation of system libraries. If you have a lot of projects that require different versions of system libraries, then you have problems\n\nIn production, this problem has long been solved by container insulation, and as a rule, it is a `Docker`. Therefore, many of my colleagues use docker-images and docker-compose, not only to run services in a production environment but also to develop and debug programs on a local machine\n\nUnfortunately, there are several problems along the way:\n\n- Some of your familiar utilities may not be preinstalled in the container\n- If you try to install packages in the process, you will encounter the lack of necessary rights\n- Forget about debugging with `print`\n- The main thing is lost the usual experience, you can not use your favorite customized shell\n\nOf course, the problems described above are solved by creating a docker image specifically for developing a specific project, `zenv` just helps to create such containers very simply\n\n## Features\n\n- Simplify: all interaction with the container occurs with one short command: `ze`\n- Zenv automatically forwarded current directory to the container with the same PWD\n- Zenv automatically forwarded current UserID, GroupID to container\n\n Therefore, files created in the container have the same rights as those created in the native console and you can also use `sudo` to get privileges\n ```shell\n > sudo ze <command>\n ```\n or\n\n ```shell\n > sudo !!\n ```\n\n- Zenv can forwarded environment vars as is native\n ```shell\n > MYVAR=LIVE!!!! ze env\n ```\n- And of course your could combinate native and containerized commands in Unix pipes\n ```shell\n > ze ls | head -7 | ze tail -5\n ```\n- Minimal performance impact\n- Customization: you can additionally control container parameters using Zenvfile\n\n\n## Install\n 1. Make sure you have the latest version of `Docker` installed\n 2. For linux, make sure you have your user’s [rights are allowed](https://docs.docker.com/install/linux/linux-postinstall/) to interact with doker\n 3. Make sure that you have python version 3.6 or higher\n 4. Execute:\n ```shell\n > sudo pip install zenv-cli\n # or\n > sudo pip3 install zenv-cli\n ```\n\n## How It works\nBy nature, zenv is a small automated layer over the official docker CLI\n\n### init\n\nCommand `zenv init` create `Zenvfile` in current directory. This file describes the relationship with the docker image and container that will be created to execute isolated commands.\n\nBy default, used image is `ubuntu: latest`.\nBut you can change it by setting `-i` flag. For example:\n```shell\n> zenv init -i python:latest\n```\nOr edit `Zenvfile` manually\n\n\n### Execute\n\nCommand `zenv exec <COMMAND>` or it shot alias `ze <COMMAND>` run `<COMMAND>` in a container environment. When running the command:\n- Zenv checks current container status (running, stopped, removed), and up container if need.\n- The container run with the command `sleep infinity`. Therefore it will be easily accessible\n- UID and GID that ran the command are pushed into the container. Therefor your could use `sudo ze <COMMAND>`\n- When executing the command, the directory from the path where Zenvfile is located is forwarded to the container as is a current PWD. Therefor your could run `ze` from deep into directories relative to Zenvfile\n- Environment variables are also thrown into the container as a native.\n ```\n > MYVAR=SUPER ze env\n ```\n To avoid conflicts between host and container variables, all installed system variables are placed in the blacklist when Zenvfile is created, from which editing can be removed\n\n### Other commands\n\n```shell\n> zenv --help\nUsage: zenv [OPTIONS] COMMAND [ARGS]...\n\n ZENV(Zen-env): Containers manager for developer environment\n\n Usage:\n\n > zenv init -i centos:latest & ze cat /etc/redhat-release\n\nOptions:\n --help Show this message and exit.\n\nCommands:\n exec Call some command inside the container\n info Show current container info\n init Initialize Environment: create Zenvfile\n rm Remove container (will stop the container, if need)\n stop Stop container\n stop-all Stop all zenv containers\n```\n\n## Example install jupyter notebook\n```shell\n> mkgir notebooks\n> cd notebooks\n> zenv init -i python:3.7.3\n```\nAfter edit Zenvfile to explode notebook ports. Update `ports = []` to `ports = ["8888:8888"]`\n\n```\n> sudo ze pip install jupyter numpy scipy matplotlib\n```\nRun notebook\n```\n> ze jupyter notebook --ip 0.0.0.0\n```\nlaunch your browser with url: http://localhost:8888\n\nAlso you could add this commands to Zenvfile:\n```toml\n[run]\ninit_commands = [\n [ "__create_user__"],\n ["pip", "install", "jupyter", "numpy", "scipy", "matplotlib"]\n]\n\n[commands]\nnotebook = ["jupyter", "notebook", "--ip", "0.0.0.0"]\n```\n\nAnd launch notebook with command\n\n```\n> ze notebook\n```\n\n## Zenvfile\n```toml\n[main]\nimage = "ubuntu:latest"\nname = "zenv-project" # container name\ndebug = false # for show docker commands\n\n[run]\ncommand = [ "__sleep__",]\ninit_commands = [ [ "__create_user__",],]\n\n[exec]\nenv_file = ""\nenv_excludes = [ "TMPDIR",]\n\n[run.options]\nvolume = [ "{zenvfilepath}:{zenvfilepath}:rw",]\ndetach = "true"\npublish = []\n\n[commands]\n__sleep__ = [ "sleep", "365d",]\n__create_user__ = [ "useradd", "-m", "-r", "-u", "{uid}", "-g", "{gid}", "zenv",]\n```\n\n',
21
- 'author': 'evegny.zuev',
22
- 'author_email': 'zueves@gmail.com',
23
- 'maintainer': None,
24
- 'maintainer_email': None,
25
- 'url': 'https://github.com/zueve/zenv',
26
- 'packages': packages,
27
- 'package_data': package_data,
28
- 'install_requires': install_requires,
29
- 'entry_points': entry_points,
30
- 'python_requires': '>=3.7,<4.0',
31
- }
32
-
33
-
34
- setup(**setup_kwargs)
@@ -1,137 +0,0 @@
1
- import subprocess
2
- import logging as logger
3
- from . import const, utils
4
-
5
-
6
- def get_command_with_options(command, aliases, exec_params):
7
- """
8
- Find command by aliases and build exec docker options
9
-
10
- """
11
- if command[0] in aliases:
12
- key = command[0]
13
- command = aliases[key]['command'] + list(command[1:])
14
- command_exec_params = aliases[key].get('exec', {})
15
- exec_params = utils.merge_config(command_exec_params, exec_params)
16
- dotenv_env = (
17
- utils.load_dotenv(exec_params['env_file'])
18
- if 'env_file' in exec_params and exec_params['env_file'] else {}
19
- )
20
- exec_options = exec_params.get('options', {})
21
- exec_options['env'] = utils.composit_environment(
22
- dotenv_env=dotenv_env,
23
- zenvfile_env=exec_options.get('env', {}),
24
- blacklist=exec_params.get('env_excludes', {})
25
- )
26
- docker_exec_options = utils.build_docker_options(exec_options)
27
- return command, docker_exec_options
28
-
29
-
30
- def call(config, command):
31
- container_name = config['main']['name']
32
- container_status = status(container_name)
33
-
34
- # composite environments
35
- command, exec_options = get_command_with_options(
36
- command, config['aliases'], config['exec']
37
- )
38
-
39
- if container_status == const.STATUS_NOT_EXIST:
40
- options = {'name': container_name, **config['run']['options']}
41
- run_command, _ = get_command_with_options(
42
- config['run']['command'], config['aliases'], {})
43
- run(
44
- image=config['main']['image'],
45
- command=run_command,
46
- options=utils.build_docker_options(options),
47
- path=config['main']['zenvfilepath']
48
- )
49
-
50
- # run init commands:
51
- for init_command in config['run']['init_commands']:
52
- init_command, init_options = get_command_with_options(
53
- init_command, config['aliases'], {}
54
- )
55
- exec_(container_name, init_command, init_options)
56
-
57
- elif container_status == const.STATUS_STOPED:
58
- cmd = ['docker', 'start', container_name]
59
- logger.debug(cmd)
60
- subprocess.run(cmd)
61
-
62
- return exec_(container_name, command, exec_options)
63
-
64
-
65
- def run(image, command, options, path):
66
- cmd = ['docker', 'run', *options, image, *command]
67
-
68
- with utils.in_directory(path):
69
- logger.debug(cmd)
70
- result = subprocess.run(cmd)
71
- return result.returncode
72
-
73
-
74
- def exec_(container_name, command, options):
75
- cmd = ('docker', 'exec', *options, container_name, *command)
76
- logger.debug(cmd)
77
- return subprocess.run(cmd).returncode
78
-
79
-
80
- def status(container_name):
81
-
82
- cmd = (
83
- f"docker ps --all --filter 'name={container_name}' "
84
- "--format='{{.Status}}'"
85
- )
86
-
87
- logger.debug(cmd)
88
- result = subprocess.run(cmd, shell=True, check=True, capture_output=True)
89
- status = (
90
- result.stdout.decode().split()[0].upper() if result.stdout else None
91
- )
92
-
93
- if not status:
94
- return const.STATUS_NOT_EXIST
95
- elif status == 'EXITED':
96
- return const.STATUS_STOPED
97
- elif status == 'UP':
98
- return const.STATUS_RUNNING
99
-
100
-
101
- def version():
102
- cmd = 'docker version'
103
- subprocess.run(cmd, shell=True)
104
-
105
-
106
- def stop(container_name):
107
- cmd = f'docker stop {container_name}'
108
- subprocess.run(cmd, shell=True)
109
-
110
-
111
- def rm(container_name):
112
- current_status = status(container_name)
113
- if current_status == const.STATUS_RUNNING:
114
- stop(container_name)
115
- if current_status == const.STATUS_NOT_EXIST:
116
- return
117
- cmd = f'docker rm {container_name}'
118
- subprocess.run(cmd, shell=True)
119
-
120
-
121
- def stop_all(exclude_containers=()):
122
- """
123
- Stop all containers started with `zenv-`
124
-
125
- """
126
-
127
- cmd = (
128
- "docker ps --format='{{.Names}}'"
129
- )
130
- result = subprocess.run(cmd, shell=True, check=True, capture_output=True)
131
-
132
- for container_name in result.stdout.decode().split('\n'):
133
- if (
134
- container_name.startswith(const.CONTAINER_PREFIX + '-')
135
- and container_name not in exclude_containers
136
- ):
137
- stop(container_name)
File without changes
File without changes