Skip to content

Commit

Permalink
Add adjustment to filename if needed.
Browse files Browse the repository at this point in the history
  • Loading branch information
WilliamJamieson committed Nov 24, 2023
1 parent 5290be9 commit 9c5fc90
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/roman_datamodels/datamodels/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import datetime
import functools
import sys
from contextlib import contextmanager
from pathlib import Path, PurePath

import asdf
Expand Down Expand Up @@ -46,6 +47,22 @@ def wrapper(self, *args, **kwargs):
return wrapper


@contextmanager
def _temporary_update_filename(datamodel, filename):
"""
Context manager to temporarily update the filename of a datamodel so that it
can be saved with that new file name without changing the current model's filename
"""
from roman_datamodels.stnode import Filename

if "meta" in datamodel._instance and "filename" in datamodel._instance.meta:
old_filename = datamodel._instance.meta.filename
datamodel._instance.meta.filename = Filename(filename)

yield
datamodel._instance.meta.filename = old_filename


class DataModel(abc.ABC):
"""Base class for all top level datamodels"""

Expand Down Expand Up @@ -196,10 +213,10 @@ def open_asdf(self, init=None, **kwargs):
return asdf.open(init, **kwargs) if isinstance(init, str) else asdf.AsdfFile(init, **kwargs)

def to_asdf(self, init, *args, **kwargs):
with validate.nuke_validation():
asdffile = self.open_asdf(**kwargs)
asdffile.tree = {"roman": self._instance}
asdffile.write_to(init, *args, **kwargs)
with validate.nuke_validation(), _temporary_update_filename(self, Path(init).name):
asdf_file = self.open_asdf(**kwargs)
asdf_file.tree = {"roman": self._instance}
asdf_file.write_to(init, *args, **kwargs)

def get_primary_array_name(self):
"""
Expand Down

0 comments on commit 9c5fc90

Please sign in to comment.