|
| 1 | +# Copyright 2023 Open Source Robotics Foundation, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Module for the FileContent substitution.""" |
| 16 | + |
| 17 | +from typing import List |
| 18 | +from typing import Sequence |
| 19 | +from typing import Text |
| 20 | + |
| 21 | +from .substitution_failure import SubstitutionFailure |
| 22 | +from ..frontend import expose_substitution |
| 23 | +from ..launch_context import LaunchContext |
| 24 | +from ..some_substitutions_type import SomeSubstitutionsType |
| 25 | +from ..substitution import Substitution |
| 26 | + |
| 27 | + |
| 28 | +@expose_substitution('file-content') |
| 29 | +class FileContent(Substitution): |
| 30 | + """ |
| 31 | + Substitution that reads the contents of a file. |
| 32 | +
|
| 33 | + If the file is not found a `SubstitutionFailure` error is raised. |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__(self, path: SomeSubstitutionsType) -> None: |
| 37 | + """Create a FileContent substitution.""" |
| 38 | + super().__init__() |
| 39 | + |
| 40 | + from ..utilities import normalize_to_list_of_substitutions |
| 41 | + self.__path = normalize_to_list_of_substitutions(path) |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def parse(cls, data: Sequence[SomeSubstitutionsType]): |
| 45 | + """Parse `FileContent` substitution.""" |
| 46 | + if not data or len(data) != 1: |
| 47 | + raise AttributeError('file content substitutions expect 1 argument') |
| 48 | + kwargs = {'path': data[0]} |
| 49 | + return cls, kwargs |
| 50 | + |
| 51 | + @property |
| 52 | + def path(self) -> List[Substitution]: |
| 53 | + """Getter for path.""" |
| 54 | + return self.__path |
| 55 | + |
| 56 | + def describe(self) -> Text: |
| 57 | + """Return a description of this substitution as a string.""" |
| 58 | + return 'FileContent({})'.format( |
| 59 | + ', '.join([sub.describe() for sub in self.path])) |
| 60 | + |
| 61 | + def perform(self, context: LaunchContext) -> Text: |
| 62 | + """Perform the substitution by evaluating the expression.""" |
| 63 | + from ..utilities import perform_substitutions |
| 64 | + path = perform_substitutions(context, self.path) |
| 65 | + try: |
| 66 | + with open(path, 'r') as f: |
| 67 | + return f.read() |
| 68 | + except FileNotFoundError: |
| 69 | + raise SubstitutionFailure('File not found: {}'.format(path)) |
0 commit comments