Ejemplo n.º 1
0
    def _parse_version(self, value):
        if isinstance(value, semver.VersionInfo):
            version_info = value
        else:
            version_info = semver.parse_version_info(value)

        version = semver.format_version(*tuple(version_info))
        return version, version_info
Ejemplo n.º 2
0
    def __str__(self):
        """
        Return version as string compatible with semver

        :return:str
        """

        return semver.format_version(self.major, self.minor, self.patch, self.prerelease or None, self.build or None)
Ejemplo n.º 3
0
 def __str__(self):
     return semver.format_version(*self.version)
import pyspatialite.dbapi2 as db
import logging
from logging.config import dictConfig
import pandas as pd
import os
import semver
import datetime

version = semver.format_version(0, 1, 0, 'pre.6', 'build.1')


def get_or_create(session, model, **kwargs):
    '''
  Creates an object or returns the object if exists
  credit to Kevin @ StackOverflow
  from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
  '''
    instance = session.query(model).filter_by(**kwargs).first()
    if not instance:
        instance = model(**kwargs)
        session.add(instance)

    return instance


########################################################################################################################
# Hilfsklasse fuer Beobachtungen
class beobachtung(object):
    def __init__(self, cur):
        self.cur = cur
        # do something
Ejemplo n.º 5
0
        default=DEFAULT_WINDOWS_BASETAG,
        help=
        'Windows Server Core base image tag to use for Windows containers (default is '
        + DEFAULT_WINDOWS_BASETAG + ')')

    # If no command-line arguments were supplied, display the help message and exit
    if len(sys.argv) < 2:
        parser.print_help()
        sys.exit(0)

    # Parse the supplied command-line arguments and validate the specified version string
    args = parser.parse_args()
    try:
        ue4Version = semver.parse(args.release)
        ue4VersionStr = semver.format_version(ue4Version['major'],
                                              ue4Version['minor'],
                                              ue4Version['patch'])
        if ue4Version['major'] != 4 or ue4Version['prerelease'] != None:
            raise Exception()
    except:
        logger.error(
            'Error: invalid UE4 release number "{}", full semver format required (e.g. "4.19.0")'
            .format(args.release))
        sys.exit(1)

    # Determine if we are building Windows or Linux containers
    containerPlatform = 'windows' if platform.system(
    ) == 'Windows' and args.linux == False else 'linux'
    platformArgs = []
    if containerPlatform == 'windows':
Ejemplo n.º 6
0
 def _sort_images_by_name(self, clist):
     # We have a flag day where we start putting underscores into
     #  image tags.  Those always go at the top.
     # We begin by splitting the list of candidate images into new
     #  and old style images.
     oldstyle = []
     newstyle = []
     for cimg in clist:
         name = cimg["name"]
         if name.find("_") == -1:
             oldstyle.append(cimg)
         else:
             # "latest_X" is not a semantic version tag.
             if name.startswith("latest_"):
                 oldstyle.append(cimg)
             else:
                 newstyle.append(cimg)
     # Old-style sort is simple string comparison.
     oldstyle.sort(key=lambda x: x["name"], reverse=True)
     # New style, we refer to semver module for comparison.
     #  (also works fine for date sorts)
     seml = []
     for cimg in newstyle:
         name = cimg["name"]
         components = name.split("_")
         # Get this.  It's not represented as r_17, no, it's r17.
         # So if we find that the end of the first group is digits,
         #  we split those off with a regular expression, and insert
         #  them into the list where the major number should be.
         ctype = components[0]
         ctm = re.search(r'\d+$', ctype)
         if ctm is not None:
             mj = int(ctm.group())
             components.insert(1, mj)
         # First character is image type, not semantically significant
         #  for versioning.
         if components[0] == "exp":
             _ = components.pop(0)
         major = 0
         if len(components) > 1:
             major = int(components[1])
         minor = 0
         if len(components) > 2:
             minor = int(components[2])
         patch = 0
         prerelease = None
         if len(components) > 3:
             try:
                 patch = int(components[3])
             except ValueError:
                 # Not an integer, so this is probably an experimental/
                 #  not-for-release version, so leave it at patch level 0
                 #  and treat the string as a prerelease version
                 prerelease = components[3]
         if len(components) > 4:
             prerelease = components[4]
         build = None
         if len(components) > 5:
             build = '_'.join(components[5:])
         cimg["semver"] = semver.format_version(major, minor, patch,
                                                prerelease, build)
         seml.append(cimg["semver"])
     seml.sort(key=functools.cmp_to_key(semver.compare), reverse=True)
     sorted_newstyle = []
     for skey in seml:
         for ni in newstyle:
             if ni["semver"] == skey:
                 sorted_newstyle.append(ni)
                 break
     # Return all new style names first.
     return sorted_newstyle.extend(oldstyle)
from troposphere import Template, Ref, Tags, Join, Parameter, Output
from troposphere.ec2 import VPC as ec2VPC
from troposphere.ec2 import Subnet, NetworkAcl, NetworkAclEntry,\
     InternetGateway, VPCGatewayAttachment, RouteTable, Route,\
     SubnetRouteTableAssociation, SubnetNetworkAclAssociation
import semver
import argparse
import boto3


VERSION_MAJOR = 0
VERSION_MINOR = 0
VERSION_PATCH = 1
VERSION_PRE = None
VERSION_BUILD = "build.1"
VERSION = semver.format_version(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_PRE, VERSION_BUILD)

from default import *
CF_TEMPLATE_NAME = "vpc.template"

class VPC:
    t = Template()

    def buildTemplate(self):
        self.t.add_metadata({
            "Comments": "This will build a standard VPC with public and private subnets",
            "Version": VERSION,
            "Author": "Derek Belrose <*****@*****.**>",
            })

        ### Back references
Ejemplo n.º 8
0
        path
        field
        format
      }
      internal
      disable {
        integrations
      }
    }
  }
}
""" % (indent(OPENSHIFT_RESOURCE, 8 * ' '), indent(OPENSHIFT_RESOURCE,
                                                   6 * ' '))

QONTRACT_INTEGRATION = 'openshift_resources_base'
QONTRACT_INTEGRATION_VERSION = semver.format_version(1, 9, 2)
QONTRACT_BASE64_SUFFIX = '_qb64'

_log_lock = Lock()


class FetchVaultSecretError(Exception):
    def __init__(self, msg):
        super(FetchVaultSecretError,
              self).__init__("error fetching vault secret: " + str(msg))


class FetchRouteError(Exception):
    def __init__(self, msg):
        super(FetchRouteError,
              self).__init__("error fetching route: " + str(msg))
Ejemplo n.º 9
0
def test_should_correctly_format_version():
    assert format_version(3, 4, 5) == '3.4.5'
    assert format_version(3, 4, 5, 'rc.1') == '3.4.5-rc.1'
    assert format_version(3, 4, 5, prerelease='rc.1') == '3.4.5-rc.1'
    assert format_version(3, 4, 5, build='build.4') == '3.4.5+build.4'
    assert format_version(3, 4, 5, 'rc.1', 'build.4') == '3.4.5-rc.1+build.4'
Ejemplo n.º 10
0
def write_version_py(filename="wradlib/version.py"):
    cnt = """
# THIS FILE IS GENERATED FROM WRADLIB SETUP.PY
short_version = '%(short_version)s'
version = '%(version)s'
full_version = '%(full_version)s'
git_revision = '%(git_revision)s'
release = %(isrelease)s
"""
    # Adding the git rev number needs to be done inside write_version_py(),
    # otherwise the import of wradlib.version messes up the build under
    # Python 3.

    SHORT_VERSION = VERSION
    FULL_VERSION = VERSION
    GIT_REVISION = VERSION + "-unknown"
    GIT_HASH = "unknown"
    ISRELEASED = "'unknown'"

    if os.path.exists(".git"):
        GIT_REVISION, GIT_HASH = git_version()
    elif os.path.exists("wradlib/version.py"):
        # must be a source distribution, use existing version file
        try:
            from wradlib.version import full_version as GIT_REVISION
            from wradlib.version import git_revision as GIT_HASH
        except ImportError:
            raise ImportError("Unable to import git_revision. Try removing "
                              "wradlib/version.py and the build directory "
                              "before building.")
    else:
        warnings.warn(
            "wradlib source does not contain detailed version info "
            "via git or version.py, exact version can't be "
            "retrieved.",
            UserWarning,
        )

    # parse version using semver
    ver = semver.VersionInfo.parse(GIT_REVISION)

    # get commit count, dev0 means tagged commit -> release
    ISRELEASED = ver.prerelease == "dev0"
    if not ISRELEASED:
        SHORT_VERSION = semver.format_version(ver.major, ver.minor, ver.patch,
                                              ver.prerelease)
        FULL_VERSION = GIT_REVISION

    a = open(filename, "w")
    try:
        a.write(
            cnt % {
                "short_version": SHORT_VERSION,
                "version": FULL_VERSION,
                "full_version": GIT_REVISION,
                "git_revision": GIT_HASH,
                "isrelease": str(ISRELEASED),
            })
    finally:
        a.close()

    return SHORT_VERSION
import sys
import semver

import reconcile.queries as queries

from utils.saasherder import SaasHerder

QONTRACT_INTEGRATION = 'saas-file-validator'
QONTRACT_INTEGRATION_VERSION = semver.format_version(0, 1, 0)


def run(dry_run):
    saas_files = queries.get_saas_files()
    settings = queries.get_app_interface_settings()
    saasherder = SaasHerder(saas_files,
                            thread_pool_size=1,
                            gitlab=None,
                            integration=QONTRACT_INTEGRATION,
                            integration_version=QONTRACT_INTEGRATION_VERSION,
                            settings=settings)
    if not saasherder.valid:
        sys.exit(1)
Ejemplo n.º 12
0
from __future__ import absolute_import

import sys
import os
import semver


__all__ = ['APPS_DIR','TOP_DIR']


VERSION = (1, 1, 2)
__version__ = semver.format_version(*VERSION)


# assume we are ./apps/mainsite/__init__.py
APPS_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
if APPS_DIR not in sys.path:
    sys.path.insert(0, APPS_DIR)

# Path to the whole project (one level up from apps)
TOP_DIR = os.path.dirname(APPS_DIR)

# import the celery app so INSTALLED_APPS gets autodiscovered
from .celery import app as celery_app
Ejemplo n.º 13
0
def test_should_correctly_format_version():
    assert format_version(3, 4, 5) == "3.4.5"
    assert format_version(3, 4, 5, "rc.1") == "3.4.5-rc.1"
    assert format_version(3, 4, 5, prerelease="rc.1") == "3.4.5-rc.1"
    assert format_version(3, 4, 5, build="build.4") == "3.4.5+build.4"
    assert format_version(3, 4, 5, "rc.1", "build.4") == "3.4.5-rc.1+build.4"
Ejemplo n.º 14
0
def get_version(version=None):
    if version is None:
        from .version import VERSION
        version = VERSION
    return semver.format_version(*version)
Ejemplo n.º 15
0
from __future__ import absolute_import

import sys
import os
import semver

__all__ = ['APPS_DIR', 'TOP_DIR']

VERSION = (1, 1, 8)
__version__ = semver.format_version(*VERSION)

# assume we are ./apps/mainsite/__init__.py
APPS_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
if APPS_DIR not in sys.path:
    sys.path.insert(0, APPS_DIR)

# Path to the whole project (one level up from apps)
TOP_DIR = os.path.dirname(APPS_DIR)

# import the celery app so INSTALLED_APPS gets autodiscovered
from .celery import app as celery_app
Ejemplo n.º 16
0
def create_version_tag(command_context: CommandContext,
                       operation: Callable[[VersionConfig, Optional[str], Optional[int]], Result]) -> Result:
    result = Result()
    context: Context = command_context.context

    release_branches = command_context.context.get_release_branches(reverse=True)

    # TODO configuration
    allow_merge_base_tags = True  # context.config.allow_shared_release_branch_base

    selected_branch = command_context.selected_ref
    selected_branch_base_version = context.release_branch_matcher.format(command_context.selected_ref.name)
    if selected_branch_base_version is not None:
        selected_branch_base_version_info = semver.parse_version_info(selected_branch_base_version)
    else:
        selected_branch_base_version_info = None

    if selected_branch_base_version is None:
        result.fail(os.EX_USAGE,
                    _("Cannot bump version."),
                    _("{branch} is not a release branch.")
                    .format(branch=repr(command_context.selected_ref.name)))

    latest_version_tag = None
    preceding_version_tag = None
    preceding_branch_version_tag = None
    version_tags_on_same_commit = list()
    subsequent_version_tags = list()
    enclosing_versions = set()

    # abort scan, when a preceding commit for each tag type has been processed.
    # enclosing_versions now holds enough information for operation validation,
    # assuming the branch has not gone haywire in earlier commits
    # TODO evaluate upper and lower bound version for efficiency
    abort_version_scan = False

    on_selected_branch = False

    before_commit = False
    before_selected_branch = False

    for release_branch in release_branches:
        # fork_point = repotools.git_merge_base(context.repo, context.config.release_branch_base,
        #                                       command_context.selected_commit)
        # if fork_point is None:
        #     result.fail(os.EX_USAGE,
        #                 _("Cannot bump version."),
        #                 _("{branch} has no fork point on {base_branch}.")
        #                 .format(branch=repr(command_context.selected_ref.name),
        #                         base_branch=repr(context.config.release_branch_base)))
        fork_point = None

        branch_base_version = context.release_branch_matcher.format(release_branch.name)
        if branch_base_version is not None:
            branch_base_version_info = semver.parse_version_info(branch_base_version)
        else:
            branch_base_version_info = None

        on_selected_branch = not before_selected_branch and release_branch.name == selected_branch.name

        for history_commit in repotools.git_list_commits(
                context=context.repo,
                start=fork_point,
                end=release_branch.obj_name,
                options=const.BRANCH_COMMIT_SCAN_OPTIONS):
            at_commit = not before_commit and on_selected_branch and history_commit.obj_name == command_context.selected_commit

            version_tag_refs = None

            assert not at_commit if before_commit else not before_commit

            for tag_ref in repotools.git_get_tags_by_referred_object(context.repo, history_commit.obj_name):
                version_info = context.version_tag_matcher.to_version_info(tag_ref.name)
                if version_info is not None:
                    tag_matches = version_info.major == branch_base_version_info.major \
                                  and version_info.minor == branch_base_version_info.minor

                    if tag_matches:
                        if version_tag_refs is None:
                            version_tag_refs = list()
                        version_tag_refs.append(tag_ref)
                    else:
                        if fork_point is not None:
                            # fail stray tags on exclusive branch commits
                            result.fail(os.EX_DATAERR,
                                        _("Cannot bump version."),
                                        _("Found stray version tag: {version}.")
                                        .format(version=repr(version.format_version_info(version_info)))
                                        )
                        else:
                            # when no merge base is used, abort at the first mismatching tag
                            break

            if not abort_version_scan and version_tag_refs is not None and len(version_tag_refs):
                version_tag_refs.sort(
                    reverse=True,
                    key=utils.cmp_to_key(
                        lambda tag_ref_a, tag_ref_b: semver.compare(
                            context.version_tag_matcher.format(tag_ref_a.name),
                            context.version_tag_matcher.format(tag_ref_b.name)
                        )
                    )
                )
                if latest_version_tag is None:
                    latest_version_tag = version_tag_refs[0]
                if at_commit:
                    version_tags_on_same_commit.extend(version_tag_refs)
                if at_commit or before_commit:
                    if preceding_version_tag is None:
                        preceding_version_tag = version_tag_refs[0]
                    if on_selected_branch and preceding_branch_version_tag is None:
                        preceding_branch_version_tag = version_tag_refs[0]
                else:
                    subsequent_version_tags.extend(version_tag_refs)

                for tag_ref in version_tag_refs:
                    enclosing_versions.add(context.version_tag_matcher.format(tag_ref.name))

                if before_commit:
                    abort_version_scan = True

            if at_commit:
                before_commit = True

        if on_selected_branch:
            before_commit = True
            before_selected_branch = True

        if abort_version_scan:
            break

    if context.config.sequential_versioning and preceding_version_tag is not None:
        match = context.version_tag_matcher.fullmatch(preceding_version_tag.name)
        preceding_sequential_version = match.group(context.version_tag_matcher.group_unique_code)
    else:
        preceding_sequential_version = None
    if preceding_sequential_version is not None:
        preceding_sequential_version = int(preceding_sequential_version)

    if context.verbose:
        cli.print("Tags on selected commit:\n"
                  + '\n'.join(' - ' + repr(tag_ref.name) for tag_ref in version_tags_on_same_commit))

        cli.print("Tags in subsequent history:\n"
                  + '\n'.join(' - ' + repr(tag_ref.name) for tag_ref in subsequent_version_tags))

    if preceding_branch_version_tag is not None:
        latest_branch_version = context.version_tag_matcher.format(preceding_branch_version_tag.name)
    else:
        latest_branch_version = None

    global_sequence_number = get_global_sequence_number(context)
    if latest_branch_version is not None:
        version_result = operation(context.config.version_config, latest_branch_version, global_sequence_number)
        result.add_subresult(version_result)

        new_version = version_result.value
        if result.has_errors():
            return result
    else:
        template_version_info = semver.parse_version_info(context.config.version_config.initial_version)
        new_version = semver.format_version(
            major=selected_branch_base_version_info.major,
            minor=selected_branch_base_version_info.minor,

            patch=template_version_info.patch,
            prerelease=str(global_sequence_number + 1) if context.config.tie_sequential_version_to_semantic_version and global_sequence_number is not None else template_version_info.prerelease,
            build=template_version_info.build,
        )

    new_version_info = semver.parse_version_info(new_version)
    new_sequential_version = scheme_procedures.get_sequence_number(context.config.version_config, new_version_info)

    if new_version_info.major != selected_branch_base_version_info.major or new_version_info.minor != selected_branch_base_version_info.minor:
        result.fail(os.EX_USAGE,
                    _("Tag creation failed."),
                    _("The major.minor part of the new version {new_version}"
                      " does not match the branch version {branch_version}.")
                    .format(new_version=repr(new_version),
                            branch_version=repr(
                                "%d.%d" % (selected_branch_base_version_info.major, selected_branch_base_version_info.minor)))
                    )

    try:
        config_in_selected_commit = read_config_in_commit(context.repo, command_context.selected_commit)
    except FileNotFoundError:
        config_in_selected_commit = dict()

    try:
        properties_in_selected_commit = read_properties_in_commit(context,
                                                                  context.repo,
                                                                  config_in_selected_commit,
                                                                  command_context.selected_commit)
    except FileNotFoundError:
        properties_in_selected_commit = dict()

    if context.verbose:
        print("properties in selected commit:")
        print(json.dumps(obj=properties_in_selected_commit, indent=2))

    valid_tag = False

    # validate the commit
    if len(version_tags_on_same_commit):
        if config_in_selected_commit is None:
            result.fail(os.EX_DATAERR,
                        _("Tag creation failed."),
                        _("The selected commit does not contain a configuration file.")
                        )

        version_property_name = config_in_selected_commit.get(const.CONFIG_VERSION_PROPERTY)
        if version_property_name is not None \
                and properties_in_selected_commit.get(version_property_name) is None:
            result.warn(_("Missing version info."),
                        _("The selected commit does not contain a version in property '{property_name}'.")
                        .format(property_name=version_property_name)
                        )

    if len(version_tags_on_same_commit):
        if context.config.allow_qualifier_increments_within_commit:
            preceding_commit_version = context.version_tag_matcher.format(
                version_tags_on_same_commit[0].name)
            prerelease_keywords_list = [context.config.version_config.qualifiers, 1]

            preceding_commit_version_ = version.parse_version(preceding_commit_version)
            new_commit_version_ = version.parse_version(new_version)
            version_delta = version.determine_version_delta(preceding_commit_version_,
                                                            new_commit_version_,
                                                            prerelease_keywords_list
                                                            )

            version_increment_eval_result = version.evaluate_version_increment(preceding_commit_version_,
                                                                               new_commit_version_,
                                                                               context.config.strict_mode,
                                                                               prerelease_keywords_list)
            result.add_subresult(version_increment_eval_result)
            if result.has_errors():
                return result

            if not version_delta.prerelease_field_only(0, False):
                result.fail(os.EX_USAGE,
                            _("Tag creation failed."),
                            _("The selected commit already has version tags.\n"
                              "Operations on such a commit are limited to pre-release type increments.")
                            )

            valid_tag = True
        else:
            result.fail(os.EX_USAGE,
                        _("Tag creation failed."),
                        _("There are version tags pointing to the selected commit {commit}.\n"
                          "Consider reusing these versions or bumping them to stable."
                          "{listing}")
                        .format(commit=command_context.selected_commit,
                                listing='\n'.join(
                                    ' - ' + repr(tag_ref.name) for tag_ref in subsequent_version_tags))
                        )

    if not valid_tag:
        if len(subsequent_version_tags):
            result.fail(os.EX_USAGE,
                        _("Tag creation failed."),
                        _("There are version tags in branch history following the selected commit {commit}:\n"
                          "{listing}")
                        .format(commit=command_context.selected_commit,
                                listing='\n'.join(
                                    ' - ' + repr(tag_ref.name) for tag_ref in subsequent_version_tags))
                        )

    global_seq_number = global_sequence_number
    if context.config.tie_sequential_version_to_semantic_version \
            and global_seq_number is not None \
            and new_sequential_version is not None \
            and preceding_sequential_version != global_seq_number:
        result.fail(os.EX_USAGE,
                    _("Tag creation failed."),
                    _(
                        "The preceding sequential version {seq_val} "
                        "does not equal the global sequential version {global_seq_val}.")
                    .format(seq_val=preceding_sequential_version
                    if preceding_sequential_version is not None
                    else '<none>',
                            global_seq_val=global_seq_number)
                    )

    if not result.has_errors():
        if new_version is None:
            result.fail(os.EX_SOFTWARE,
                        _("Internal error."),
                        _("Missing result version.")
                        )
        if latest_branch_version is not None and semver.compare(latest_branch_version, new_version) >= 0:
            result.fail(os.EX_DATAERR,
                        _("Failed to increment version from {current} to {new}.")
                        .format(current=repr(latest_branch_version), new=repr(new_version)),
                        _("The new version is lower than or equal to the current version.")
                        )

        if context.config.push_to_local \
                and command_context.current_branch.short_name == command_context.selected_ref.short_name:
            if context.verbose:
                cli.print(
                    _('Checking out {base_branch} in order to avoid failing the push to a checked-out release branch')
                        .format(base_branch=repr(context.config.release_branch_base)))

            git_or_fail(context.repo, result, ['checkout', context.config.release_branch_base])
            original_current_branch = command_context.current_branch
        else:
            original_current_branch = None

        branch_name = get_branch_name_for_version(context, new_version_info)
        tag_name = get_tag_name_for_version(context, new_version_info)

        clone_result = clone_repository(context, context.config.release_branch_base)
        cloned_repo = clone_result.value

        commit_info = CommitInfo()
        commit_info.add_message("#version: " + cli.if_none(new_version))

        # run version change hooks on release branch
        checkout_command = ['checkout', '--force', '--track', '-b', branch_name,
                            repotools.create_ref_name(const.REMOTES_PREFIX,
                                                      context.config.remote_name,
                                                      branch_name)]
        returncode, out, err = repotools.git(cloned_repo, *checkout_command)
        if returncode != os.EX_OK:
            result.fail(os.EX_DATAERR,
                        _("Failed to check out release branch."),
                        _("An unexpected error occurred.")
                        )

        clone_context: Context = create_temp_context(context, result, cloned_repo.dir)
        clone_context.config.remote_name = 'origin'

        if (context.config.commit_version_property and new_version is not None) \
                or (context.config.commit_sequential_version_property and new_sequential_version is not None):

            update_result = update_project_property_file(clone_context,
                                                         properties_in_selected_commit,
                                                         new_version,
                                                         new_sequential_version,
                                                         commit_info)
            result.add_subresult(update_result)
            if result.has_errors():
                result.fail(os.EX_DATAERR,
                            _("Property update failed."),
                            _("An unexpected error occurred.")
                            )

        if new_version is not None:
            execute_version_change_actions(clone_context, latest_branch_version, new_version)

        if commit_info is not None:
            if command_context.selected_commit != command_context.selected_ref.target.obj_name:
                result.fail(os.EX_USAGE,
                            _("Failed to commit version update."),
                            _("The selected parent commit {commit} does not represent the tip of {branch}.")
                            .format(commit=command_context.selected_commit,
                                    branch=repr(command_context.selected_ref.name))
                            )

            # commit changes
            commit_info.add_parent(command_context.selected_commit)
            object_to_tag = create_commit(clone_context, result, commit_info)
            new_branch_ref_object = object_to_tag
        else:
            object_to_tag = command_context.selected_commit
            new_branch_ref_object = None

        # if command_context.selected_branch not in repotools.git_list_refs(context.repo,
        #                                                                   '--contains', object_to_tag,
        #                                                                   command_context.selected_branch.ref):

        # show info and prompt for confirmation
        cli.print("ref                 : " + cli.if_none(command_context.selected_ref.name))
        cli.print("ref_" + const.DEFAULT_VERSION_VAR_NAME + "         : " + cli.if_none(latest_branch_version))
        cli.print("new_tag             : " + cli.if_none(tag_name))
        cli.print("new_" + const.DEFAULT_VERSION_VAR_NAME + "         : " + cli.if_none(new_version))
        cli.print("selected object     : " + cli.if_none(command_context.selected_commit))
        cli.print("tagged object       : " + cli.if_none(object_to_tag))

        prompt_result = prompt_for_confirmation(
            context=context,
            fail_title=_("Failed to create release tag based on {branch}.")
                .format(branch=repr(command_context.selected_ref.name)),
            message=_("The tags are about to be pushed."),
            prompt=_("Continue?"),
        )
        result.add_subresult(prompt_result)
        if result.has_errors() or not prompt_result.value:
            return result

        # push atomically
        push_command = ['push', '--atomic']
        if context.dry_run:
            push_command.append('--dry-run')
        if context.verbose:
            push_command.append('--verbose')
        push_command.append(context.config.remote_name)

        # push the release branch commit or its version increment commit
        if new_branch_ref_object is not None:
            push_command.append(
                new_branch_ref_object + ':' + repotools.create_ref_name(const.LOCAL_BRANCH_PREFIX, branch_name))

        # check, if preceding tags exist on remote
        if preceding_version_tag is not None:
            push_command.append('--force-with-lease='
                                + preceding_version_tag.name + ':'
                                + preceding_version_tag.name)

        # push the new version tag or fail if it exists
        push_command.extend(['--force-with-lease=' + repotools.create_ref_name(const.LOCAL_TAG_PREFIX, tag_name) + ':',
                             repotools.ref_target(object_to_tag) + ':' + repotools.create_ref_name(
                                 const.LOCAL_TAG_PREFIX, tag_name)])

        returncode, out, err = repotools.git(clone_context.repo, *push_command)
        if returncode != os.EX_OK:
            result.fail(os.EX_DATAERR,
                        _("Failed to push."),
                        _("git push exited with " + str(returncode))
                        )

        if original_current_branch is not None:
            if context.verbose:
                cli.print(
                    _('Switching back to {original_branch} ')
                        .format(original_branch=repr(original_current_branch.name)))

            git_or_fail(context.repo, result, ['checkout', original_current_branch.short_name])

    return result
Ejemplo n.º 17
0
import requests
import semver
from datetime import datetime
import subprocess

from locations import Locations

CWD = os.path.abspath(os.path.split(sys.argv[0])[0])
app = QApplication(sys.argv)

if 'DEBUG' in os.environ:
    DEBUG = os.environ['DEBUG'].lower() in ('true', 'yes', '1')
else:
    DEBUG = False

VERSION = semver.format_version(0, 2, 0)
BASE_URL = 'http://diaboli.averr.in/'
LOCAL = os.path.isdir(os.path.join(CWD, 'data'))
if LOCAL:
    BASE_URL = 'http://book.dev/'
    DEBUG = True

META = requests.get(BASE_URL + '/data/meta.json').json()


class TemplateLoader(BaseLoader):
    def __init__(self, base_url):
        self.base_url = base_url
        self.cache = {}
        self.base = ''
Ejemplo n.º 18
0
 def fw_version_string(self):
     return semver.format_version(
         self.major, self.minor, self.patch, prerelease=self.prerelease, build=self.build
     )
Ejemplo n.º 19
0
def set_pyversion(version):
    version_info = semver.parse_version_info(version)
    version_string = semver.format_version(*version_info)
    with open(os.path.join(GMAPS_DIR, 'gmaps', '_version.py'), 'w') as f:
        f.write(VERSION_TEMPLATE.format(version_string=version_string))
Ejemplo n.º 20
0
 def get_formatted_version(self) -> str:
     return semver.format_version(*self.version)
import pytest
from .fixtures import Fixtures

import semver

from reconcile.utils.openshift_resource import (OpenshiftResource as OR,
                                                ConstructResourceError)

fxt = Fixtures('openshift_resource')

TEST_INT = 'test_openshift_resources'
TEST_INT_VER = semver.format_version(1, 9, 2)


class TestOpenshiftResource(object):
    def test_verify_valid_k8s_object(self):
        resource = fxt.get_anymarkup('valid_resource.yml')
        openshift_resource = OR(resource, TEST_INT, TEST_INT_VER)

        assert openshift_resource.verify_valid_k8s_object() is None

    def test_verify_valid_k8s_object_false(self):
        resource = fxt.get_anymarkup('invalid_resource.yml')

        with pytest.raises(ConstructResourceError):
            openshift_resource = OR(resource, TEST_INT, TEST_INT_VER)
            assert openshift_resource.verify_valid_k8s_object() is None

    def test_invalid_name_format(self):
        resource = fxt.get_anymarkup('invalid_resource_name_format.yml')
Ejemplo n.º 22
0
def get_version(version=None):
    if version is None:
        from .version import VERSION
        version = VERSION
    return semver.format_version(*version)
Ejemplo n.º 23
0
def write_version_py(filename='wradlib/version.py'):
    cnt = """
# THIS FILE IS GENERATED FROM WRADLIB SETUP.PY
short_version = '%(short_version)s'
version = '%(version)s'
full_version = '%(full_version)s'
git_revision = '%(git_revision)s'
release = %(isrelease)s
"""
    # Adding the git rev number needs to be done inside write_version_py(),
    # otherwise the import of wradlib.version messes up the build under
    # Python 3.

    SHORT_VERSION = VERSION
    FULL_VERSION = VERSION
    GIT_REVISION = VERSION + '-unknown'
    GIT_HASH = 'unknown'
    ISRELEASED = "'unknown'"

    if os.path.exists('.git'):
        GIT_REVISION, GIT_HASH = git_version()
    elif os.path.exists('wradlib/version.py'):
        # must be a source distribution, use existing version file
        try:
            from wradlib.version import full_version as GIT_REVISION
            from wradlib.version import git_revision as GIT_HASH
        except ImportError:
            raise ImportError('Unable to import git_revision. Try removing '
                              'wradlib/version.py and the build directory '
                              'before building.')

    # parse version using semver
    ver = semver.parse_version_info(GIT_REVISION)

    # get commit count, dev0 means tagged commit -> release
    try:
        ISRELEASED = ver.prerelease == 'dev0'
        if not ISRELEASED:
            if not ver.patch:
                patch = 0
                minor = 1
            else:
                patch = 1
                minor = 0

            SHORT_VERSION = semver.format_version(ver.major,
                                                  ver.minor + minor,
                                                  ver.patch + patch,
                                                  ver.prerelease)
            FULL_VERSION = GIT_REVISION

    except ValueError:
        warnings.warn("wradlib source does not contain detailed version info "
                      "via git or version.py, exact version can't be "
                      "retrieved.", UserWarning)

    print(SHORT_VERSION, FULL_VERSION, GIT_REVISION, GIT_HASH, ISRELEASED)
    a = open(filename, 'w')
    try:
        a.write(cnt % {'short_version': SHORT_VERSION,
                       'version': FULL_VERSION,
                       'full_version': GIT_REVISION,
                       'git_revision': GIT_HASH,
                       'isrelease': str(ISRELEASED)})
    finally:
        a.close()

    return SHORT_VERSION
Ejemplo n.º 24
0
def test_should_correctly_format_version():
    assert format_version(3, 4, 5) == '3.4.5'
    assert format_version(3, 4, 5, 'rc.1') == '3.4.5-rc.1'
    assert format_version(3, 4, 5, prerelease='rc.1') == '3.4.5-rc.1'
    assert format_version(3, 4, 5, build='build.4') == '3.4.5+build.4'
    assert format_version(3, 4, 5, 'rc.1', 'build.4') == '3.4.5-rc.1+build.4'
Ejemplo n.º 25
0
 def test_should_correctly_format_version(self):
     self.assertEqual(format_version(3, 4, 5), '3.4.5')
     self.assertEqual(format_version(3, 4, 5, 'rc.1'), '3.4.5-rc.1')
     self.assertEqual(format_version(3, 4, 5, prerelease='rc.1'), '3.4.5-rc.1')
     self.assertEqual(format_version(3, 4, 5, build='build.4'), '3.4.5+build.4')
     self.assertEqual(format_version(3, 4, 5, 'rc.1', 'build.4'), '3.4.5-rc.1+build.4')
class Subnet():
    VERSION_MAJOR = 0
    VERSION_MINOR = 0
    VERSION_PATCH = 1
    VERSION_PRE = None
    VERSION_BUILD = "build.1"
    VERSION = semver.format_version(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_PRE, VERSION_BUILD)
    conditions = {
    }


            
    def __init__(self): 
        self.t = Template()       

    def buildParams(self):
        self.paramVPCID=self.t.add_parameter(Parameter(
            "VPCID",
            Description="The VPCID that this subnet will be attached to",
            Type="String"
        ))

        self.paramDepartment=self.t.add_parameter(Parameter(
            "Department",
            Description="The department that is managing this resource",
            Type="String",
            Default="OPS",
        ))
        
        self.paramCIDRBLock=self.t.add_parameter(Parameter(
            "CidrBlock",
            Description="The CIDR Block that will make up this subnet",
            Type="String",
        ))

        self.paramMapPublicIP=self.t.add_parameter(Parameter(
            "MapPublicIP",
            Description="Boolean switch for Mapping a public IP on Launch",
            Type="String",
            Default="False",
            AllowedValues=[
                "True", "False" ],
        ))

        self.paramRouteTable=self.t.add_parameter(Parameter(
            "RouteTableId",
            Description="Route Table to attach subnets",
            Type="String",
        ))

    def buildTemplate(self):
        self.buildParams()
        
        for c in self.conditions:
            self.t.add_condition(c, self.conditions[c])

        mysubnet=self.t.add_resource(ec2Subnet(
            "Subnet",
            CidrBlock=Ref(self.paramCIDRBLock),
            MapPublicIpOnLaunch=Ref(self.paramMapPublicIP),
            VpcId=Ref(self.paramVPCID),
        ))

        self.t.add_resource(SubnetRouteTableAssociation(
            "SubnetAssociation",
            RouteTableId=Ref(self.paramRouteTable),
            SubnetId=Ref(mysubnet),
            ))
        
        self.t.add_output([
            Output(
                "SubnetId",
                Description="SubnetId of the created Subnet",
                Value=Ref(mysubnet)
                )
            ])
            
    def uploadTemplate(self):
        botosession = boto3.Session(profile_name=AWS_PROFILE)
        s3_client = botosession.client('s3')
        res = s3_client.put_object(
            Body=self.t.to_json(),
            Bucket=AWS_BUCKET,
            Key=CF_TEMPLATE_NAME
            )

    def __str__(self):
        return self.t.to_json()