未验证 提交 ea55cddf 编写于 作者: F Frost Ming

fix regression tests

上级 df44ce87
......@@ -27,7 +27,7 @@ from pdm.models.requirements import Requirement, parse_requirement, strip_extras
from pdm.models.specifiers import get_specifier
from pdm.project import Project
from pdm.resolver import resolve
from pdm.utils import get_python_version
from pdm.utils import get_python_version, setdefault
PEP582_PATH = os.path.join(
os.path.dirname(sys.modules[__name__.split(".")[0]].__file__), "pep582"
......@@ -274,7 +274,7 @@ def do_remove(
(i for i, r in enumerate(deps) if req.matches(r)),
None,
)
if not matched_index:
if matched_index is None:
raise ProjectError(
"{} does not exist in {} dependencies.".format(
stream.green(name, bold=True), section
......@@ -498,14 +498,12 @@ def do_import(project: Project, filename: str, format: Optional[str] = None) ->
tomlkit.comment("See https://www.python.org/dev/peps/pep-0621/")
)
for key, value in project_data.items():
pyproject["project"].add(key, value)
pyproject["project"].update(project_data)
if "tool" not in pyproject or "pdm" not in pyproject["tool"]:
pyproject.setdefault("tool", {})["pdm"] = tomlkit.table()
setdefault(pyproject, "tool", {})["pdm"] = tomlkit.table()
for key, value in settings.items():
pyproject["tool"]["pdm"][key] = value
pyproject["tool"]["pdm"].update(settings)
pyproject["build-system"] = {
"requires": ["pdm-pep517"],
......
......@@ -4,7 +4,13 @@ from pathlib import Path
import tomlkit
import tomlkit.exceptions
from pdm.formats.base import MetaConverter, convert_from, make_array, make_inline_table
from pdm.formats.base import (
MetaConverter,
array_of_inline_tables,
convert_from,
make_array,
make_inline_table,
)
def check_fingerprint(project, filename):
......@@ -20,7 +26,7 @@ def check_fingerprint(project, filename):
def _get_author(metadata, type_="author"):
name = metadata.pop(type_)
email = metadata.pop(f"{type_}-email", None)
return [{"name": name, "email": email}]
return array_of_inline_tables([{"name": name, "email": email}])
class FlitMetaConverter(MetaConverter):
......
......@@ -21,7 +21,11 @@ def check_fingerprint(project, filename):
except tomlkit.exceptions.TOMLKitError:
return False
return "tool" in data and "pdm" in data["tool"] and "name" in data["tool"]["pdm"]
return (
"tool" in data
and "pdm" in data["tool"]
and "dependencies" in data["tool"]["pdm"]
)
class LegacyMetaConverter(MetaConverter):
......
import functools
import operator
import os
import re
import tomlkit
......@@ -16,6 +17,7 @@ from pdm.formats.base import (
from pdm.models.markers import Marker
from pdm.models.requirements import Requirement
from pdm.models.specifiers import PySpecSet
from pdm.utils import cd
def check_fingerprint(project, filename):
......@@ -164,7 +166,7 @@ class PoetryMetaConverter(MetaConverter):
def convert(project, filename):
with open(filename, encoding="utf-8") as fp:
with open(filename, encoding="utf-8") as fp, cd(os.path.dirname(filename)):
converter = PoetryMetaConverter(tomlkit.parse(fp.read())["tool"]["poetry"])
return dict(converter), converter.settings
......
......@@ -57,6 +57,7 @@ def main():
libpath = get_pypackages_path()
if not libpath:
return
pypackages = os.path.dirname(os.path.dirname(libpath))
# First, drop site related paths.
original_sys_path = sys.path[:]
paths_to_remove = set()
......@@ -66,7 +67,7 @@ def main():
with_site_packages
or needs_site_packages
or script_path
and not script_path.startswith(os.path.normcase(os.path.dirname(libpath)))
and not script_path.startswith(os.path.normcase(os.path.dirname(pypackages)))
):
site.addsitepackages(paths_to_remove)
paths_to_remove = set(os.path.normcase(path) for path in paths_to_remove)
......
......@@ -134,7 +134,9 @@ class Config(MutableMapping):
*parts, last = key.split(".")
temp = toml_data
for part in parts:
temp = temp.setdefault(part, {})
if part not in temp:
temp[part] = {}
temp = temp[part]
temp[last] = value
with self._config_file.open("w", encoding="utf-8") as fp:
......
......@@ -7,6 +7,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Type, Union
import tomlkit
from tomlkit.items import Comment, Whitespace
from pdm._types import Source
from pdm.exceptions import ProjectError
......@@ -26,6 +27,7 @@ from pdm.utils import (
find_project_root,
get_python_version,
get_venv_python,
setdefault,
)
if TYPE_CHECKING:
......@@ -97,7 +99,7 @@ class Project:
data = self.pyproject
if not data:
return {}
return data.setdefault("tool", {}).setdefault("pdm", {})
return setdefault(setdefault(data, "tool", {}), "pdm", {})
@property
def lockfile(self):
......@@ -347,12 +349,12 @@ class Project:
def get_pyproject_dependencies(self, section: str) -> List[str]:
"""Get the dependencies array in the pyproject.toml"""
if section == "default":
return self.meta.setdefault("dependencies", [])
return setdefault(self.meta, "dependencies", [])
elif section == "dev":
return self.meta.setdefault("dev-dependencies", [])
return setdefault(self.meta, "dev-dependencies", [])
else:
return self.meta.setdefault("optional-dependencies", {}).setdefault(
section, []
return setdefault(
setdefault(self.meta, "optional-dependencies", {}), section, []
)
def add_dependencies(
......@@ -366,7 +368,17 @@ class Project:
if matched_index is None:
deps.append(dep.as_line())
else:
deps[matched_index] = dep.as_line()
req = dep.as_line()
deps[matched_index] = req
# XXX: This dirty part is for tomlkit.Array.__setitem__()
j = 0
for i in range(len(deps._value)):
if isinstance(deps._value[i], (Comment, Whitespace)):
continue
if j == matched_index:
deps._value[i] = tomlkit.item(req)
break
j += 1
self.write_pyproject(show_message)
def write_pyproject(self, show_message: bool = True) -> None:
......
......@@ -243,7 +243,7 @@ def convert_hashes(hashes: Dict[str, str]) -> Dict[str, List[str]]:
name, hash_value = hash_value.split(":")
except ValueError:
name = "sha256"
result.setdefault(name, []).append(hash_value)
setdefault(result, name, []).append(hash_value)
return result
......@@ -384,3 +384,10 @@ def populate_link(
return
link = getattr(link, "link", link)
ireq.link = link
def setdefault(document, key, value):
"""A compatiable dict.setdefault() for tomlkit data structures."""
if key not in document:
document[key] = value
return document[key]
......@@ -47,7 +47,7 @@ def test_build_single_module(fixture_project):
def test_build_single_module_with_readme(fixture_project):
project = fixture_project("demo-module")
project.tool_settings["readme"] = "README.md"
project.meta["readme"] = "README.md"
project.write_pyproject()
actions.do_build(project)
assert "demo-module-0.1.0/README.md" in get_tarball_names(
......@@ -91,12 +91,12 @@ def test_build_src_package(fixture_project):
def test_build_package_include(fixture_project):
project = fixture_project("demo-package")
project.tool_settings["includes"] = [
project.meta["includes"] = [
"my_package/",
"single_module.py",
"data_out.json",
]
project.tool_settings["excludes"] = ["my_package/*.json"]
project.meta["excludes"] = ["my_package/*.json"]
project.write_pyproject()
actions.do_build(project)
......
......@@ -236,6 +236,7 @@ def test_cache_clear_command(project, invoke, mocker):
def test_import_other_format_file(project, invoke, filename):
requirements_file = FIXTURES / filename
result = invoke(["import", str(requirements_file)], obj=project)
print(result.stderr)
assert result.exit_code == 0
......
......@@ -253,6 +253,7 @@ def fixture_project(project_no_init):
def func(project_name):
source = FIXTURES / "projects" / project_name
copy_tree(source.as_posix(), project_no_init.root.as_posix())
project_no_init._pyproject = None
return project_no_init
return func
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册