Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

xcpy: search multiple directories for a script #105

Merged
merged 3 commits into from
Jul 22, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 74 additions & 39 deletions nmrglue/util/xcpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def topspin_location():
return toppath


def read_cfg(filename):
def read_cfg(filename, check_python=True):
"""
Reads in the configuration file

Expand All @@ -134,14 +134,13 @@ def read_cfg(filename):

try:
scripts_location = config.get("xcpy", "scripts_location")
scripts_location = scripts_location.split(",")
except (NoSectionError, NoOptionerror, KeyError):
scripts_location = ""
scripts_location = [""]

if cpyname:
verify_python(cpyname)

if scripts_location:
exists(scripts_location, raise_error=True)
if check_python:
if cpyname:
verify_python(cpyname)

return cpyname, scripts_location

Expand All @@ -154,33 +153,39 @@ def write_cfg(outfile, infile=None):
if infile is not None:
try:
cpyname, scripts_location = read_cfg(infile)
except Exception:
except OSError:
if exists(infile):
errmsg = """
The following configuration was found in the file {}:

{}

These settings are likely incorrect.
you can enter the correct settings at the next dialog box.
You can enter the correct settings at the next dialog box.
Press 'Close' to continue.
""".format(
infile, show_config(infile, printing=False)
)
MSG(errmsg)
cpyname, scripts_location = "", ""

cpyname, scripts_location = read_cfg(infile, check_python=False)
else:
cpyname, scripts_location = "", ""
cpyname, scripts_location = "", [""]

cpyname, scripts_location = INPUT_DIALOG(
"XCPy Configuration",
"Please Click on OK to write this configuration.",
["CPython Executable", "CPython Scripts Location"],
[cpyname, scripts_location],
["", ""],
["1", "1"],
title="XCPy Configuration",
header="Only one directory path per line. The order for the folders\n"
"given here is the order of priority in which they will be searched.\n"
"Click on OK to write this configuration.",
items=["CPython Executable", "CPython Scripts Location"],
values=[cpyname, "\n".join(scripts_location)],
comments=["", ""],
types=["1", "5"],
columns=40,
)

scripts_location = scripts_location.replace("\n", ",")

if not cpyname or not scripts_location:
MSG("Invalid configartion specified. Config file not written")
else:
Expand Down Expand Up @@ -226,7 +231,7 @@ def current_data():
MSG(
"""No data folder seems to be open!
No arguments will be passed on. If this is intentional,
you should run the command with the --no-args option
you should run the command with the --no-args option,
which will get rid of this message"""
)
return []
Expand Down Expand Up @@ -272,9 +277,7 @@ def run(cpython, script, pass_current_folder=True, use_shell=None, dry=None):
process = None

else:
process = Popen(
args, stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=use_shell
)
process = Popen(args, stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=use_shell)
process.stdin.close()

return process
Expand Down Expand Up @@ -351,11 +354,11 @@ def main():
toppath = topspin_location()

# path and name of the configuration file is hard-coded
config_file = os.path.join(
toppath, "exp", "stan", "nmr", "py", "user", "xcpy.cfg"
)
config_file = os.path.join(toppath, "exp", "stan", "nmr", "py", "user", "xcpy.cfg")

# get arguments passed to xcpy
# if no arguments are passed, tag on --help
# so that the docstring shows up in the next step
argv = sys.argv
if len(argv) == 1:
argv.append("--help")
Expand All @@ -367,6 +370,7 @@ def main():
MSG(__doc__)

# check if configuration exists
# if it does not, alert the user and open up a dialog box to write it out
elif not os.path.exists(config_file):
MSG(
"""
Expand All @@ -380,50 +384,81 @@ def main():
)
write_cfg(config_file)

# if configuration settings are to be changed
# if configuration settings are to be changed,
# open up a dialog box to do so
elif argv[1] in ["-s", "--settings"]:
if len(argv) > 2:
MSG("Opening configuration settings. Ignored all other options")
write_cfg(config_file, config_file)

# show configuration
# prints out the contents of the configuration file
elif argv[1] in ["-c", "--config"]:
show_config(config_file)

# if -h, -c, -s are not used, actual script run is required
else:

# STEP 1: Check for flags that need to be set

# careful!, uses shell and only sanity check is
# that the script being run is called 'python'
# this is required for windows and by default off for *nix
if "--use-shell" in argv:
use_shell = True
else:
use_shell = False

# if no arguments are to be passed to the script
if "--no-args" in argv:
pass_current_folder = False
else:
pass_current_folder = True


# prints out the exact command that will be run using subprocess
# does not actually run anything
if "--dry-run" in argv or "-d" in argv:
dry = True
else:
dry = False

# read configuration
cpyname, folder = read_cfg(config_file)
# STEP 2: READ in configuration file
cpyname, folders = read_cfg(config_file)

# STEP 3: See what script needs to be run
# If a script at unknown location is to be used
if "-n" in argv or "--name" in argv:
scriptname = get_scriptname()
else:
# see if script is there and then run
scriptname = os.path.join(folder, argv[-1])

if exists(scriptname):
process = run(
cpyname, scriptname, pass_current_folder, use_shell, dry
)
else:
scriptname = scriptname + ".py"
if exists(scriptname, raise_error=True):
process = run(
cpyname, scriptname, pass_current_folder, use_shell, dry
# see if script is in one of the folders that
# are given in the cfg file
executed = False

# search priority is top to bottom in the given list
# if a file is found, it stops searching
for folder in folders:
scriptname = os.path.join(folder, argv[-1])

# check for .py extension and append it if not given
if not scriptname.endswith('.py'):
scriptname = scriptname + '.py'

# run the script if it exists and then break from the for loop
# and set the executed status to true
if exists(scriptname):
process = run(
cpyname, scriptname, pass_current_folder, use_shell, dry
)
executed = True
break

# executed should be false iff no script was found
if not executed:
raise Exception(
"The file {} was not found in the following folders:\n\n{}".format(
argv[-1] + ".py", "\n".join(folders)
)
)

# handle errors and print messages from cpython
Expand Down