Ejemplo n.º 1
0
    def test_correct_behaviour(self, get_input, config_file):
        get_input.side_effect = [
            "/home/user/Documents",
            None,
            "mybucket",
            "Documents",
            "eu-west-2",
            "aaaaaaaaaaaaaaaaaaaaaaaa",
            "bbbbbbbbbbbbbbbbbbbbbbbb",
            "",
        ]
        args = argparse.Namespace(copy_target_credentials=None)

        command = AddCommand(args, {"targets": {}}, utils.create_logger())
        command.run()

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

        expected_config = {
            "targets": {
                "Documents": {
                    "local_folder": "/home/user/Documents",
                    "endpoint_url": None,
                    "s3_uri": "s3://mybucket/Documents",
                    "aws_access_key_id": "aaaaaaaaaaaaaaaaaaaaaaaa",
                    "aws_secret_access_key": "bbbbbbbbbbbbbbbbbbbbbbbb",
                    "region_name": "eu-west-2",
                }
            }
        }
        assert new_config == expected_config
Ejemplo n.º 2
0
    def test_custom_target_name(self, get_input, config_file):
        get_input.side_effect = [
            "/home/user/Music",
            None,
            "mybucket",
            "Musiccccc",
            "us-west-1",
            "1234567890",
            "abcdefghij",
            "Tunes",
        ]
        args = argparse.Namespace(copy_target_credentials=None)

        command = AddCommand(args, {"targets": {}}, utils.create_logger())
        command.run()

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

        expected_config = {
            "targets": {
                "Tunes": {
                    "local_folder": "/home/user/Music",
                    "endpoint_url": None,
                    "s3_uri": "s3://mybucket/Musiccccc",
                    "aws_access_key_id": "1234567890",
                    "aws_secret_access_key": "abcdefghij",
                    "region_name": "us-west-1",
                }
            }
        }
        assert new_config == expected_config
Ejemplo n.º 3
0
    def test_copy_target_credentials_bad_target(self, get_input, capsys):
        fake_stream = utils.FakeInputStream(
            ["/home/user/Animals", "s3://mybucket/Zoo", "us-west-2", "Beasts"])
        get_input.side_effect = fake_stream
        args = argparse.Namespace(copy_target_credentials="Foo")

        command = AddCommand(args, {"targets": {
            "bar": {}
        }}, utils.create_logger())
        command.run()

        out, err = capsys.readouterr()
        assert out == ""
        assert err == ('"Foo" is an unknown target\n' "Choices are: ['bar']\n")
Ejemplo n.º 4
0
    def test_copy_target_credentials(self, get_input, config_file):
        get_input.side_effect = [
            "/home/user/Animals",
            None,
            "mybucket",
            "Zoo",
            "us-west-2",
            "Beasts",
        ]
        args = argparse.Namespace(copy_target_credentials="bar")

        command = AddCommand(
            args,
            {
                "targets": {
                    "bar": {
                        "aws_secret_access_key": "bar-secretz",
                        "aws_access_key_id": "so-much-bar",
                    }
                }
            },
            utils.create_logger(),
        )
        command.run()

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

        expected_config = {
            "targets": {
                "bar": {
                    "aws_access_key_id": "so-much-bar",
                    "aws_secret_access_key": "bar-secretz",
                },
                "Beasts": {
                    "local_folder": "/home/user/Animals",
                    "endpoint_url": None,
                    "s3_uri": "s3://mybucket/Zoo",
                    "aws_access_key_id": "so-much-bar",
                    "aws_secret_access_key": "bar-secretz",
                    "region_name": "us-west-2",
                },
            }
        }
        assert new_config == expected_config
Ejemplo n.º 5
0
    def test_default_local_folder(self, get_input, config_file):
        get_input.side_effect = [
            None,
            None,
            "mybucket",
            "Documents",
            "eu-west-2",
            "aaaaaaaaaaaaaaaaaaaaaaaa",
            "bbbbbbbbbbbbbbbbbbbbbbbb",
            "",
        ]
        args = argparse.Namespace(copy_target_credentials=None)

        command = AddCommand(args, {"targets": {}}, utils.create_logger())
        command.run()

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

        assert config["targets"]["Documents"]["local_folder"] == os.getcwd()
Ejemplo n.º 6
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
Ejemplo n.º 7
0
Archivo: cli.py Proyecto: 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