index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
26,867 | argparse | _StoreTrueAction | null | class _StoreTrueAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=False,
required=False,
help=None):
super(_StoreTrueAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=True,
default=default,
required=required,
help=help)
| (option_strings, dest, default=False, required=False, help=None) |
26,869 | argparse | __init__ | null | def __init__(self,
option_strings,
dest,
default=False,
required=False,
help=None):
super(_StoreTrueAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=True,
default=default,
required=required,
help=help)
| (self, option_strings, dest, default=False, required=False, help=None) |
26,874 | argparse | _SubParsersAction | null | class _SubParsersAction(Action):
class _ChoicesPseudoAction(Action):
def __init__(self, name, aliases, help):
metavar = dest = name
if aliases:
metavar += ' (%s)' % ', '.join(aliases)
sup = super(_SubParsersAction._ChoicesPseudoAction, self)
sup.__init__(option_strings=[], dest=dest, help=help,
metavar=metavar)
def __init__(self,
option_strings,
prog,
parser_class,
dest=SUPPRESS,
required=False,
help=None,
metavar=None):
self._prog_prefix = prog
self._parser_class = parser_class
self._name_parser_map = {}
self._choices_actions = []
super(_SubParsersAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=PARSER,
choices=self._name_parser_map,
required=required,
help=help,
metavar=metavar)
def add_parser(self, name, **kwargs):
# set prog from the existing prefix
if kwargs.get('prog') is None:
kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
aliases = kwargs.pop('aliases', ())
# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, aliases, help)
self._choices_actions.append(choice_action)
# create the parser and add it to the map
parser = self._parser_class(**kwargs)
self._name_parser_map[name] = parser
# make parser available under aliases also
for alias in aliases:
self._name_parser_map[alias] = parser
return parser
def _get_subactions(self):
return self._choices_actions
def __call__(self, parser, namespace, values, option_string=None):
parser_name = values[0]
arg_strings = values[1:]
# set the parser name if requested
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
# select the parser
try:
parser = self._name_parser_map[parser_name]
except KeyError:
args = {'parser_name': parser_name,
'choices': ', '.join(self._name_parser_map)}
msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
raise ArgumentError(self, msg)
# parse all the remaining options into the namespace
# store any unrecognized options on the object, so that the top
# level parser can decide what to do with them
# In case this subparser defines new defaults, we parse them
# in a new namespace object and then update the original
# namespace for the relevant parts.
subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
for key, value in vars(subnamespace).items():
setattr(namespace, key, value)
if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
| (option_strings, prog, parser_class, dest='==SUPPRESS==', required=False, help=None, metavar=None) |
26,875 | argparse | __call__ | null | def __call__(self, parser, namespace, values, option_string=None):
parser_name = values[0]
arg_strings = values[1:]
# set the parser name if requested
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
# select the parser
try:
parser = self._name_parser_map[parser_name]
except KeyError:
args = {'parser_name': parser_name,
'choices': ', '.join(self._name_parser_map)}
msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
raise ArgumentError(self, msg)
# parse all the remaining options into the namespace
# store any unrecognized options on the object, so that the top
# level parser can decide what to do with them
# In case this subparser defines new defaults, we parse them
# in a new namespace object and then update the original
# namespace for the relevant parts.
subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
for key, value in vars(subnamespace).items():
setattr(namespace, key, value)
if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
| (self, parser, namespace, values, option_string=None) |
26,876 | argparse | __init__ | null | def __init__(self,
option_strings,
prog,
parser_class,
dest=SUPPRESS,
required=False,
help=None,
metavar=None):
self._prog_prefix = prog
self._parser_class = parser_class
self._name_parser_map = {}
self._choices_actions = []
super(_SubParsersAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=PARSER,
choices=self._name_parser_map,
required=required,
help=help,
metavar=metavar)
| (self, option_strings, prog, parser_class, dest='==SUPPRESS==', required=False, help=None, metavar=None) |
26,880 | argparse | _get_subactions | null | def _get_subactions(self):
return self._choices_actions
| (self) |
26,881 | argparse | add_parser | null | def add_parser(self, name, **kwargs):
# set prog from the existing prefix
if kwargs.get('prog') is None:
kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
aliases = kwargs.pop('aliases', ())
# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, aliases, help)
self._choices_actions.append(choice_action)
# create the parser and add it to the map
parser = self._parser_class(**kwargs)
self._name_parser_map[name] = parser
# make parser available under aliases also
for alias in aliases:
self._name_parser_map[alias] = parser
return parser
| (self, name, **kwargs) |
26,883 | argparse | _VersionAction | null | class _VersionAction(Action):
def __init__(self,
option_strings,
version=None,
dest=SUPPRESS,
default=SUPPRESS,
help="show program's version number and exit"):
super(_VersionAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
self.version = version
def __call__(self, parser, namespace, values, option_string=None):
version = self.version
if version is None:
version = parser.version
formatter = parser._get_formatter()
formatter.add_text(version)
parser._print_message(formatter.format_help(), _sys.stdout)
parser.exit()
| (option_strings, version=None, dest='==SUPPRESS==', default='==SUPPRESS==', help="show program's version number and exit") |
26,884 | argparse | __call__ | null | def __call__(self, parser, namespace, values, option_string=None):
version = self.version
if version is None:
version = parser.version
formatter = parser._get_formatter()
formatter.add_text(version)
parser._print_message(formatter.format_help(), _sys.stdout)
parser.exit()
| (self, parser, namespace, values, option_string=None) |
26,885 | argparse | __init__ | null | def __init__(self,
option_strings,
version=None,
dest=SUPPRESS,
default=SUPPRESS,
help="show program's version number and exit"):
super(_VersionAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
self.version = version
| (self, option_strings, version=None, dest='==SUPPRESS==', default='==SUPPRESS==', help="show program's version number and exit") |
26,890 | argparse | _copy_items | null | def _copy_items(items):
if items is None:
return []
# The copy module is used only in the 'append' and 'append_const'
# actions, and it is needed only when the default value isn't a list.
# Delay its import for speeding up the common case.
if type(items) is list:
return items[:]
import copy
return copy.copy(items)
| (items) |
26,891 | argparse | _get_action_name | null | def _get_action_name(argument):
if argument is None:
return None
elif argument.option_strings:
return '/'.join(argument.option_strings)
elif argument.metavar not in (None, SUPPRESS):
return argument.metavar
elif argument.dest not in (None, SUPPRESS):
return argument.dest
elif argument.choices:
return '{' + ','.join(argument.choices) + '}'
else:
return None
| (argument) |
26,895 | gettext | ngettext | null | def ngettext(msgid1, msgid2, n):
return dngettext(_current_domain, msgid1, msgid2, n)
| (msgid1, msgid2, n) |
26,897 | sdv | _find_addons | Find and load all sdv add-ons. | def _find_addons():
"""Find and load all sdv add-ons."""
group = 'sdv_modules'
try:
eps = entry_points(group=group)
except TypeError:
# Load-time selection requires Python >= 3.10 or importlib_metadata >= 3.6
eps = entry_points().get(group, [])
for entry_point in eps:
try:
addon = entry_point.load()
except Exception as e: # pylint: disable=broad-exception-caught
msg = (
f'Failed to load "{entry_point.name}" from "{entry_point.version}" '
f'with error:\n{e}'
)
warnings.warn(msg)
continue
try:
addon_target, addon_name = _get_addon_target(entry_point.name)
except AttributeError as error:
msg = f"Failed to set '{entry_point.name}': {error}."
warnings.warn(msg)
continue
if isinstance(addon, ModuleType):
addon_module_name = f'{addon_target.__name__}.{addon_name}'
if addon_module_name not in sys.modules:
sys.modules[addon_module_name] = addon
setattr(addon_target, addon_name, addon)
| () |
26,918 | xmlsec | EncryptionContext | XML Encryption implementation | from xmlsec import EncryptionContext
| null |
26,920 | xmlsec | Error | The common exception class. | from xmlsec import Error
| null |
26,921 | xmlsec | InternalError | The internal exception class. | from xmlsec import InternalError
| null |
26,922 | xmlsec | Key | Key | from xmlsec import Key
| null |
26,926 | xmlsec | KeysManager | Keys Manager | from xmlsec import KeysManager
| null |
26,929 | xmlsec | SignatureContext | XML Digital Signature implementation | from xmlsec import SignatureContext
| null |
26,931 | xmlsec | VerificationError | The verification exception class. | from xmlsec import VerificationError
| null |
26,935 | dunamai | Concern |
A concern/warning discovered while producing the version.
| class Concern(Enum):
"""
A concern/warning discovered while producing the version.
"""
ShallowRepository = "shallow-repository"
"""Repository does not contain full history"""
def message(self) -> str:
"""
Produce a human-readable description of the concern.
:returns: Concern description.
"""
if self == Concern.ShallowRepository:
return "This is a shallow repository, so Dunamai may not produce the correct version."
else:
return ""
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
27,003 | dunamai | Pattern |
Regular expressions used to parse tags as versions.
| class Pattern(Enum):
"""
Regular expressions used to parse tags as versions.
"""
Default = "default"
"""Default pattern, including `v` prefix."""
DefaultUnprefixed = "default-unprefixed"
"""Default pattern, but without `v` prefix."""
def regex(self, prefix: Optional[str] = None) -> str:
"""
Get the regular expression for this preset pattern.
:param prefix: Insert this after the pattern's start anchor (`^`).
:returns: Regular expression.
"""
variants = {
Pattern.Default: VERSION_SOURCE_PATTERN,
Pattern.DefaultUnprefixed: VERSION_SOURCE_PATTERN.replace("^v", "^v?", 1),
}
out = variants[self]
if prefix:
out = out.replace("^", "^{}".format(prefix), 1)
return out
@staticmethod
def parse(pattern: Union[str, "Pattern"], prefix: Optional[str] = None) -> str:
"""
Parse a pattern string into a regular expression.
If the pattern contains the capture group `?P<base>`, then it is
returned as-is. Otherwise, it is interpreted as a variant of the
`Pattern` enum.
:param pattern: Pattern to parse.
:param prefix: Insert this after the pattern's start anchor (`^`).
:returns: Regular expression.
"""
if isinstance(pattern, str) and "?P<base>" in pattern:
if prefix:
return pattern.replace("^", "^{}".format(prefix), 1)
else:
return pattern
try:
pattern = Pattern(pattern)
except ValueError:
raise ValueError(
_pattern_error(
(
"The pattern does not contain the capture group '?P<base>'"
" and is not a known preset like '{}'".format(Pattern.Default.value)
),
pattern,
)
)
return pattern.regex(prefix)
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
27,004 | dunamai | Style |
Standard styles for serializing a version.
| class Style(Enum):
"""
Standard styles for serializing a version.
"""
Pep440 = "pep440"
"""PEP 440"""
SemVer = "semver"
"""Semantic Versioning"""
Pvp = "pvp"
"""Haskell Package Versioning Policy"""
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
27,006 | dunamai | Vcs |
Version control systems.
| class Vcs(Enum):
"""
Version control systems.
"""
Any = "any"
"""Automatically determine the VCS."""
Git = "git"
"""Git"""
Mercurial = "mercurial"
"""Mercurial"""
Darcs = "darcs"
"""Darcs"""
Subversion = "subversion"
"""Subversion"""
Bazaar = "bazaar"
"""Bazaar"""
Fossil = "fossil"
"""Fossil"""
Pijul = "pijul"
"""Pijul"""
| (value, names=None, *, module=None, qualname=None, type=None, start=1) |
27,007 | dunamai | Version |
A dynamic version.
:ivar base: Release segment.
:vartype base: str
:ivar stage: Alphabetical part of prerelease segment.
:vartype stage: Optional[str]
:ivar revision: Numerical part of prerelease segment.
:vartype revision: Optional[int]
:ivar distance: Number of commits since the last tag.
:vartype distance: int
:ivar commit: Commit ID.
:vartype commit: Optional[str]
:ivar dirty: Whether there are uncommitted changes.
:vartype dirty: Optional[bool]
:ivar tagged_metadata: Any metadata segment from the tag itself.
:vartype tagged_metadata: Optional[str]
:ivar epoch: Optional PEP 440 epoch.
:vartype epoch: Optional[int]
:ivar branch: Name of the current branch.
:vartype branch: Optional[str]
:ivar timestamp: Timestamp of the current commit.
:vartype timestamp: Optional[dt.datetime]
:ivar concerns: Any concerns regarding the version.
:vartype concerns: Optional[Set[Concern]]
:ivar vcs: Version control system from which the version was detected.
:vartype vcs: Vcs
| class Version:
"""
A dynamic version.
:ivar base: Release segment.
:vartype base: str
:ivar stage: Alphabetical part of prerelease segment.
:vartype stage: Optional[str]
:ivar revision: Numerical part of prerelease segment.
:vartype revision: Optional[int]
:ivar distance: Number of commits since the last tag.
:vartype distance: int
:ivar commit: Commit ID.
:vartype commit: Optional[str]
:ivar dirty: Whether there are uncommitted changes.
:vartype dirty: Optional[bool]
:ivar tagged_metadata: Any metadata segment from the tag itself.
:vartype tagged_metadata: Optional[str]
:ivar epoch: Optional PEP 440 epoch.
:vartype epoch: Optional[int]
:ivar branch: Name of the current branch.
:vartype branch: Optional[str]
:ivar timestamp: Timestamp of the current commit.
:vartype timestamp: Optional[dt.datetime]
:ivar concerns: Any concerns regarding the version.
:vartype concerns: Optional[Set[Concern]]
:ivar vcs: Version control system from which the version was detected.
:vartype vcs: Vcs
"""
def __init__(
self,
base: str,
*,
stage: Optional[Tuple[str, Optional[int]]] = None,
distance: int = 0,
commit: Optional[str] = None,
dirty: Optional[bool] = None,
tagged_metadata: Optional[str] = None,
epoch: Optional[int] = None,
branch: Optional[str] = None,
timestamp: Optional[dt.datetime] = None,
concerns: Optional[Set[Concern]] = None,
# fmt: off
vcs: Vcs = Vcs.Any
# fmt: on
) -> None:
"""
:param base: Release segment, such as 0.1.0.
:param stage: Pair of release stage (e.g., "a", "alpha", "b", "rc")
and an optional revision number.
:param distance: Number of commits since the last tag.
:param commit: Commit hash/identifier.
:param dirty: True if the working directory does not match the commit.
:param epoch: Optional PEP 440 epoch.
:param branch: Name of the current branch.
:param timestamp: Timestamp of the current commit.
:param concerns: Any concerns regarding the version.
"""
self.base = base
self.stage = None
self.revision = None
if stage is not None:
self.stage, self.revision = stage
self.distance = distance
self.commit = commit
self.dirty = dirty
self.tagged_metadata = tagged_metadata
self.epoch = epoch
self.branch = branch
try:
self.timestamp = timestamp.astimezone(dt.timezone.utc) if timestamp else None
except ValueError:
# Will fail for naive timestamps before Python 3.6.
self.timestamp = timestamp
self.concerns = concerns or set()
self.vcs = vcs
self._matched_tag = None # type: Optional[str]
self._newer_unmatched_tags = None # type: Optional[Sequence[str]]
self._smart_bumped = False
def __str__(self) -> str:
return self.serialize()
def __repr__(self) -> str:
return (
"Version(base={!r}, stage={!r}, revision={!r}, distance={!r}, commit={!r},"
" dirty={!r}, tagged_metadata={!r}, epoch={!r}, branch={!r}, timestamp={!r})"
).format(
self.base,
self.stage,
self.revision,
self.distance,
self.commit,
self.dirty,
self.tagged_metadata,
self.epoch,
self.branch,
self.timestamp,
)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Version):
raise TypeError(
"Cannot compare Version with type {}".format(other.__class__.__qualname__)
)
return (
self.base == other.base
and self.stage == other.stage
and self.revision == other.revision
and self.distance == other.distance
and self.commit == other.commit
and self.dirty == other.dirty
and self.tagged_metadata == other.tagged_metadata
and self.epoch == other.epoch
and self.branch == other.branch
and self.timestamp == other.timestamp
)
def _matches_partial(self, other: "Version") -> bool:
"""
Compare this version to another version, but ignore None values in the other version.
Distance is also ignored when `other.distance == 0`.
:param other: The version to compare to.
:returns: True if this version equals the other version.
"""
return (
_equal_if_set(self.base, other.base)
and _equal_if_set(self.stage, other.stage)
and _equal_if_set(self.revision, other.revision)
and _equal_if_set(self.distance, other.distance, unset=[None, 0])
and _equal_if_set(self.commit, other.commit)
and _equal_if_set(self.dirty, other.dirty)
and _equal_if_set(self.tagged_metadata, other.tagged_metadata)
and _equal_if_set(self.epoch, other.epoch)
and _equal_if_set(self.branch, other.branch)
and _equal_if_set(self.timestamp, other.timestamp)
)
def __lt__(self, other: Any) -> bool:
if not isinstance(other, Version):
raise TypeError(
"Cannot compare Version with type {}".format(other.__class__.__qualname__)
)
import packaging.version as pv
return (
pv.Version(self.base) < pv.Version(other.base)
and _blank(self.stage, "") < _blank(other.stage, "")
and _blank(self.revision, 0) < _blank(other.revision, 0)
and _blank(self.distance, 0) < _blank(other.distance, 0)
and _blank(self.commit, "") < _blank(other.commit, "")
and bool(self.dirty) < bool(other.dirty)
and _blank(self.tagged_metadata, "") < _blank(other.tagged_metadata, "")
and _blank(self.epoch, 0) < _blank(other.epoch, 0)
and _blank(self.branch, "") < _blank(other.branch, "")
and _blank(self.timestamp, dt.datetime(0, 0, 0, 0, 0, 0))
< _blank(other.timestamp, dt.datetime(0, 0, 0, 0, 0, 0))
)
def serialize(
self,
metadata: Optional[bool] = None,
dirty: bool = False,
format: Optional[Union[str, Callable[["Version"], str]]] = None,
style: Optional[Style] = None,
bump: bool = False,
tagged_metadata: bool = False,
) -> str:
"""
Create a string from the version info.
:param metadata: Metadata (commit ID, dirty flag) is normally included
in the metadata/local version part only if the distance is nonzero.
Set this to True to always include metadata even with no distance,
or set it to False to always exclude it.
This is ignored when `format` is used.
:param dirty: Set this to True to include a dirty flag in the
metadata if applicable. Inert when metadata=False.
This is ignored when `format` is used.
:param format: Custom output format. It is either a formatted string or a
callback. In the string you can use substitutions, such as "v{base}"
to get "v0.1.0". Available substitutions:
* {base}
* {stage}
* {revision}
* {distance}
* {commit}
* {dirty} which expands to either "dirty" or "clean"
* {tagged_metadata}
* {epoch}
* {branch}
* {branch_escaped} which omits any non-letter/number characters
* {timestamp} which expands to YYYYmmddHHMMSS as UTC
:param style: Built-in output formats. Will default to PEP 440 if not
set and no custom format given. If you specify both a style and a
custom format, then the format will be validated against the
style's rules.
:param bump: If true, increment the last part of the `base` by 1,
unless `stage` is set, in which case either increment `revision`
by 1 or set it to a default of 2 if there was no revision.
Does nothing when on a commit with a version tag.
:param tagged_metadata: If true, insert the `tagged_metadata` in the
version as the first part of the metadata segment.
This is ignored when `format` is used.
:returns: Serialized version.
"""
base = self.base
revision = self.revision
if bump:
bumped = self.bump(smart=True)
base = bumped.base
revision = bumped.revision
if format is not None:
if callable(format):
new_version = copy.deepcopy(self)
new_version.base = base
new_version.revision = revision
out = format(new_version)
else:
try:
out = format.format(
base=base,
stage=_blank(self.stage, ""),
revision=_blank(revision, ""),
distance=_blank(self.distance, ""),
commit=_blank(self.commit, ""),
tagged_metadata=_blank(self.tagged_metadata, ""),
dirty="dirty" if self.dirty else "clean",
epoch=_blank(self.epoch, ""),
branch=_blank(self.branch, ""),
branch_escaped=_escape_branch(_blank(self.branch, "")),
timestamp=self.timestamp.strftime("%Y%m%d%H%M%S") if self.timestamp else "",
)
except KeyError as e:
raise KeyError("Format contains invalid placeholder: {}".format(e))
except ValueError as e:
raise ValueError("Format is invalid: {}".format(e))
if style is not None:
check_version(out, style)
return out
if style is None:
style = Style.Pep440
out = ""
meta_parts = []
if metadata is not False:
if tagged_metadata and self.tagged_metadata:
meta_parts.append(self.tagged_metadata)
if (metadata or self.distance > 0) and self.commit is not None:
meta_parts.append(self.commit)
if dirty and self.dirty:
meta_parts.append("dirty")
pre_parts = []
if self.stage is not None:
pre_parts.append(self.stage)
if revision is not None:
pre_parts.append(str(revision))
if self.distance > 0:
pre_parts.append("pre" if bump or self._smart_bumped else "post")
pre_parts.append(str(self.distance))
if style == Style.Pep440:
stage = self.stage
post = None
dev = None
if stage == "post":
stage = None
post = revision
elif stage == "dev":
stage = None
dev = revision
if self.distance > 0:
if bump or self._smart_bumped:
if dev is None:
dev = self.distance
else:
dev += self.distance
else:
if post is None and dev is None:
post = self.distance
dev = 0
elif dev is None:
dev = self.distance
else:
dev += self.distance
out = serialize_pep440(
base,
stage=stage,
revision=revision,
post=post,
dev=dev,
metadata=meta_parts,
epoch=self.epoch,
)
elif style == Style.SemVer:
out = serialize_semver(base, pre=pre_parts, metadata=meta_parts)
elif style == Style.Pvp:
out = serialize_pvp(base, metadata=[*pre_parts, *meta_parts])
check_version(out, style)
return out
@classmethod
def parse(cls, version: str, pattern: Union[str, Pattern] = Pattern.Default) -> "Version":
"""
Attempt to parse a string into a Version instance.
This uses inexact heuristics, so its output may vary slightly between
releases. Consider this a "best effort" conversion.
:param version: Full version, such as 0.3.0a3+d7.gb6a9020.dirty.
:param pattern: Regular expression matched against the version.
Refer to `from_any_vcs` for more info.
:returns: Parsed version.
"""
normalized = version
if not version.startswith("v") and pattern in [VERSION_SOURCE_PATTERN, Pattern.Default]:
normalized = "v{}".format(version)
failed = False
try:
matched_pattern = _match_version_pattern(
pattern, [normalized], True, strict=True, pattern_prefix=None
)
except ValueError:
failed = True
if failed or matched_pattern is None:
replaced = re.sub(r"(\.post(\d+)\.dev\d+)", r".dev\2", version, 1)
if replaced != version:
alt = Version.parse(replaced, pattern)
if alt.base != replaced:
return alt
return cls(version)
base = matched_pattern.base
stage = matched_pattern.stage_revision
distance = None
commit = None
dirty = None
tagged_metadata = matched_pattern.tagged_metadata
epoch = matched_pattern.epoch
if tagged_metadata:
pop = [] # type: list
parts = tagged_metadata.split(".")
for i, value in enumerate(parts):
if dirty is None:
if value == "dirty":
dirty = True
pop.append(i)
continue
elif value == "clean":
dirty = False
pop.append(i)
continue
if distance is None:
match = re.match(r"d?(\d+)", value)
if match:
distance = int(match.group(1))
pop.append(i)
continue
if commit is None:
match = re.match(r"g?([\da-z]+)", value)
if match:
commit = match.group(1)
pop.append(i)
continue
for i in reversed(sorted(pop)):
parts.pop(i)
tagged_metadata = ".".join(parts)
if distance is None:
distance = 0
if tagged_metadata is not None and tagged_metadata.strip() == "":
tagged_metadata = None
if stage is not None and stage[0] == "dev" and stage[1] is not None:
distance += stage[1]
stage = None
return cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
)
def bump(self, index: int = -1, increment: int = 1, smart: bool = False) -> "Version":
"""
Increment the version.
The base is bumped unless there is a stage defined, in which case,
the revision is bumped instead.
:param index: Numerical position to increment in the base.
This follows Python indexing rules, so positive numbers start from
the left side and count up from 0, while negative numbers start from
the right side and count down from -1.
Only has an effect when the base is bumped.
:param increment: By how much to increment the relevant position.
:param smart: If true, only bump when distance is not 0.
This will also make `Version.serialize()` use pre-release formatting automatically,
like calling `Version.serialize(bump=True)`.
:returns: Bumped version.
"""
bumped = copy.deepcopy(self)
if smart:
if bumped.distance == 0:
return bumped
bumped._smart_bumped = True
if bumped.stage is None:
bumped.base = bump_version(bumped.base, index, increment)
else:
if bumped.revision is None:
bumped.revision = 2
else:
bumped.revision += increment
return bumped
@classmethod
def _fallback(
cls,
strict: bool,
*,
stage: Optional[Tuple[str, Optional[int]]] = None,
distance: int = 0,
commit: Optional[str] = None,
dirty: Optional[bool] = None,
tagged_metadata: Optional[str] = None,
epoch: Optional[int] = None,
branch: Optional[str] = None,
timestamp: Optional[dt.datetime] = None,
concerns: Optional[Set[Concern]] = None,
# fmt: off
vcs: Vcs = Vcs.Any
# fmt: on
):
if strict:
raise RuntimeError("No tags available and fallbacks disabled by strict mode")
return cls(
"0.0.0",
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
timestamp=timestamp,
concerns=concerns,
vcs=vcs,
)
@classmethod
def from_git(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
tag_branch: Optional[str] = None,
full_commit: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
ignore_untracked: bool = False,
) -> "Version":
r"""
Determine a version based on Git tags.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param tag_branch: Branch on which to find tags, if different than the
current branch.
:param full_commit: Get the full commit hash instead of the short form.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:param ignore_untracked:
Ignore untracked files when determining whether the repository is dirty.
:returns: Detected version.
"""
vcs = Vcs.Git
archival = _find_higher_file(".git_archival.json", path, ".git")
if archival is not None:
content = archival.read_text("utf8")
if "$Format:" not in content:
data = json.loads(content)
if full_commit:
commit = data.get("hash-full")
else:
commit = data.get("hash-short")
timestamp = None
raw_timestamp = data.get("timestamp")
if raw_timestamp:
timestamp = _parse_git_timestamp_iso_strict(raw_timestamp)
branch = None
refs = data.get("refs")
if refs:
parts = refs.split(" -> ")
if len(parts) == 2:
branch = parts[1].split(", ")[0]
tag = None
distance = 0
dirty = None
describe = data.get("describe")
if describe:
if describe.endswith("-dirty"):
dirty = True
describe = describe[:-6]
else:
dirty = False
parts = describe.rsplit("-", 2)
tag = parts[0]
if len(parts) > 1:
distance = int(parts[1])
if tag is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
matched_pattern = _match_version_pattern(
pattern, [tag], latest_tag, strict, pattern_prefix
)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
_detect_vcs(vcs, path)
concerns = set() # type: Set[Concern]
if tag_branch is None:
tag_branch = "HEAD"
git_version = _get_git_version()
if git_version < [2, 15]:
flag_file = _find_higher_file(".git/shallow", path)
if flag_file:
concerns.add(Concern.ShallowRepository)
else:
code, msg = _run_cmd("git rev-parse --is-shallow-repository", path)
if msg.strip() == "true":
concerns.add(Concern.ShallowRepository)
if strict and concerns:
raise RuntimeError("\n".join(x.message() for x in concerns))
code, msg = _run_cmd("git symbolic-ref --short HEAD", path, codes=[0, 128])
if code == 128:
branch = None
else:
branch = msg
code, msg = _run_cmd(
'{} -n 1 --format="format:{}"'.format(
_git_log(git_version), "%H" if full_commit else "%h"
),
path,
codes=[0, 128],
)
if code == 128:
return cls._fallback(
strict, distance=0, dirty=True, branch=branch, concerns=concerns, vcs=vcs
)
commit = msg
timestamp = None
if git_version < [2, 2]:
code, msg = _run_cmd(
'{} -n 1 --pretty=format:"%ci"'.format(_git_log(git_version)), path
)
timestamp = _parse_git_timestamp_iso(msg)
else:
code, msg = _run_cmd(
'{} -n 1 --pretty=format:"%cI"'.format(_git_log(git_version)), path
)
timestamp = _parse_git_timestamp_iso_strict(msg)
code, msg = _run_cmd("git describe --always --dirty", path)
dirty = msg.endswith("-dirty")
if not dirty and not ignore_untracked:
code, msg = _run_cmd("git status --porcelain", path)
if msg.strip() != "":
dirty = True
if git_version < [2, 7]:
code, msg = _run_cmd(
'git for-each-ref "refs/tags/**" --format "%(refname)" --sort -creatordate', path
)
if not msg:
try:
code, msg = _run_cmd("git rev-list --count HEAD", path)
distance = int(msg)
except Exception:
distance = 0
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
concerns=concerns,
vcs=vcs,
)
tags = [line.replace("refs/tags/", "") for line in msg.splitlines()]
matched_pattern = _match_version_pattern(
pattern, tags, latest_tag, strict, pattern_prefix
)
else:
code, msg = _run_cmd(
'git for-each-ref "refs/tags/**" --merged {}'.format(tag_branch)
+ ' --format "%(refname)'
"@{%(objectname)"
"@{%(creatordate:iso-strict)"
"@{%(*committerdate:iso-strict)"
"@{%(taggerdate:iso-strict)"
'"',
path,
)
if not msg:
try:
code, msg = _run_cmd("git rev-list --count HEAD", path)
distance = int(msg)
except Exception:
distance = 0
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
concerns=concerns,
vcs=vcs,
)
detailed_tags = [] # type: List[_GitRefInfo]
tag_topo_lookup = _GitRefInfo.from_git_tag_topo_order(tag_branch, git_version, path)
for line in msg.strip().splitlines():
parts = line.split("@{")
if len(parts) != 5:
continue
detailed_tags.append(_GitRefInfo(*parts).with_tag_topo_lookup(tag_topo_lookup))
tags = [t.ref for t in sorted(detailed_tags, key=lambda x: x.sort_key, reverse=True)]
matched_pattern = _match_version_pattern(
pattern, tags, latest_tag, strict, pattern_prefix
)
if matched_pattern is None:
try:
code, msg = _run_cmd("git rev-list --count HEAD", path)
distance = int(msg)
except Exception:
distance = 0
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
concerns=concerns,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
code, msg = _run_cmd("git rev-list --count refs/tags/{}..HEAD".format(tag), path)
distance = int(msg)
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
timestamp=timestamp,
concerns=concerns,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
@classmethod
def from_mercurial(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
full_commit: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
) -> "Version":
r"""
Determine a version based on Mercurial tags.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param full_commit: Get the full commit hash instead of the short form.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:returns: Detected version.
"""
vcs = Vcs.Mercurial
archival = _find_higher_file(".hg_archival.txt", path, ".hg")
if archival is not None:
content = archival.read_text("utf8")
data = {}
for line in content.splitlines():
parts = line.split(":", 1)
if len(parts) != 2:
continue
data[parts[0].strip()] = parts[1].strip()
tag = data.get("latesttag")
# The distance is 1 on a new repo or on a tagged commit.
distance = int(data.get("latesttagdistance", 1)) - 1
commit = data.get("node")
branch = data.get("branch")
if tag is None or tag == "null":
return cls._fallback(
strict, distance=distance, commit=commit, branch=branch, vcs=vcs
)
all_tags_file = _find_higher_file(".hgtags", path, ".hg")
if all_tags_file is None:
all_tags = [tag]
else:
all_tags = []
all_tags_content = all_tags_file.read_text("utf8")
for line in reversed(all_tags_content.splitlines()):
parts = line.split(" ", 1)
if len(parts) != 2:
continue
all_tags.append(parts[1])
matched_pattern = _match_version_pattern(
pattern, all_tags, latest_tag, strict, pattern_prefix
)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
branch=branch,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
_detect_vcs(vcs, path)
code, msg = _run_cmd("hg summary", path)
dirty = "commit: (clean)" not in msg.splitlines()
code, msg = _run_cmd("hg branch", path)
branch = msg
code, msg = _run_cmd(
'hg id --template "{}"'.format("{id}" if full_commit else "{id|short}"), path
)
commit = msg if set(msg) != {"0"} else None
code, msg = _run_cmd('hg log --limit 1 --template "{date|rfc3339date}"', path)
timestamp = _parse_git_timestamp_iso_strict(msg) if msg != "" else None
code, msg = _run_cmd(
'hg log -r "sort(tag(){}, -rev)" --template "{{join(tags, \':\')}}\\n"'.format(
" and ancestors({})".format(commit) if commit is not None else ""
),
path,
)
if not msg:
try:
code, msg = _run_cmd("hg id --num --rev tip", path)
distance = int(msg) + 1
except Exception:
distance = 0
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tags = [tag for tags in [line.split(":") for line in msg.splitlines()] for tag in tags]
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
code, msg = _run_cmd('hg log -r "{0}::{1} - {0}" --template "."'.format(tag, commit), path)
# The tag itself is in the list, so offset by 1.
distance = max(len(msg) - 1, 0)
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
@classmethod
def from_darcs(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
) -> "Version":
r"""
Determine a version based on Darcs tags.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:returns: Detected version.
"""
vcs = Vcs.Darcs
_detect_vcs(vcs, path)
code, msg = _run_cmd("darcs status", path, codes=[0, 1])
dirty = msg != "No changes!"
code, msg = _run_cmd("darcs log --last 1 --xml-output", path)
root = ElementTree.fromstring(msg)
if len(root) == 0:
commit = None
timestamp = None
else:
commit = root[0].attrib["hash"]
timestamp = dt.datetime.strptime(root[0].attrib["date"] + "+0000", "%Y%m%d%H%M%S%z")
code, msg = _run_cmd("darcs show tags", path)
if not msg:
try:
code, msg = _run_cmd("darcs log --count", path)
distance = int(msg)
except Exception:
distance = 0
return cls._fallback(
strict, distance=distance, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs
)
tags = msg.splitlines()
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
timestamp=timestamp,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
code, msg = _run_cmd("darcs log --from-tag {} --count".format(tag), path)
# The tag itself is in the list, so offset by 1.
distance = int(msg) - 1
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
timestamp=timestamp,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
@classmethod
def from_subversion(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
tag_dir: str = "tags",
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
) -> "Version":
r"""
Determine a version based on Subversion tags.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param tag_dir: Location of tags relative to the root.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:returns: Detected version.
"""
vcs = Vcs.Subversion
_detect_vcs(vcs, path)
tag_dir = tag_dir.strip("/")
code, msg = _run_cmd("svn status", path)
dirty = bool(msg)
code, msg = _run_cmd("svn info --show-item repos-root-url", path)
url = msg.strip("/")
code, msg = _run_cmd("svn info --show-item revision", path)
if not msg or msg == "0":
commit = None
else:
commit = msg
timestamp = None
if commit:
code, msg = _run_cmd("svn info --show-item last-changed-date", path)
timestamp = _parse_timestamp(msg)
if not commit:
return cls._fallback(
strict, distance=0, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs
)
code, msg = _run_cmd('svn ls -v -r {} "{}/{}"'.format(commit, url, tag_dir), path)
lines = [line.split(maxsplit=5) for line in msg.splitlines()[1:]]
tags_to_revs = {line[-1].strip("/"): int(line[0]) for line in lines}
if not tags_to_revs:
try:
distance = int(commit)
except Exception:
distance = 0
return cls._fallback(
strict, distance=distance, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs
)
tags_to_sources_revs = {}
for tag, rev in tags_to_revs.items():
code, msg = _run_cmd(
'svn log -v "{}/{}/{}" --stop-on-copy'.format(url, tag_dir, tag), path
)
for line in msg.splitlines():
match = re.search(r"A /{}/{} \(from .+?:(\d+)\)".format(tag_dir, tag), line)
if match:
source = int(match.group(1))
tags_to_sources_revs[tag] = (source, rev)
tags = sorted(tags_to_sources_revs, key=lambda x: tags_to_sources_revs[x], reverse=True)
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
timestamp=timestamp,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
source, rev = tags_to_sources_revs[tag]
# The tag itself is in the list, so offset by 1.
distance = int(commit) - 1 - source
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
timestamp=timestamp,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
@classmethod
def from_bazaar(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
) -> "Version":
r"""
Determine a version based on Bazaar tags.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:returns: Detected version.
"""
vcs = Vcs.Bazaar
_detect_vcs(vcs, path)
code, msg = _run_cmd("bzr status", path)
dirty = msg != ""
code, msg = _run_cmd("bzr log --limit 1", path)
commit = None
branch = None
timestamp = None
for line in msg.splitlines():
info = line.split("revno: ", maxsplit=1)
if len(info) == 2:
commit = info[1]
info = line.split("branch nick: ", maxsplit=1)
if len(info) == 2:
branch = info[1]
info = line.split("timestamp: ", maxsplit=1)
if len(info) == 2:
timestamp = dt.datetime.strptime(info[1], "%a %Y-%m-%d %H:%M:%S %z")
code, msg = _run_cmd("bzr tags", path)
if not msg or not commit:
try:
distance = int(commit) if commit is not None else 0
except Exception:
distance = 0
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tags_to_revs = {
line.split()[0]: int(line.split()[1])
for line in msg.splitlines()
if line.split()[1] != "?"
}
tags = [x[1] for x in sorted([(v, k) for k, v in tags_to_revs.items()], reverse=True)]
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
distance = int(commit) - tags_to_revs[tag]
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
@classmethod
def from_fossil(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
) -> "Version":
r"""
Determine a version based on Fossil tags.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag for a pattern
match. If false, keep looking at tags until there is a match.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:returns: Detected version.
"""
vcs = Vcs.Fossil
_detect_vcs(vcs, path)
code, msg = _run_cmd("fossil changes --differ", path)
dirty = bool(msg)
code, msg = _run_cmd("fossil branch current", path)
branch = msg
code, msg = _run_cmd(
"fossil sql \"SELECT value FROM vvar WHERE name = 'checkout-hash' LIMIT 1\"", path
)
commit = msg.strip("'")
code, msg = _run_cmd(
'fossil sql "'
"SELECT DATETIME(mtime) FROM event JOIN blob ON event.objid=blob.rid WHERE type = 'ci'"
" AND uuid = (SELECT value FROM vvar WHERE name = 'checkout-hash' LIMIT 1) LIMIT 1\"",
path,
)
timestamp = dt.datetime.strptime(msg.strip("'") + "+0000", "%Y-%m-%d %H:%M:%S%z")
code, msg = _run_cmd("fossil sql \"SELECT count() FROM event WHERE type = 'ci'\"", path)
# The repository creation itself counts as a commit.
total_commits = int(msg) - 1
if total_commits <= 0:
return cls._fallback(
strict,
distance=0,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
# Based on `compute_direct_ancestors` from descendants.c in the
# Fossil source code:
query = """
CREATE TEMP TABLE IF NOT EXISTS
dunamai_ancestor(
rid INTEGER UNIQUE NOT NULL,
generation INTEGER PRIMARY KEY
);
DELETE FROM dunamai_ancestor;
WITH RECURSIVE g(x, i)
AS (
VALUES((SELECT value FROM vvar WHERE name = 'checkout' LIMIT 1), 1)
UNION ALL
SELECT plink.pid, g.i + 1 FROM plink, g
WHERE plink.cid = g.x AND plink.isprim
)
INSERT INTO dunamai_ancestor(rid, generation) SELECT x, i FROM g;
SELECT tag.tagname, dunamai_ancestor.generation
FROM tag
JOIN tagxref ON tag.tagid = tagxref.tagid
JOIN event ON tagxref.origid = event.objid
JOIN dunamai_ancestor ON tagxref.origid = dunamai_ancestor.rid
WHERE tagxref.tagtype = 1
ORDER BY event.mtime DESC, tagxref.mtime DESC;
"""
code, msg = _run_cmd('fossil sql "{}"'.format(" ".join(query.splitlines())), path)
if not msg:
try:
distance = int(total_commits)
except Exception:
distance = 0
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tags_to_distance = [
(line.rsplit(",", 1)[0][5:-1], int(line.rsplit(",", 1)[1]) - 1)
for line in msg.splitlines()
]
matched_pattern = _match_version_pattern(
pattern, [t for t, d in tags_to_distance], latest_tag, strict, pattern_prefix
)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
distance = dict(tags_to_distance)[tag]
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
@classmethod
def from_pijul(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
) -> "Version":
r"""
Determine a version based on Pijul tags.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:returns: Detected version.
"""
vcs = Vcs.Pijul
_detect_vcs(vcs, path)
code, msg = _run_cmd("pijul diff --short", path)
dirty = msg.strip() != ""
code, msg = _run_cmd("pijul channel", path)
branch = "main"
for line in msg.splitlines():
if line.startswith("* "):
branch = line.split("* ", 1)[1]
break
code, msg = _run_cmd("pijul log --limit 1 --output-format json", path)
limited_commits = json.loads(msg)
if len(limited_commits) == 0:
return cls._fallback(strict, dirty=dirty, branch=branch, vcs=vcs)
commit = limited_commits[0]["hash"]
timestamp = _parse_timestamp(limited_commits[0]["timestamp"])
code, msg = _run_cmd("pijul log --output-format json", path)
channel_commits = json.loads(msg)
code, msg = _run_cmd("pijul tag", path)
if not msg:
# The channel creation is in the list, so offset by 1.
distance = len(channel_commits) - 1
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tag_meta = [] # type: List[dict]
tag_state = ""
tag_timestamp = dt.datetime.now()
tag_message = ""
tag_after_header = False
for line in msg.splitlines():
if not tag_after_header:
if line.startswith("State "):
tag_state = line.split("State ", 1)[1]
elif line.startswith("Date:"):
tag_timestamp = _parse_timestamp(
line.split("Date: ", 1)[1].replace(" UTC", "Z"), space=True
)
elif line.startswith(" "):
tag_message += line[4:]
tag_after_header = True
else:
if line.startswith("State "):
tag_meta.append(
{
"state": tag_state,
"timestamp": tag_timestamp,
"message": tag_message.strip(),
}
)
tag_state = line.split("State ", 1)[1]
tag_timestamp = dt.datetime.now()
tag_message = ""
tag_after_header = False
else:
tag_message += line
if tag_after_header:
tag_meta.append(
{"state": tag_state, "timestamp": tag_timestamp, "message": tag_message.strip()}
)
tag_meta_by_msg = {} # type: dict
for meta in tag_meta:
if (
meta["message"] not in tag_meta_by_msg
or meta["timestamp"] > tag_meta_by_msg[meta["message"]]["timestamp"]
):
tag_meta_by_msg[meta["message"]] = meta
tags = [
t["message"]
for t in sorted(tag_meta_by_msg.values(), key=lambda x: x["timestamp"], reverse=True)
]
matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
if matched_pattern is None:
return cls._fallback(
strict,
distance=distance,
commit=commit,
dirty=dirty,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern
tag_id = tag_meta_by_msg[tag]["state"]
_run_cmd("pijul tag checkout {}".format(tag_id), path, codes=[0, 1])
code, msg = _run_cmd("pijul log --output-format json --channel {}".format(tag_id), path)
if msg.strip() == "":
tag_commits = [] # type: list
else:
tag_commits = json.loads(msg)
distance = len(channel_commits) - len(tag_commits)
version = cls(
base,
stage=stage,
distance=distance,
commit=commit,
dirty=dirty,
tagged_metadata=tagged_metadata,
epoch=epoch,
branch=branch,
timestamp=timestamp,
vcs=vcs,
)
version._matched_tag = tag
version._newer_unmatched_tags = unmatched
return version
@classmethod
def from_any_vcs(
cls,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
tag_dir: str = "tags",
tag_branch: Optional[str] = None,
full_commit: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
ignore_untracked: bool = False,
) -> "Version":
r"""
Determine a version based on a detected version control system.
:param pattern: Regular expression matched against the version source.
This must contain one capture group named `base` corresponding to
the release segment of the source. Optionally, it may contain another
two groups named `stage` and `revision` corresponding to a prerelease
type (such as 'alpha' or 'rc') and number (such as in 'alpha-2' or 'rc3').
It may also contain a group named `tagged_metadata` corresponding to extra
metadata after the main part of the version (typically after a plus sign).
There may also be a group named `epoch` for the PEP 440 concept.
If the `base` group is not included, then this will be interpreted
as the name of a variant of the `Pattern` enum. For example, passing
`"default"` is the same as passing `Pattern.Default`.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param tag_dir: Location of tags relative to the root.
This is only used for Subversion.
:param tag_branch: Branch on which to find tags, if different than the
current branch. This is only used for Git currently.
:param full_commit: Get the full commit hash instead of the short form.
This is only used for Git and Mercurial.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:param ignore_untracked:
Ignore untracked files when determining whether the repository is dirty.
This is only used for Git currently.
:returns: Detected version.
"""
vcs = _detect_vcs_from_archival(path)
if vcs is None:
vcs = _detect_vcs(None, path)
return cls._do_vcs_callback(
vcs,
pattern,
latest_tag,
tag_dir,
tag_branch,
full_commit,
strict,
path,
pattern_prefix,
ignore_untracked,
)
@classmethod
def from_vcs(
cls,
vcs: Vcs,
pattern: Union[str, Pattern] = Pattern.Default,
latest_tag: bool = False,
tag_dir: str = "tags",
tag_branch: Optional[str] = None,
full_commit: bool = False,
strict: bool = False,
path: Optional[Path] = None,
pattern_prefix: Optional[str] = None,
ignore_untracked: bool = False,
) -> "Version":
r"""
Determine a version based on a specific VCS setting.
This is primarily intended for other tools that want to generically
use some VCS setting based on user configuration, without having to
maintain a mapping from the VCS name to the appropriate function.
:param pattern: Regular expression matched against the version source.
Refer to `from_any_vcs` for more info.
:param latest_tag: If true, only inspect the latest tag on the latest
tagged commit for a pattern match. If false, keep looking at tags
until there is a match.
:param tag_dir: Location of tags relative to the root.
This is only used for Subversion.
:param tag_branch: Branch on which to find tags, if different than the
current branch. This is only used for Git currently.
:param full_commit: Get the full commit hash instead of the short form.
This is only used for Git and Mercurial.
:param strict: Elevate warnings to errors.
When there are no tags, fail instead of falling back to 0.0.0.
:param path: Directory to inspect, if not the current working directory.
:param pattern_prefix: Insert this after the pattern's start anchor (`^`).
:param ignore_untracked:
Ignore untracked files when determining whether the repository is dirty.
This is only used for Git currently.
:returns: Detected version.
"""
return cls._do_vcs_callback(
vcs,
pattern,
latest_tag,
tag_dir,
tag_branch,
full_commit,
strict,
path,
pattern_prefix,
ignore_untracked,
)
@classmethod
def _do_vcs_callback(
cls,
vcs: Vcs,
pattern: Union[str, Pattern],
latest_tag: bool,
tag_dir: str,
tag_branch: Optional[str],
full_commit: bool,
strict: bool,
path: Optional[Path],
pattern_prefix: Optional[str] = None,
ignore_untracked: bool = False,
) -> "Version":
mapping = {
Vcs.Any: cls.from_any_vcs,
Vcs.Git: cls.from_git,
Vcs.Mercurial: cls.from_mercurial,
Vcs.Darcs: cls.from_darcs,
Vcs.Subversion: cls.from_subversion,
Vcs.Bazaar: cls.from_bazaar,
Vcs.Fossil: cls.from_fossil,
Vcs.Pijul: cls.from_pijul,
} # type: Mapping[Vcs, Callable[..., "Version"]]
kwargs = {}
callback = mapping[vcs]
for kwarg, value in [
("pattern", pattern),
("latest_tag", latest_tag),
("tag_dir", tag_dir),
("tag_branch", tag_branch),
("full_commit", full_commit),
("strict", strict),
("path", path),
("pattern_prefix", pattern_prefix),
("ignore_untracked", ignore_untracked),
]:
if kwarg in inspect.getfullargspec(callback).args:
kwargs[kwarg] = value
return callback(**kwargs)
| (base: str, *, stage: Optional[Tuple[str, Optional[int]]] = None, distance: int = 0, commit: Optional[str] = None, dirty: Optional[bool] = None, tagged_metadata: Optional[str] = None, epoch: Optional[int] = None, branch: Optional[str] = None, timestamp: Optional[datetime.datetime] = None, concerns: Optional[Set[dunamai.Concern]] = None, vcs: dunamai.Vcs = <Vcs.Any: 'any'>) -> None |
27,008 | dunamai | __eq__ | null | def __eq__(self, other: Any) -> bool:
if not isinstance(other, Version):
raise TypeError(
"Cannot compare Version with type {}".format(other.__class__.__qualname__)
)
return (
self.base == other.base
and self.stage == other.stage
and self.revision == other.revision
and self.distance == other.distance
and self.commit == other.commit
and self.dirty == other.dirty
and self.tagged_metadata == other.tagged_metadata
and self.epoch == other.epoch
and self.branch == other.branch
and self.timestamp == other.timestamp
)
| (self, other: Any) -> bool |
27,011 | dunamai | __init__ |
:param base: Release segment, such as 0.1.0.
:param stage: Pair of release stage (e.g., "a", "alpha", "b", "rc")
and an optional revision number.
:param distance: Number of commits since the last tag.
:param commit: Commit hash/identifier.
:param dirty: True if the working directory does not match the commit.
:param epoch: Optional PEP 440 epoch.
:param branch: Name of the current branch.
:param timestamp: Timestamp of the current commit.
:param concerns: Any concerns regarding the version.
| def __init__(
self,
base: str,
*,
stage: Optional[Tuple[str, Optional[int]]] = None,
distance: int = 0,
commit: Optional[str] = None,
dirty: Optional[bool] = None,
tagged_metadata: Optional[str] = None,
epoch: Optional[int] = None,
branch: Optional[str] = None,
timestamp: Optional[dt.datetime] = None,
concerns: Optional[Set[Concern]] = None,
# fmt: off
vcs: Vcs = Vcs.Any
# fmt: on
) -> None:
"""
:param base: Release segment, such as 0.1.0.
:param stage: Pair of release stage (e.g., "a", "alpha", "b", "rc")
and an optional revision number.
:param distance: Number of commits since the last tag.
:param commit: Commit hash/identifier.
:param dirty: True if the working directory does not match the commit.
:param epoch: Optional PEP 440 epoch.
:param branch: Name of the current branch.
:param timestamp: Timestamp of the current commit.
:param concerns: Any concerns regarding the version.
"""
self.base = base
self.stage = None
self.revision = None
if stage is not None:
self.stage, self.revision = stage
self.distance = distance
self.commit = commit
self.dirty = dirty
self.tagged_metadata = tagged_metadata
self.epoch = epoch
self.branch = branch
try:
self.timestamp = timestamp.astimezone(dt.timezone.utc) if timestamp else None
except ValueError:
# Will fail for naive timestamps before Python 3.6.
self.timestamp = timestamp
self.concerns = concerns or set()
self.vcs = vcs
self._matched_tag = None # type: Optional[str]
self._newer_unmatched_tags = None # type: Optional[Sequence[str]]
self._smart_bumped = False
| (self, base: str, *, stage: Optional[Tuple[str, Optional[int]]] = None, distance: int = 0, commit: Optional[str] = None, dirty: Optional[bool] = None, tagged_metadata: Optional[str] = None, epoch: Optional[int] = None, branch: Optional[str] = None, timestamp: Optional[datetime.datetime] = None, concerns: Optional[Set[dunamai.Concern]] = None, vcs: dunamai.Vcs = <Vcs.Any: 'any'>) -> NoneType |
27,013 | dunamai | __lt__ | null | def __lt__(self, other: Any) -> bool:
if not isinstance(other, Version):
raise TypeError(
"Cannot compare Version with type {}".format(other.__class__.__qualname__)
)
import packaging.version as pv
return (
pv.Version(self.base) < pv.Version(other.base)
and _blank(self.stage, "") < _blank(other.stage, "")
and _blank(self.revision, 0) < _blank(other.revision, 0)
and _blank(self.distance, 0) < _blank(other.distance, 0)
and _blank(self.commit, "") < _blank(other.commit, "")
and bool(self.dirty) < bool(other.dirty)
and _blank(self.tagged_metadata, "") < _blank(other.tagged_metadata, "")
and _blank(self.epoch, 0) < _blank(other.epoch, 0)
and _blank(self.branch, "") < _blank(other.branch, "")
and _blank(self.timestamp, dt.datetime(0, 0, 0, 0, 0, 0))
< _blank(other.timestamp, dt.datetime(0, 0, 0, 0, 0, 0))
)
| (self, other: Any) -> bool |
27,014 | dunamai | __repr__ | null | def __repr__(self) -> str:
return (
"Version(base={!r}, stage={!r}, revision={!r}, distance={!r}, commit={!r},"
" dirty={!r}, tagged_metadata={!r}, epoch={!r}, branch={!r}, timestamp={!r})"
).format(
self.base,
self.stage,
self.revision,
self.distance,
self.commit,
self.dirty,
self.tagged_metadata,
self.epoch,
self.branch,
self.timestamp,
)
| (self) -> str |
27,015 | dunamai | __str__ | null | def __str__(self) -> str:
return self.serialize()
| (self) -> str |
27,016 | dunamai | _matches_partial |
Compare this version to another version, but ignore None values in the other version.
Distance is also ignored when `other.distance == 0`.
:param other: The version to compare to.
:returns: True if this version equals the other version.
| def _matches_partial(self, other: "Version") -> bool:
"""
Compare this version to another version, but ignore None values in the other version.
Distance is also ignored when `other.distance == 0`.
:param other: The version to compare to.
:returns: True if this version equals the other version.
"""
return (
_equal_if_set(self.base, other.base)
and _equal_if_set(self.stage, other.stage)
and _equal_if_set(self.revision, other.revision)
and _equal_if_set(self.distance, other.distance, unset=[None, 0])
and _equal_if_set(self.commit, other.commit)
and _equal_if_set(self.dirty, other.dirty)
and _equal_if_set(self.tagged_metadata, other.tagged_metadata)
and _equal_if_set(self.epoch, other.epoch)
and _equal_if_set(self.branch, other.branch)
and _equal_if_set(self.timestamp, other.timestamp)
)
| (self, other: dunamai.Version) -> bool |
27,017 | dunamai | bump |
Increment the version.
The base is bumped unless there is a stage defined, in which case,
the revision is bumped instead.
:param index: Numerical position to increment in the base.
This follows Python indexing rules, so positive numbers start from
the left side and count up from 0, while negative numbers start from
the right side and count down from -1.
Only has an effect when the base is bumped.
:param increment: By how much to increment the relevant position.
:param smart: If true, only bump when distance is not 0.
This will also make `Version.serialize()` use pre-release formatting automatically,
like calling `Version.serialize(bump=True)`.
:returns: Bumped version.
| def bump(self, index: int = -1, increment: int = 1, smart: bool = False) -> "Version":
"""
Increment the version.
The base is bumped unless there is a stage defined, in which case,
the revision is bumped instead.
:param index: Numerical position to increment in the base.
This follows Python indexing rules, so positive numbers start from
the left side and count up from 0, while negative numbers start from
the right side and count down from -1.
Only has an effect when the base is bumped.
:param increment: By how much to increment the relevant position.
:param smart: If true, only bump when distance is not 0.
This will also make `Version.serialize()` use pre-release formatting automatically,
like calling `Version.serialize(bump=True)`.
:returns: Bumped version.
"""
bumped = copy.deepcopy(self)
if smart:
if bumped.distance == 0:
return bumped
bumped._smart_bumped = True
if bumped.stage is None:
bumped.base = bump_version(bumped.base, index, increment)
else:
if bumped.revision is None:
bumped.revision = 2
else:
bumped.revision += increment
return bumped
| (self, index: int = -1, increment: int = 1, smart: bool = False) -> dunamai.Version |
27,018 | dunamai | serialize |
Create a string from the version info.
:param metadata: Metadata (commit ID, dirty flag) is normally included
in the metadata/local version part only if the distance is nonzero.
Set this to True to always include metadata even with no distance,
or set it to False to always exclude it.
This is ignored when `format` is used.
:param dirty: Set this to True to include a dirty flag in the
metadata if applicable. Inert when metadata=False.
This is ignored when `format` is used.
:param format: Custom output format. It is either a formatted string or a
callback. In the string you can use substitutions, such as "v{base}"
to get "v0.1.0". Available substitutions:
* {base}
* {stage}
* {revision}
* {distance}
* {commit}
* {dirty} which expands to either "dirty" or "clean"
* {tagged_metadata}
* {epoch}
* {branch}
* {branch_escaped} which omits any non-letter/number characters
* {timestamp} which expands to YYYYmmddHHMMSS as UTC
:param style: Built-in output formats. Will default to PEP 440 if not
set and no custom format given. If you specify both a style and a
custom format, then the format will be validated against the
style's rules.
:param bump: If true, increment the last part of the `base` by 1,
unless `stage` is set, in which case either increment `revision`
by 1 or set it to a default of 2 if there was no revision.
Does nothing when on a commit with a version tag.
:param tagged_metadata: If true, insert the `tagged_metadata` in the
version as the first part of the metadata segment.
This is ignored when `format` is used.
:returns: Serialized version.
| def serialize(
self,
metadata: Optional[bool] = None,
dirty: bool = False,
format: Optional[Union[str, Callable[["Version"], str]]] = None,
style: Optional[Style] = None,
bump: bool = False,
tagged_metadata: bool = False,
) -> str:
"""
Create a string from the version info.
:param metadata: Metadata (commit ID, dirty flag) is normally included
in the metadata/local version part only if the distance is nonzero.
Set this to True to always include metadata even with no distance,
or set it to False to always exclude it.
This is ignored when `format` is used.
:param dirty: Set this to True to include a dirty flag in the
metadata if applicable. Inert when metadata=False.
This is ignored when `format` is used.
:param format: Custom output format. It is either a formatted string or a
callback. In the string you can use substitutions, such as "v{base}"
to get "v0.1.0". Available substitutions:
* {base}
* {stage}
* {revision}
* {distance}
* {commit}
* {dirty} which expands to either "dirty" or "clean"
* {tagged_metadata}
* {epoch}
* {branch}
* {branch_escaped} which omits any non-letter/number characters
* {timestamp} which expands to YYYYmmddHHMMSS as UTC
:param style: Built-in output formats. Will default to PEP 440 if not
set and no custom format given. If you specify both a style and a
custom format, then the format will be validated against the
style's rules.
:param bump: If true, increment the last part of the `base` by 1,
unless `stage` is set, in which case either increment `revision`
by 1 or set it to a default of 2 if there was no revision.
Does nothing when on a commit with a version tag.
:param tagged_metadata: If true, insert the `tagged_metadata` in the
version as the first part of the metadata segment.
This is ignored when `format` is used.
:returns: Serialized version.
"""
base = self.base
revision = self.revision
if bump:
bumped = self.bump(smart=True)
base = bumped.base
revision = bumped.revision
if format is not None:
if callable(format):
new_version = copy.deepcopy(self)
new_version.base = base
new_version.revision = revision
out = format(new_version)
else:
try:
out = format.format(
base=base,
stage=_blank(self.stage, ""),
revision=_blank(revision, ""),
distance=_blank(self.distance, ""),
commit=_blank(self.commit, ""),
tagged_metadata=_blank(self.tagged_metadata, ""),
dirty="dirty" if self.dirty else "clean",
epoch=_blank(self.epoch, ""),
branch=_blank(self.branch, ""),
branch_escaped=_escape_branch(_blank(self.branch, "")),
timestamp=self.timestamp.strftime("%Y%m%d%H%M%S") if self.timestamp else "",
)
except KeyError as e:
raise KeyError("Format contains invalid placeholder: {}".format(e))
except ValueError as e:
raise ValueError("Format is invalid: {}".format(e))
if style is not None:
check_version(out, style)
return out
if style is None:
style = Style.Pep440
out = ""
meta_parts = []
if metadata is not False:
if tagged_metadata and self.tagged_metadata:
meta_parts.append(self.tagged_metadata)
if (metadata or self.distance > 0) and self.commit is not None:
meta_parts.append(self.commit)
if dirty and self.dirty:
meta_parts.append("dirty")
pre_parts = []
if self.stage is not None:
pre_parts.append(self.stage)
if revision is not None:
pre_parts.append(str(revision))
if self.distance > 0:
pre_parts.append("pre" if bump or self._smart_bumped else "post")
pre_parts.append(str(self.distance))
if style == Style.Pep440:
stage = self.stage
post = None
dev = None
if stage == "post":
stage = None
post = revision
elif stage == "dev":
stage = None
dev = revision
if self.distance > 0:
if bump or self._smart_bumped:
if dev is None:
dev = self.distance
else:
dev += self.distance
else:
if post is None and dev is None:
post = self.distance
dev = 0
elif dev is None:
dev = self.distance
else:
dev += self.distance
out = serialize_pep440(
base,
stage=stage,
revision=revision,
post=post,
dev=dev,
metadata=meta_parts,
epoch=self.epoch,
)
elif style == Style.SemVer:
out = serialize_semver(base, pre=pre_parts, metadata=meta_parts)
elif style == Style.Pvp:
out = serialize_pvp(base, metadata=[*pre_parts, *meta_parts])
check_version(out, style)
return out
| (self, metadata: Optional[bool] = None, dirty: bool = False, format: Union[str, Callable[[dunamai.Version], str], NoneType] = None, style: Optional[dunamai.Style] = None, bump: bool = False, tagged_metadata: bool = False) -> str |
27,019 | poetry_dynamic_versioning | _Config | null | class _Config(Mapping):
pass
| null |
27,020 | poetry_dynamic_versioning | _File | null | from poetry_dynamic_versioning import _File
| null |
27,021 | poetry_dynamic_versioning | _FolderConfig | null | class _FolderConfig:
def __init__(self, path: Path, files: Sequence[str], patterns: Sequence[_SubPattern]):
self.path = path
self.files = files
self.patterns = patterns
@staticmethod
def from_config(config: _Config, root: Path) -> Sequence["_FolderConfig"]:
files = config["substitution"]["files"]
patterns = _SubPattern.from_config(config["substitution"]["patterns"])
main = _FolderConfig(root, files, patterns)
extra = [
_FolderConfig(
root / x["path"],
x["files"] if x["files"] is not None else files,
_SubPattern.from_config(x["patterns"]) if x["patterns"] is not None else patterns,
)
for x in config["substitution"]["folders"]
]
return [main, *extra]
| (path: pathlib.Path, files: Sequence[str], patterns: Sequence[poetry_dynamic_versioning._SubPattern]) |
27,022 | poetry_dynamic_versioning | __init__ | null | def __init__(self, path: Path, files: Sequence[str], patterns: Sequence[_SubPattern]):
self.path = path
self.files = files
self.patterns = patterns
| (self, path: pathlib.Path, files: Sequence[str], patterns: Sequence[poetry_dynamic_versioning._SubPattern]) |
27,023 | poetry_dynamic_versioning | from_config | null | @staticmethod
def from_config(config: _Config, root: Path) -> Sequence["_FolderConfig"]:
files = config["substitution"]["files"]
patterns = _SubPattern.from_config(config["substitution"]["patterns"])
main = _FolderConfig(root, files, patterns)
extra = [
_FolderConfig(
root / x["path"],
x["files"] if x["files"] is not None else files,
_SubPattern.from_config(x["patterns"]) if x["patterns"] is not None else patterns,
)
for x in config["substitution"]["folders"]
]
return [main, *extra]
| (config: poetry_dynamic_versioning._Config, root: pathlib.Path) -> Sequence[poetry_dynamic_versioning._FolderConfig] |
27,024 | poetry_dynamic_versioning | _FromFile | null | from poetry_dynamic_versioning import _FromFile
| null |
27,025 | poetry_dynamic_versioning | _JinjaImport | null | from poetry_dynamic_versioning import _JinjaImport
| null |
27,026 | poetry_dynamic_versioning | _ProjectState | null | class _ProjectState:
def __init__(
self,
path: Path,
original_version: str,
version: str,
substitutions: Optional[MutableMapping[Path, str]] = None,
) -> None:
self.path = path
self.original_version = original_version
self.version = version
self.substitutions = (
{} if substitutions is None else substitutions
) # type: MutableMapping[Path, str]
| (path: pathlib.Path, original_version: str, version: str, substitutions: Optional[MutableMapping[pathlib.Path, str]] = None) -> None |
27,027 | poetry_dynamic_versioning | __init__ | null | def __init__(
self,
path: Path,
original_version: str,
version: str,
substitutions: Optional[MutableMapping[Path, str]] = None,
) -> None:
self.path = path
self.original_version = original_version
self.version = version
self.substitutions = (
{} if substitutions is None else substitutions
) # type: MutableMapping[Path, str]
| (self, path: pathlib.Path, original_version: str, version: str, substitutions: Optional[MutableMapping[pathlib.Path, str]] = None) -> NoneType |
27,028 | poetry_dynamic_versioning | _State | null | class _State:
def __init__(self) -> None:
self.patched_core_poetry_create = False
self.cli_mode = False
self.projects = {} # type: MutableMapping[str, _ProjectState]
| () -> None |
27,029 | poetry_dynamic_versioning | __init__ | null | def __init__(self) -> None:
self.patched_core_poetry_create = False
self.cli_mode = False
self.projects = {} # type: MutableMapping[str, _ProjectState]
| (self) -> NoneType |
27,030 | poetry_dynamic_versioning | _SubPattern | null | class _SubPattern:
def __init__(self, value: str, mode: str):
self.value = value
self.mode = mode
@staticmethod
def from_config(config: Sequence[Union[str, Mapping]]) -> Sequence["_SubPattern"]:
patterns = []
for x in config:
if isinstance(x, str):
patterns.append(_SubPattern(x, mode="str"))
else:
patterns.append(_SubPattern(x["value"], mode=x.get("mode", "str")))
return patterns
| (value: str, mode: str) |
27,031 | poetry_dynamic_versioning | __init__ | null | def __init__(self, value: str, mode: str):
self.value = value
self.mode = mode
| (self, value: str, mode: str) |
27,032 | poetry_dynamic_versioning | from_config | null | @staticmethod
def from_config(config: Sequence[Union[str, Mapping]]) -> Sequence["_SubPattern"]:
patterns = []
for x in config:
if isinstance(x, str):
patterns.append(_SubPattern(x, mode="str"))
else:
patterns.append(_SubPattern(x["value"], mode=x.get("mode", "str")))
return patterns
| (config: Sequence[Union[str, Mapping]]) -> Sequence[poetry_dynamic_versioning._SubPattern] |
27,033 | poetry_dynamic_versioning | _Substitution | null | from poetry_dynamic_versioning import _Substitution
| null |
27,034 | poetry_dynamic_versioning | _SubstitutionFolder | null | from poetry_dynamic_versioning import _SubstitutionFolder
| null |
27,035 | poetry_dynamic_versioning | _SubstitutionPattern | null | from poetry_dynamic_versioning import _SubstitutionPattern
| null |
27,036 | poetry_dynamic_versioning | _apply_version | null | def _apply_version(
version: str, instance: Version, config: _Config, pyproject_path: Path, retain: bool = False
) -> None:
pyproject = tomlkit.parse(pyproject_path.read_bytes().decode("utf-8"))
pyproject["tool"]["poetry"]["version"] = version # type: ignore
# Disable the plugin in case we're building a source distribution,
# which won't have access to the VCS info at install time.
# We revert this later when we deactivate.
if not retain and not _state.cli_mode:
pyproject["tool"]["poetry-dynamic-versioning"]["enable"] = False # type: ignore
pyproject_path.write_bytes(tomlkit.dumps(pyproject).encode("utf-8"))
name = pyproject["tool"]["poetry"]["name"] # type: ignore
for file_name, file_info in config["files"].items():
full_file = pyproject_path.parent.joinpath(file_name)
if file_info["initial-content-jinja"] is not None:
if not full_file.parent.exists():
full_file.parent.mkdir()
initial = textwrap.dedent(
_render_jinja(
instance,
file_info["initial-content-jinja"],
config,
{"formatted_version": version},
)
)
full_file.write_bytes(initial.encode("utf-8"))
elif file_info["initial-content"] is not None:
if not full_file.parent.exists():
full_file.parent.mkdir()
initial = textwrap.dedent(file_info["initial-content"])
full_file.write_bytes(initial.encode("utf-8"))
_substitute_version(
name, # type: ignore
version,
_FolderConfig.from_config(config, pyproject_path.parent),
)
| (version: str, instance: dunamai.Version, config: poetry_dynamic_versioning._Config, pyproject_path: pathlib.Path, retain: bool = False) -> NoneType |
27,037 | poetry_dynamic_versioning | _debug | null | def _debug(message: str) -> None:
enabled = os.environ.get(_DEBUG_ENV) == "1"
if enabled:
print(message, file=sys.stderr)
| (message: str) -> NoneType |
27,038 | poetry_dynamic_versioning | _deep_merge_dicts | null | def _deep_merge_dicts(base: Mapping, addition: Mapping) -> Mapping:
result = dict(copy.deepcopy(base))
for key, value in addition.items():
if isinstance(value, dict) and key in base and isinstance(base[key], dict):
result[key] = _deep_merge_dicts(base[key], value)
else:
result[key] = value
return result
| (base: Mapping, addition: Mapping) -> Mapping |
27,039 | poetry_dynamic_versioning | _default_config | null | def _default_config() -> Mapping:
return {
"tool": {
"poetry-dynamic-versioning": {
"enable": False,
"vcs": "any",
"dirty": False,
"pattern": None,
"pattern-prefix": None,
"latest-tag": False,
"substitution": {
"files": ["*.py", "*/__init__.py", "*/__version__.py", "*/_version.py"],
"patterns": [
r"(^__version__\s*(?::.*?)?=\s*['\"])[^'\"]*(['\"])",
{
"value": r"(^__version_tuple__\s*(?::.*?)?=\s*\()[^)]*(\))",
"mode": "tuple",
},
],
"folders": [],
},
"files": {},
"style": None,
"metadata": None,
"format": None,
"format-jinja": None,
"format-jinja-imports": [],
"bump": False,
"tagged-metadata": False,
"full-commit": False,
"tag-branch": None,
"tag-dir": "tags",
"strict": False,
"fix-shallow-repository": False,
"ignore-untracked": False,
"from-file": {
"source": None,
"pattern": None,
},
}
}
}
| () -> Mapping |
27,040 | poetry_dynamic_versioning | _escape_branch | null | def _escape_branch(value: Optional[str]) -> Optional[str]:
if value is None:
return None
return re.sub(r"[^a-zA-Z0-9]", "", value)
| (value: Optional[str]) -> Optional[str] |
27,041 | poetry_dynamic_versioning | _find_higher_file | null | def _find_higher_file(*names: str, start: Optional[Path] = None) -> Optional[Path]:
# Note: We need to make sure we get a pathlib object. Many tox poetry
# helpers will pass us a string and not a pathlib object. See issue #40.
if start is None:
start = Path.cwd()
elif not isinstance(start, Path):
start = Path(start)
for level in [start, *start.parents]:
for name in names:
if (level / name).is_file():
return level / name
return None
| (*names: str, start: Optional[pathlib.Path] = None) -> Optional[pathlib.Path] |
27,042 | poetry_dynamic_versioning | _format_timestamp | null | def _format_timestamp(value: Optional[dt.datetime]) -> Optional[str]:
if value is None:
return None
return value.strftime("%Y%m%d%H%M%S")
| (value: Optional[datetime.datetime]) -> Optional[str] |
27,043 | poetry_dynamic_versioning | _get_and_apply_version | null | def _get_and_apply_version(
name: Optional[str] = None,
original: Optional[str] = None,
pyproject: Optional[Mapping] = None,
pyproject_path: Optional[Path] = None,
retain: bool = False,
force: bool = False,
# fmt: off
io: bool = True
# fmt: on
) -> Optional[str]:
if name is not None and name in _state.projects:
return name
if pyproject_path is None:
pyproject_path = _get_pyproject_path()
if pyproject_path is None:
raise RuntimeError("Unable to find pyproject.toml")
if pyproject is None:
pyproject = tomlkit.parse(pyproject_path.read_bytes().decode("utf-8"))
if name is None or original is None:
name = pyproject["tool"]["poetry"]["name"]
original = pyproject["tool"]["poetry"]["version"]
if name in _state.projects:
return name
config = _get_config(pyproject)
if not config["enable"] and not force:
return name if name in _state.projects else None
initial_dir = Path.cwd()
target_dir = pyproject_path.parent
os.chdir(str(target_dir))
try:
version, instance = _get_version(config, name)
finally:
os.chdir(str(initial_dir))
# Condition will always be true, but it makes Mypy happy.
if name is not None and original is not None:
_state.projects[name] = _ProjectState(pyproject_path, original, version)
if io:
_apply_version(version, instance, config, pyproject_path, retain)
return name
| (name: Optional[str] = None, original: Optional[str] = None, pyproject: Optional[Mapping] = None, pyproject_path: Optional[pathlib.Path] = None, retain: bool = False, force: bool = False, io: bool = True) -> Optional[str] |
27,044 | poetry_dynamic_versioning | _get_config | null | def _get_config(local: Mapping) -> _Config:
def initialize(data, key):
if isinstance(data, dict) and key not in data:
data[key] = None
if isinstance(local, tomlkit.TOMLDocument):
local = local.unwrap()
merged = _deep_merge_dicts(_default_config(), local)["tool"][
"poetry-dynamic-versioning"
] # type: _Config
# Add default values so we don't have to worry about missing keys
for x in merged["files"].values():
initialize(x, "initial-content")
initialize(x, "initial-content-jinja")
initialize(x, "persistent-substitution")
for x in merged["format-jinja-imports"]:
initialize(x, "item")
for x in merged["substitution"]["folders"]:
initialize(x, "files")
initialize(x, "patterns")
for x in merged["substitution"]["patterns"]:
initialize(x, "mode")
return merged
| (local: Mapping) -> poetry_dynamic_versioning._Config |
27,045 | poetry_dynamic_versioning | _get_config_from_path | null | def _get_config_from_path(start: Optional[Path] = None) -> Mapping:
pyproject_path = _get_pyproject_path(start)
if pyproject_path is None:
return _default_config()["tool"]["poetry-dynamic-versioning"]
pyproject = tomlkit.parse(pyproject_path.read_bytes().decode("utf-8"))
result = _get_config(pyproject)
return result
| (start: Optional[pathlib.Path] = None) -> Mapping |
27,046 | poetry_dynamic_versioning | _get_override_version | null | def _get_override_version(name: Optional[str], env: Optional[Mapping] = None) -> Optional[str]:
env = env if env is not None else os.environ
if name is not None:
raw_overrides = env.get(_OVERRIDE_ENV)
if raw_overrides is not None:
pairs = raw_overrides.split(",")
for pair in pairs:
if "=" not in pair:
continue
k, v = pair.split("=", 1)
if k.strip() == name:
return v.strip()
bypass = env.get(_BYPASS_ENV)
if bypass is not None:
return bypass
return None
| (name: Optional[str], env: Optional[Mapping] = None) -> Optional[str] |
27,047 | poetry_dynamic_versioning | _get_pyproject_path | null | def _get_pyproject_path(start: Optional[Path] = None) -> Optional[Path]:
return _find_higher_file("pyproject.toml", start=start)
| (start: Optional[pathlib.Path] = None) -> Optional[pathlib.Path] |
27,048 | poetry_dynamic_versioning | _get_pyproject_path_from_poetry | null | def _get_pyproject_path_from_poetry(pyproject) -> Path:
# poetry-core 1.6.0+:
recommended = getattr(pyproject, "path", None)
# poetry-core <1.6.0:
legacy = getattr(pyproject, "file", None)
if recommended:
return recommended
elif legacy:
return legacy
else:
raise RuntimeError("Unable to determine pyproject.toml path from Poetry instance")
| (pyproject) -> pathlib.Path |
27,049 | poetry_dynamic_versioning | _get_version | null | def _get_version(config: _Config, name: Optional[str] = None) -> Tuple[str, Version]:
override = _get_override_version(name)
if override is not None:
return (override, Version.parse(override))
override = _get_version_from_file(config)
if override is not None:
return (override, Version.parse(override))
vcs = Vcs(config["vcs"])
style = Style(config["style"]) if config["style"] is not None else None
pattern = (
config["pattern"] if config["pattern"] is not None else Pattern.Default
) # type: Union[str, Pattern]
if config["fix-shallow-repository"]:
# We start without strict so we can inspect the concerns.
version = _get_version_from_dunamai(vcs, pattern, config, strict=False)
retry = config["strict"]
if Concern.ShallowRepository in version.concerns and version.vcs == Vcs.Git:
retry = True
_run_cmd("git fetch --unshallow")
if retry:
version = _get_version_from_dunamai(vcs, pattern, config)
else:
version = _get_version_from_dunamai(vcs, pattern, config)
for concern in version.concerns:
print("Warning: {}".format(concern.message()), file=sys.stderr)
if config["format-jinja"]:
serialized = _render_jinja(version, config["format-jinja"], config)
if style is not None:
check_version(serialized, style)
else:
serialized = version.serialize(
metadata=config["metadata"],
dirty=config["dirty"],
format=config["format"],
style=style,
bump=config["bump"],
tagged_metadata=config["tagged-metadata"],
)
return (serialized, version)
| (config: poetry_dynamic_versioning._Config, name: Optional[str] = None) -> Tuple[str, dunamai.Version] |
27,050 | poetry_dynamic_versioning | _get_version_from_dunamai | null | def _get_version_from_dunamai(
vcs: Vcs, pattern: Union[str, Pattern], config: _Config, *, strict: Optional[bool] = None
) -> Version:
return Version.from_vcs(
vcs=vcs,
pattern=pattern,
latest_tag=config["latest-tag"],
tag_dir=config["tag-dir"],
tag_branch=config["tag-branch"],
full_commit=config["full-commit"],
strict=config["strict"] if strict is None else strict,
pattern_prefix=config["pattern-prefix"],
ignore_untracked=config["ignore-untracked"],
)
| (vcs: dunamai.Vcs, pattern: Union[str, dunamai.Pattern], config: poetry_dynamic_versioning._Config, *, strict: Optional[bool] = None) -> dunamai.Version |
27,051 | poetry_dynamic_versioning | _get_version_from_file | null | def _get_version_from_file(config: _Config) -> Optional[str]:
source = config["from-file"]["source"]
pattern = config["from-file"]["pattern"]
if source is None:
return None
pyproject_path = _get_pyproject_path()
if pyproject_path is None:
raise RuntimeError("Unable to find pyproject.toml")
content = pyproject_path.parent.joinpath(source).read_bytes().decode("utf-8").strip()
if pattern is None:
return content
result = re.search(pattern, content, re.MULTILINE)
if result is None:
raise ValueError("File '{}' did not contain a match for '{}'".format(source, pattern))
return result.group(1)
| (config: poetry_dynamic_versioning._Config) -> Optional[str] |
27,052 | poetry_dynamic_versioning | _render_jinja | null | def _render_jinja(
version: Version, template: str, config: _Config, extra: Optional[Mapping] = None
) -> str:
if extra is None:
extra = {}
if config["bump"] and version.distance > 0:
version = version.bump()
default_context = {
"base": version.base,
"version": version,
"stage": version.stage,
"revision": version.revision,
"distance": version.distance,
"commit": version.commit,
"dirty": version.dirty,
"branch": version.branch,
"branch_escaped": _escape_branch(version.branch),
"timestamp": _format_timestamp(version.timestamp),
"env": os.environ,
"bump_version": bump_version,
"tagged_metadata": version.tagged_metadata,
"serialize_pep440": serialize_pep440,
"serialize_pvp": serialize_pvp,
"serialize_semver": serialize_semver,
**extra,
}
custom_context = {} # type: dict
for entry in config["format-jinja-imports"]:
if "module" in entry:
module = import_module(entry["module"])
if entry["item"] is not None:
custom_context[entry["item"]] = getattr(module, entry["item"])
else:
custom_context[entry["module"]] = module
serialized = jinja2.Template(template).render(**default_context, **custom_context)
return serialized
| (version: dunamai.Version, template: str, config: poetry_dynamic_versioning._Config, extra: Optional[Mapping] = None) -> str |
27,053 | poetry_dynamic_versioning | _revert_version | null | def _revert_version(retain: bool = False) -> None:
for project, state in _state.projects.items():
pyproject = tomlkit.parse(state.path.read_bytes().decode("utf-8"))
if state.substitutions:
config = _get_config(pyproject)
persistent = []
for file, file_info in config["files"].items():
if file_info["persistent-substitution"]:
persistent.append(state.path.parent.joinpath(file))
for file, content in state.substitutions.items():
if file in persistent:
continue
file.write_bytes(content.encode("utf-8"))
# Reread pyproject.toml in case the substitutions affected it.
pyproject = tomlkit.parse(state.path.read_bytes().decode("utf-8"))
pyproject["tool"]["poetry"]["version"] = state.original_version # type: ignore
if not retain and not _state.cli_mode:
pyproject["tool"]["poetry-dynamic-versioning"]["enable"] = True # type: ignore
state.path.write_bytes(tomlkit.dumps(pyproject).encode("utf-8"))
_state.projects.clear()
| (retain: bool = False) -> NoneType |
27,054 | poetry_dynamic_versioning | _run_cmd | null | def _run_cmd(command: str, codes: Sequence[int] = (0,)) -> Tuple[int, str]:
result = subprocess.run(
shlex.split(command),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
output = result.stdout.decode().strip()
if codes and result.returncode not in codes:
raise RuntimeError(
"The command '{}' returned code {}. Output:\n{}".format(
command, result.returncode, output
)
)
return (result.returncode, output)
| (command: str, codes: Sequence[int] = (0,)) -> Tuple[int, str] |
27,055 | poetry_dynamic_versioning | _substitute_version | null | def _substitute_version(name: str, version: str, folders: Sequence[_FolderConfig]) -> None:
if _state.projects[name].substitutions:
# Already ran; don't need to repeat.
return
files = {} # type: MutableMapping[Path, _FolderConfig]
for folder in folders:
for file_glob in folder.files:
i = 0
# call str() since file_glob here could be a non-internable string
for match in folder.path.glob(str(file_glob)):
i += 1
resolved = match.resolve()
if resolved in files:
continue
files[resolved] = folder
if i == 0:
_debug(
"No files found for substitution with glob '{}' in folder '{}'".format(
file_glob, folder.path
)
)
for file, config in files.items():
original_content = file.read_bytes().decode("utf-8")
new_content = _substitute_version_in_text(version, original_content, config.patterns)
if original_content != new_content:
_state.projects[name].substitutions[file] = original_content
file.write_bytes(new_content.encode("utf-8"))
else:
_debug("No changes made during substitution in file '{}'".format(file))
| (name: str, version: str, folders: Sequence[poetry_dynamic_versioning._FolderConfig]) -> NoneType |
27,056 | poetry_dynamic_versioning | _substitute_version_in_text | null | def _substitute_version_in_text(version: str, content: str, patterns: Sequence[_SubPattern]) -> str:
new_content = content
for pattern in patterns:
if pattern.mode == "str":
insert = version
elif pattern.mode == "tuple":
parts = []
split = version.split("+", 1)
split = [*re.split(r"[-.]", split[0]), *split[1:]]
for part in split:
if part == "":
continue
try:
parts.append(str(int(part)))
except ValueError:
parts.append('"{}"'.format(part))
insert = ", ".join(parts)
if len(parts) == 1:
insert += ","
else:
raise ValueError("Invalid substitution mode: {}".format(pattern.mode))
new_content = re.sub(
pattern.value, r"\g<1>{}\g<2>".format(insert), new_content, flags=re.MULTILINE
)
return new_content
| (version: str, content: str, patterns: Sequence[poetry_dynamic_versioning._SubPattern]) -> str |
27,057 | poetry_dynamic_versioning | _validate_config | null | def _validate_config(config: Optional[Mapping] = None) -> Sequence[str]:
if config is None:
pyproject_path = _get_pyproject_path()
if pyproject_path is None:
raise RuntimeError("Unable to find pyproject.toml")
config = tomlkit.parse(pyproject_path.read_bytes().decode("utf-8"))
return _validate_config_section(
config.get("tool", {}).get("poetry-dynamic-versioning", {}),
_default_config()["tool"]["poetry-dynamic-versioning"],
["tool", "poetry-dynamic-versioning"],
)
| (config: Optional[Mapping] = None) -> Sequence[str] |
27,058 | poetry_dynamic_versioning | _validate_config_section | null | def _validate_config_section(
config: Mapping, default: Mapping, path: Sequence[str]
) -> Sequence[str]:
if not default:
return []
errors = []
for (key, value) in config.items():
if key not in default:
escaped_key = key if "." not in key else '"{}"'.format(key)
errors.append("Unknown key: " + ".".join([*path, escaped_key]))
elif isinstance(value, dict) and isinstance(config.get(key), dict):
errors.extend(_validate_config_section(config[key], default[key], [*path, key]))
return errors
| (config: Mapping, default: Mapping, path: Sequence[str]) -> Sequence[str] |
27,059 | dunamai | bump_version |
Increment one of the numerical positions of a version.
:param base: Version core, such as 0.1.0.
Do not include pre-release identifiers.
:param index: Numerical position to increment.
This follows Python indexing rules, so positive numbers start from
the left side and count up from 0, while negative numbers start from
the right side and count down from -1.
:param increment: By how much the `index` needs to increment.
:returns: Bumped version.
| def bump_version(base: str, index: int = -1, increment: int = 1) -> str:
"""
Increment one of the numerical positions of a version.
:param base: Version core, such as 0.1.0.
Do not include pre-release identifiers.
:param index: Numerical position to increment.
This follows Python indexing rules, so positive numbers start from
the left side and count up from 0, while negative numbers start from
the right side and count down from -1.
:param increment: By how much the `index` needs to increment.
:returns: Bumped version.
"""
bases = [int(x) for x in base.split(".")]
bases[index] += increment
limit = 0 if index < 0 else len(bases)
i = index + 1
while i < limit:
bases[i] = 0
i += 1
return ".".join(str(x) for x in bases)
| (base: str, index: int = -1, increment: int = 1) -> str |
27,060 | dunamai | check_version |
Check if a version is valid for a style.
:param version: Version to check.
:param style: Style against which to check.
:raises ValueError: If the version is invalid.
| def check_version(version: str, style: Style = Style.Pep440) -> None:
"""
Check if a version is valid for a style.
:param version: Version to check.
:param style: Style against which to check.
:raises ValueError: If the version is invalid.
"""
name, pattern = {
Style.Pep440: ("PEP 440", _VALID_PEP440),
Style.SemVer: ("Semantic Versioning", _VALID_SEMVER),
Style.Pvp: ("PVP", _VALID_PVP),
}[style]
failure_message = "Version '{}' does not conform to the {} style".format(version, name)
if not re.search(pattern, version):
raise ValueError(failure_message)
if style == Style.SemVer:
parts = re.split(r"[.-]", version.split("+", 1)[0])
if any(re.search(r"^0[0-9]+$", x) for x in parts):
raise ValueError(failure_message)
| (version: str, style: dunamai.Style = <Style.Pep440: 'pep440'>) -> NoneType |
27,067 | dunamai | serialize_pep440 |
Serialize a version based on PEP 440.
Use this instead of `Version.serialize()` if you want more control
over how the version is mapped.
:param base: Release segment, such as 0.1.0.
:param stage: Pre-release stage ("a", "b", or "rc").
:param revision: Pre-release revision (e.g., 1 as in "rc1").
This is ignored when `stage` is None.
:param post: Post-release number.
:param dev: Developmental release number.
:param epoch: Epoch number.
:param metadata: Any local version label segments.
:returns: Serialized version.
| def serialize_pep440(
base: str,
stage: Optional[str] = None,
revision: Optional[int] = None,
post: Optional[int] = None,
dev: Optional[int] = None,
epoch: Optional[int] = None,
metadata: Optional[Sequence[Union[str, int]]] = None,
) -> str:
"""
Serialize a version based on PEP 440.
Use this instead of `Version.serialize()` if you want more control
over how the version is mapped.
:param base: Release segment, such as 0.1.0.
:param stage: Pre-release stage ("a", "b", or "rc").
:param revision: Pre-release revision (e.g., 1 as in "rc1").
This is ignored when `stage` is None.
:param post: Post-release number.
:param dev: Developmental release number.
:param epoch: Epoch number.
:param metadata: Any local version label segments.
:returns: Serialized version.
"""
out = [] # type: list
if epoch is not None:
out.extend([epoch, "!"])
out.append(base)
if stage is not None:
alternative_stages = {"alpha": "a", "beta": "b", "c": "rc", "pre": "rc", "preview": "rc"}
out.append(alternative_stages.get(stage.lower(), stage.lower()))
if revision is None:
# PEP 440 does not allow omitting the revision, so assume 0.
out.append(0)
else:
out.append(revision)
if post is not None:
out.extend([".post", post])
if dev is not None:
out.extend([".dev", dev])
if metadata is not None and len(metadata) > 0:
out.extend(["+", ".".join(map(str, metadata))])
serialized = "".join(map(str, out))
check_version(serialized, Style.Pep440)
return serialized
| (base: str, stage: Optional[str] = None, revision: Optional[int] = None, post: Optional[int] = None, dev: Optional[int] = None, epoch: Optional[int] = None, metadata: Optional[Sequence[Union[str, int]]] = None) -> str |
27,068 | dunamai | serialize_pvp |
Serialize a version based on the Haskell Package Versioning Policy.
Use this instead of `Version.serialize()` if you want more control
over how the version is mapped.
:param base: Version core, such as 0.1.0.
:param metadata: Version tag metadata.
:returns: Serialized version.
| def serialize_pvp(base: str, metadata: Optional[Sequence[Union[str, int]]] = None) -> str:
"""
Serialize a version based on the Haskell Package Versioning Policy.
Use this instead of `Version.serialize()` if you want more control
over how the version is mapped.
:param base: Version core, such as 0.1.0.
:param metadata: Version tag metadata.
:returns: Serialized version.
"""
out = [base]
if metadata is not None and len(metadata) > 0:
out.extend(["-", "-".join(map(str, metadata))])
serialized = "".join(map(str, out))
check_version(serialized, Style.Pvp)
return serialized
| (base: str, metadata: Optional[Sequence[Union[str, int]]] = None) -> str |
27,069 | dunamai | serialize_semver |
Serialize a version based on Semantic Versioning.
Use this instead of `Version.serialize()` if you want more control
over how the version is mapped.
:param base: Version core, such as 0.1.0.
:param pre: Pre-release identifiers.
:param metadata: Build metadata identifiers.
:returns: Serialized version.
| def serialize_semver(
base: str,
pre: Optional[Sequence[Union[str, int]]] = None,
metadata: Optional[Sequence[Union[str, int]]] = None,
) -> str:
"""
Serialize a version based on Semantic Versioning.
Use this instead of `Version.serialize()` if you want more control
over how the version is mapped.
:param base: Version core, such as 0.1.0.
:param pre: Pre-release identifiers.
:param metadata: Build metadata identifiers.
:returns: Serialized version.
"""
out = [base]
if pre is not None and len(pre) > 0:
out.extend(["-", ".".join(map(str, pre))])
if metadata is not None and len(metadata) > 0:
out.extend(["+", ".".join(map(str, metadata))])
serialized = "".join(str(x) for x in out)
check_version(serialized, Style.SemVer)
return serialized
| (base: str, pre: Optional[Sequence[Union[str, int]]] = None, metadata: Optional[Sequence[Union[str, int]]] = None) -> str |
27,075 | sqlobject.sqlbuilder | AND | null | def AND(*ops):
if not ops:
return None
op1 = ops[0]
ops = ops[1:]
if ops:
return SQLOp("AND", op1, AND(*ops))
else:
return op1
| (*ops) |
27,076 | sqlobject.col | BLOBCol | null | class BLOBCol(StringCol):
baseClass = SOBLOBCol
| (name=None, **kw) |
27,077 | sqlobject.col | __init__ | null | def __init__(self, name=None, **kw):
super(Col, self).__init__()
self.__dict__['_name'] = name
self.__dict__['_kw'] = kw
self.__dict__['creationOrder'] = next(creationOrder)
self.__dict__['_extra_vars'] = {}
| (self, name=None, **kw) |
27,078 | sqlobject.col | __repr__ | null | def __repr__(self):
return '<%s %s %s>' % (
self.__class__.__name__, hex(abs(id(self)))[2:],
self._name or '(unnamed)')
| (self) |
27,079 | sqlobject.col | __setattr__ | null | def __setattr__(self, var, value):
if var == 'name':
super(Col, self).__setattr__(var, value)
return
self._extra_vars[var] = value
| (self, var, value) |
27,080 | sqlobject.col | _get_name | null | def _get_name(self):
return self._name
| (self) |
27,081 | sqlobject.col | _set_name | null | def _set_name(self, value):
assert self._name is None or self._name == value, (
"You cannot change a name after it has already been set "
"(from %s to %s)" % (self.name, value))
self.__dict__['_name'] = value
| (self, value) |
27,082 | sqlobject.col | withClass | null | def withClass(self, soClass):
return self.baseClass(soClass=soClass, name=self._name,
creationOrder=self.creationOrder,
columnDef=self,
extra_vars=self._extra_vars,
**self._kw)
| (self, soClass) |
27,083 | sqlobject.col | BigIntCol | null | class BigIntCol(Col):
baseClass = SOBigIntCol
| (name=None, **kw) |
27,090 | sqlobject.col | BoolCol | null | class BoolCol(Col):
baseClass = SOBoolCol
| (name=None, **kw) |
27,097 | sqlobject.sqlbuilder | CONTAINSSTRING | null | def CONTAINSSTRING(expr, pattern):
return LIKE(expr, '%' + _LikeQuoted(pattern) + '%', escape='\\')
| (expr, pattern) |
27,098 | sqlobject.col | Col | null | class Col(object):
baseClass = SOCol
def __init__(self, name=None, **kw):
super(Col, self).__init__()
self.__dict__['_name'] = name
self.__dict__['_kw'] = kw
self.__dict__['creationOrder'] = next(creationOrder)
self.__dict__['_extra_vars'] = {}
def _set_name(self, value):
assert self._name is None or self._name == value, (
"You cannot change a name after it has already been set "
"(from %s to %s)" % (self.name, value))
self.__dict__['_name'] = value
def _get_name(self):
return self._name
name = property(_get_name, _set_name)
def withClass(self, soClass):
return self.baseClass(soClass=soClass, name=self._name,
creationOrder=self.creationOrder,
columnDef=self,
extra_vars=self._extra_vars,
**self._kw)
def __setattr__(self, var, value):
if var == 'name':
super(Col, self).__setattr__(var, value)
return
self._extra_vars[var] = value
def __repr__(self):
return '<%s %s %s>' % (
self.__class__.__name__, hex(abs(id(self)))[2:],
self._name or '(unnamed)')
| (name=None, **kw) |
27,105 | sqlobject.col | CurrencyCol | null | class CurrencyCol(DecimalCol):
baseClass = SOCurrencyCol
| (name=None, **kw) |
27,112 | sqlobject.sqlbuilder | DESC | null | class DESC(SQLExpression):
def __init__(self, expr):
self.expr = expr
def __sqlrepr__(self, db):
if isinstance(self.expr, DESC):
return sqlrepr(self.expr.expr, db)
return '%s DESC' % sqlrepr(self.expr, db)
| (expr) |
27,113 | sqlobject.sqlbuilder | __abs__ | null | def __abs__(self):
return SQLConstant("ABS")(self)
| (self) |
27,114 | sqlobject.sqlbuilder | __add__ | null | def __add__(self, other):
return SQLOp("+", self, other)
| (self, other) |
27,115 | sqlobject.sqlbuilder | __and__ | null | def __and__(self, other):
return SQLOp("AND", self, other)
| (self, other) |
27,116 | sqlobject.sqlbuilder | __call__ | null | def __call__(self, *args):
return SQLCall(self, args)
| (self, *args) |
27,117 | sqlobject.sqlbuilder | __cmp__ | null | def __cmp__(self, other):
raise VersionError("Python 2.1+ required")
| (self, other) |
27,118 | sqlobject.sqlbuilder | __div__ | null | def __div__(self, other):
return SQLOp("/", self, other)
| (self, other) |
27,119 | sqlobject.sqlbuilder | __eq__ | null | def __eq__(self, other):
if other is None:
return ISNULL(self)
else:
return SQLOp("=", self, other)
| (self, other) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.