diff --git a/doc/changelog.d/951.added.md b/doc/changelog.d/951.added.md new file mode 100644 index 000000000..7eb904cd1 --- /dev/null +++ b/doc/changelog.d/951.added.md @@ -0,0 +1 @@ +Add overwrite option for `App.save_as()` \ No newline at end of file diff --git a/src/ansys/mechanical/core/embedding/app.py b/src/ansys/mechanical/core/embedding/app.py index 34c7443ab..5921a1fc5 100644 --- a/src/ansys/mechanical/core/embedding/app.py +++ b/src/ansys/mechanical/core/embedding/app.py @@ -25,6 +25,8 @@ import atexit import os +import shutil +import tempfile import typing import warnings @@ -194,9 +196,46 @@ def save(self, path=None): else: self.DataModel.Project.Save() - def save_as(self, path): - """Save the project as.""" - self.DataModel.Project.SaveAs(path) + def save_as(self, path: str, overwrite: bool = False): + """Save the project as a new file. + + If the `overwrite` flag is enabled, the current saved file is temporarily moved + to a backup location. The new file is then saved in its place. If the process fails, + the backup file is restored to its original location. + + Parameters + ---------- + path: int, optional + The path where file needs to be saved. + overwrite: bool, optional + Whether the file should be overwritten if it already exists (default is False). + """ + if not os.path.exists(path): + self.DataModel.Project.SaveAs(path) + else: + if not overwrite: + raise Exception( + f"File already exists in {path}, Use ``overwrite`` flag to " + "replace the existing file." + ) + + temp_dir = tempfile.mkdtemp() + temp_file_path = os.path.join(temp_dir, os.path.basename(path)) + + try: + # Move existing file to temp location + shutil.move(path, temp_file_path) + # Save as new file + self.DataModel.Project.SaveAs(path) + # Remove file from temp location + os.remove(temp_file_path) + except Exception as e: + # Restore original file from temp location + shutil.move(temp_file_path, path) + raise e + finally: + # Cleanup temp directory + shutil.rmtree(temp_dir) def launch_gui(self, delete_tmp_on_close: bool = True, dry_run: bool = False): """Launch the GUI.""" diff --git a/tests/embedding/test_app.py b/tests/embedding/test_app.py index a90d3ac7f..fbf1809cd 100644 --- a/tests/embedding/test_app.py +++ b/tests/embedding/test_app.py @@ -66,6 +66,9 @@ def test_app_save_open(embedded_app, tmp_path: pytest.TempPathFactory): embedded_app.DataModel.Project.Name = "PROJECT 1" project_file = os.path.join(tmp_path, f"{NamedTemporaryFile().name}.mechdat") embedded_app.save_as(project_file) + with pytest.raises(Exception): + embedded_app.save_as(project_file) + embedded_app.save_as(project_file, overwrite=True) embedded_app.new() embedded_app.open(project_file) assert embedded_app.DataModel.Project.Name == "PROJECT 1"