Пример #1
0
 def test_no_targets(self, get_input, capsys):
     command = EditCommand(None, {}, utils.create_logger())
     command.run()
     out, err = capsys.readouterr()
     assert out == ''
     assert err == ('You have not added any targets yet\n'
                    'Use the "add" command to do this\n')
Пример #2
0
    def test_no_changes(self, get_input, config_file):
        fake_stream = utils.FakeInputStream(["", "", "", "", ""])
        get_input.side_effect = fake_stream

        args = argparse.Namespace(target="foo")
        config = {
            "targets": {
                "foo": {
                    "local_folder": "/home/mark/documents",
                    "s3_uri": "s3://buckets/mybackup",
                    "aws_access_key_id": "23123123123313",
                    "aws_secret_access_key": "edwdadwadwadwdd",
                    "region_name": "eu-west-1",
                }
            }
        }
        command = EditCommand(args, config, utils.create_logger())
        command.run()

        with open(config_file, "r") as fp:
            config = json.load(fp)

        expected_config = {
            "targets": {
                "foo": {
                    "local_folder": "/home/mark/documents",
                    "s3_uri": "s3://buckets/mybackup",
                    "aws_access_key_id": "23123123123313",
                    "aws_secret_access_key": "edwdadwadwadwdd",
                    "region_name": "eu-west-1",
                }
            }
        }
        assert expected_config == config
Пример #3
0
    def test_missing_target(self, get_input, capsys):
        args = argparse.Namespace(target='idontexist')
        config = {'targets': {'foo': {}}}
        command = EditCommand(args, config, utils.create_logger())
        command.run()

        out, err = capsys.readouterr()
        assert out == ''
        assert err == ('"idontexist" is an unknown target\n'
                       'Choices are: [\'foo\']\n')
Пример #4
0
    def test_missing_target(self, get_input, capsys):
        args = argparse.Namespace(target="idontexist")
        config = {"targets": {"foo": {}}}
        command = EditCommand(args, config, utils.create_logger())
        command.run()

        out, err = capsys.readouterr()
        assert out == ""
        assert err == ('"idontexist" is an unknown target\n'
                       "Choices are: ['foo']\n")
Пример #5
0
    def test_correct_output(self, get_input, config_file):
        fake_stream = [
            "/home/user/Documents",
            "https://example.com",
            "s3://buckets/mybackup222",
            "9999999999",
            "bbbbbbbbbbbbbbbbbbbbbbbb",
            "eu-west-2",
        ]
        get_input.side_effect = fake_stream

        args = argparse.Namespace(target="foo")
        config = {
            "targets": {
                "foo": {
                    "local_folder": "/home/mark/documents",
                    "endpoint_url": "",
                    "s3_uri": "s3://buckets/mybackup",
                    "aws_access_key_id": "23123123123313",
                    "aws_secret_access_key": "edwdadwadwadwdd",
                    "region_name": "eu-west-1",
                }
            }
        }
        command = EditCommand(args, config, utils.create_logger())
        command.run()

        with open(config_file, "r") as fp:
            config = json.load(fp)

        expected_config = {
            "targets": {
                "foo": {
                    "local_folder": "/home/user/Documents",
                    "endpoint_url": "https://example.com",
                    "s3_uri": "s3://buckets/mybackup222",
                    "aws_access_key_id": "9999999999",
                    "aws_secret_access_key": "bbbbbbbbbbbbbbbbbbbbbbbb",
                    "region_name": "eu-west-2",
                }
            }
        }
        assert expected_config == config
Пример #6
0
    def test_correct_output(self, get_input, config_file):
        fake_stream = utils.FakeInputStream([
            '/home/user/Documents',
            's3://buckets/mybackup222',
            '9999999999',
            'bbbbbbbbbbbbbbbbbbbbbbbb',
            'eu-west-2',
        ])
        get_input.side_effect = fake_stream

        args = argparse.Namespace(target='foo')
        config = {
            'targets': {
                'foo': {
                    'local_folder': '/home/mark/documents',
                    's3_uri': 's3://buckets/mybackup',
                    'aws_access_key_id': '23123123123313',
                    'aws_secret_access_key': 'edwdadwadwadwdd',
                    'region_name': 'eu-west-1',
                }
            }
        }
        command = EditCommand(args, config, utils.create_logger())
        command.run()

        with open(config_file, 'r') as fp:
            config = json.load(fp)

        expected_config = {
            'targets': {
                'foo': {
                    'local_folder': '/home/user/Documents',
                    's3_uri': 's3://buckets/mybackup222',
                    'aws_access_key_id': '9999999999',
                    'aws_secret_access_key': 'bbbbbbbbbbbbbbbbbbbbbbbb',
                    'region_name': 'eu-west-2',
                }
            }
        }
        assert expected_config == config
Пример #7
0
def main(arguments):
    parser = argparse.ArgumentParser(
        prog='s4',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=('Fast and cheap synchronisation of files with Amazon S3\n'
                     '\n'
                     'Version: {}\n'
                     '\n'
                     'To start off, add a Target with the "add" command\n'
                     ).format(VERSION),
    )
    parser.add_argument(
        '--log-level',
        default='INFO',
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
    )
    parser.add_argument(
        '--no-colors',
        action='store_true',
        help='Display without colors',
    )
    parser.add_argument(
        '--timestamps',
        action='store_true',
        help='Display timestamps for each log message',
    )
    subparsers = parser.add_subparsers(dest='command')

    daemon_parser = subparsers.add_parser('daemon',
                                          help="Run S4 sync continiously")
    daemon_parser.add_argument('targets', nargs='*')
    daemon_parser.add_argument('--read-delay', default=1000, type=int)
    daemon_parser.add_argument('--conflicts',
                               default='ignore',
                               choices=['1', '2', 'ignore'])

    add_parser = subparsers.add_parser('add',
                                       help="Add a new Target to synchronise")
    add_parser.add_argument(
        '--copy-target-credentials',
        '-C',
        help=
        "Copy credentials from an existing target instead of typing them in again"
    )

    sync_parser = subparsers.add_parser('sync',
                                        help="Synchronise Targets with S3")
    sync_parser.add_argument('targets', nargs='*')
    sync_parser.add_argument('--conflicts',
                             default=None,
                             choices=['1', '2', 'ignore'])
    sync_parser.add_argument('--dry-run', action='store_true')

    edit_parser = subparsers.add_parser('edit', help="Edit Target details")
    edit_parser.add_argument('target')

    subparsers.add_parser('targets', help="Print available Targets")

    subparsers.add_parser('version', help="Print S4 Version")

    ls_parser = subparsers.add_parser(
        'ls', help="Display list of files for a Target")
    ls_parser.add_argument('target')
    ls_parser.add_argument('--sort-by',
                           '-s',
                           choices=['key', 'local', 's3'],
                           default='key')
    ls_parser.add_argument('--descending', '-d', action='store_true')
    ls_parser.add_argument(
        '--all',
        '-A',
        dest='show_all',
        action='store_true',
        help='show deleted files',
    )

    remove_parser = subparsers.add_parser('rm', help="Remove a Target")
    remove_parser.add_argument('target')

    args = parser.parse_args(arguments)

    if args.log_level == 'DEBUG':
        log_format = '%(levelname)s:%(module)s:%(lineno)s %(message)s'
    else:
        log_format = '%(message)s'

    if args.timestamps:
        log_format = '%(asctime)s: ' + log_format

    logging.basicConfig(format=log_format, level=args.log_level)

    # shut boto up
    logging.getLogger('boto3').setLevel(logging.CRITICAL)
    logging.getLogger('botocore').setLevel(logging.CRITICAL)
    logging.getLogger('nose').setLevel(logging.CRITICAL)
    logging.getLogger('s3transfer').setLevel(logging.CRITICAL)
    logging.getLogger('filelock').setLevel(logging.CRITICAL)

    logger = logging.getLogger(__name__)
    logger.setLevel(args.log_level)

    config = utils.get_config()

    try:
        command = None
        if args.command == 'version':
            print(VERSION)
            return
        elif args.command == 'sync':
            command = SyncCommand(args, config, logger)
        elif args.command == 'targets':
            command = TargetsCommand(args, config, logger)
        elif args.command == 'add':
            command = AddCommand(args, config, logger)
        elif args.command == 'edit':
            command = EditCommand(args, config, logger)
        elif args.command == 'ls':
            command = LsCommand(args, config, logger)
        elif args.command == 'rm':
            command = RmCommand(args, config, logger)
        elif args.command == 'daemon':
            command = DaemonCommand(args, config, logger)

        if command:
            try:
                command.run()
            except Exception as e:
                logger.error('An unhandled error has occurred: %s', e)
                # Only display a scary stack trace to the user if in DEBUG mode
                if args.log_level == 'DEBUG':
                    raise e
        else:
            parser.print_help()
    except KeyboardInterrupt:
        pass
Пример #8
0
Файл: cli.py Проект: troylar/S4
def main(arguments):
    parser = argparse.ArgumentParser(
        prog="s4",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=("Fast and cheap synchronisation of files with Amazon S3\n"
                     "\n"
                     "Version: {}\n"
                     "\n"
                     'To start off, add a Target with the "add" command\n'
                     ).format(VERSION),
    )
    parser.add_argument("--log-level",
                        default="INFO",
                        choices=["DEBUG", "INFO", "WARNING", "ERROR"])
    parser.add_argument("--no-colors",
                        action="store_true",
                        help="Display without colors")
    parser.add_argument(
        "--timestamps",
        action="store_true",
        help="Display timestamps for each log message",
    )
    subparsers = parser.add_subparsers(dest="command")

    daemon_parser = subparsers.add_parser("daemon",
                                          help="Run S4 sync continiously",
                                          aliases=["d"])
    daemon_parser.add_argument("targets", nargs="*")
    daemon_parser.add_argument("--read-delay", default=1000, type=int)
    daemon_parser.add_argument("--conflicts",
                               default="ignore",
                               choices=["1", "2", "ignore"])

    add_parser = subparsers.add_parser("add",
                                       help="Add a new Target to synchronise",
                                       aliases=["a"])
    add_parser.add_argument(
        "--copy-target-credentials",
        "-C",
        help=
        "Copy credentials from an existing target instead of typing them in again",
    )

    sync_parser = subparsers.add_parser("sync",
                                        help="Synchronise Targets with S3",
                                        aliases=["s"])
    sync_parser.add_argument("targets", nargs="*")
    sync_parser.add_argument("--conflicts",
                             default=None,
                             choices=["1", "2", "ignore"])
    sync_parser.add_argument("--dry-run", action="store_true")

    edit_parser = subparsers.add_parser("edit",
                                        help="Edit Target details",
                                        aliases=["e"])
    edit_parser.add_argument("target")

    subparsers.add_parser("targets",
                          help="Print available Targets",
                          aliases=["t"])

    subparsers.add_parser("version", help="Print S4 Version", aliases=["v"])

    ls_parser = subparsers.add_parser(
        "ls", help="Display list of files for a Target")
    ls_parser.add_argument("target")
    ls_parser.add_argument("--sort-by",
                           "-s",
                           choices=["key", "local", "s3"],
                           default="key")
    ls_parser.add_argument("--descending", "-d", action="store_true")
    ls_parser.add_argument("--all",
                           "-A",
                           dest="show_all",
                           action="store_true",
                           help="show deleted files")

    remove_parser = subparsers.add_parser("rm", help="Remove a Target")
    remove_parser.add_argument("target")

    args = parser.parse_args(arguments)

    if args.log_level == "DEBUG":
        log_format = "%(levelname)s:%(module)s:%(lineno)s %(message)s"
    else:
        log_format = "%(message)s"

    if args.timestamps:
        log_format = "%(asctime)s: " + log_format

    logging.basicConfig(format=log_format, level=args.log_level)

    # shut boto up
    logging.getLogger("boto3").setLevel(logging.CRITICAL)
    logging.getLogger("botocore").setLevel(logging.CRITICAL)
    logging.getLogger("nose").setLevel(logging.CRITICAL)
    logging.getLogger("s3transfer").setLevel(logging.CRITICAL)
    logging.getLogger("filelock").setLevel(logging.CRITICAL)

    logger = logging.getLogger(__name__)
    logger.setLevel(args.log_level)

    config = utils.get_config()

    try:
        command = None
        if args.command in ("version", "v"):
            print(VERSION)
            return
        elif args.command in ("sync", "s"):
            command = SyncCommand(args, config, logger)
        elif args.command in ("targets", "t"):
            command = TargetsCommand(args, config, logger)
        elif args.command in ("add", "a"):
            command = AddCommand(args, config, logger)
        elif args.command in ("edit", "e"):
            command = EditCommand(args, config, logger)
        elif args.command == "ls":
            command = LsCommand(args, config, logger)
        elif args.command == "rm":
            command = RmCommand(args, config, logger)
        elif args.command in ("daemon", "d"):
            command = DaemonCommand(args, config, logger)

        if command:
            try:
                command.run()
            except Exception as e:
                logger.error("An unhandled error has occurred: %s", e)
                # Only display a scary stack trace to the user if in DEBUG mode
                if args.log_level == "DEBUG":
                    raise e
        else:
            parser.print_help()
    except KeyboardInterrupt:
        pass