How to use the tomlkit.document function in tomlkit

To help you get started, we’ve selected a few tomlkit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python-poetry / poetry / tests / console / commands / env / test_use.py View on Github external
app, tmp_dir, mocker
):
    os.environ["VIRTUAL_ENV"] = "/environment/prefix"

    venv_name = EnvManager.generate_env_name(
        "simple-project", str(app.poetry.file.parent)
    )
    current_python = sys.version_info[:3]
    python_minor = ".".join(str(v) for v in current_python[:2])
    python_patch = ".".join(str(v) for v in current_python)

    app.poetry.config.merge({"virtualenvs": {"path": str(tmp_dir)}})
    (Path(tmp_dir) / "{}-py{}".format(venv_name, python_minor)).mkdir()

    envs_file = TomlFile(Path(tmp_dir) / "envs.toml")
    doc = tomlkit.document()
    doc[venv_name] = {"minor": python_minor, "patch": python_patch}
    envs_file.write(doc)

    mocker.patch(
        "poetry.utils._compat.subprocess.check_output",
        side_effect=check_output_wrapper(Version(*current_python)),
    )
    mocker.patch(
        "poetry.utils._compat.subprocess.Popen.communicate",
        side_effect=[("/prefix", None), ("/prefix", None), ("/prefix", None)],
    )

    command = app.find("env use")
    tester = CommandTester(command)
    tester.execute(python_minor)
github sdispater / tomlkit / tests / test_build.py View on Github external
def test_build_example(example):
    content = example("example")

    doc = document()
    doc.add(comment("This is a TOML document. Boom."))
    doc.add(nl())
    doc.add("title", "TOML Example")

    owner = table()
    owner.add("name", "Tom Preston-Werner")
    owner.add("organization", "GitHub")
    owner.add("bio", "GitHub Cofounder & CEO\nLikes tater tots and beer.")
    owner.add("dob", datetime.datetime(1979, 5, 27, 7, 32, tzinfo=_utc))
    owner["dob"].comment("First class dates? Why not?")

    doc.add("owner", owner)

    database = table()
    database["server"] = "192.168.1.1"
    database["ports"] = [8001, 8001, 8002]
github dnkorpushov / libro / src / main / python / libro / converterconfig.py View on Github external
def generate_default():
    css_file = os.path.normpath(os.path.join(config.config_dir, 'default.css'))
    doc = document()
    doc.add(comment('fb2c configuration file'))
    doc.add(comment('Generated by Libro'))

    logger = table()

    logger_console = table()
    logger_console.add('level', 'none')

    logger_file = table()
    logger_file.add('level', 'debug')
    logger_file.add('destination', config.converter_log_file)
    logger_file.add('mode', 'overwrite')

    logger.add('console', logger_console)
    logger.add('file', logger_file)
github dephell / dephell / dephell / converters / flit.py View on Github external
def dumps(self, reqs, project: RootDependency, content=None) -> str:
        # read config
        if content:
            doc = tomlkit.parse(content)
        else:
            doc = tomlkit.document()

        # get tool section from config
        if 'tool' not in doc:
            doc['tool'] = {'flit': {'metadata': tomlkit.table()}}
        elif 'flit' not in doc['tool']:
            doc['tool']['flit'] = {'metadata': tomlkit.table()}
        elif 'metadata' not in doc['tool']['flit']:
            doc['tool']['flit']['metadata'] = tomlkit.table()
        section = doc['tool']['flit']['metadata']

        # project and module names
        packages = project.package.packages
        if packages:
            module = packages[0].module
            section['module'] = module
            if project.raw_name != module:
github python-poetry / poetry / poetry / utils / env.py View on Github external
if is_root_venv:
            create = False
            venv = self._poetry.file.parent / ".venv"
            if venv.exists():
                # We need to check if the patch version is correct
                _venv = VirtualEnv(venv)
                current_patch = ".".join(str(v) for v in _venv.version_info[:3])

                if patch != current_patch:
                    create = True

            self.create_venv(io, executable=python, force=create)

            return self.get(reload=True)

        envs = tomlkit.document()
        base_env_name = self.generate_env_name(self._poetry.package.name, str(cwd))
        if envs_file.exists():
            envs = envs_file.read()
            current_env = envs.get(base_env_name)
            if current_env is not None:
                current_minor = current_env["minor"]
                current_patch = current_env["patch"]

                if current_minor == minor and current_patch != patch:
                    # We need to recreate
                    create = True

        name = "{}-py{}".format(base_env_name, minor)
        venv = venv_path / name

        # Create if needed
github pypa / pipenv / pipenv / project.py View on Github external
def write_toml(self, data, path=None):
        """Writes the given data structure out as TOML."""
        if path is None:
            path = self.pipfile_location
        data = convert_toml_outline_tables(data)
        try:
            formatted_data = tomlkit.dumps(data).rstrip()
        except Exception:
            document = tomlkit.document()
            for section in ("packages", "dev-packages"):
                document[section] = tomlkit.container.Table()
                # Convert things to inline tables — fancy :)
                for package in data.get(section, {}):
                    if hasattr(data[section][package], "keys"):
                        table = tomlkit.inline_table()
                        table.update(data[section][package])
                        document[section][package] = table
                    else:
                        document[section][package] = tomlkit.string(data[section][package])
            formatted_data = tomlkit.dumps(document).rstrip()

        if (
            vistir.compat.Path(path).absolute()
            == vistir.compat.Path(self.pipfile_location).absolute()
        ):
github awslabs / aws-sam-cli / samcli / lib / config / samconfig.py View on Github external
def _read(self):
        if not self.document:
            try:
                txt = self.filepath.read_text()
                self.document = tomlkit.loads(txt)
                self._version_sanity_check(self._version())
            except OSError:
                self.document = tomlkit.document()

        if self.document.body:
            self._version_sanity_check(self._version())
        return self.document
github bundlewrap / bundlewrap / bundlewrap / utils / dicts.py View on Github external
def dict_to_toml(dict_obj):
    toml_doc = toml_document()
    for key, value in dict_obj.items():
        if isinstance(value, tuple):
            toml_doc[key] = list(value)
        elif isinstance(value, set):
            toml_doc[key] = sorted(value)
        elif isinstance(value, dict):
            toml_doc[key] = dict_to_toml(value)
        else:
            toml_doc[key] = value
    return toml_doc