Skip to content

Commit

Permalink
Stateful shell compatibility improvements (project-chip#19006)
Browse files Browse the repository at this point in the history
* Chef - Use latin1 encoding when reading tmp files

* Chef - Use local temp files to support Docker usage
  • Loading branch information
cpagravel committed Jun 15, 2022
1 parent 734b9e2 commit bedb58a
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions examples/chef/stateful_shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
import shlex
import subprocess
import sys
import tempfile
from typing import Dict, Optional

import constants

_ENV_FILENAME = ".shell_env"
_OUTPUT_FILENAME = ".shell_output"
_HERE = os.path.dirname(os.path.abspath(__file__))

TermColors = constants.TermColors

Expand All @@ -42,8 +44,8 @@ def __init__(self) -> None:

# This file holds the env after running a command. This is a better approach
# than writing to stdout because commands could redirect the stdout.
self.envfile_path: str = os.path.join(tempfile.gettempdir(), "envfile")
self.cmd_output_path: str = os.path.join(tempfile.gettempdir(), "cmd_output")
self.envfile_path: str = os.path.join(_HERE, _ENV_FILENAME)
self.cmd_output_path: str = os.path.join(_HERE, _OUTPUT_FILENAME)

def print_env(self) -> None:
"""Print environment variables in commandline friendly format for export.
Expand All @@ -57,7 +59,11 @@ def print_env(self) -> None:
if env_var:
print(f"export {env_var}={quoted_value}")

def run_cmd(self, cmd: str, *, raise_on_returncode=False, return_cmd_output=True) -> Optional[str]:
def run_cmd(
self, cmd: str, *,
raise_on_returncode=False,
return_cmd_output=False,
) -> Optional[str]:
"""Runs a command and updates environment.
Args:
Expand Down Expand Up @@ -96,7 +102,7 @@ def run_cmd(self, cmd: str, *, raise_on_returncode=False, return_cmd_output=True
returncode = proc.wait()

# Load env state from envfile.
with open(self.envfile_path) as f:
with open(self.envfile_path, encoding="latin1") as f:
# Split on null char because we use env -0.
env_entries = f.read().split("\0")
for entry in env_entries:
Expand All @@ -111,6 +117,6 @@ def run_cmd(self, cmd: str, *, raise_on_returncode=False, return_cmd_output=True
f"Error. Return code is not 0. It is: {returncode}")

if return_cmd_output:
with open(self.cmd_output_path) as f:
with open(self.cmd_output_path, encoding="latin1") as f:
output = f.read()
return output

0 comments on commit bedb58a

Please sign in to comment.