Skip to content

[FEAT][Shell Exec]: allow variable substituition #216

@NSPC911

Description

@NSPC911

Tracker issue for string substitution. Child of #169, blocked by both #214 and #215.

Implementation Details:

  • Use both os.path.expandvars and string.Template (with .safe_substitute) before running the command. Will also need to escape any words that aren't expanded by os.path.expandvars.
  • It should only allow ${var} syntax to be expanded, syntax like $var should be first expanded by os.path.expandvars before being escaped using a \$[^\{]([^\s]+) into \$\$$1 then be passed to string.Template.safe_substitute

Example Function:

import os
import re
from string import Template

def escape_dollar_vars(template_str: str) -> str:
    return re.sub(r'\$([^{])', r'$$\1', template_str)

def prepare_command(template: str, **custom_vars) -> str:
    # Step 1: expand env vars
    expanded = os.path.expandvars(template)
    # Step 2: escape extra dollar vars
    escaped = escape_dollar_vars(expanded)
    # Step 3: substitute with template
    return Template(escaped).safe_substitute(**custom_vars)

# Example
cmd = "file $EDITOR && echo ${message} && echo $message"
result = prepare_command(cmd, folder="/mnt/c/Users/notso", message="All done!")
print(result)
# returns `file hx && echo All done! && echo $message`

Metadata

Metadata

Assignees

No one assigned

    Labels

    difficulty: easythis feature is easy to implement, or this bug is easy to fixfeature-requestnew feature or requesttracker-issueThis issue is a child of another issue, acts as a tracker for the parent.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions