Commit e135944d authored by Tanner Prestegard's avatar Tanner Prestegard

Significant linting of package with flake8

parent 7c3e3dae
from __future__ import absolute_import, print_function
import argparse
import json
import os
import six
import sys
import shutil
import textwrap
from ligo.gracedb.rest import GraceDb, DEFAULT_SERVICE_URL
......@@ -62,34 +60,83 @@ class CommandLineInterface(CommandBase):
parser.add_argument("command", nargs='?')
# Other options
parser.add_argument("-s", "--service-url", dest="service",
help="GraceDB service URL", metavar="URL", type=str,
default=os.environ.get("GRACEDB_SERVICE_URL", DEFAULT_SERVICE_URL))
parser.add_argument("-p", "--proxy", dest="proxy", help="HTTP Proxy",
default=os.environ.get("HTTP_PROXY", None), metavar="PROXY[:PORT]",
type=str)
parser.add_argument("-V", "--version", action='version',
version=VERSION_STRING)
parser.add_argument("--output-type", type=str, dest='output_type',
default='json', choices=['status', 'json'],
help=("Select output type: 'status' = status code only, "
"'json' = full response JSON. Doesn't apply to some some "
"commands which have pre-defined outputs, like 'info', "
"'ping', 'search', etc."))
parser.add_argument('--username', type=str, dest='username',
help='Basic auth username', default=None)
parser.add_argument('--password', type=str, dest='password',
help='Basic auth password', default=None)
parser.add_argument('--creds', type=str, dest='creds', default=None,
help=('Paths to certficate file and key file (comma-separated) OR '
'path to single combined proxy file. Used for X.509 '
'authentication'))
parser.add_argument("-n", "--force-noauth", dest="force_noauth",
parser.add_argument(
"-s",
"--service-url",
dest="service",
type=str,
metavar="URL",
help="GraceDB service URL",
default=os.environ.get("GRACEDB_SERVICE_URL", DEFAULT_SERVICE_URL)
)
parser.add_argument(
"-p",
"--proxy",
dest="proxy",
type=str,
metavar="PROXY[:PORT]",
help="HTTP Proxy",
default=os.environ.get("HTTP_PROXY", None)
)
parser.add_argument(
"-V",
"--version",
action='version',
version=VERSION_STRING
)
parser.add_argument(
"--output-type",
dest='output_type',
type=str,
help=textwrap.dedent("""\
Select output type: 'status' = status code
only, 'json' = full response JSON. Doesn't
apply to some some commands which have
pre-defined outputs, like 'info', 'ping',
'search', etc.""").rstrip(),
default='json', choices=['status', 'json']
)
parser.add_argument(
'--username',
dest='username',
type=str,
help='Basic auth username',
default=None
)
parser.add_argument(
'--password',
dest='password',
type=str,
help='Basic auth password',
default=None
)
parser.add_argument(
'--creds',
dest='creds',
type=str,
help=textwrap.dedent("""\
Paths to certficate file and key file
(comma-separated) OR path to single combined
proxy file. Used for X.509 authentication
""").rstrip(),
default=None
)
parser.add_argument(
"-n",
"--force-noauth",
dest="force_noauth",
action="store_true",
help="Do not use any authentication credentials",
action="store_true", default=False)
parser.add_argument("-f", "--fail-if-noauth", dest="fail_if_noauth",
default=False
)
parser.add_argument(
"-f",
"--fail-if-noauth",
dest="fail_if_noauth",
action="store_true",
help="Fail if no authentication credentials are found",
action="store_true", default=False)
default=False
)
return parser
# Utils -------------------------------------------------------------------
......@@ -101,7 +148,7 @@ class CommandLineInterface(CommandBase):
try:
proxy, proxyport = proxy.split(':')
proxyport = int(proxyport)
except Exception as e:
except Exception:
print("Malformed proxy: '{0}'".format(proxy))
sys.exit(1)
......@@ -118,7 +165,7 @@ class CommandLineInterface(CommandBase):
else:
print("Malformed 'creds' argument: {0}".format(args.creds))
sys.exit(1)
# Define kwargs for initializing client
client_kwargs = {
'service_url': args.service,
......@@ -157,7 +204,7 @@ def main(args=None):
# Handle errors
if response.status >= 400:
output = '{code} {reason}'.format(code=response.status,
reason=response.reason)
reason=response.reason)
# Only add message if it's not really long (i.e., it's not
# an HTML error page)
msg = response.read()
......
import argparse
import textwrap
from .base import RegisteredCommandBase, RegisteredSubCommandBase
from ..parsers import object_id_parser, superevent_id_parser
# Command registry - don't touch!
registry = []
###############################################################################
# Base command
###############################################################################
registry = []
class AddCommand(RegisteredCommandBase):
name = "add"
description = textwrap.dedent("""\
......@@ -36,8 +38,11 @@ class AddEventCommand(AddChildBase):
parent_parsers = (superevent_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument('graceid', type=str,
help='Graceid of event to add to superevent')
parser.add_argument(
'graceid',
type=str,
help='Graceid of event to add to superevent'
)
return parser
def run(self, client, args):
......@@ -50,9 +55,12 @@ class AddLabelCommand(AddChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("label", type=str, help=("Name of label to apply "
"(do '{prog} info labels' to see options)").format(
prog=self.base_prog))
parser.add_argument(
"label",
type=str,
help=("Name of label to apply (do '{prog} info labels' to see "
"options)").format(prog=self.base_prog)
)
return parser
def run(self, client, args):
......@@ -65,14 +73,26 @@ class AddTagCommand(AddChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("log_number", metavar="N", type=int,
help="Index number of log entry")
parser.add_argument("tag_name", type=str,
parser.add_argument(
"log_number",
metavar="N",
type=int,
help="Index number of log entry"
)
parser.add_argument(
"tag_name",
type=str,
help="Name of tag to apply")
parser.add_argument("-d", "--tag-display-name", type=str,
help="Display name for tag (new tags only)")
parser.add_argument(
"-d",
"--tag-display-name",
type=str,
help="Display name for tag (new tags only)"
)
return parser
def run(self, client, args):
return client.addTag(args.object_id, args.log_number,
tag_name=args.tag_name, displayName=args.tag_display_name)
return client.addTag(
args.object_id, args.log_number, tag_name=args.tag_name,
displayName=args.tag_display_name
)
import argparse
from six import with_metaclass
import sys
import textwrap
import types
from . import command_registry
from ..parsers import CustomHelpArgumentParser
......@@ -23,7 +21,7 @@ class CommandBase(object):
# Set up list of tuples of subcommand name and the subcommand
# object itself, sorted by name
self.subcommand_list = sorted([(sc.name, sc) for sc in
self.subcommands])
self.subcommands])
# Set up dict of subcommands, where key is name and value is
# the subcommand
......@@ -52,7 +50,7 @@ class CommandBase(object):
# Set up epilog
parser.epilog = ("\n\nUse '{prog} <command> --help' to read about a "
"specific command.").format(prog=parser.prog)
"specific command.").format(prog=parser.prog)
# Store base prog name
self.base_prog = base_prog
......@@ -64,8 +62,8 @@ class CommandBase(object):
def parse_args(self, args):
# Modify args to allow passing --help flag to subcommands
modified_args = [arg for arg in args if (arg != '--help' and
arg != '-h')]
modified_args = [arg for arg in args if (arg != '--help'
and arg != '-h')]
# Check if help is requested (or needed)
send_help = False
......@@ -79,7 +77,6 @@ class CommandBase(object):
self.args = main_args
# If send_help and no command is specified, print help and exit
#if send_help and main_args.command is None:
if main_args.command is None:
if send_help:
self.parser.print_help()
......@@ -94,15 +91,15 @@ class CommandBase(object):
except ValueError:
# Command not found
error_str = ("Command '{prog} {cmd}' not found. Do "
"'{prog} --help' to see available commands.\n").format(
prog=self.parser.prog, cmd=main_args.command)
"'{prog} --help' to see available commands.\n") \
.format(prog=self.parser.prog, cmd=main_args.command)
print(error_str)
sys.exit(1)
# If base_prog is not set, assume this is the base prog
base_prog = self.base_prog or self.parser.prog
subcommand = self.subcommands[sc_index](parent_prog=self.parser.prog,
base_prog=base_prog)
base_prog=base_prog)
# Append --help to cmd_args, if needed
if send_help:
......@@ -141,9 +138,12 @@ class SubCommandBase(object):
description += '.'
# Set up parser
parser = argparse.ArgumentParser(description=description,
parents=self.parent_parsers, prog=self.get_prog(parent_prog),
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser = argparse.ArgumentParser(
description=description,
parents=self.parent_parsers,
prog=self.get_prog(parent_prog),
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser = self.add_custom_arguments(parser)
self.parser = parser
......@@ -168,7 +168,7 @@ class SubCommandBase(object):
###############################################################################
# Registering commands
# Registering commands
###############################################################################
class RegisteredCommandMeta(type):
def __new__(meta, name, bases, attrs):
......@@ -180,7 +180,8 @@ class RegisteredCommandMeta(type):
class RegisteredCommandBase(
with_metaclass(RegisteredCommandMeta, CommandBase)):
with_metaclass(RegisteredCommandMeta, CommandBase)
):
@classmethod
def _register(cls):
......
This diff is collapsed.
import argparse
import textwrap
from .base import RegisteredCommandBase, RegisteredSubCommandBase
from ..parsers import object_id_parser
# Command registry - don't touch!
registry = []
###############################################################################
# Base command
###############################################################################
registry = []
class DeleteCommand(RegisteredCommandBase):
name = "delete"
description = "Delete a superevent signoff"
......@@ -32,16 +34,23 @@ class DeleteSignoffCommand(DeleteChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("signoff_type", type=str,
parser.add_argument(
"signoff_type",
type=str,
help=("Signoff type (do '{prog} info signoff_types') to see "
"options").format(prog=self.base_prog))
parser.add_argument("instrument", type=str, nargs='?',
"options").format(prog=self.base_prog)
)
parser.add_argument(
"instrument",
type=str,
nargs='?',
help=("Instrument code (do {prog} info instruments to see "
"options). Required for operator signoffs.").format(
prog=self.base_prog))
"options). Required for operator signoffs.")
.format(prog=self.base_prog)
)
return parser
def run(self, client, args):
instrument = args.instrument or '' # Convert None to ''
instrument = args.instrument or '' # Convert None to ''
return client.delete_signoff(args.object_id, args.signoff_type,
instrument=instrument)
instrument=instrument)
import argparse
import os
import shutil
import textwrap
......@@ -7,10 +6,13 @@ from .base import RegisteredCommandBase, RegisteredSubCommandBase
from ..parsers import object_id_parser, graceid_parser, superevent_id_parser
# Command registry - don't touch!
registry = []
###############################################################################
# Base command
###############################################################################
registry = []
class GetCommand(RegisteredCommandBase):
name = "get"
description = textwrap.dedent("""\
......@@ -36,13 +38,16 @@ class GetEmobservationCommand(GetChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("N", type=int,
help="Index number of the EM observation")
parser.add_argument(
"N",
type=int,
help="Index number of the EM observation"
)
return parser
def run(self, client, args):
return client.emobservations(args.object_id,
emobservation_num=args.N)
emobservation_num=args.N)
class GetEventCommand(GetChildBase):
......@@ -60,11 +65,19 @@ class GetFileCommand(GetChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("filename", type=str,
help="Name of file (on the server) to download")
parser.add_argument("destination", type=str, nargs='?',
default='-', help=("Path to save file at. Default is '-', which "
"prints the contents to stdout"))
parser.add_argument(
"filename",
type=str,
help="Name of file (on the server) to download"
)
parser.add_argument(
"destination",
type=str,
nargs='?',
help=("Path to save file at. Default is '-', which prints "
"the contents to stdout"),
default='-'
)
return parser
def run(self, client, args):
......@@ -72,10 +85,10 @@ class GetFileCommand(GetChildBase):
# of getting it. Also, try not to open a file until we know that we
# we have data.
if args.destination != '-':
if not os.access(os.path.dirname(os.path.abspath(
args.destination)), os.W_OK):
full_dir_path = os.path.dirname(os.path.abspath(args.destination))
if not os.access(full_dir_path, os.W_OK):
raise IOError("{0}: permission denied".format(
args.destination))
args.destination))
# Get file content
response = client.files(args.object_id, args.filename)
......@@ -118,8 +131,11 @@ class GetLogCommand(GetChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("N", type=int,
help="Index number of the log entry")
parser.add_argument(
"N",
type=int,
help="Index number of the log entry"
)
return parser
def run(self, client, args):
......@@ -136,19 +152,28 @@ class GetSignoffCommand(GetChildBase):
parent_parsers = (superevent_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("signoff_type", type=str,
parser.add_argument(
"signoff_type",
type=str,
help=("Signoff type (do '{prog} info signoff_types' to see "
"options)").format(prog=self.base_prog))
parser.add_argument("instrument", type=str, nargs='?',
"options)").format(prog=self.base_prog)
)
parser.add_argument(
"instrument",
type=str,
nargs='?',
help=("Instrument code (do '{prog} info instruments' to see "
"options). Required for operator signoffs.").format(
prog=self.base_prog))
"options). Required for operator signoffs.")
.format(prog=self.base_prog)
)
return parser
def run(self, client, args):
instrument = args.instrument or '' # Convert None to ''
return client.signoffs(args.superevent_id,
signoff_type=args.signoff_type, instrument=instrument)
instrument = args.instrument or '' # Convert None to ''
return client.signoffs(
args.superevent_id, signoff_type=args.signoff_type,
instrument=instrument
)
class GetSupereventCommand(GetChildBase):
......
import argparse
import textwrap
from .base import RegisteredCommandBase, RegisteredSubCommandBase
from ..parsers import object_id_parser, graceid_parser, superevent_id_parser
from ..parsers import object_id_parser, superevent_id_parser
# Command registry - don't touch!
registry = []
###############################################################################
# Base command
###############################################################################
registry = []
class ListCommand(RegisteredCommandBase):
name = "list"
description = textwrap.dedent("""\
......@@ -78,8 +79,11 @@ class ListTagsCommand(ListChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("N", type=int,
help="Index number of the log entry")
parser.add_argument(
"N",
type=int,
help="Index number of the log entry"
)
return parser
def run(self, client, args):
......
import argparse
import textwrap
from .base import RegisteredCommandBase, RegisteredSubCommandBase
from ..parsers import object_id_parser, superevent_id_parser, graceid_parser
# Command registry - don't touch!
registry = []
###############################################################################
# Base command
###############################################################################
registry = []
class RemoveCommand(RegisteredCommandBase):
name = "remove"
description = textwrap.dedent("""\
......@@ -44,10 +46,12 @@ class RemoveTagCommand(RemoveChildBase):
parent_parsers = (object_id_parser,)
def add_custom_arguments(self, parser):
parser.add_argument("log_number", type=int,
help="Index number of log entry")
parser.add_argument("tag_name", type=str,
help="Name of tag to remove")
parser.add_argument(
"log_number",
type=int,
help="Index number of log entry"
)
parser.add_argument("tag_name", type=str, help="Name of tag to remove")
return parser
def run(self, client, args):
......@@ -61,4 +65,4 @@ class RemoveEventCommand(RemoveChildBase):
def run(self, client, args):
return client.removeEventFromSuperevent(args.superevent_id,
args.graceid)
args.graceid)
import argparse
import textwrap
import sys
from .base import RegisteredCommandBase, RegisteredSubCommandBase
from ..parsers import object_id_parser, superevent_id_parser, graceid_parser
from ..utils import parse_delimited_string
# Command registry - don't touch!
registry = []
###############################################################################
# Base command
###############################################################################
registry = []
class SearchCommand(RegisteredCommandBase):
name = "search"
description = "Get a list of events or superevents based on a search query"
......@@ -36,16 +37,31 @@ class SearchSupereventsCommand(SearchChildBase):
client_func = "superevents"
def add_custom_arguments(self, parser):
parser.add_argument("query", type=str,
help="Search query (surround with quotes)")
parser.add_argument("--columns", type=parse_delimited_string,
parser.add_argument(
"query",
type=str,
help="Search query (surround with quotes)"
)
parser.add_argument(
"--columns",
type=parse_delimited_string,
help=("Comma-separated list of parameters to show for each search "
"result. Use '.' to get nested parameters (ex: 'links.files')"),
default=self.default_columns)
parser.add_argument("--max-results", type=int,
help="Maximum number of results to show", default=None)
parser.add_argument("--delimiter", type=str, default="TAB",
help="Delimiter for output")
"result. Use '.' to get nested parameters "
"(ex: 'links.files')"),
default=self.default_columns
)
parser.add_argument(
"--max-results",
type=int,
help="Maximum number of results to show",
default=None
)
parser.add_argument(
"--delimiter",
type=str,
default="TAB",
help="Delimiter for output"
)
return parser
def run(self, client, args):
......@@ -57,7 +73,7 @@ class SearchSupereventsCommand(SearchChildBase):
output = []
for item in iterator:
output.append([self.process_element(item, col) for col in
args.columns])
args.columns])
# Kludge for handling delimiter (if we set the default directly as
# \t, it's not obvious in the help message)
......@@ -82,11 +98,11 @@ class SearchSupereventsCommand(SearchChildBase):
for c in col_levels:
try:
a = a[c]
except KeyError as e:
except KeyError:
msg = ("'{col}' is not available in the response JSON. Check "
"the format on the server or by using '{prog} get' to "
"retrieve an individual event or superevent.").format(
col=col, prog=self.base_prog)
"the format on the server or by using '{prog} get' to "
"retrieve an individual event or superevent.") \
.format(col=col, prog=self.base_prog)
print(msg)
sys.exit(1)
......
import argparse
import os
import six
import sys
import textwrap
from .base import RegisteredSubCommandBase
from ..parsers import (
object_id_parser, superevent_id_parser, graceid_parser, comment_parser,
tag_parser, label_parser,
)
from ..parsers import superevent_id_parser
class ConfirmAsGwCommand(RegisteredSubCommandBase):
......@@ -35,10 +29,13 @@ class CredentialsCommand(RegisteredSubCommandBase):
""").rstrip()
def add_custom_arguments(self, parser):
parser.add_argument('type', type=str,
parser.add_argument(
'type',
type=str,
choices=['client', 'server'],
help=('View credentials found by the client or get your user '
'account information from the server'))
'account information from the server')
)
return parser
def run(self, client, args):
......@@ -57,8 +54,11 @@ class ExposeCommand(RegisteredSubCommandBase):
""").rstrip()
def add_custom_arguments(self, parser):
parser.add_argument('superevent_id', type=str,
help="ID of the superevent to expose")
parser.add_argument(
'superevent_id',
type=str,
help="ID of the superevent to expose"
)
return parser
def run(self, client, args):
......@@ -75,8 +75,11 @@ class HideCommand(RegisteredSubCommandBase):
""").rstrip()
def add_custom_arguments(self, parser):
parser.add_argument('superevent_id', type=str,
help="ID of the superevent to hide")
parser.add_argument(
'superevent_id',
type=str,
help="ID of the superevent to hide"
)