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() ): newlines = self._pipfile_newlines else: newlines = DEFAULT_NEWLINES formatted_data = cleanup_toml(formatted_data) with io.open(path, "w", newline=newlines) as f: f.write(formatted_data) # pipfile is mutated! self.clear_pipfile_cache()
async def suggest_typeshed_obsolete(obsolete: Obsolete, session: aiohttp.ClientSession, action_level: ActionLevel) -> None: if action_level <= ActionLevel.nothing: return title = f"[stubsabot] Mark {obsolete.distribution} as obsolete since {obsolete.obsolete_since_version}" async with _repo_lock: branch_name = f"{BRANCH_PREFIX}/{normalize(obsolete.distribution)}" subprocess.check_call( ["git", "checkout", "-B", branch_name, "origin/master"]) with open(obsolete.stub_path / "METADATA.toml", "rb") as f: meta = tomlkit.load(f) obs_string = tomlkit.string(obsolete.obsolete_since_version) obs_string.comment( f"Released on {obsolete.obsolete_since_date.date().isoformat()}") meta["obsolete_since"] = obs_string with open(obsolete.stub_path / "METADATA.toml", "w") as f: tomlkit.dump(meta, f) subprocess.check_call(["git", "commit", "--all", "-m", title]) if action_level <= ActionLevel.local: return somewhat_safe_force_push(branch_name) if action_level <= ActionLevel.fork: return body = "\n".join(f"{k}: {v}" for k, v in obsolete.links.items()) await create_or_update_pull_request(title=title, body=body, branch_name=branch_name, session=session)
def create_configuration(self, config: Configuration, *style_urls: str) -> None: """Create a configuration file.""" from nitpick.style import StyleManager # pylint: disable=import-outside-toplevel if config.file: doc: TOMLDocument = tomlkit.parse(config.file.read_text()) else: doc = tomlkit.document() config.file = self.root / DOT_NITPICK_TOML if not style_urls: style_urls = (str(StyleManager.get_default_style_url()), ) tool_nitpick = tomlkit.table() tool_nitpick.add( tomlkit.comment("Generated by the 'nitpick init' command")) tool_nitpick.add( tomlkit.comment( f"More info at {READ_THE_DOCS_URL}configuration.html")) tool_nitpick.add( "style", tomlkit.array([tomlkit.string(url) for url in style_urls])) doc.add(SingleKey(TOOL_NITPICK_KEY, KeyType.Bare), tool_nitpick) # config.file will always have a value at this point, but mypy can't see it. config.file.write_text(tomlkit.dumps(doc, sort_keys=True)) # type: ignore
def tomlstring(value: Any) -> str: """Create a fully-quoted TOML string from a path. This ensures proper quoting of Windows paths and other values with backslashes. """ return tomlkit.string(str(value)).as_string()
def get_lock_metadata(self) -> Dict[str, Any]: content_hash = tomlkit.string("sha256:" + self.get_content_hash("sha256")) content_hash.trivia.trail = "\n\n" return { "lock_version": self.PYPROJECT_VERSION, "content_hash": content_hash }
def test_string(): s = tomlkit.string('foo "') assert s.value == 'foo "' assert s.as_string() == '"foo \\""'
def test_create_string_with_invalid_characters(kwargs, example): with pytest.raises(InvalidStringError): tomlkit.string(example, **kwargs)
def test_create_string(kwargs, example, expected): value = tomlkit.string(example, **kwargs) assert value.as_string() == expected