Python click.format_filename() Examples

The following are 5 code examples of click.format_filename(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: cli.py    From chaostoolkit with Apache License 2.0 5 votes vote down vote up
def cli(ctx: click.Context, verbose: bool = False,
        no_version_check: bool = False, change_dir: str = None,
        no_log_file: bool = False, log_file: str = "chaostoolkit.log",
        log_format: str = "string", settings: str = CHAOSTOOLKIT_CONFIG_PATH):

    if no_log_file:
        configure_logger(
            verbose=verbose, log_format=log_format,
            context_id=str(uuid.uuid4()))
    else:
        configure_logger(
            verbose=verbose, log_file=log_file, log_format=log_format,
            context_id=str(uuid.uuid4()))

    subcommand = ctx.invoked_subcommand

    # make it nicer for going through the log file
    logger.debug("#" * 79)
    logger.debug("Running command '{}'".format(subcommand))

    ctx.obj = {}
    ctx.obj["settings_path"] = click.format_filename(settings)
    logger.debug("Using settings file '{}'".format(ctx.obj["settings_path"]))

    if not no_version_check:
        check_newer_version(command=subcommand)

    if change_dir:
        logger.warning("Moving to {d}".format(d=change_dir))
        os.chdir(change_dir) 
Example #2
Source File: binary.py    From MHWorldData with MIT License 5 votes vote down vote up
def dump(file, outfile: click.File):
    "Parses and dumps the file into stdout"
    dumped = binary.dump_file(click.format_filename(file))
    outfile.write(dumped) 
Example #3
Source File: cli.py    From twtxt with MIT License 4 votes vote down vote up
def quickstart():
    """Quickstart wizard for setting up twtxt."""
    width = click.get_terminal_size()[0]
    width = width if width <= 79 else 79

    click.secho("twtxt - quickstart", fg="cyan")
    click.secho("==================", fg="cyan")
    click.echo()

    help_text = "This wizard will generate a basic configuration file for twtxt with all mandatory options set. " \
                "You can change all of these later with either twtxt itself or by editing the config file manually. " \
                "Have a look at the docs to get information about the other available options and their meaning."
    click.echo(textwrap.fill(help_text, width))

    click.echo()
    nick = click.prompt("➤ Please enter your desired nick", default=os.environ.get("USER", ""))

    def overwrite_check(path):
        if os.path.isfile(path):
            click.confirm("➤ '{0}' already exists. Overwrite?".format(path), abort=True)

    cfgfile = click.prompt("➤ Please enter the desired location for your config file",
                           os.path.join(Config.config_dir, Config.config_name),
                           type=click.Path(readable=True, writable=True, file_okay=True))
    cfgfile = os.path.expanduser(cfgfile)
    overwrite_check(cfgfile)

    twtfile = click.prompt("➤ Please enter the desired location for your twtxt file",
                           os.path.expanduser("~/twtxt.txt"),
                           type=click.Path(readable=True, writable=True, file_okay=True))
    twtfile = os.path.expanduser(twtfile)
    overwrite_check(twtfile)

    twturl = click.prompt("➤ Please enter the URL your twtxt file will be accessible from",
                          default="https://example.org/twtxt.txt")

    disclose_identity = click.confirm("➤ Do you want to disclose your identity? Your nick and URL will be shared when "
                                      "making HTTP requests", default=False)

    click.echo()
    add_news = click.confirm("➤ Do you want to follow the twtxt news feed?", default=True)

    conf = Config.create_config(cfgfile, nick, twtfile, twturl, disclose_identity, add_news)

    twtfile_dir = os.path.dirname(twtfile)
    if not os.path.exists(twtfile_dir):
        os.makedirs(twtfile_dir)
    open(twtfile, "a").close()

    click.echo()
    click.echo("✓ Created config file at '{0}'.".format(click.format_filename(conf.config_file)))
    click.echo("✓ Created twtxt file at '{0}'.".format(click.format_filename(twtfile))) 
Example #4
Source File: cli.py    From mappyfile with MIT License 4 votes vote down vote up
def validate(ctx, mapfiles, expand):
    """
    Validate Mapfile(s) against the Mapfile schema

    The MAPFILES argument is a list of paths, either to individual Mapfiles, or a folders containing Mapfiles.
    Wildcards are supported (natively on Linux, and up to one level deep on Windows).
    Validation errors are reported to the console. The program returns the error count - this will be 0 if no
    validation errors are encountered.

    Example of validating a single Mapfile:

        mappyfile validate C:/Temp/valid.map

    Example of validating two folders containing Mapfiles, without expanding INCLUDES:

        mappyfile validate C:/Temp/*.map D:/GitHub/mappyfile/tests/mapfiles/*.map --no-expand
    """

    all_mapfiles = get_mapfiles(mapfiles)

    if len(all_mapfiles) == 0:
        click.echo("No Mapfiles found at the following paths: {}".format(",".join(mapfiles)))
        return

    validation_count = 0
    errors = 0

    for fn in all_mapfiles:
        fn = click.format_filename(fn)
        d = mappyfile.open(fn, expand_includes=expand, include_position=True)

        validation_messages = mappyfile.validate(d)
        if validation_messages:
            for v in validation_messages:
                v["fn"] = fn
                msg = "{fn} (Line: {line} Column: {column}) {message} - {error}".format(**v)
                click.echo(msg)
                errors += 1
        else:
            click.echo("{} validated successfully".format(fn))
            validation_count += 1

    click.echo("{} file(s) validated ({} successfully)".format(len(all_mapfiles), validation_count))
    sys.exit(errors) 
Example #5
Source File: cli.py    From RVD with GNU General Public License v3.0 4 votes vote down vote up
def validate_file(filename, dump=False):
    """
    Auxiliary function, validate file

    :return dict representing the YAML document. NOTE that the
    returned dict hasn't removed any 'additional' key from the original
    file.
    """
    validated = False  # reflect whether the overall process suceeded
    cyan("Validating " + str(filename) + "...")
    doc = None
    try:
        with open(click.format_filename(filename), "r") as stream:
            try:
                doc = yaml.load(stream, Loader=yaml.FullLoader)
            except yaml.YAMLError as exception:
                raise exception
    except FileNotFoundError:
        red("File " + str(filename) + " not found")

    v = Validator(SCHEMA, allow_unknown=True)  # allow unknown values
    if doc:
        # print(MyNormalizer().normalized(doc, SCHEMA))
        if not v.validate(doc, SCHEMA):
            # print(v.errors)
            for key in v.errors.keys():
                print("\t" + str(key) + ": ", end="")
                red("not valid", end="")
                print(": " + str(v.errors[key]))
        else:
            # print(v.validated(doc))
            # valid_documents = [x for x in v.validated(doc)]
            # for document in valid_documents:
            #     print("\t" + str(document) + ": ", end='')
            #     green("valid")
            green("Validated successfully!")
            validated = True
    # else:
    #     red("file to validate not processed correctly!")

    if dump:
        # print(json.dumps(v.document, indent=4, default=default))
        # print(yaml.dump(v.document))  # reorder
        print(
            yaml.dump(v.document(), default_flow_style=False, sort_keys=False)
        )  # maintain order

        # flaw = Flaw(v.document)
        # print the final document after validations and normalizations
        # print(flaw)
        # print(flaw.yml())
    return validated, v.document


#  ┌─┐┬ ┬┌┬┐┌┬┐┌─┐┬─┐┬ ┬
#  └─┐│ │││││││├─┤├┬┘└┬┘
#  └─┘└─┘┴ ┴┴ ┴┴ ┴┴└─ ┴