Ejemplo n.º 1
0
def convert(path):
    cp = configparser.ConfigParser()
    with path.open(encoding='utf-8') as f:
        cp.read_file(f)

    ep_file = Path('entry_points.txt')
    metadata = OrderedDict()
    for name, value in cp['metadata'].items():
        if name in metadata_list_fields:
            metadata[name] = [l for l in value.splitlines() if l.strip()]
        elif name == 'entry-points-file':
            ep_file = Path(value)
        else:
            metadata[name] = value

    if 'scripts' in cp:
        scripts = OrderedDict(cp['scripts'])
    else:
        scripts = {}

    entrypoints = CaseSensitiveConfigParser()
    if ep_file.is_file():
        with ep_file.open(encoding='utf-8') as f:
            entrypoints.read_file(f)

    written_entrypoints = False
    with Path('pyproject.toml').open('w', encoding='utf-8') as f:
        f.write(TEMPLATE.format(metadata=tomli_w.dumps(metadata)))

        if scripts:
            f.write('\n[tool.flit.scripts]\n')
            f.write(tomli_w.dumps(scripts))

        for groupname, group in entrypoints.items():
            if not dict(group):
                continue

            if '.' in groupname:
                groupname = '"{}"'.format(groupname)
            f.write('\n[tool.flit.entrypoints.{}]\n'.format(groupname))
            f.write(tomli_w.dumps(OrderedDict(group)))
            written_entrypoints = True

    print("Written 'pyproject.toml'")
    files = str(path)
    if written_entrypoints:
        files += ' and ' + str(ep_file)
    print("Please check the new file, then remove", files)
Ejemplo n.º 2
0
 def toml_dumps(data):  # type: (t.Any) -> str
     if HAS_TOML:
         return toml.dumps(convert_yaml_objects_to_native(data))
     elif HAS_TOMLIW:
         return tomli_w.dumps(convert_yaml_objects_to_native(data))
     raise AnsibleRuntimeError(
         'The python "toml" or "tomli-w" library is required when using the TOML output format'
     )
Ejemplo n.º 3
0
    def write(self, file_handler):
        value = self.config_root.as_dict()
        config_as_str = tomli_w.dumps(value)

        try:
            # Assuming file_handler has a write attribute
            file_handler.write(config_as_str)
        except AttributeError:
            # Otherwise we expect a path to a file
            with open(file_handler, mode="w") as fh:
                fh.write(config_as_str)
Ejemplo n.º 4
0
def make_project(
    tmpdir: Path,
    requires: Optional[List[str]] = None,
    backend: Optional[str] = None,
    backend_path: Optional[List[str]] = None,
) -> Path:
    requires = requires or []
    project_dir = tmpdir / "project"
    project_dir.mkdir()
    buildsys: Dict[str, Any] = {"requires": requires}
    if backend:
        buildsys["build-backend"] = backend
    if backend_path:
        buildsys["backend-path"] = backend_path
    data = tomli_w.dumps({"build-system": buildsys})
    project_dir.joinpath("pyproject.toml").write_text(data)
    return project_dir
Ejemplo n.º 5
0
def _make_project(
    tmpdir: Path, backend_code: str, with_setup_py: bool, with_pyproject: bool = True
) -> Path:
    project_dir = tmpdir / "project"
    project_dir.mkdir()
    project_dir.joinpath("setup.cfg").write_text(SETUP_CFG)
    if with_setup_py:
        project_dir.joinpath("setup.py").write_text(SETUP_PY)
    if backend_code:
        assert with_pyproject
        buildsys: Dict[str, Any] = {"requires": ["setuptools", "wheel"]}
        buildsys["build-backend"] = "test_backend"
        buildsys["backend-path"] = ["."]
        data = tomli_w.dumps({"build-system": buildsys})
        project_dir.joinpath("pyproject.toml").write_text(data)
        project_dir.joinpath("test_backend.py").write_text(backend_code)
    elif with_pyproject:
        project_dir.joinpath("pyproject.toml").touch()
    project_dir.joinpath("log.txt").touch()
    return project_dir
Ejemplo n.º 6
0
def make_pyproject_with_setup(
    tmpdir: Path, build_system: bool = True, set_backend: bool = True
) -> Tuple[Path, str]:
    project_dir = tmpdir / "project"
    project_dir.mkdir()
    setup_script = "from setuptools import setup\n"
    expect_script_dir_on_path = True
    if build_system:
        buildsys: Dict[str, Any] = {
            "requires": ["setuptools", "wheel"],
        }
        if set_backend:
            buildsys["build-backend"] = "setuptools.build_meta"
            expect_script_dir_on_path = False
        project_data = tomli_w.dumps({"build-system": buildsys})
    else:
        project_data = ""

    if expect_script_dir_on_path:
        setup_script += "from pep517_test import __version__\n"
    else:
        setup_script += (
            "try:\n"
            "    import pep517_test\n"
            "except ImportError:\n"
            "    pass\n"
            "else:\n"
            '    raise RuntimeError("Source dir incorrectly on sys.path")\n'
        )

    setup_script += 'setup(name="pep517_test", version="0.1", packages=["pep517_test"])'

    project_dir.joinpath("pyproject.toml").write_text(project_data)
    project_dir.joinpath("setup.py").write_text(setup_script)
    package_dir = project_dir / "pep517_test"
    package_dir.mkdir()
    package_dir.joinpath("__init__.py").write_text('__version__ = "0.1"')
    return project_dir, "pep517_test"
Ejemplo n.º 7
0
    return cur


def update(mapping, path, value, sep="/"):
    new = copy.deepcopy(mapping)

    parts = split_path(path, sep=sep)
    parent = extract(new, parts[:-1])
    parent[parts[-1]] = value

    return new


parser = argparse.ArgumentParser()
parser.add_argument("path", type=pathlib.Path)
args = parser.parse_args()

content = args.path.read_text()
decoded = tomli.loads(content)
with_local_scheme = update(
    decoded, "tool.setuptools_scm.local_scheme", "no-local-version", sep="."
)
# work around a bug in setuptools / setuptools-scm
with_setuptools_pin = copy.deepcopy(with_local_scheme)
requires = extract(with_setuptools_pin, "build-system.requires", sep=".")
requires[0] = "setuptools>=42,<60"

new_content = tomli_w.dumps(with_setuptools_pin)
args.path.write_text(new_content)
Ejemplo n.º 8
0
 def save(self, changelog: Changelog, fp: t.TextIO, filename: str) -> None:
     import databind.json
     import tomli_w
     fp.write(
         tomli_w.dumps(
             t.cast(dict, databind.json.dump(changelog, Changelog))))
Ejemplo n.º 9
0
Archivo: init.py Proyecto: sbidoul/flit
    def initialise(self):
        if (self.directory / 'pyproject.toml').exists():
            resp = input("pyproject.toml exists - overwrite it? [y/N]: ")
            if (not resp) or resp[0].lower() != 'y':
                return

        module = self.prompt_text('Module name', self.guess_module_name(),
                                  str.isidentifier)
        author = self.prompt_text('Author', self.defaults.get('author'),
                                  lambda s: True)
        author_email = self.prompt_text('Author email',
                        self.defaults.get('author_email'), self.validate_email)
        if 'home_page_template' in self.defaults:
            home_page_default = self.defaults['home_page_template'].replace(
                                                        '{modulename}', module)
        else:
            home_page_default = None
        home_page = self.prompt_text('Home page', home_page_default, self.validate_homepage,
                                     retry_msg="Should start with http:// or https:// - try again.")
        license = self.prompt_options('Choose a license (see http://choosealicense.com/ for more info)',
                    license_choices, self.defaults.get('license'))

        readme = self.find_readme()

        self.update_defaults(author=author, author_email=author_email,
                             home_page=home_page, module=module, license=license)

        # Format information as TOML
        # This is ugly code, but I want the generated pyproject.toml, which
        # will mostly be edited by hand, to look a particular way - e.g. authors
        # in inline tables. It's easier to 'cheat' with some string formatting
        # than to do this through a TOML library.
        author_info = []
        if author:
            author_info.append(f'name = {json.dumps(author)}')
        if author_email:
            author_info.append(f'email = {json.dumps(author_email)}')
        if author_info:
            authors_list = "[{%s}]" % ", ".join(author_info)
        else:
            authors_list = "[]"

        classifiers = []
        if license != 'skip':
            classifiers = [license_names_to_classifiers[license]]
            self.write_license(license, author)

        with (self.directory / 'pyproject.toml').open('w', encoding='utf-8') as f:
            f.write(TEMPLATE.format(
                name=json.dumps(module), authors=authors_list
            ))
            if readme:
                f.write(tomli_w.dumps({'readme': readme}))
            if classifiers:
                f.write(f"classifiers = {json.dumps(classifiers)}\n")
            f.write('dynamic = ["version", "description"]\n')
            if home_page:
                f.write("\n" + tomli_w.dumps({
                    'project': {'urls': {'Home': home_page}}
                }))

        print()
        print("Written pyproject.toml; edit that file to add optional extra info.")
Ejemplo n.º 10
0
def toml_highlight(toml_data: dict[str, t.Any]) -> str:
    import tomli_w
    import pygments, pygments.lexers, pygments.formatters
    return pygments.highlight(
        tomli_w.dumps(toml_data), pygments.lexers.get_lexer_by_name('toml'),
        pygments.formatters.get_formatter_by_name('terminal'))
Ejemplo n.º 11
0
 def print_config(self):
     """Print the current state of the configuration."""
     if self.configuration:
         print(tomli_w.dumps(self.configuration))
Ejemplo n.º 12
0
def write_project_file_at(path, project_data):
    write_file(path, tomli_w.dumps(project_data))
Ejemplo n.º 13
0
def pytask_configure(pm: pluggy.PluginManager,
                     config_from_cli: dict[str, Any]) -> dict[str, Any]:
    """Configure pytask."""
    config = {"pm": pm}

    # Either the path to the configuration is passed via the CLI or it needs to be
    # detected from the paths passed to pytask.
    if config_from_cli.get("config"):
        config["config"] = Path(config_from_cli["config"])
        config["root"] = config["config"].parent
    else:
        paths = (parse_paths(config_from_cli.get("paths"))
                 if config_from_cli.get("paths") is not None else [Path.cwd()])
        config["root"], config["config"] = _find_project_root_and_config(paths)

    if config["config"] is None:
        config_from_file = {}
    else:
        read_config = get_config_reader(config["config"])
        config_from_file = read_config(config["config"])

        if read_config.__name__ == "_read_ini_config":
            toml_string = "# Content of pyproject.toml\n\n" + tomli_w.dumps(
                {"tool": {
                    "pytask": {
                        "ini_options": config_from_file
                    }
                }})
            console.print(
                Text(
                    _DEPRECATION_MESSAGE.format(
                        config["config"].with_name("pyproject.toml")),
                    style="warning",
                ))
            console.print(Syntax(toml_string, "toml"))

    # If paths are set in the configuration, process them.
    if config_from_file.get("paths"):
        paths_from_file = to_list(
            parse_value_or_multiline_option(config_from_file.get("paths")))
        config_from_file["paths"] = [
            config["config"].parent.joinpath(p).resolve()
            for p in paths_from_file
        ]

    config["paths"] = get_first_non_none_value(
        config_from_cli,
        config_from_file,
        key="paths",
        default=[Path.cwd()],
        callback=parse_paths,
    )

    config["markers"] = {
        "depends_on":
        ("Add dependencies to a task. See this tutorial for more information: "
         "[link https://bit.ly/3JlxylS]https://bit.ly/3JlxylS[/]."),
        "produces":
        ("Add products to a task. See this tutorial for more information: "
         "[link https://bit.ly/3JlxylS]https://bit.ly/3JlxylS[/]."),
        "try_first":
        "Try to execute a task a early as possible.",
        "try_last":
        "Try to execute a task a late as possible.",
    }

    pm.hook.pytask_parse_config(
        config=config,
        config_from_cli=config_from_cli,
        config_from_file=config_from_file,
    )

    pm.hook.pytask_post_parse(config=config)

    return config