Skip to content

Commit

Permalink
feat(launch_ext): allow user to specify file paths in WriteTempFile
Browse files Browse the repository at this point in the history
  • Loading branch information
MrBlenny committed Nov 19, 2024
1 parent 7a213e0 commit ff7e868
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions launch_ext/substitutions/write_temp_file.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Module for the WriteTempFile substitution."""

from typing import Text, List, BinaryIO
from typing import Text, List, BinaryIO, Optional
from tempfile import NamedTemporaryFile

from launch.launch_context import LaunchContext
Expand All @@ -13,10 +13,11 @@
class WriteTempFile(Substitution):
"""Substitution that writes the contents to a named temporary file and returns the file path."""

def __init__(self, contents: SomeSubstitutionsType) -> None:
def __init__(self, contents: SomeSubstitutionsType, path: Optional[str] = None) -> None:
"""Create a WriteTempFile substitution."""
super().__init__()
self.__contents = contents
self.__path = path

@property
def contents(self) -> List[Substitution]:
Expand All @@ -34,6 +35,13 @@ def write(self, handle: BinaryIO, context: LaunchContext) -> None:
def perform(self, context: LaunchContext) -> Text:
"""Perform the substitution by writing the contents to a temporary file and returning the file path."""

# If a path is provided, write to that
if self.__path:
with open(self.__path, 'w') as file:
self.write(file, context)
return self.__path

# Otherwise, write to a temporary file
temp_file = NamedTemporaryFile(delete=False)
self.write(temp_file, context)
temp_file.flush()
Expand Down

0 comments on commit ff7e868

Please sign in to comment.