23
23
4C."""
24
24
25
25
import copy as _copy
26
- import datetime as _datetime
27
26
import os as _os
28
27
import shutil as _shutil
29
28
import subprocess as _subprocess # nosec B404
30
29
import sys as _sys
30
+ from datetime import datetime as _datetime
31
31
from pathlib import Path as _Path
32
32
from typing import Any as _Any
33
33
from typing import Dict as _Dict
34
34
from typing import List as _List
35
35
from typing import Optional as _Optional
36
+ from typing import Tuple as _Tuple
36
37
37
38
import yaml as _yaml
38
39
@@ -346,16 +347,27 @@ def delete_section(self, section_name):
346
347
raise Warning (f"Section { section_name } does not exist!" )
347
348
348
349
def write_input_file (
349
- self , file_path : _Path , * , nox_xml_file : _Optional [str ] = None , ** kwargs
350
+ self ,
351
+ file_path : _Path ,
352
+ * ,
353
+ nox_xml_file : _Optional [str ] = None ,
354
+ add_header_default : bool = True ,
355
+ add_footer_application_script : bool = True ,
356
+ ** kwargs ,
350
357
):
351
358
"""Write the input file to disk.
352
359
353
360
Args:
354
- file_path: str
361
+ file_path:
355
362
Path to the input file that should be created.
356
- nox_xml_file: str
363
+ nox_xml_file:
357
364
(optional) If this argument is given, the xml file will be created
358
365
with this name, in the same directory as the input file.
366
+ add_header_default:
367
+ Prepend the default MeshPy header comment to the input file.
368
+ add_footer_application_script:
369
+ Append the application script which creates the input files as a
370
+ comment at the end of the input file.
359
371
"""
360
372
361
373
# Check if a xml file needs to be written.
@@ -375,29 +387,41 @@ def write_input_file(
375
387
xml_file .write (self .nox_xml )
376
388
377
389
with open (file_path , "w" ) as input_file :
390
+ # write MeshPy header
391
+ if add_header_default :
392
+ input_file .writelines (
393
+ "# " + line + "\n " for line in _mpy .input_file_meshpy_header
394
+ )
395
+
378
396
_yaml .dump (
379
397
self .get_dict_to_dump (** kwargs ),
380
398
input_file ,
381
399
Dumper = _MeshPyDumper ,
382
400
width = float ("inf" ),
383
401
)
384
402
403
+ # Add the application script to the input file.
404
+ if add_footer_application_script :
405
+ application_path = _Path (_sys .argv [0 ]).resolve ()
406
+ application_script_lines = self ._get_application_script (
407
+ application_path
408
+ )
409
+ input_file .writelines (application_script_lines )
410
+
385
411
def get_dict_to_dump (
386
412
self ,
387
413
* ,
388
- header : bool = True ,
389
- add_script_to_header : bool = True ,
414
+ add_header_information : bool = True ,
390
415
check_nox : bool = True ,
391
416
):
392
417
"""Return the dictionary representation of this input file for dumping
393
418
to a yaml file.
394
419
395
420
Args:
396
- header:
397
- If the header should be exported to the input file files.
398
- add_script_to_header:
399
- If true, a copy of the executing script will be added to the input
400
- file. This is only in affect when header is True.
421
+ add_header_information:
422
+ If the information header should be exported to the input file
423
+ Contains creation date, git details of MeshPy, CubitPy and
424
+ original application which created the input file if available.
401
425
check_nox:
402
426
If this is true, an error will be thrown if no nox file is set.
403
427
"""
@@ -412,14 +436,9 @@ def get_dict_to_dump(
412
436
# TODO: Check if the deepcopy makes sense to be optional
413
437
yaml_dict = _copy .deepcopy (self .sections )
414
438
415
- # TODO: Add header to yaml
416
- # # Add header to the input file.
417
- # end_text = None
418
-
419
- # lines.extend(["// " + line for line in _mpy.input_file_meshpy_header])
420
- # if header:
421
- # header_text, end_text = self._get_header(add_script_to_header)
422
- # lines.append(header_text)
439
+ # Add information header to the input file
440
+ if add_header_information :
441
+ yaml_dict ["TITLE" ] = self ._get_header ()
423
442
424
443
# Check if a file has to be created for the NOX xml information.
425
444
if self .nox_xml is not None :
@@ -622,104 +641,106 @@ def get_number_of_coupling_conditions(key):
622
641
_dump_mesh_items (yaml_dict , "NODE COORDS" , self .nodes )
623
642
_dump_mesh_items (yaml_dict , "STRUCTURE ELEMENTS" , self .elements )
624
643
625
- # TODO: what to do here - how to add the script
626
- # # Add end text.
627
- # if end_text is not None:
628
- # lines.append(end_text)
629
-
630
644
return yaml_dict
631
645
632
- def _get_header (self , add_script ):
633
- """Return the header for the input file."""
646
+ def _get_header (self ) -> dict :
647
+ """Return the information header for the current MeshPy run.
648
+
649
+ Returns:
650
+ A dictionary with the header information.
651
+ """
634
652
635
- def get_git_data (repo ):
636
- """Return the hash and date of the current git commit."""
653
+ def _get_git_data (repo_path : _Path ) -> _Tuple [_Optional [str ], _Optional [str ]]:
654
+ """Return the hash and date of the current git commit.
655
+
656
+ Args:
657
+ repo_path: Path to the git repository.
658
+ Returns:
659
+ A tuple with the hash and date of the current git commit
660
+ if available, otherwise None.
661
+ """
637
662
git = _shutil .which ("git" )
638
663
if git is None :
639
664
raise RuntimeError ("Git executable not found" )
640
665
out_sha = _subprocess .run ( # nosec B603
641
666
[git , "rev-parse" , "HEAD" ],
642
- cwd = repo ,
667
+ cwd = repo_path ,
643
668
stdout = _subprocess .PIPE ,
644
669
stderr = _subprocess .DEVNULL ,
645
670
)
646
671
out_date = _subprocess .run ( # nosec B603
647
672
[git , "show" , "-s" , "--format=%ci" ],
648
- cwd = repo ,
673
+ cwd = repo_path ,
649
674
stdout = _subprocess .PIPE ,
650
675
stderr = _subprocess .DEVNULL ,
651
676
)
677
+
652
678
if not out_sha .returncode + out_date .returncode == 0 :
653
679
return None , None
654
- else :
655
- sha = out_sha .stdout .decode ("ascii" ).strip ()
656
- date = out_date .stdout .decode ("ascii" ).strip ()
657
- return sha , date
658
-
659
- headers = []
660
- end_text = None
661
-
662
- # Header containing model information.
663
- current_time_string = _datetime .datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
664
- model_header = f"// Date: { current_time_string } \n "
665
- if self .description :
666
- model_header += f"// Description: { self .description } \n "
667
- headers .append (model_header )
668
-
669
- # Get information about the script.
670
- script_path = _os .path .realpath (_sys .argv [0 ])
671
- script_git_sha , script_git_date = get_git_data (_os .path .dirname (script_path ))
672
- script_header = "// Script used to create input file:\n "
673
- script_header += f"// path: { script_path } \n "
674
- if script_git_sha is not None :
675
- script_header += (
676
- f"// git sha: { script_git_sha } \n // git date: { script_git_date } \n "
677
- )
678
- headers .append (script_header )
679
680
680
- # Header containing meshpy information.
681
- meshpy_git_sha , meshpy_git_date = get_git_data (
682
- _os .path .dirname (_os .path .realpath (__file__ ))
681
+ git_sha = out_sha .stdout .decode ("ascii" ).strip ()
682
+ git_date = out_date .stdout .decode ("ascii" ).strip ()
683
+ return git_sha , git_date
684
+
685
+ header : dict = {"MeshPy" : {}}
686
+
687
+ header ["MeshPy" ]["creation_date" ] = _datetime .now ().isoformat (
688
+ sep = " " , timespec = "seconds"
683
689
)
684
- headers .append (
685
- "// Input file created with meshpy\n "
686
- f"// git sha: { meshpy_git_sha } \n "
687
- f"// git date: { meshpy_git_date } \n "
690
+
691
+ # application which created the input file
692
+ application_path = _Path (_sys .argv [0 ]).resolve ()
693
+ header ["MeshPy" ]["Application" ] = {"path" : str (application_path )}
694
+
695
+ application_git_sha , application_git_date = _get_git_data (
696
+ application_path .parent
688
697
)
698
+ if application_git_sha is not None and application_git_date is not None :
699
+ header ["MeshPy" ]["Application" ].update (
700
+ {
701
+ "git_sha" : application_git_sha ,
702
+ "git_date" : application_git_date ,
703
+ }
704
+ )
689
705
706
+ # MeshPy information
707
+ meshpy_git_sha , meshpy_git_date = _get_git_data (
708
+ _Path (__file__ ).resolve ().parent
709
+ )
710
+ if meshpy_git_sha is not None and meshpy_git_date is not None :
711
+ header ["MeshPy" ]["MeshPy" ] = {
712
+ "git_SHA" : meshpy_git_sha ,
713
+ "git_date" : meshpy_git_date ,
714
+ }
715
+
716
+ # CubitPy information
690
717
if _cubitpy_is_available ():
691
- # Get git information about cubitpy.
692
- cubitpy_git_sha , cubitpy_git_date = get_git_data (
718
+ cubitpy_git_sha , cubitpy_git_date = _get_git_data (
693
719
_os .path .dirname (_cubitpy .__file__ )
694
720
)
695
721
696
- if cubitpy_git_sha is not None :
697
- # Cubitpy_header.
698
- headers .append (
699
- "// The module cubitpy was loaded\n "
700
- f"// git sha: { cubitpy_git_sha } \n "
701
- f"// git date: { cubitpy_git_date } \n "
702
- )
722
+ if cubitpy_git_sha is not None and cubitpy_git_date is not None :
723
+ header ["MeshPy" ]["CubitPy" ] = {
724
+ "git_SHA" : cubitpy_git_sha ,
725
+ "git_date" : cubitpy_git_date ,
726
+ }
703
727
704
- string_line = "// " + "" . join ([ "-" ] * 80 )
728
+ return header
705
729
706
- # If needed, append the contents of the script.
707
- if add_script :
708
- # Header for the script 'section'.
709
- script_lines = [
710
- string_line
711
- + "\n // Full script used to create this input file.\n "
712
- + string_line
713
- + "\n "
714
- ]
730
+ def _get_application_script (self , application_path : _Path ) -> list [str ]:
731
+ """Get the script that created this input file.
732
+
733
+ Args:
734
+ application_path: Path to the script that created this input file.
735
+ Returns:
736
+ A list of strings with the script that created this input file.
737
+ """
715
738
716
- # Get the contents of script.
717
- with open ( script_path ) as script_file :
718
- script_lines . extend ( script_file . readlines ())
739
+ application_script_lines = [
740
+ "# Application script which created this input file: \n "
741
+ ]
719
742
720
- # Comment the python code lines.
721
- end_text = "//" . join ( script_lines )
743
+ with open ( application_path ) as script_file :
744
+ application_script_lines . extend ( "# " + line for line in script_file )
722
745
723
- return (
724
- string_line + "\n " + (string_line + "\n " ).join (headers ) + string_line
725
- ), end_text
746
+ return application_script_lines
0 commit comments