本文整理汇总了Python中tomlkit.document方法的典型用法代码示例。如果您正苦于以下问题:Python tomlkit.document方法的具体用法?Python tomlkit.document怎么用?Python tomlkit.document使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tomlkit
的用法示例。
在下文中一共展示了tomlkit.document方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_remove_also_deactivates
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def test_remove_also_deactivates(tmp_dir, manager, poetry, config, mocker):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir()
(Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir()
mocker.patch(
"poetry.utils._compat.subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
envs_file = TomlFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.6", "patch": "3.6.6"}
envs_file.write(doc)
venv = manager.remove("python3.6")
assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venv.path
assert not (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists()
envs = envs_file.read()
assert venv_name not in envs
示例2: secure
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def secure(self):
if self.file.exists():
initial_config = self.file.read()
config = self.file.read()
else:
initial_config = document()
config = document()
new_file = not self.file.exists()
yield config
try:
# Ensuring the file is only readable and writable
# by the current user
mode = 0o600
if new_file:
self.file.touch(mode=mode)
self.file.write(config)
except Exception:
self.file.write(initial_config)
raise
示例3: ensure_package_sections
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def ensure_package_sections(cls, data):
# type: (tomlkit.toml_document.TOMLDocument[Text, Any]) -> tomlkit.toml_document.TOMLDocument[Text, Any]
"""
Ensure that all pipfile package sections are present in the given toml document
:param :class:`~tomlkit.toml_document.TOMLDocument` data: The toml document to
ensure package sections are present on
:return: The updated toml document, ensuring ``packages`` and ``dev-packages``
sections are present
:rtype: :class:`~tomlkit.toml_document.TOMLDocument`
"""
package_keys = (
k for k in plette.pipfiles.PIPFILE_SECTIONS.keys() if k.endswith("packages")
)
for key in package_keys:
if key not in data:
data.update({key: tomlkit.table()})
return data
示例4: load
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def load(cls, f, encoding=None):
# type: (Any, Text) -> PipfileLoader
content = f.read()
if encoding is not None:
content = content.decode(encoding)
_data = tomlkit.loads(content)
should_reload = "source" not in _data
_data = reorder_source_keys(_data)
if should_reload:
if "sources" in _data:
content = tomlkit.dumps(_data)
else:
# HACK: There is no good way to prepend a section to an existing
# TOML document, but there's no good way to copy non-structural
# content from one TOML document to another either. Modify the
# TOML content directly, and load the new in-memory document.
sep = "" if content.startswith("\n") else "\n"
content = plette.pipfiles.DEFAULT_SOURCE_TOML + sep + content
data = tomlkit.loads(content)
data = cls.ensure_package_sections(data)
instance = cls(data)
instance._data = dict(instance._data)
return instance
示例5: dumps
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def dumps(self, reqs, project: RootDependency, content=None) -> str:
doc = document()
deps = []
for req in reqs:
deps.append(self._format_req(req=req))
doc['build-system']['requires'] = deps
return dumps(doc)
示例6: test_activate_activates_same_virtualenv_with_envs_file
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def test_activate_activates_same_virtualenv_with_envs_file(
tmp_dir, manager, poetry, config, mocker
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
envs_file = TomlFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"}
envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name)))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"poetry.utils._compat.subprocess.check_output",
side_effect=check_output_wrapper(),
)
mocker.patch(
"poetry.utils._compat.subprocess.Popen.communicate",
side_effect=[("/prefix", None)],
)
m = mocker.patch("poetry.utils.env.EnvManager.create_venv")
env = manager.activate("python3.7", NullIO())
m.assert_not_called()
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name)
assert env.base == Path("/prefix")
示例7: test_activate_activates_different_virtualenv_with_envs_file
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def test_activate_activates_different_virtualenv_with_envs_file(
tmp_dir, manager, poetry, config, mocker
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
envs_file = TomlFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"}
envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name)))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"poetry.utils._compat.subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
mocker.patch(
"poetry.utils._compat.subprocess.Popen.communicate",
side_effect=[("/prefix", None), ("/prefix", None), ("/prefix", None)],
)
m = mocker.patch("poetry.utils.env.EnvManager.build_venv", side_effect=build_venv)
env = manager.activate("python3.6", NullIO())
m.assert_called_with(
Path(tmp_dir) / "{}-py3.6".format(venv_name), executable="python3.6"
)
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.6"
assert envs[venv_name]["patch"] == "3.6.6"
assert env.path == Path(tmp_dir) / "{}-py3.6".format(venv_name)
assert env.base == Path("/prefix")
示例8: test_deactivate_activated
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def test_deactivate_activated(tmp_dir, manager, poetry, config, mocker):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
version = Version.parse(".".join(str(c) for c in sys.version_info[:3]))
other_version = Version.parse("3.4") if version.major == 2 else version.next_minor
(
Path(tmp_dir) / "{}-py{}.{}".format(venv_name, version.major, version.minor)
).mkdir()
(
Path(tmp_dir)
/ "{}-py{}.{}".format(venv_name, other_version.major, other_version.minor)
).mkdir()
envs_file = TomlFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {
"minor": "{}.{}".format(other_version.major, other_version.minor),
"patch": other_version.text,
}
envs_file.write(doc)
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"poetry.utils._compat.subprocess.check_output",
side_effect=check_output_wrapper(),
)
manager.deactivate(NullIO())
env = manager.get()
assert env.path == Path(tmp_dir) / "{}-py{}.{}".format(
venv_name, version.major, version.minor
)
assert Path("/prefix")
envs = envs_file.read()
assert len(envs) == 0
示例9: test_get_prefers_explicitly_activated_virtualenvs_over_env_var
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
app, tmp_dir, mocker
):
mocker.stopall()
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)
expected = """\
Using virtualenv: {}
""".format(
os.path.join(tmp_dir, "{}-py{}".format(venv_name, python_minor))
)
assert expected == tester.io.fetch_output()
示例10: test_activated
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def test_activated(app, tmp_dir):
app.poetry.config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = EnvManager.generate_env_name(
"simple-project", str(app.poetry.file.parent)
)
(Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir()
(Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir()
envs_file = TomlFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
envs_file.write(doc)
command = app.find("env list")
tester = CommandTester(command)
tester.execute()
expected = """\
{}-py3.6
{}-py3.7 (Activated)
""".format(
venv_name, venv_name
)
assert expected == tester.io.fetch_output()
示例11: set_lock_data
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def set_lock_data(self, root, packages): # type: (...) -> bool
files = table()
packages = self._lock_packages(packages)
# Retrieving hashes
for package in packages:
if package["name"] not in files:
files[package["name"]] = []
for f in package["files"]:
file_metadata = inline_table()
for k, v in sorted(f.items()):
file_metadata[k] = v
files[package["name"]].append(file_metadata)
if files[package["name"]]:
files[package["name"]] = item(files[package["name"]]).multiline(True)
del package["files"]
lock = document()
lock["package"] = packages
if root.extras:
lock["extras"] = {
extra: [dep.pretty_name for dep in deps]
for extra, deps in root.extras.items()
}
lock["metadata"] = {
"python-versions": root.python_versions,
"content-hash": self._content_hash,
"files": files,
}
if not self.is_locked() or lock != self.lock_data:
self._write_lock_data(lock)
return True
return False
示例12: format_lockfile
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def format_lockfile(mapping, fetched_dependencies, summary_collection):
"""Format lock file from a dict of resolved candidates, a mapping of dependencies
and a collection of package summaries.
"""
packages = tomlkit.aot()
metadata = tomlkit.table()
for k, v in sorted(mapping.items()):
base = tomlkit.table()
base.update(v.as_lockfile_entry())
base.add("summary", summary_collection[strip_extras(k)[0]])
deps = tomlkit.table()
for r in fetched_dependencies[k].values():
name, req = r.as_req_dict()
if getattr(req, "items", None) is not None:
inline = tomlkit.inline_table()
inline.update(req)
deps.add(name, inline)
else:
deps.add(name, req)
if len(deps) > 0:
base.add("dependencies", deps)
packages.append(base)
if v.hashes:
key = f"{k} {v.version}"
array = tomlkit.array()
array.multiline(True)
for filename, hash_value in v.hashes.items():
inline = tomlkit.inline_table()
inline.update({"file": filename, "hash": hash_value})
array.append(inline)
if array:
metadata.add(key, array)
doc = tomlkit.document()
doc.update({"package": packages, "metadata": metadata})
return doc
示例13: write_toml
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
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.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()
示例14: write_lockfile
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def write_lockfile(self, content):
"""Write out the lockfile.
"""
s = self._lockfile_encoder.encode(content)
open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"}
with vistir.contextmanagers.atomic_open_for_write(
self.lockfile_location, **open_kwargs
) as f:
f.write(s)
# Write newline at end of document. GH-319.
# Only need '\n' here; the file object handles the rest.
if not s.endswith(u"\n"):
f.write(u"\n")
示例15: __call__
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import document [as 别名]
def __call__(self) -> bool:
config_path = Path(self.config['config'])
exists = config_path.exists()
if exists:
# read
with config_path.open('r', encoding='utf8') as stream:
doc = tomlkit.parse(stream.read())
else:
doc = tomlkit.document()
# add section
if 'tool' not in doc:
doc.add('tool', tomlkit.table())
if 'dephell' not in doc['tool']:
doc['tool'].add('dephell', tomlkit.table())
# detect requirements files
project_path = Path(self.config['project'])
parsable_files = defaultdict(list)
for file_path in project_path.iterdir():
if file_path.suffix not in SUFFIXES:
continue
content = None if file_path.is_dir() else file_path.read_text()
for converter_name, converter in CONVERTERS.items():
if converter.can_parse(path=file_path, content=content):
parsable_files[converter_name].append(file_path.name)
for from_format, to_format in PAIRS:
for from_path in parsable_files[from_format]:
for to_path in parsable_files[to_format]:
if from_format not in doc['tool']['dephell']:
doc['tool']['dephell'].add(
from_format,
self._make_env(from_format, from_path, to_format, to_path),
)
if not doc['tool']['dephell'].value:
if 'example' not in doc['tool']['dephell']:
doc['tool']['dephell'].add(
'example',
self._make_env('pip', 'requirements.in', 'piplock', 'requirements.lock'),
)
# write
with config_path.open('w', encoding='utf8') as stream:
stream.write(tomlkit.dumps(doc))
if exists:
self.logger.info('pyproject.toml updated')
else:
self.logger.info('pyproject.toml created')
return True