I have two files, let's call them foo.py
and fixed_rule_map
. I need to:
- find the line in
foo.py
that contains the pattern rule_map =
. It would be enough to find the pattern rule_map
, if that's easier, but since there are more than one line in foo.py
which contains rule_map
, in this case I need to match only the first occurrence.
- substitute the line in
foo.py
with the contents of fix_rule_map_in_foo
(which contains a single line of text).
For example, foo.py
may look like this:
class example:
"""some useless text.
"""
rule_map = {'greater': lambda x, y: x > y, 'less': lambda x, y: x < y}
def __init__(self,
rule=None,
):
self._init_rule(rule)
def _init_rule(self, rule):
if rule not in self.rule_map and rule is not None:
raise KeyError(f'rule must be greater, less or None, '
f'but got {rule}.')
self.rule = rule
if self.rule is not None:
self.compare_func = self.rule_map[self.rule]
and I would like to correct it to this:
class example:
"""some useless text.
"""
rule_map = {'greater': lambda x, y: (x if x is not None else -inf) > (y if y is not None else -inf), 'less': lambda x, y: (x if x is not None else -inf) < (y if y is not None else -inf)}
def __init__(self,
rule=None,
):
self._init_rule(rule)
def _init_rule(self, rule):
if rule not in self.rule_map and rule is not None:
raise KeyError(f'rule must be greater, less or None, '
f'but got {rule}.')
self.rule = rule
if self.rule is not None:
self.compare_func = self.rule_map[self.rule]
thus fixed_rule_map
would be a text file containing
rule_map = {'greater': lambda x, y: (x if x is not None else -inf) > (y if y is not None else -inf), 'less': lambda x, y: (x if x is not None else -inf) < (y if y is not None else -inf)}
Note that since foo.py
is a Python file, the substitution must preserve indentation.
The command that performs the substitution has to go in a Dockerfile, since the substitution must be performed when building the Docker image. Docker uses /bin/sh
as an interpreter for RUN commands, rather than /bin/bash
, which may be a problem if your solution uses bash
. However, I think I could fix this by using a shell script fix_rule_map_in_foo.sh
:
#! /bin/bash
FOO_PATH = /path/to/foo
<your_solution>
and adding this line in the Dockerfile:
RUN fix_rule_map_in_foo.sh