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

Attempt to use null separation when invoking 'env' #684

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
34 changes: 34 additions & 0 deletions colcon_core/shell/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,40 @@
'Could not find a shell extension for the command environment')


async def get_null_separated_environment_variables(
cmd, *, cwd=None, shell=True,
):
"""
Get null-separated environment variables from the output of the command.

:param args: the sequence of program arguments
:param cwd: the working directory for the subprocess
:param shell: whether to use the shell as the program to execute
:rtype: dict
"""
encoding = locale.getpreferredencoding()
output = await check_output(cmd, cwd=cwd, shell=shell)
env = OrderedDict()
for kvp in output.split(b'\0'):
kvp = kvp.rstrip()
if not kvp:
continue
try:
parts = kvp.decode(encoding).split('=', 1)
except UnicodeDecodeError:
kvp_replaced = kvp.decode(encoding=encoding, errors='replace')
logger.warning(

Check warning on line 357 in colcon_core/shell/__init__.py

View check run for this annotation

Codecov / codecov/patch

colcon_core/shell/__init__.py#L355-L357

Added lines #L355 - L357 were not covered by tests
'Failed to decode line from the environment using the '
f"encoding '{encoding}': {kvp_replaced}")
continue

Check warning on line 360 in colcon_core/shell/__init__.py

View check run for this annotation

Codecov / codecov/patch

colcon_core/shell/__init__.py#L360

Added line #L360 was not covered by tests
if len(parts) != 2:
# skip lines which don't contain an equal sign
continue
env[parts[0]] = parts[1]
assert len(env) > 0, "The environment shouldn't be empty"
return env


async def get_environment_variables(cmd, *, cwd=None, shell=True):
"""
Get the environment variables from the output of the command.
Expand Down
10 changes: 8 additions & 2 deletions colcon_core/shell/sh.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from colcon_core.prefix_path import get_chained_prefix_path
from colcon_core.shell import check_dependency_availability
from colcon_core.shell import get_environment_variables
from colcon_core.shell import get_null_separated_environment_variables
from colcon_core.shell import logger
from colcon_core.shell import ShellExtensionPoint
from colcon_core.shell.template import expand_template
Expand Down Expand Up @@ -150,8 +151,13 @@
hook_path,
{'dependencies': dependencies})

cmd = ['.', str(hook_path), '&&', 'env']
env = await get_environment_variables(cmd, cwd=str(build_base))
cmd = ['.', str(hook_path), '&&', 'env', '-0']
try:
env = await get_null_separated_environment_variables(
cmd, cwd=str(build_base))
except Exception: # noqa: B902
cmd.pop()
env = await get_environment_variables(cmd, cwd=str(build_base))

Check warning on line 160 in colcon_core/shell/sh.py

View check run for this annotation

Codecov / codecov/patch

colcon_core/shell/sh.py#L158-L160

Added lines #L158 - L160 were not covered by tests

# write environment variables to file for debugging
env_path = build_base / ('colcon_command_prefix_%s.sh.env' % task_name)
Expand Down
37 changes: 37 additions & 0 deletions test/test_shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from colcon_core.shell import get_command_environment
from colcon_core.shell import get_environment_variables
from colcon_core.shell import get_find_installed_packages_extensions
from colcon_core.shell import get_null_separated_environment_variables
from colcon_core.shell import get_shell_extensions
from colcon_core.shell import ShellExtensionPoint
from colcon_core.shell.installed_packages import IsolatedInstalledPackageFinder
Expand Down Expand Up @@ -156,6 +157,42 @@ async def check_output(cmd, **kwargs):
assert 'DECODE_ERROR=' in warn.call_args[0][0]


def test_get_null_separated_environment_variables():
cmd = [
sys.executable, '-c',
r'print("FOO\0NAME=value\nSOMETHING\0NAME2=value with spaces'
r'\0NAME3=NAME4\nNAME5=NAME6")']

coroutine = get_null_separated_environment_variables(cmd, shell=False)
env = run_until_complete(coroutine)

assert len(env.keys()) == 3
assert 'NAME' in env.keys()
assert env['NAME'] == f'value{os.linesep}SOMETHING'
assert 'NAME2' in env.keys()
assert env['NAME2'] == 'value with spaces'
assert 'NAME3' in env.keys()
assert env['NAME3'] == f'NAME4{os.linesep}NAME5=NAME6'

# test with environment strings which isn't decodable
async def check_output(cmd, **kwargs):
return b'DECODE_ERROR=\x81\nNAME=value'
with patch('colcon_core.shell.check_output', side_effect=check_output):
with patch('colcon_core.shell.logger.warning') as warn:
coroutine = get_environment_variables(['not-used'], shell=False)
env = run_until_complete(coroutine)

assert len(env.keys()) == 1
assert 'NAME' in env.keys()
assert env['NAME'] == 'value'
# the raised decode error is catched and results in a warning message
assert warn.call_count == 1
assert len(warn.call_args[0]) == 1
assert warn.call_args[0][0].startswith(
"Failed to decode line from the environment using the encoding '")
assert 'DECODE_ERROR=' in warn.call_args[0][0]


class Extension3(ShellExtensionPoint):
PRIORITY = 105

Expand Down
Loading