Пример #1
0
def set_target(new_target):
    if new_target != '':
        print 'Setting Target: %s' % new_target.split('@')[0]

    global_target_pth = os.path.join('/', 'usr', 'lib', 'yotta_targets')
    target_list = os.listdir(global_target_pth)
    available_target_list = []
    
    for subdir in target_list:
        target_json = os.path.join(global_target_pth, subdir, 'target.json')
        with open(target_json, 'r') as json_file:
            data = json.load(json_file)
            available_target_list.append(data['name'])
    
    if new_target in available_target_list:
        globalconf.set('plain', False)
        link_target_args = argparse.Namespace(target_or_path=new_target, 
                                              config=None,
                                              target=new_target,
                                              set_target=new_target,
                                              save_global=False,
                                              no_install=False)
        link_target.execCommand(link_target_args, '')
        target.execCommand(link_target_args, '')
    else:
        if new_target != '':
            print >>sys.stderr, 'Error: Requested target %s not available. Available targets are:\n' % new_target
        else:
            print >>sys.stderr, 'Available targets are:\n'
        for _target in available_target_list:
            print >>sys.stderr, _target
        sys.exit(1)
def main():
    argparse.ArgumentParser._check_value = kubos_check_value
    parser    = argparse.ArgumentParser('kubos-sdk')
    subparser = parser.add_subparsers(dest='command')

    init_parser   = subparser.add_parser('init')
    target_parser = subparser.add_parser('target')
    build_parser  = subparser.add_parser('build')
    help_parser   = subparser.add_parser('help')

    init_parser.add_argument('proj_name', type=str, nargs=1)
    target_parser.add_argument('target', nargs='?', type=str)

    init_container()

    args, unknown_args = parser.parse_known_args()
    provided_args = vars(args)

    globalconf.set('interactive', False)

    command = provided_args['command']
    if command == 'init':
        proj_name = provided_args['proj_name'][0]
        _init(proj_name)
    elif command == 'target':
        provided_target = provided_args['target']
        if provided_target:
            set_target(provided_target)
        else:
            show_target()
    elif command == 'build':
        _build(unknown_args)
def _build(unknown_args):
    link_std_modules()
    link_mounted_modules()
    current_target = get_current_target()
    globalconf.set('plain', False)
    args = argparse.Namespace(config=None,
                          cmake_generator='Ninja',
                          debug=None,
                          generate_only=False,
                          interactive=False,
                          target=current_target,
                          plain=False,
                          release_build=True,
                          registry=None)

    build_status = build.installAndBuild(args, unknown_args)

    if all(value == 0 for value in build_status.values()):
        print '\nBuild Succeeded'
    else:
        print '\nBuild Failed'
def set_target(new_target):
    available_target_list = get_target_list()
    print 'Setting Target: %s' % new_target.split('@')[0]

    if new_target in available_target_list:
        globalconf.set('plain', False)
        link_global_targets()
        new_target_args = argparse.Namespace(target_or_path=new_target,
                                              config=None,
                                              target=new_target,
                                              set_target=new_target,
                                              save_global=False,
                                              no_install=False)
        target.execCommand(new_target_args, '')
        link_std_modules()
        link_mounted_modules()
        print '\nTarget Successfully Set to: %s' % new_target
    else:
        if new_target != '':
            print >>sys.stderr, 'Error: Requested target %s not available.' % new_target
        print 'Available targets are:\n'
        for _target in available_target_list:
            print >>sys.stderr, _target
        sys.exit(1)
Пример #5
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='Build software using re-usable components.\n'+
        'For more detailed help on each subcommand, run: yotta <subcommand> --help'
    )
    subparser = parser.add_subparsers(metavar='<subcommand>')

    parser.add_argument('--version', nargs=0, action=FastVersionAction,
        help='display the version'
    )
    parser.add_argument('-v', '--verbose', dest='verbosity', action='count',
        default=0,
        help='increase verbosity: can be used multiple times'
    )
    parser.add_argument('-d', '--debug', dest='debug', action='append',
        metavar='SUBSYS',
        help=argparse.SUPPRESS
        #help='specify subsystems to debug: use in conjunction with -v to '+
        #     'increase the verbosity only for specified subsystems'
    )

    parser.add_argument('-t', '--target', dest='target',
        default=detect.defaultTarget(),
        help='Set the build and dependency resolution target (targetname[,versionspec_or_url])'
    )

    parser.add_argument('--plain', dest='plain',
        action='store_true', default=False,
        help="Use a simple output format with no colours"
    )

    parser.add_argument('--noninteractive', '-n', dest='interactive',
        action='store_false', default=True,
        help="Do not wait for user interaction (for example to log in), fail instead."
    )

    parser.add_argument(
        '--registry', default=None, dest='registry', help=argparse.SUPPRESS
    )

    def addParser(name, module_name, description, help=None):
        if help is None:
            help = description
        def onParserAdded(parser):
            import importlib
            module = importlib.import_module('.' + module_name, 'yotta')
            module.addOptions(parser)
            parser.set_defaults(command=module.execCommand)
        subparser.add_parser_async(
            name, description=description, help=help,
            formatter_class=argparse.RawTextHelpFormatter,
            callback=onParserAdded
        )

    addParser('search', 'search',
        'Search for open-source modules and targets that have been published '+
        'to the yotta registry (with yotta publish). See help for `yotta '+
        'install` for installing modules, and for `yotta target` for '+
        'switching targets.'
    )
    addParser('init', 'init', 'Create a new module.')
    addParser('install', 'install',
        'Add a specific module as a dependency, and download it, or install all '+
        'dependencies for the current module.'
    )
    addParser('build', 'build',
        'Build the current module. Options can be passed to the underlying '+
        'build tool by passing them after --, e.g. to do a verbose build '+
        'which will display each command as it is run, use:\n'+
        '  yotta build -- -v\n\n'+
        'The programs or libraries to build can be specified (by default '+
        'only the libraries needed by the current module and the current '+
        "module's own tests are built). For example, to build the tests of "+
        'all dependencies, run:\n  yotta build all_tests\n\n',
        'Build the current module.'
    )
    addParser('version', 'version', 'Bump the module version, or (with no arguments) display the current version.')
    addParser('link', 'link', 'Symlink a module.')
    addParser('link-target', 'link_target', 'Symlink a target.')
    addParser('update', 'update', 'Update dependencies for the current module, or a specific module.')
    addParser('target', 'target', 'Set or display the target device.')
    addParser('debug', 'debug', 'Attach a debugger to the current target.  Requires target support.')
    addParser('test', 'test_subcommand',
        'Run the tests for the current module on the current target. A build '+
        'will be run first, and options to the build subcommand are also '+
        'accepted by test.\nThis subcommand requires the target to provide a '+
        '"test" script that will be used to run each test. Modules may also '+
        'define a "testReporter" script, which will be piped the output from '+
        'each test, and may produce a summary.',
        'Run the tests for the current module on the current target. Requires target support.'
    )
    addParser('publish', 'publish', 'Publish a module or target to the public registry.')
    addParser('unpublish', 'unpublish', 'Un-publish a recently published module or target.')
    addParser('login', 'login', 'Authorize for access to private github repositories and publishing to the yotta registry.')
    addParser('logout', 'logout', 'Remove saved authorization token for the current user.')
    addParser('list', 'list', 'List the dependencies of the current module, or the inherited targets of the current target.')
    addParser('outdated', 'outdated', 'Display information about dependencies which have newer versions available.')
    addParser('uninstall', 'uninstall', 'Remove a specific dependency of the current module, both from module.json and from disk.')
    addParser('remove', 'remove', 'Remove the downloaded version of a dependency, or un-link a linked module.')
    addParser('owners', 'owners', 'Add/remove/display the owners of a module or target.')
    addParser('licenses', 'licenses', 'List the licenses of the current module and its dependencies.')
    addParser('clean', 'clean', 'Remove files created by yotta and the build.')
    addParser('config', 'config', 'Display the target configuration info.')

    # short synonyms, subparser.choices is a dictionary, so use update() to
    # merge in the keys from another dictionary
    short_commands = {
            'up':subparser.choices['update'],
            'in':subparser.choices['install'],
            'ln':subparser.choices['link'],
             'v':subparser.choices['version'],
            'ls':subparser.choices['list'],
            'rm':subparser.choices['remove'],
        'unlink':subparser.choices['remove'],
         'owner':subparser.choices['owners'],
          'lics':subparser.choices['licenses']
    }
    subparser.choices.update(short_commands)

    # split the args into those before and after any '--'
    # argument - subcommands get raw access to arguments following '--', and
    # may pass them on to (for example) the build tool being used
    split_args = splitList(sys.argv, '--')
    following_args = reduce(lambda x,y: x + ['--'] + y, split_args[1:], [])[1:]

    # complete all the things :)
    argcomplete.autocomplete(
         parser,
        exclude = list(short_commands.keys()) + ['-d', '--debug', '-v', '--verbose']
    )

    # when args are passed directly we need to strip off the program name
    # (hence [:1])
    args = parser.parse_args(split_args[0][1:])

    # set global arguments that are shared everywhere and never change
    globalconf.set('interactive', args.interactive)
    globalconf.set('plain', args.plain)

    loglevel = logLevelFromVerbosity(args.verbosity)
    logging_setup.init(level=loglevel, enable_subsystems=args.debug, plain=args.plain)

    # finally, do stuff!
    if 'command' not in args:
        parser.print_usage()
        sys.exit(0)

    try:
        status = args.command(args, following_args)
    except KeyboardInterrupt:
        logging.warning('interrupted')
        status = -1

    sys.exit(status or 0)
Пример #6
0
def main():
    # standard library modules, , ,
    import logging
    from functools import reduce

    # logging setup, , setup the logging system, internal
    from yotta.lib import logging_setup
    # options, , common argument parser options, internal
    import yotta.options as options

    logging_setup.init(level=logging.INFO, enable_subsystems=None, plain=False)

    # we override many argparse things to make options more re-usable across
    # subcommands, and allow lazy loading of subcommand modules:
    parser = options.parser.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='Build software using re-usable components.\n'+
        'For more detailed help on each subcommand, run: yotta <subcommand> --help'
    )
    subparser = parser.add_subparsers(dest='subcommand_name', metavar='<subcommand>')

    parser.add_argument('--version', action='version', version=__version__,
        help='display the version'
    )

    # add re-usable top-level options which subcommands may also accept
    options.verbosity.addTo(parser)
    options.debug.addTo(parser)
    options.plain.addTo(parser)
    options.noninteractive.addTo(parser)
    options.registry.addTo(parser)
    options.target.addTo(parser)
    options.config.addTo(parser)

    def addParser(name, module_name, description, help=None):
        if help is None:
            help = description
        def onParserAdded(parser):
            import importlib
            module = importlib.import_module('.' + module_name, 'yotta')
            module.addOptions(parser)
            parser.set_defaults(command=module.execCommand)
        subparser.add_parser_async(
            name, description=description, help=help,
            formatter_class=argparse.RawTextHelpFormatter,
            callback=onParserAdded
        )

    addParser('search', 'search',
        'Search for open-source modules and targets that have been published '+
        'to the yotta registry (with yotta publish). See help for `yotta '+
        'install` for installing modules, and for `yotta target` for '+
        'switching targets.',
        'Search for published modules and targets'
    )
    addParser('init', 'init', 'Create a new module.')
    addParser('install', 'install',
        'Add a specific module as a dependency, and download it, or install all '+
        'dependencies for the current module.'
    )
    addParser('build', 'build',
        'Build the current module. Options can be passed to the underlying '+
        'build tool by passing them after --, e.g. to do a verbose build '+
        'which will display each command as it is run, use:\n'+
        '  yotta build -- -v\n\n'+
        'The programs or libraries to build can be specified (by default '+
        'only the libraries needed by the current module and the current '+
        "module's own tests are built). For example, to build the tests of "+
        'all dependencies, run:\n  yotta build all_tests\n\n',
        'Build the current module.'
    )
    addParser('version', 'version', 'Bump the module version, or (with no arguments) display the current version.')
    addParser('link', 'link',
        'Symlink a module to be used in another module. Use "yotta link" '+
        '(with no arguments) to link the current module globally. Or use '+
        '"yotta link module-name" To use a module that was previously linked '+
        'globally in the current module.',
        'Symlink a module'
    )
    addParser('link-target', 'link_target',
        'Symlink a target to be used in another module. Use "yotta link-target" '+
        '(with no arguments) to link the current target globally. Or use '+
        '"yotta link-target target-name" To use a target that was previously linked '+
        'globally in the current module.',
        'Symlink a target'
    )
    addParser('update', 'update', 'Update dependencies for the current module, or a specific module.')
    addParser('target', 'target', 'Set or display the target device.')
    addParser('debug', 'debug', 'Attach a debugger to the current target.  Requires target support.')
    addParser('test', 'test_subcommand',
        'Run the tests for the current module on the current target. A build '+
        'will be run first, and options to the build subcommand are also '+
        'accepted by test.\nThis subcommand requires the target to provide a '+
        '"test" script that will be used to run each test. Modules may also '+
        'define a "testReporter" script, which will be piped the output from '+
        'each test, and may produce a summary.',
        'Run the tests for the current module on the current target. Requires target support.'
    )
    addParser('publish', 'publish', 'Publish a module or target to the public registry.')
    addParser('unpublish', 'unpublish', 'Un-publish a recently published module or target.')
    addParser('login', 'login', 'Authorize for access to private github repositories and publishing to the yotta registry.')
    addParser('logout', 'logout', 'Remove saved authorization token for the current user.')
    addParser('whoami', 'whoami', 'Display who the currently logged in user is (if any).')
    addParser('list', 'list', 'List the dependencies of the current module, or the inherited targets of the current target.')
    addParser('outdated', 'outdated', 'Display information about dependencies which have newer versions available.')
    addParser('uninstall', 'uninstall', 'Remove a specific dependency of the current module, both from module.json and from disk.')
    addParser('remove', 'remove',
        'Remove the downloaded version of a dependency module or target, or '+
        'un-link a linked module or target (see yotta link --help for details '+
        'of linking). This command does not modify your module.json file.',
        'Remove or unlink a dependency without removing it from module.json.'
    )
    addParser('owners', 'owners', 'Add/remove/display the owners of a module or target.')
    addParser('licenses', 'licenses', 'List the licenses of the current module and its dependencies.')
    addParser('clean', 'clean', 'Remove files created by yotta and the build.')
    addParser('config', 'config', 'Display the target configuration info.')
    addParser('shrinkwrap', 'shrinkwrap', 'Create a yotta-shrinkwrap.json file to freeze dependency versions.')

    # short synonyms, subparser.choices is a dictionary, so use update() to
    # merge in the keys from another dictionary
    short_commands = {
                'up':subparser.choices['update'],
                'in':subparser.choices['install'],
                'ln':subparser.choices['link'],
                 'v':subparser.choices['version'],
                'ls':subparser.choices['list'],
                'rm':subparser.choices['remove'],
            'unlink':subparser.choices['remove'],
     'unlink-target':subparser.choices['remove'],
             'owner':subparser.choices['owners'],
              'lics':subparser.choices['licenses'],
               'who':subparser.choices['whoami']
    }
    subparser.choices.update(short_commands)

    # split the args into those before and after any '--'
    # argument - subcommands get raw access to arguments following '--', and
    # may pass them on to (for example) the build tool being used
    split_args = splitList(sys.argv, '--')
    following_args = reduce(lambda x,y: x + ['--'] + y, split_args[1:], [])[1:]

    # complete all the things :)
    argcomplete.autocomplete(
         parser,
        exclude = list(short_commands.keys()) + ['-d', '--debug', '-v', '--verbose']
    )

    # when args are passed directly we need to strip off the program name
    # (hence [:1])
    args = parser.parse_args(split_args[0][1:])

    # set global arguments that are shared everywhere and never change
    globalconf.set('interactive', args.interactive)
    globalconf.set('plain', args.plain)

    # finally, do stuff!
    if 'command' not in args:
        parser.print_usage()
        sys.exit(0)

    try:
        status = args.command(args, following_args)
    except KeyboardInterrupt:
        logging.warning('interrupted')
        status = -1

    sys.exit(status or 0)
Пример #7
0
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.

# standard library modules, , ,
import unittest
from collections import namedtuple

# settings, , load and save settings, internal
from yotta.lib import settings
# globalconf, share global arguments between modules, internal
from yotta.lib import globalconf
# install, , install components, internal
from yotta import install

globalconf.set('interactive', False)

Test_Name = 'testing-dummy'
Test_Deps_Name = "autopulated/github-access-testing"
Test_Branch_Name = "autopulated/github-access-testing#master"
Test_Deps_Target = "x86-osx-native,*"


def hasGithubConfig():
    # can't run tests that hit github without an authn token
    if not settings.getProperty('github', 'authtoken'):
        return False
    return True


class TestGitHubAccess(unittest.TestCase):
Пример #8
0
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.


# standard library modules, , ,
import unittest
from collections import namedtuple

# settings, , load and save settings, internal
from yotta.lib import settings
# globalconf, share global arguments between modules, internal
from yotta.lib import globalconf
# install, , install components, internal
from yotta import install

globalconf.set('interactive', False)

Test_Name = 'testing-dummy'
Test_Deps_Name = "autopulated/github-access-testing"
Test_Branch_Name = "autopulated/github-access-testing#master"
Test_Deps_Target = "x86-osx-native,*"

def hasGithubConfig():
    # can't run tests that hit github without an authn token
    if not settings.getProperty('github', 'authtoken'):
        return False
    return True

class TestGitHubAccess(unittest.TestCase):
    def setUp(self):
        pass
Пример #9
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='Build software using re-usable components.\n'+
        'For more detailed help on each subcommand, run: yotta <subcommand> --help'
    )
    subparser = parser.add_subparsers(dest='subcommand_name', metavar='<subcommand>')

    parser.add_argument('--version', nargs=0, action=FastVersionAction,
        help='display the version'
    )
    parser.add_argument('-v', '--verbose', dest='verbosity', action='count',
        default=0,
        help='increase verbosity: can be used multiple times'
    )
    parser.add_argument('-d', '--debug', dest='debug', action='append',
        metavar='SUBSYS',
        help=argparse.SUPPRESS
        #help='specify subsystems to debug: use in conjunction with -v to '+
        #     'increase the verbosity only for specified subsystems'
    )

    parser.add_argument('-t', '--target', dest='target',
        default=detect.defaultTarget(),
        help='Set the build and dependency resolution target (targetname[,versionspec_or_url])'
    )

    parser.add_argument('--plain', dest='plain',
        action='store_true', default=False,
        help="Use a simple output format with no colours"
    )

    parser.add_argument('--noninteractive', '-n', dest='interactive',
        action='store_false', default=True,
        help="Do not wait for user interaction (for example to log in), fail instead."
    )

    parser.add_argument(
        '--registry', default=None, dest='registry', help=argparse.SUPPRESS
    )

    def addParser(name, module_name, description, help=None):
        if help is None:
            help = description
        def onParserAdded(parser):
            import importlib
            module = importlib.import_module('.' + module_name, 'yotta')
            module.addOptions(parser)
            parser.set_defaults(command=module.execCommand)
        subparser.add_parser_async(
            name, description=description, help=help,
            formatter_class=argparse.RawTextHelpFormatter,
            callback=onParserAdded
        )

    addParser('search', 'search',
        'Search for open-source modules and targets that have been published '+
        'to the yotta registry (with yotta publish). See help for `yotta '+
        'install` for installing modules, and for `yotta target` for '+
        'switching targets.',
        'Search for published modules and targets'
    )
    addParser('init', 'init', 'Create a new module.')
    addParser('install', 'install',
        'Add a specific module as a dependency, and download it, or install all '+
        'dependencies for the current module.'
    )
    addParser('build', 'build',
        'Build the current module. Options can be passed to the underlying '+
        'build tool by passing them after --, e.g. to do a verbose build '+
        'which will display each command as it is run, use:\n'+
        '  yotta build -- -v\n\n'+
        'The programs or libraries to build can be specified (by default '+
        'only the libraries needed by the current module and the current '+
        "module's own tests are built). For example, to build the tests of "+
        'all dependencies, run:\n  yotta build all_tests\n\n',
        'Build the current module.'
    )
    addParser('version', 'version', 'Bump the module version, or (with no arguments) display the current version.')
    addParser('link', 'link',
        'Symlink a module to be used in another module. Use "yotta link" '+
        '(with no arguments) to link the current module globally. Or use '+
        '"yotta link module-name" To use a module that was previously linked '+
        'globally in the current module.',
        'Symlink a module'
    )
    addParser('link-target', 'link_target',
        'Symlink a target to be used in another module. Use "yotta link-target" '+
        '(with no arguments) to link the current target globally. Or use '+
        '"yotta link-target target-name" To use a target that was previously linked '+
        'globally in the current module.',
        'Symlink a target'
    )
    addParser('update', 'update', 'Update dependencies for the current module, or a specific module.')
    addParser('target', 'target', 'Set or display the target device.')
    addParser('debug', 'debug', 'Attach a debugger to the current target.  Requires target support.')
    addParser('test', 'test_subcommand',
        'Run the tests for the current module on the current target. A build '+
        'will be run first, and options to the build subcommand are also '+
        'accepted by test.\nThis subcommand requires the target to provide a '+
        '"test" script that will be used to run each test. Modules may also '+
        'define a "testReporter" script, which will be piped the output from '+
        'each test, and may produce a summary.',
        'Run the tests for the current module on the current target. Requires target support.'
    )
    addParser('publish', 'publish', 'Publish a module or target to the public registry.')
    addParser('unpublish', 'unpublish', 'Un-publish a recently published module or target.')
    addParser('login', 'login', 'Authorize for access to private github repositories and publishing to the yotta registry.')
    addParser('logout', 'logout', 'Remove saved authorization token for the current user.')
    addParser('whoami', 'whoami', 'Display who the currently logged in user is (if any).')
    addParser('list', 'list', 'List the dependencies of the current module, or the inherited targets of the current target.')
    addParser('outdated', 'outdated', 'Display information about dependencies which have newer versions available.')
    addParser('uninstall', 'uninstall', 'Remove a specific dependency of the current module, both from module.json and from disk.')
    addParser('remove', 'remove',
        'Remove the downloaded version of a dependency module or target, or '+
        'un-link a linked module or target (see yotta link --help for details '+
        'of linking). This command does not modify your module.json file.',
        'Remove or unlink a dependency without removing it from module.json.'
    )
    addParser('owners', 'owners', 'Add/remove/display the owners of a module or target.')
    addParser('licenses', 'licenses', 'List the licenses of the current module and its dependencies.')
    addParser('clean', 'clean', 'Remove files created by yotta and the build.')
    addParser('config', 'config', 'Display the target configuration info.')

    # short synonyms, subparser.choices is a dictionary, so use update() to
    # merge in the keys from another dictionary
    short_commands = {
                'up':subparser.choices['update'],
                'in':subparser.choices['install'],
                'ln':subparser.choices['link'],
                 'v':subparser.choices['version'],
                'ls':subparser.choices['list'],
                'rm':subparser.choices['remove'],
            'unlink':subparser.choices['remove'],
     'unlink-target':subparser.choices['remove'],
             'owner':subparser.choices['owners'],
              'lics':subparser.choices['licenses'],
               'who':subparser.choices['whoami']
    }
    subparser.choices.update(short_commands)

    # split the args into those before and after any '--'
    # argument - subcommands get raw access to arguments following '--', and
    # may pass them on to (for example) the build tool being used
    split_args = splitList(sys.argv, '--')
    following_args = reduce(lambda x,y: x + ['--'] + y, split_args[1:], [])[1:]

    # complete all the things :)
    argcomplete.autocomplete(
         parser,
        exclude = list(short_commands.keys()) + ['-d', '--debug', '-v', '--verbose']
    )

    # when args are passed directly we need to strip off the program name
    # (hence [:1])
    args = parser.parse_args(split_args[0][1:])

    # set global arguments that are shared everywhere and never change
    globalconf.set('interactive', args.interactive)
    globalconf.set('plain', args.plain)

    loglevel = logLevelFromVerbosity(args.verbosity)
    logging_setup.init(level=loglevel, enable_subsystems=args.debug, plain=args.plain)

    # finally, do stuff!
    if 'command' not in args:
        parser.print_usage()
        sys.exit(0)

    try:
        status = args.command(args, following_args)
    except KeyboardInterrupt:
        logging.warning('interrupted')
        status = -1

    sys.exit(status or 0)
Пример #10
0
def main():
    # standard library modules, , ,
    import logging
    from functools import reduce

    # logging setup, , setup the logging system, internal
    from yotta.lib import logging_setup
    # options, , common argument parser options, internal
    import yotta.options as options

    logging_setup.init(level=logging.INFO, enable_subsystems=None, plain=False)

    # we override many argparse things to make options more re-usable across
    # subcommands, and allow lazy loading of subcommand modules:
    parser = options.parser.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='Build software using re-usable components.\n' +
        'For more detailed help on each subcommand, run: yotta <subcommand> --help'
    )
    subparser = parser.add_subparsers(dest='subcommand_name',
                                      metavar='<subcommand>')

    parser.add_argument('--version',
                        action='version',
                        version=__version__,
                        help='display the version')

    # add re-usable top-level options which subcommands may also accept
    options.verbosity.addTo(parser)
    options.debug.addTo(parser)
    options.plain.addTo(parser)
    options.noninteractive.addTo(parser)
    options.registry.addTo(parser)
    options.target.addTo(parser)
    options.config.addTo(parser)

    def addParser(name, module_name, description, help=None):
        if help is None:
            help = description

        def onParserAdded(parser):
            import importlib
            try:
                module = importlib.import_module('.' + module_name, 'yotta')
            except ImportError:
                module = importlib.import_module('.' + module_name,
                                                 'yotta_plugins')
            module.addOptions(parser)
            parser.set_defaults(command=module.execCommand)

        subparser.add_parser_async(
            name,
            description=description,
            help=help,
            formatter_class=argparse.RawTextHelpFormatter,
            callback=onParserAdded)

    addParser(
        'search', 'search',
        'Search for open-source modules and targets that have been published '
        + 'to the yotta registry (with yotta publish). See help for `yotta ' +
        'install` for installing modules, and for `yotta target` for ' +
        'switching targets.', 'Search for published modules and targets')
    addParser('init', 'init', 'Create a new module.')
    addParser(
        'install', 'install',
        'Add a specific module as a dependency, and download it, or install all '
        + 'dependencies for the current module. Use yotta install ' +
        'modulename@version to install a specific version.')
    addParser(
        'build', 'build',
        'Build the current module. Options can be passed to the underlying ' +
        'build tool by passing them after --, e.g. to do a verbose build ' +
        'which will display each command as it is run, use:\n' +
        '  yotta build -- -v\n\n' +
        'The programs or libraries to build can be specified (by default ' +
        'only the libraries needed by the current module and the current ' +
        "module's own tests are built). For example, to build the tests of " +
        'all dependencies, run:\n  yotta build all_tests\n\n',
        'Build the current module.')
    addParser(
        'version', 'version',
        'Bump the module version, or (with no arguments) display the current version.'
    )
    addParser(
        'link', 'link',
        'Symlink a module to be used into another module.\n\n' +
        'Use: "yotta link" in a module to link it globally, then use "yotta ' +
        'link <modulename>" to link it into the module where you want to use '
        + 'it.\n\n' +
        '"yotta link ../path/to/module" is also supported, which will create '
        +
        'the global link and a link into the current module in a single step.',
        'Symlink a module')
    addParser(
        'link-target', 'link_target',
        'Symlink a target to be used into another module.\n\n' +
        'Use: "yotta link" in a target to link it globally, then use "yotta ' +
        'link-target <targetname>" to link it into the module where you want to use '
        + 'it.\n\n' +
        '"yotta link ../path/to/target" is also supported, which will create '
        +
        'the global link and a link into the current module in a single step.',
        'Symlink a target')
    addParser(
        'update', 'update',
        'Update dependencies for the current module, or a specific module.')
    addParser('target', 'target', 'Set or display the target device.')
    addParser(
        'debug', 'debug',
        'Attach a debugger to the current target.  Requires target support.')
    addParser(
        'test', 'test_subcommand',
        'Run the tests for the current module on the current target. A build '
        + 'will be run first, and options to the build subcommand are also ' +
        'accepted by test.\nThis subcommand requires the target to provide a '
        +
        '"test" script that will be used to run each test. Modules may also ' +
        'define a "testReporter" script, which will be piped the output from '
        + 'each test, and may produce a summary.',
        'Run the tests for the current module on the current target. Requires target support for cross-compiling targets.'
    )
    addParser(
        'start', 'start',
        'Launch the compiled program (available for executable modules only). Requires target support for cross-compiling targets.'
    )
    addParser('publish', 'publish',
              'Publish a module or target to the public registry.')
    addParser('unpublish', 'unpublish',
              'Un-publish a recently published module or target.')
    addParser(
        'login', 'login',
        'Authorize for access to private github repositories and publishing to the yotta registry.'
    )
    addParser('logout', 'logout',
              'Remove saved authorization token for the current user.')
    addParser('whoami', 'whoami',
              'Display who the currently logged in user is (if any).')
    addParser(
        'list', 'list',
        'List the dependencies of the current module, or the inherited targets of the current target.'
    )
    addParser(
        'outdated', 'outdated',
        'Display information about dependencies which have newer versions available.'
    )
    addParser(
        'uninstall', 'uninstall',
        'Remove a specific dependency of the current module, both from module.json and from disk.'
    )
    addParser(
        'remove', 'remove',
        'Remove the downloaded version of a dependency module or target, or ' +
        'un-link a linked module or target (see yotta link --help for details '
        + 'of linking). This command does not modify your module.json file.',
        'Remove or unlink a dependency without removing it from module.json.')
    addParser('owners', 'owners',
              'Add/remove/display the owners of a module or target.')
    addParser('licenses', 'licenses',
              'List the licenses of the current module and its dependencies.')
    addParser('clean', 'clean', 'Remove files created by yotta and the build.')
    addParser('config', 'config', 'Display the target configuration info.')
    addParser(
        'shrinkwrap', 'shrinkwrap',
        'Create a yotta-shrinkwrap.json file to freeze dependency versions.')

    # check for plugins in ./yotta_plugins
    # if found, import them and add parsers accordingly
    searchdir = os.getcwd() + '/yotta_plugins'
    if os.path.exists(searchdir):
        sys.path.append(os.getcwd())
        for directory, subdirectories, files in os.walk(searchdir):
            for file in files:
                if file.endswith(".py") and file != '__init__.py':
                    import importlib
                    try:
                        mod = importlib.import_module(
                            'yotta_plugins.' +
                            os.path.splitext(os.path.basename(file))[0])
                        try:
                            addParser(
                                mod.name,
                                os.path.splitext(os.path.basename(file))[0],
                                mod.description, mod.help)
                        except AttributeError:
                            continue
                    except ImportError:
                        if not os.path.exists(searchdir + '/__init__.py'):
                            logging.error(
                                '\"./yotta_plugins/\" does not contain \"__init__.py\"'
                            )
                            sys.exit(-1)
                        else:
                            logging.error("Unknown plugin import error.")
                            sys.exit(-1)

    # short synonyms, subparser.choices is a dictionary, so use update() to
    # merge in the keys from another dictionary
    short_commands = {
        'up': subparser.choices['update'],
        'in': subparser.choices['install'],
        'ln': subparser.choices['link'],
        'v': subparser.choices['version'],
        'ls': subparser.choices['list'],
        'rm': subparser.choices['remove'],
        'unlink': subparser.choices['remove'],
        'unlink-target': subparser.choices['remove'],
        'owner': subparser.choices['owners'],
        'lics': subparser.choices['licenses'],
        'who': subparser.choices['whoami'],
        'run': subparser.choices['start']
    }
    subparser.choices.update(short_commands)

    # split the args into those before and after any '--'
    # argument - subcommands get raw access to arguments following '--', and
    # may pass them on to (for example) the build tool being used
    split_args = splitList(sys.argv, '--')
    following_args = reduce(lambda x, y: x + ['--'] + y, split_args[1:],
                            [])[1:]

    # complete all the things :)
    argcomplete.autocomplete(parser,
                             exclude=list(short_commands.keys()) +
                             ['-d', '--debug', '-v', '--verbose'])

    # when args are passed directly we need to strip off the program name
    # (hence [:1])
    args = parser.parse_args(split_args[0][1:])

    # set global arguments that are shared everywhere and never change
    globalconf.set('interactive', args.interactive)
    globalconf.set('plain', args.plain)

    # finally, do stuff!
    if 'command' not in args:
        parser.print_usage()
        sys.exit(0)

    try:
        status = args.command(args, following_args)
    except KeyboardInterrupt:
        logging.warning('interrupted')
        status = -1

    sys.exit(status or 0)
Пример #11
0
def main():
    setup_yotta()

    # Everything from yotta.lib needs to be imported after setup_yotta() has been called.
    # Otherwise, default yotta behavior will be imported rather than the overridden kubos
    # behavior that was "injected" into yotta.
    from yotta.lib import lazyregex, errors
    # globalconf, share global arguments between modules, internal
    import yotta.lib.globalconf as globalconf
    import yotta.options as options
    # logging setup, , setup the logging system, internal
    from yotta.lib import logging_setup

    logging_setup.init(level=logging.INFO, enable_subsystems=None, plain=False)

    # we override many argparse things to make options more re-usable across
    # subcommands, and allow lazy loading of subcommand modules:
    parser = options.parser.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='Kubos-CLI For working with Kubos Projects.\n'+
        'For more detailed help on each subcommand, run: kubos <subcommand> --help'
    )
    subparser = parser.add_subparsers(dest='subcommand_name', metavar='<subcommand>')

    # add re-usable top-level options which subcommands may also accept
    options.verbosity.addTo(parser)
    options.debug.addTo(parser)
    options.plain.addTo(parser)
    options.noninteractive.addTo(parser)
    options.registry.addTo(parser)
    options.target.addTo(parser)
    options.config.addTo(parser)


    local_config = sdk_config.load_config()
    add_kubos_command = functools.partial(kubos_options.command.add_command, local_config, subparser, 'kubos') #add our own implemented commands
    add_yotta_command = functools.partial(kubos_options.command.add_command, local_config, subparser, 'yotta') #add from the default yotta commands
    add_kubos_command('init', 'init', 'Create a new module.')
    add_yotta_command('build', 'build',
        'Build the current module. Options can be passed to the underlying '+
        'build tool by passing them after --, e.g. to do a verbose build '+
        'which will display each command as it is run, use:\n'+
        '  yotta build -- -v\n\n'+
        'The programs or libraries to build can be specified (by default '+
        'only the libraries needed by the current module and the current '+
        "module's own tests are built). For example, to build the tests of "+
        'all dependencies, run:\n  yotta build all_tests\n\n',
        'Build the current module.'
    )
    add_kubos_command('link', 'link',
        'Symlink a module to be used into another module.\n\n'+
        'Use: "yotta link" in a module to link it globally, then use "yotta '+
        'link <modulename>" to link it into the module where you want to use '+
        'it.\n\n'+
        '"yotta link ../path/to/module" is also supported, which will create '+
        'the global link and a link into the current module in a single step.',
        'Symlink a module'
    )
    add_yotta_command('link-target', 'link_target',
        'Symlink a target to be used into another module.\n\n'+
        'Use: "yotta link" in a target to link it globally, then use "yotta '+
        'link-target <targetname>" to link it into the module where you want to use '+
        'it.\n\n'+
        '"yotta link ../path/to/target" is also supported, which will create '+
        'the global link and a link into the current module in a single step.',
        'Symlink a target'
    )
    add_kubos_command('update', 'update', 'Download newer versions of the KubOS Modules')
    add_kubos_command('target', 'target', 'Set or display the target device.')
    add_yotta_command('debug', 'debug', 'Attach a debugger to the current target.  Requires target support.')
    add_yotta_command('test', 'test_subcommand',
        'Run the tests for the current module on the current target. A build '+
        'will be run first, and options to the build subcommand are also '+
        'accepted by test.\nThis subcommand requires the target to provide a '+
        '"test" script that will be used to run each test. Modules may also '+
        'define a "testReporter" script, which will be piped the output from '+
        'each test, and may produce a summary.',
        'Run the tests for the current module on the current target. Requires target support for cross-compiling targets.'
    )
    add_yotta_command('start', 'start',
        'Launch the compiled program (available for executable modules only). Requires target support for cross-compiling targets.'
    )
    add_yotta_command('list', 'list', 'List the dependencies of the current module, or the inherited targets of the current target.')
    add_yotta_command('outdated', 'outdated', 'Display information about dependencies which have newer versions available.')
    add_yotta_command('remove', 'remove',
        'Remove the downloaded version of a dependency module or target, or '+
        'un-link a linked module or target (see yotta link --help for details '+
        'of linking). This command does not modify your module.json file.',
        'Remove or unlink a dependency without removing it from module.json.'
    )
    add_yotta_command('licenses', 'licenses', 'List the licenses of the current module and its dependencies.')
    add_yotta_command('clean', 'clean', 'Remove files created by yotta and the build.')
    add_yotta_command('config', 'config', 'Display the target configuration info.')
    add_yotta_command('shrinkwrap', 'shrinkwrap', 'Create a yotta-shrinkwrap.json file to freeze dependency versions.')
    add_kubos_command('version', 'version', 'Display the current active version of the cli and KubOS source repo.')
    add_kubos_command('use', 'use', 'Set a new version of the KubOS modules to build your projects against.')
    add_kubos_command('versions', 'versions', 'Display the available versions of the KubOS source.')

    # short synonyms, subparser.choices is a dictionary, so use update() to
    # merge in the keys from another dictionary
    short_commands = {
                'up':subparser.choices['update'],
                'ln':subparser.choices['link'],
                 'v':subparser.choices['version'],
                'ls':subparser.choices['list'],
                'rm':subparser.choices['remove'],
            'unlink':subparser.choices['remove'],
     'unlink-target':subparser.choices['remove'],
              'lics':subparser.choices['licenses'],
               'run':subparser.choices['start'],
             'flash':subparser.choices['start']
    }
    subparser.choices.update(short_commands)

    # split the args into those before and after any '--'
    # argument - subcommands get raw access to arguments following '--', and
    # may pass them on to (for example) the build tool being used
    split_args = splitList(sys.argv, '--')
    following_args = functools.reduce(lambda x,y: x + ['--'] + y, split_args[1:], [])[1:]

    # complete all the things :)
    argcomplete.autocomplete(
         parser,
        exclude = list(short_commands.keys()) + ['-d', '--debug', '-v', '--verbose']
    )

    # when args are passed directly we need to strip off the program name
    # (hence [:1])
    args = parser.parse_args(split_args[0][1:])

    # set global arguments that are shared everywhere and never change
    globalconf.set('interactive', args.interactive)
    globalconf.set('plain', args.plain)

    # finally, do stuff!
    if 'command' not in args:
        parser.print_usage()
        sys.exit(0)

    try:
        status = args.command(args, following_args)
    except KeyboardInterrupt:
        logging.warning('interrupted')
        status = -1

    return status or 0