Skip to content

Commit

Permalink
Add dev script to work on persistent environment variable on Linux #322
Browse files Browse the repository at this point in the history
  • Loading branch information
Guts committed Nov 15, 2023
1 parent db9bb58 commit 8d3da6a
Show file tree
Hide file tree
Showing 2 changed files with 159 additions and 0 deletions.
159 changes: 159 additions & 0 deletions tests/dev/dev_manage_persistent_env_var_linux.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# standard
import logging
import os
from functools import lru_cache
from os import getenv
from pathlib import Path

# 3rd party
import shellingham

# project
from qgis_deployment_toolbelt.utils.check_path import check_path

logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s||%(levelname)s||%(module)s||%(lineno)d||%(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)

qdt_block_comment_start = "# BEGIN QDT MANAGED BLOCK"
qdt_block_comment_end = "# END QDT MANAGED BLOCK"
shell_path_to_names = {
"bash": ("/bin/bash", "/usr/bin/bash"),
"zsh": ("/bin/bash/zsh", "/usr/bin/zsh"),
}


@lru_cache()
def find_key_from_values(value_to_find: str) -> str | None:
"""Finds the key corresponding to a given value in a dictionary where values are
tuples.
Args:
value_to_find (str): The value to search for in the dictionary values.
Returns:
str | None: The key corresponding to the found value. Returns None if the value
is not found.
"""
for key, values in shell_path_to_names.items():
if value_to_find in values:
return key
return None


def get_shell_to_use() -> tuple[str, str] | None:
try:
shell = shellingham.detect_shell()
logger.debug(f"Detected active shell: {shell}")
except shellingham.ShellDetectionFailure as exc:
logger.warning(
"Failed to detect active shell. Using default from environment "
f"variable. Trace: {exc}"
)
if os.name == "posix":
if shell_path := getenv("SHELL"):
shell_name = find_key_from_values(value_to_find=getenv("SHELL"))
if shell_name:
return (shell_name, shell_path)
return None
elif os.name == "nt":
return getenv("COMSPEC")
else:
raise NotImplementedError(f"OS {os.name!r} support not available")

logger.debug(f"Default shell from environment variable: {shell}")

return shell


def is_dot_profile_file() -> bool:
return check_path(
input_path=Path.home().joinpath(".profile"),
must_be_a_file=True,
must_exists=True,
raise_error=False,
)


def add_to_user_profile(env_key: str, env_value: str | bool | int) -> bool:
if isinstance(env_value, bool):
env_value = str(bool(env_value)).lower()

shell: tuple[str, str] | None = get_shell_to_use()
if shell is None:
logger.error("Shell to use is not recognized.")
return False

if shell[0] == "bash":
bash_profile = Path.home().joinpath(".profile")
if not is_dot_profile_file():
logger.error(
f"Shell profile does not exist and will be created {bash_profile}"
)
bash_profile.touch()

logger.debug(f"parsing {bash_profile}")

export_line = f"export {env_key}={str(env_value)}"
block_start_found = False
block_end_found = False
block_end_line: int = 0
line_found = False

# Lire le contenu du fichier
with bash_profile.open(mode="r", encoding="UTF-8") as file:
lines = file.readlines()

# look for block and export line
line_number: int = 0
for line in lines:
if line.strip() == qdt_block_comment_start:
block_start_found = True
elif line.strip() == qdt_block_comment_end:
block_end_found = True
block_end_line = line_number
elif line.strip() == export_line:
line_found = True
# line counter
line_number += 1

# check if block exist
block_found = all([block_start_found, block_end_found])

if line_found:
logger.debug(
f"Environment variable and key {env_key}={env_value} is already present"
)
return True
elif block_found and not line_found:
lines.insert(block_end_line, f"{export_line}\n")

with bash_profile.open(mode="w", encoding="UTF-8") as file:
file.writelines(lines)
logger.info(
f"QDT block was already here but not the line: '{export_line}. "
"It has been added."
)
return True
elif not block_found and not line_found:
new_lines = (
f"\n{qdt_block_comment_start}\n",
f"{export_line}\n",
f"{qdt_block_comment_end}\n",
)
with open(bash_profile, "a") as file:
file.writelines(new_lines)
logger.info(
f"Nor QDT block and the line: '{export_line}' were present. "
"Both have been added."
)
return True
else:
logger.error(f"Shell {shell[0]} is not supported")
return False


add_to_user_profile("TEST_PERSISTENT_ENVIRONMENT_VARIABLE", True)
File renamed without changes.

0 comments on commit 8d3da6a

Please sign in to comment.