From de30114e8cfcef0d4b392e5e5c0be3f04b9c6c4c Mon Sep 17 00:00:00 2001 From: wjr21 Date: Sun, 26 May 2024 00:46:02 +0100 Subject: [PATCH] Ensuring we have the placeholders for a command --- src/dir_wand/command_runner.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/dir_wand/command_runner.py b/src/dir_wand/command_runner.py index b177fac..234570e 100644 --- a/src/dir_wand/command_runner.py +++ b/src/dir_wand/command_runner.py @@ -9,6 +9,7 @@ """ import os +import re import threading @@ -44,6 +45,25 @@ def __init__(self, command): # complete at a later stage self.threads = [] + # Unpack placeholders + self._placeholders = set() + self.get_placeholders() + + def get_placeholders(self): + """Extract what place holders the command contains.""" + # Define the regex pattern to extract the placeholders + # (e.g. {placeholder}) + pattern = re.compile(r"\{([a-zA-Z0-9_]+)\}") + + # Find all the matches in the command + matches = pattern.findall(self.command) + + # If we have matches... + if matches is not None: + # Add the placeholders to the set + for match in matches: + self._placeholders.add(match) + def run_command(self, **swaps): """ Run the command. @@ -63,6 +83,11 @@ def run_command(self, **swaps): if not self.command: return + # Ensure we have all the placeholders before we start swapping + missing = self._placeholders - set(swaps.keys()) + if len(missing) > 0: + raise ValueError(f"Missing placeholders: {missing}") + # Replace any swaps in the command command = self.command.format(**swaps) @@ -110,6 +135,8 @@ def run_command_for_all_swaps(self, **swaps): {swap: swaps[swap][i] for swap in swaps} for i in range(nswaps) ] + # Ensure we have all the swaps we need for the command + # Loop over the swaps we'll have to make for swap in swaps: self.run_command(**swap)