Skip to content

Commit 3e98283

Browse files
committed
pymcnp/cli: updated io
1 parent 7d5ace0 commit 3e98283

File tree

12 files changed

+123
-100
lines changed

12 files changed

+123
-100
lines changed

src/demo/main.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,19 @@
1-
import sys
2-
3-
import docopt
4-
5-
6-
DEMO_DOCOPT = """
1+
"""
72
Usage:
83
demo <inp>
94
"""
105

6+
import docopt
7+
118

129
def main():
13-
args = docopt.docopt(DEMO_DOCOPT)
10+
args = docopt.docopt(__doc__)
1411

1512
try:
1613
open(args['<inp>'])
17-
print(f"[DEMO] Args: {' '.join(sys.argv)}")
1814
except FileNotFoundError:
19-
print('[DEMO] Input file not found.')
2015
exit(1)
2116

2217
path = ''.join(args['<inp>'].split('.')[:-1]) + '.outp'
2318
with open(path, 'x') as file:
24-
print(path)
2519
file.write('MCNP Output! :)')

src/pymcnp/cli/_errors.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,15 @@ class CliCode(enum.Enum):
1111
Represents ``CliError`` error codes.
1212
1313
Notes:
14-
10X: Value, ``Run``.
14+
10X: System.
15+
11X: Value, ``Run``.
1516
"""
1617

17-
INVALID_INP = 100
18-
INVALID_PATH = 101
19-
INVALID_PREHOOK = 102
20-
INVALID_POSTHOOK = 103
21-
INVALID_COMMAND = 104
18+
INVALID_INP = 110
19+
INVALID_PATH = 111
20+
INVALID_PREHOOK = 112
21+
INVALID_POSTHOOK = 113
22+
INVALID_COMMAND = 114
2223

2324

2425
class CliError(Exception):
@@ -73,6 +74,6 @@ def __str__(self) -> str:
7374
hint += ''
7475

7576
if hint:
76-
return f'\n\033[31;4;1mCliError[{self.code.name}]\033[0m: {head}\n|\n| {repr(self.info)}\n|\n| \033[35;4mHint\033[0m: {hint}\n|'
77+
return f'[red][bold]McnpError[{self.code.name}]:[/][/] {head}\n\n``{self.info[:]}``\n\n[magenta][bold]Hint:[/bold][/magenta] {hint}'
7778
else:
78-
return f'\n\033[31;4;1mCliError[{self.code.name}]\033[0m: {head}\n|\n| {repr(self.info)}\n|'
79+
return f'[red][bold]McnpError[{self.code.name}]:[/][/] {head}\n\n``{self.info[:]}``'

src/pymcnp/cli/_io.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,31 @@
55
import datetime
66

77
import rich
8+
import rich.panel
89

910

1011
def get_timestamp() -> str:
1112
return datetime.datetime.today().strftime('%Y-%m-%d--%H-%M-%S')
1213

1314

1415
def error(msg):
15-
rich.print(msg)
16+
rich.print(rich.panel.Panel(msg))
1617
exit(1)
1718

1819

19-
def warning(msg):
20+
def print(msg):
2021
rich.print(rich.panel.Panel(msg))
21-
return
22+
23+
24+
def done():
25+
rich.print(rich.panel.Panel('[deep_sky_blue1][bold]Info:[/][/] Done!'))
26+
27+
28+
def warning():
29+
rich.print(
30+
rich.panel.Panel(
31+
'[bold][gold3]Warning:[/][/] PyMCNP is just getting started! '
32+
'Please, double check the output to make sure everything works. '
33+
'If you find errors, please, report them on [link=https://github.com/FSIBT/PyMCNP/issues]GitHub[/link].'
34+
)
35+
)

src/pymcnp/cli/check.py

Lines changed: 25 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
"""
22
Usage:
3-
pymcnp check [options] <input_file>
3+
pymcnp check [options] <file>
44
55
Options:
66
-f --fix Reformat input file.
7-
-o file --output=file Write to file instead of overwriting the input file.
87
"""
98

10-
from pathlib import Path
11-
import sys
9+
import pathlib
10+
import difflib
1211

1312
from docopt import docopt
14-
from rich import print
15-
from rich.panel import Panel
1613

17-
import pymcnp
14+
from . import _io
15+
from .. import files
1816

1917

2018
def main() -> None:
@@ -24,42 +22,27 @@ def main() -> None:
2422
``pymcnp check`` checks INP file syntax.
2523
"""
2624

27-
args = docopt(__doc__)
28-
29-
input_file = Path(args['<input_file>'])
30-
31-
print(
32-
Panel(
33-
'[orange3]Warning[/] PyMCNP is just getting started.'
34-
'Please double check the output to make sure everyhing is working as expected'
35-
'If you find an error, please report it at https://github.com/FSIBT/PyMCNP/issues'
36-
)
37-
)
25+
_io.warning()
3826

39-
if not input_file.is_file():
40-
print(f'[red]ERROR[/] Input file {input_file} does not exists.')
41-
sys.exit(1)
27+
# Processing CLI arguments.
28+
args = docopt(__doc__)
29+
file = pathlib.Path(args['<file>'])
4230

31+
# Reading INP file.
4332
try:
44-
data = pymcnp.read_input(input_file)
45-
except: # noqa
46-
print('[red]ERROR[/] Cannot read input file.')
47-
print(
48-
' We would appreciate if you can report this '
49-
'(and if possible share the input file) at https://github.com/FSIBT/PyMCNP/issues'
50-
'Thanks! -- your PyMCNP team'
51-
)
52-
sys.exit(2)
53-
33+
inp = files.inp.Inp.from_mcnp_file(file)
34+
except files.utils.errors.McnpError as err:
35+
_io.error(err.__str__())
36+
except FileNotFoundError:
37+
_io.error(f'[red][bold]IoError:[/][/] ``{file}`` not found.')
38+
39+
# Running ``diff``!
40+
with open(file, 'r') as file:
41+
diff = difflib.unified_diff(file.readlines(), inp.to_mcnp().split('\n'))
42+
_io.print('\n'.join(line.rstrip('\n') for line in diff))
43+
44+
# Handling ``--fix``.
5445
if args['--fix']:
55-
output = args['--output']
56-
if output is None:
57-
print(data.to_mcnp())
58-
else:
59-
output = Path(output)
60-
if output.is_file():
61-
print('[orange3]Warning[/] Overwriting existing file.')
62-
data.to_mcnp_file(output)
63-
print(':thumbs_up: Rewrote input file.')
64-
else:
65-
print(f':thumbs_up: Input file {input_file} can be parsed.')
46+
inp.to_mcnp_file(file)
47+
48+
_io.done()

src/pymcnp/cli/convert.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020

2121
from docopt import docopt
2222
from rich import print
23-
from rich.panel import Panel
2423

2524
import pymcnp
25+
from . import _io
2626

2727

2828
def main() -> None:
@@ -32,19 +32,13 @@ def main() -> None:
3232
``pymcnp convert`` converts MCNP output files to pandas dataframes.
3333
"""
3434

35+
_io.warning()
36+
3537
args = docopt(__doc__)
3638

3739
N = args['--number']
3840
file_in = Path(args['<input>'])
3941

40-
print(
41-
Panel(
42-
'[orange3]Warning[/] PyMCNP is just getting started.'
43-
'Please double check the output to make sure everyhing is working as expected'
44-
'If you find an error, please report it at https://github.com/FSIBT/PyMCNP/issues'
45-
)
46-
)
47-
4842
if not file_in.is_file():
4943
print(f'[red]Error[/] Cannot access file {file_in}')
5044
sys.exit(1)
@@ -69,3 +63,5 @@ def main() -> None:
6963
print(f'Saving tally {N} as parquet to ', file_out)
7064
case _:
7165
print('Currently cannot handle this file type')
66+
67+
_io.done()

src/pymcnp/cli/hooks/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from . import nps
2+
from . import clean
3+
from . import empty
4+
5+
__all__ = [
6+
'nps',
7+
'clean',
8+
'empty',
9+
]

src/pymcnp/cli/hooks/clean.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1+
import shutil
12
import pathlib
23

34

45
def main(path):
56
path = pathlib.Path(path)
67

78
for file_or_dir in path.rglob('*'):
8-
if file_or_dir.is_file():
9-
file_or_dir.unlink()
10-
else:
11-
file_or_dir.rmdir()
9+
shutil.rmtree(file_or_dir)
1210

1311
path.rmdir()

src/pymcnp/cli/plot.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
from docopt import docopt
1414
from matplotlib import pyplot as plt
1515
from rich import print
16-
from rich.panel import Panel
1716

1817
import pymcnp
18+
from . import _io
1919

2020

2121
def main() -> None:
@@ -25,19 +25,13 @@ def main() -> None:
2525
``pymcnp plot`` plots MCNP output data.
2626
"""
2727

28+
_io.warning()
29+
2830
args = docopt(__doc__)
2931

3032
N = args['--number']
3133
file_in = Path(args['<input>'])
3234

33-
print(
34-
Panel(
35-
'[orange3]Warning[/] PyMCNP is just getting started.'
36-
'Please double check the output to make sure everyhing is working as expected'
37-
'If you find an error, please report it at https://github.com/FSIBT/PyMCNP/issues'
38-
)
39-
)
40-
4135
if not file_in.is_file():
4236
print(f'[red]Error[/] Cannot access file {file_in}')
4337
sys.exit(1)
@@ -78,3 +72,5 @@ def main() -> None:
7872
plt.savefig(output_filename)
7973
else:
8074
plt.show()
75+
76+
_io.done()

src/pymcnp/cli/run.py

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
from docopt import docopt
1717

1818
from . import _io
19+
from . import hooks
1920
from . import _errors
2021
from .. import files
21-
from .hooks import default
2222

2323

2424
EXECUTABLE = """
@@ -57,15 +57,17 @@ class Run:
5757
path_subdirectories: List of paths to run directories.
5858
"""
5959

60-
PREHOOK_PASS = default
61-
POSTHOOK_PASS = default
60+
PREHOOK_EMPTY = hooks.empty
61+
POSTHOOK_EMPTY = hooks.empty
62+
PREHOOK_NPS = hooks.nps
63+
POSTHOOK_CLEAN = hooks.clean
6264

6365
def __init__(
6466
self,
6567
inps: list[files.inp.Inp],
6668
path: pathlib.Path,
67-
prehook: ModuleType = PREHOOK_PASS,
68-
posthook: ModuleType = POSTHOOK_PASS,
69+
prehook: ModuleType = PREHOOK_EMPTY,
70+
posthook: ModuleType = POSTHOOK_EMPTY,
6971
command: str = 'mcnp6',
7072
):
7173
"""
@@ -127,7 +129,7 @@ def __init__(
127129

128130
def run(self, hosts: list[str] = []):
129131
"""
130-
Runs MCNP INP files.
132+
Runs MCNP INP pymcnp.
131133
132134
Parameters:
133135
hosts: List of hostnames on which to execute.
@@ -168,25 +170,35 @@ def main() -> None:
168170
"""
169171
Executes the ``pymcnp run`` command.
170172
171-
``pymcnp run`` runs INP files.
173+
``pymcnp run`` runs INP pymcnp.
172174
"""
173175

174-
args = docopt(__doc__)
176+
_io.warning()
175177

178+
# Processing CLI arguments.
179+
args = docopt(__doc__)
176180
inps = args['<file>']
177181
hosts = args['--hosts'] if args['--hosts'] else []
178182
command = args['--command'] if args['--command'] else 'mcnp6'
179183

184+
# Reading INP files.
180185
try:
181186
inps = [files.inp.Inp.from_mcnp_file(inp) for inp in inps]
182187
except files.utils.errors.McnpError as err:
183188
_io.error(err.__str__())
189+
except FileNotFoundError:
190+
_io.error(f'[red][bold]IoError:[/][/] {inps} File not found.')
184191

185-
path = pathlib.Path(os.getcwd())
186-
192+
# Running!
187193
try:
188-
run = Run(inps, path, command=command)
194+
Run(
195+
inps,
196+
pathlib.Path(os.getcwd()),
197+
prehook=Run.PREHOOK_EMPTY,
198+
posthook=Run.POSTHOOK_CLEAN,
199+
command=command,
200+
).run(hosts)
189201
except _errors.CliError as err:
190202
_io.error(err.__str__())
191203

192-
run.run(hosts)
204+
_io.done()

0 commit comments

Comments
 (0)