codekingpro/portable-devtools
114k
1#!/usr/bin/env python32 3##########################################################################4#5# pgAdmin 4 - PostgreSQL Tools6#7# Copyright (C) 2013 - 2024, The pgAdmin Development Team8# This software is released under the PostgreSQL Licence9#10##########################################################################11 12import argparse13import os14import sys15 16 17def load_providers():18 """ Loads all the providers """19 providers = {}20 21 path = os.path.dirname(os.path.realpath(__file__))22 modules = os.listdir(path + '/providers')23 sys.path.append(path)24 for filename in modules:25 filename = path + '/providers/' + filename26 27 if os.path.isfile(filename):28 basename = os.path.basename(filename)29 _, extension = os.path.splitext(basename)30 31 if extension == ".py" and not basename.startswith("_"):32 module = __import__("providers." + basename[:-3],33 fromlist=["providers"])34 provider = module.load()35 providers[basename[:-3]] = provider36 37 return providers38 39 40def get_args(providers):41 """ Creates the parsers and returns the args """42 # Create the top-level parser43 parser = argparse.ArgumentParser(prog='pgacloud.py')44 45 # Create the provider sub-parser46 parsers = parser.add_subparsers(help='provider help', dest='provider')47 48 # Load the provider parsers49 for provider in providers:50 providers[provider].init_args(parsers)51 52 args = parser.parse_args()53 54 return parser, args55 56 57def execute_command(providers, parser, args):58 """ Executes the command in the provider """59 60 # Switch - for _ in command names. We use - in the CLI syntax for ease of61 # use, but we need an _ in Python function names62 if 'command' in args and args.command is not None:63 args.command = args.command.replace('-', '_')64 65 # Figure out what provider the command was for (if any) and call the66 # relevant function. If we don't get a match, print the help67 if args.provider in providers and \68 'command' in args and \69 args.command is not None:70 command = providers[args.provider].commands()[args.command]71 command(args)72 else:73 # If no provider has been given, display the top level help,74 # otherwise, call the help() method in the provider75 if args.provider is None:76 parser.print_help()77 else:78 command = providers[args.provider].commands()['help']79 command()80 81 82def main():83 """ Entry point """84 # Load the providers85 providers = load_providers()86 87 # Get the args88 parser, args = get_args(providers)89 90 # Execute the command91 execute_command(providers, parser, args)92 93 94if __name__ == '__main__':95 main()96 