Browse Source

start re-implementing model for Shut

shut-new-model
Niklas Rosenstein 10 months ago
parent
commit
6c4389e787
No known key found for this signature in database GPG Key ID: 6D269B33D25F6C6
13 changed files with 637 additions and 51 deletions
  1. + 21
    - 5
      README.md
  2. + 39
    - 42
      package.yaml
  3. + 23
    - 1
      src/shut/__init__.py
  4. + 7
    - 3
      src/shut/commands/pkg/__init__.py
  5. + 117
    - 0
      src/shut/model/__init__.py
  6. + 62
    - 0
      src/shut/model/author.py
  7. + 26
    - 0
      src/shut/model/changelog.py
  8. + 27
    - 0
      src/shut/model/linter.py
  9. + 35
    - 0
      src/shut/model/monorepo.py
  10. + 70
    - 0
      src/shut/model/package.py
  11. + 31
    - 0
      src/shut/model/release.py
  12. + 144
    - 0
      src/shut/model/requirements.py
  13. + 35
    - 0
      src/shut/model/version.py

+ 21
- 5
README.md

@ -1,10 +1,26 @@
# shore
# Shut
[![Build Status](https://drone.niklasrosenstein.com/api/badges/NiklasRosenstein/shore/status.svg)](https://drone.niklasrosenstein.com/NiklasRosenstein/shore)
Shut is an opinionated tool that allows you to configure everything around the Python
packaging and release process with a single YAML configuration file.
Shore is an opinionated distribution and release management tool for pure
Python packages and mono repositories and is most effectively used with Git
repositories.
```yml
package:
name: my-package
modulename: my_module
version: 0.1.0
license: MIT
description: My first every package built with Shut
author: Me <me@example.org>
requirements:
- python ^3.5
- requests ^2.22.0
entrypoints:
console_scripts:
- mycli = my_module.__main__:mycli
```
Shut handles all the rest: `setup.py`, `MANIFEST.in`, `py.typed`, package data files, changelog
management, version number bumping, linter configuration, building and publishing to PyPI, etc.
---

+ 39
- 42
package.yaml

@ -1,45 +1,42 @@
name: nr.shore
version: "1.0.1"
license: MIT
url: https://git.niklasrosenstein.com/NiklasRosenstein/shore
description: |
Automates the heavy lifting of release and distribution management
for pure Python packages.
author: Niklas Rosenstein <rosensteinniklas@gmail.com>
package:
name: shut
version: "1.0.1"
license: MIT
url: https://git.niklasrosenstein.com/NiklasRosenstein/shore
description: Automates the heavy lifting of release and distribution management for pure Python packages.
author: Niklas Rosenstein <rosensteinniklas@gmail.com>
modulename: shore
requirements:
- python ^2.7|^3.4
- beautifulsoup4 ^4.8.1
- click ^7.0
- jinja2 ^2.11.1
- networkx ^2.4
- nr.databind.core ~0.0.20
- nr.databind.json ~0.0.13
- nr.fs ^1.5.0
- nr.pylang.utils ^0.0.1
- nr.proxy ^0.0.1
- nr.utils.git ~0.1.3
- requests ^2.22.0
- packaging ^20.1
- PyYAML ^5.1.0
- termcolor ^1.1.0
- twine
- wheel
requirements:
- python ^2.7|^3.4
- beautifulsoup4 ^4.8.1
- click ^7.0
- jinja2 ^2.11.1
- networkx ^2.4
- nr.databind.core ~0.0.20
- nr.databind.json ~0.0.13
- nr.fs ^1.5.0
- nr.pylang.utils ^0.0.1
- nr.proxy ^0.0.1
- nr.utils.git ~0.1.3
- requests ^2.22.0
- packaging ^20.1
- PyYAML ^5.1.0
- termcolor ^1.1.0
- twine
- wheel
entrypoints:
console_scripts:
- shore = shore.__main__:_entry_point
- shore-conda-forge = shore.tools.conda_forge:main
- shut = shut.commands:shut
shore.core.plugins:
- core = shore.plugins.core:CorePlugin
- install-script = shore.plugins.install_script:InstallScriptRenderer
- pypi = shore.plugins.pypi:PypiPublisher
- requirements-file = shore.plugins.requirements_file:RequirementsFileRenderer
- setuptools = shore.plugins.setuptools:SetuptoolsRenderer
entrypoints:
console_scripts:
- shore = shore.__main__:_entry_point
- shore-conda-forge = shore.tools.conda_forge:main
- shut = shut.commands:shut
shore.core.plugins:
- core = shore.plugins.core:CorePlugin
- install-script = shore.plugins.install_script:InstallScriptRenderer
- pypi = shore.plugins.pypi:PypiPublisher
- requirements-file = shore.plugins.requirements_file:RequirementsFileRenderer
- setuptools = shore.plugins.setuptools:SetuptoolsRenderer
manifest:
- include src/shore/templates/install_script/install
- recursive-include src/shore/templates *.yaml *.py *.md .gitignore
manifest:
- include src/shore/templates/install_script/install
- recursive-include src/shore/templates *.yaml *.py *.md .gitignore

+ 23
- 1
src/shut/__init__.py

@ -1 +1,23 @@
pass
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>'
__version__ = '0.1.0'

+ 7
- 3
src/shut/commands/pkg/__init__.py

@ -20,7 +20,7 @@
# IN THE SOFTWARE.
from .. import shut, commons
from shore.model import Package
from shut.model import Project, PackageModel
import click
@ -31,8 +31,12 @@ def pkg():
"""
def load_package_manifest() -> Package:
return commons.load_manifest(('package.yaml', 'package.yml'), Package)
def load_package_manifest() -> PackageModel:
project = Project()
project.load('.')
print(project.subject)
assert isinstance(project.subject, PackageModel)
return project.subject
from . import bootstrap

+ 117
- 0
src/shut/model/__init__.py

@ -0,0 +1,117 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from typing import List, Type, TypeVar
from nr.databind.core import ObjectMapper
from nr.databind.json import JsonModule
import yaml
import os
from .monorepo import MonorepoModel
from .package import PackageModel
T = TypeVar('T')
def get_existing_file(directory: str, choices: List[str]) -> bool:
for fn in choices:
path = os.path.join(directory, fn)
if os.path.isfile(path):
return path
return None
class Project:
"""
Loads package and mono repo configuration files and caches them to ensure that
the same filename is never loaded into a different model object.
"""
monorepo_filenames = ['monorepo.yml', 'monorepo.yaml']
package_filenames = ['package.yml', 'package.yaml']
def __init__(self, mapper: ObjectMapper = None):
self._cache = {}
self.mapper = mapper or ObjectMapper(JsonModule())
self.subject: Union[MonorepoModel, PackageModel] = None
self.monorepo: MonorepoModel = None
self.packages: List[PackageModel] = []
def load(self, directory: str) -> None:
"""
Loads all project information from *directory*. This searches in all parent directories
for a package or monorepo configuration, then loads all resources that belong to the
project.
"""
monorepo_fn = None
package_fn = None
# TODO(NiklasRosenstein): Iterate parent dirs until match is found.
for dirname in [directory]:
package_fn = get_existing_file(dirname, self.package_filenames)
if package_fn:
break
monorepo_fn = get_existing_file(dirname, self.monorepo_filenames)
if monorepo_fn:
break
if package_fn:
monorepo_fn = get_existing_file(os.path.dirname(os.path.dirname(package_fn)),
self.monorepo_filenames)
if monorepo_fn:
self.subject = self._load_monorepo(monorepo_fn)
if package_fn:
self.subject = self._load_package(package_fn)
def _load_object(self, filename: str, type_: Type[T]) -> T:
filename = os.path.normpath(os.path.abspath(filename))
if filename in self._cache:
obj = self._cache[filename]
assert isinstance(obj, type_), 'type mismatch: have {} but expected {}'.format(
type(obj).__name__, type_.__name__)
return obj
with open(filename) as fp:
data = yaml.safe_load(fp)
# TODO(NiklasRosenstein): Store unknown keys
obj = self._cache[filename] = self.mapper.deserialize(data, type_, filename=filename)
return obj
def _load_monorepo(self, filename: str) -> MonorepoModel:
self.monorepo = self._load_object(filename, MonorepoModel)
# Load packages in that monorepo.
directory = os.path.dirname(filename)
for item_name in os.path.listdir(directory):
package_fn = get_existing_file(os.path.join(directory, item_name), self.package_filenames)
if package_fn:
self._load_package(package_fn)
return self.monorepo
def _load_package(self, filename: str) -> PackageModel:
package = self._load_object(filename, PackageModel)
if package not in self.packages:
self.packages.append(package)
return package

+ 62
- 0
src/shut/model/author.py

@ -0,0 +1,62 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from nr.databind.core import Field, Struct
from nr.databind.json import JsonSerializer
import re
@JsonSerializer(serialize='_serialize', deserialize='_deserialize')
class Author(Struct):
"""
Represents information about an author. Can be deserialized from a string of
the form `Name <user@domain.name>`
"""
AUTHOR_EMAIL_REGEX = re.compile(r'([^<]+)<([^>]+)>')
name = Field(str)
email = Field(str)
@classmethod
def parse(cls, string: str) -> 'Author':
match = Author.AUTHOR_EMAIL_REGEX.match(string)
if not match:
raise ValueError('not a valid author string: {!r}'.format(s))
author = match.group(1).strip()
email = match.group(2).strip()
return cls(author, email)
def __str__(self):
return '{} <{}>'.format(self.name, self.email)
@classmethod
def _serialize(cls, mapper, node) -> str:
return str(node.value)
@classmethod
def _deserialize(cls, mapper, node) -> 'Author':
if isinstance(node.value, str):
try:
return cls.parse(node.value)
except ValueError:
pass
raise NotImplementedError

+ 26
- 0
src/shut/model/changelog.py

@ -0,0 +1,26 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from nr.databind.core import Field, FieldName, Struct
class ChangelogConfiguration(Struct):
directory = Field(str, default='.changelog')

+ 27
- 0
src/shut/model/linter.py

@ -0,0 +1,27 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from nr.databind.core import Field, FieldName, Struct
class LinterConfiguration(Struct):
# TODO
pass

+ 35
- 0
src/shut/model/monorepo.py

@ -0,0 +1,35 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from .author import Author
from .version import Version
from .release import MonorepoReleaseConfiguration
from nr.databind.core import Field, FieldName, Struct
class MonorepoModel(Struct):
filename = Field(str, hidden=True, default=None)
name = Field(str)
version = Field(Version, default=None)
author = Field(Author, default=None)
license = Field(str, default=None)
url = Field(str, default=None)
release = Field(MonorepoReleaseConfiguration, default=Field.DEFAULT_CONSTRUCT)

+ 70
- 0
src/shut/model/package.py

@ -0,0 +1,70 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from .author import Author
from .changelog import ChangelogConfiguration
from .linter import LinterConfiguration
from .release import ReleaseConfiguration
from .requirements import Requirement
from .version import Version
from nr.databind.core import Field, FieldName, Struct
from typing import Dict, List
class PackageData(Struct):
name = Field(str)
modulename = Field(str, default=None)
version = Field(Version, default=None)
author = Field(Author)
description = Field(str, default=None)
license = Field(str, default=None)
url = Field(str, default=None)
readme = Field(str, default=None)
wheel = Field(bool, default=True)
universal = Field(bool, default=None)
typed = Field(bool, default=False)
requirements = Field(List[Requirement], default=list)
test_requirements = Field(List[Requirement], FieldName('test-requirements'), default=list)
extra_requirements = Field(Dict[str, List[Requirement]], FieldName('extra-requirements'), default=dict)
source_directory = Field(str, FieldName('source-directory'), default='src')
exclude = Field(List[str], default=lambda: ['test', 'tests', 'docs'])
entrypoints = Field(Dict[str, List[str]], default=dict)
classifiers = Field(List[str], default=list)
keywords = Field(List[str], default=list)
# TODO: Data files
class InstallConfiguration(Struct):
hooks = Field(dict(
before_install=Field(List[str], FieldName('before-install'), default=list),
after_install=Field(List[str], FieldName('after-install'), default=list),
before_develop=Field(List[str], FieldName('before-develop'), default=list),
after_develop=Field(List[str], FieldName('after-develop'), default=list),
), default=Field.DEFAULT_CONSTRUCT)
class PackageModel(Struct):
filename = Field(str, hidden=True, default=None)
data = Field(PackageData, FieldName('package'))
changelog = Field(ChangelogConfiguration, default=Field.DEFAULT_CONSTRUCT)
install = Field(InstallConfiguration, default=Field.DEFAULT_CONSTRUCT)
linter = Field(LinterConfiguration, default=Field.DEFAULT_CONSTRUCT)
release = Field(ReleaseConfiguration, default=Field.DEFAULT_CONSTRUCT)

+ 31
- 0
src/shut/model/release.py

@ -0,0 +1,31 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from nr.databind.core import Field, FieldName, Struct
class ReleaseConfiguration(Struct):
private = Field(bool, default=False)
tag_format = Field(str, FieldName('tag-format'), default='{version}')
class MonorepoReleaseConfiguration(Struct):
single_version = Field(bool, FieldName('single-version'), default=False)

+ 144
- 0
src/shut/model/requirements.py

@ -0,0 +1,144 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from .version import Version
from nr.databind.json import JsonSerializer
from typing import Union
import re
class VersionSelector(object):
"""
Represents a version selector that limits which versions of a requirement can be
picked. It simply wraps a string, but if the string looks like a semver selector,
it can be converted into a ``setuptools`` compatible version selector string (see
#to_setuptools()).
"""
def __init__(self, selector):
if isinstance(selector, VersionSelector):
selector = selector._string
self._string = selector.strip()
def __str__(self):
return str(self._string)
def __repr__(self):
return 'VersionSelector({!r})'.format(self._string)
def __eq__(self, other):
if type(self) == type(other):
return self._string == other._string
return False
def __ne__(self, other):
return not (self == other)
def to_setuptools(self): # type: () -> str
"""
Converts the version selector to a string that Setuptools/Pip can understand by
expanding the `~` and `^` range selectors.
Given a version number X.Y.Z, the selectors will be expanded as follows:
- `^X.Y.Z` -> `>=X.Y.Z,<X+1.0.0`
- `~X.Y.Z` -> `>=X.Y.Z,<X.Y+1.0`
- `X.Y.Z -> ==X.Y.Z`
"""
# Poor-mans test if this looks like the form 'X.Y.Z' without anything around it.
if not ',' in self._string and self._string[0].isdigit():
return '==' + self._string
regex = r'[~^](\d+\.\d+(\.\d+)?[.\-\w]*)'
def sub(match):
index = {'^': 0, '~': 1}[match.group(0)[0]]
max_version = match.group(1).split('.')[:3]
if len(max_version) == 2:
max_version.append('0')
if '-' in max_version[-1]:
max_version[-1] = max_version[-1].partition('-')[0]
max_version[index] = str(int(max_version[index]) + 1)
for i in range(index+1, 3):
max_version[i] = '0'
return '>={},<{}'.format(match.group(1), '.'.join(max_version))
return re.sub(regex, sub, self._string)
def is_semver_selector(self) -> bool:
return self._string and self._string[0] in '^~' and ',' not in self._string
def matches(self, version: Union[Version, str]) -> bool:
if not self.is_semver_selector():
# TODO (@NiklasRosenstein): Match setuptools version selectors.
return False
min_version = Version(self._string[1:])
if self._string[0] == '^':
max_version = bump_version(min_version, 'major')
elif self._string[0] == '~':
max_version = bump_version(min_version, 'minor')
else:
raise RuntimeError('invalid semver selector string {!r}'.format(self._string))
return min_version <= Version(version) < max_version
VersionSelector.ANY = VersionSelector('*')
@JsonSerializer(deserialize='_deserialize')
class Requirement(object):
"""
A Requirement is simply combination of a package name and a version selector.
"""
def __init__(self, package, version): # type: (str, VersionSelector)
if not isinstance(package, str):
raise TypeError('expected str for package_name')
if not isinstance(version, VersionSelector):
raise TypeError('expected VersionSelector for version')
self.package = package
self.version = version
def __str__(self):
if self.version == VersionSelector.ANY:
return self.package
return '{} {}'.format(self.package, self.version)
def __repr__(self):
return repr(str(self))#'Requirement({!r})'.format(str(self))
@classmethod
def parse(cls, requirement_string):
match = re.match(r'^\s*([^\s]+)(?:\s+(.+))?$', requirement_string)
if not match:
raise ValueError('invalid requirement: {!r}'.format(requirement_string))
package, version = match.groups()
return cls(package, VersionSelector(version or VersionSelector.ANY))
def to_setuptools(self): # type: () -> str
if self.version == VersionSelector.ANY:
return self.package
return '{} {}'.format(self.package, self.version.to_setuptools())
@classmethod
def _deserialize(cls, mapper, node):
if not isinstance(node.value, str):
raise node.type_error()
return Requirement.parse(node.value)

+ 35
- 0
src/shut/model/version.py

@ -0,0 +1,35 @@
# -*- coding: utf8 -*-
# Copyright (c) 2020 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from nr.databind.json import JsonSerializer
from shore.util.version import parse_version, Version as _Version
@JsonSerializer(serialize='_serialize', deserialize='_deserialize')
class Version(_Version):
@classmethod
def _serialize(cls, mapper, node) -> str:
return str(node.value)
@classmethod
def _deserialize(cls, mapper, node) -> 'Version':
return Version(parse_version(node.value))

Loading…
Cancel
Save