Ejemplo n.º 1
0
def deprecation_versions():
    """Create a list of valid version for deprecation entries, current+4"""
    major, minor = [int(version) for version in __version__.split('.')[0:2]]
    return Any(*[
        '{0}.{1}'.format(major, minor + increment)
        for increment in range(0, 5)
    ])
Ejemplo n.º 2
0
def get_versioned_doclink(path):
    """
    returns a versioned documentation link for the current Ansible major.minor version; used to generate
    in-product warning/error links to the configured DOCSITE_ROOT_URL
    (eg, https://docs.ansible.com/ansible/2.8/somepath/doc.html)

    :param path: relative path to a document under docs/docsite/rst;
    :return: absolute URL to the specified doc for the current version of Ansible
    """
    path = to_native(path)
    try:
        base_url = C.config.get_config_value('DOCSITE_ROOT_URL')
        if not base_url.endswith('/'):
            base_url += '/'
        if path.startswith('/'):
            path = path[1:]
        split_ver = ansible_version.split('.')
        if len(split_ver) < 3:
            raise RuntimeError('invalid version ({0})'.format(ansible_version))

        doc_version = '{0}.{1}'.format(split_ver[0], split_ver[1])

        # check to see if it's a X.Y.0 non-rc prerelease or dev release, if so, assume devel (since the X.Y doctree
        # isn't published until beta-ish)
        if split_ver[2].startswith('0'):
            # exclude rc; we should have the X.Y doctree live by rc1
            if any((pre in split_ver[2]) for pre in
                   ['a', 'b']) or len(split_ver) > 3 and 'dev' in split_ver[3]:
                doc_version = 'devel'

        return '{0}{1}/{2}'.format(base_url, doc_version, path)
    except Exception as ex:
        return '(unable to create versioned doc link for path {0}: {1})'.format(
            path, to_native(ex))
Ejemplo n.º 3
0
def get_versioned_doclink(path):
    """
    returns a versioned documentation link for the current Ansible major.minor version; used to generate
    in-product warning/error links to the configured DOCSITE_ROOT_URL
    (eg, https://docs.ansible.com/ansible/2.8/somepath/doc.html)

    :param path: relative path to a document under docs/docsite/rst;
    :return: absolute URL to the specified doc for the current version of Ansible
    """
    path = to_native(path)
    try:
        base_url = C.config.get_config_value('DOCSITE_ROOT_URL')
        if not base_url.endswith('/'):
            base_url += '/'
        if path.startswith('/'):
            path = path[1:]
        split_ver = ansible_version.split('.')
        if len(split_ver) < 2:
            raise RuntimeError('invalid version ({0})'.format(ansible_version))

        major_minor = '{0}.{1}'.format(split_ver[0], split_ver[1])

        return '{0}{1}/{2}'.format(base_url, major_minor, path)
    except Exception as ex:
        return '(unable to create versioned doc link for path {0}: {1})'.format(
            path, to_native(ex))
Ejemplo n.º 4
0
def _validate_install_ansible_base():
    """Validate that we can install ansible-base. Currently this only
    cares about upgrading to ansible-base from ansible<2.10
    """
    # Skip common commands we can ignore
    # Do NOT add bdist_wheel here, we don't ship wheels
    # and bdist_wheel is the only place we can prevent pip
    # from installing, as pip creates a wheel, and installs the wheel
    # and we have no influence over installation within a wheel
    if set(('sdist', 'egg_info')).intersection(sys.argv):
        return

    if os.getenv('ANSIBLE_SKIP_CONFLICT_CHECK', '') not in ('', '0'):
        return

    # Save these for later restoring things to pre invocation
    sys_modules = sys.modules.copy()
    sys_modules_keys = set(sys_modules)

    # Make sure `lib` isn't in `sys.path` that could confuse this
    sys_path = sys.path[:]
    abspath = os.path.abspath
    sys.path[:] = [p for p in sys.path if abspath(p) != abspath('lib')]

    try:
        from ansible.release import __version__
    except ImportError:
        pass
    else:
        version_tuple = tuple(int(v) for v in __version__.split('.')[:2])
        if version_tuple < (2, 10):
            stars = '*' * 76
            raise RuntimeError('''

    %s

    Cannot install ansible-base with a pre-existing ansible==%s
    installation.

    Installing ansible-base with ansible-2.9 or older currently installed with
    pip is known to cause problems. Please uninstall ansible and install the new
    version:

        pip uninstall ansible
        pip install ansible-base

    If you want to skip the conflict checks and manually resolve any issues
    afterwards, set the ANSIBLE_SKIP_CONFLICT_CHECK environment variable:

        ANSIBLE_SKIP_CONFLICT_CHECK=1 pip install ansible-base

    %s
                ''' % (stars, __version__, stars))
    finally:
        sys.path[:] = sys_path
        for key in sys_modules_keys.symmetric_difference(sys.modules):
            sys.modules.pop(key, None)
        sys.modules.update(sys_modules)
Ejemplo n.º 5
0
    'E9502': ("Display.deprecated call without a version",
              "ansible-deprecated-no-version",
              "Used when a call to Display.deprecated does not specify a "
              "version", {
                  'minversion': (2, 6)
              }),
    'E9503': ("Invalid deprecated version (%r) found in call to "
              "Display.deprecated or AnsibleModule.deprecate",
              "ansible-invalid-deprecated-version",
              "Used when a call to Display.deprecated specifies an invalid "
              "version number", {
                  'minversion': (2, 6)
              }),
}

ANSIBLE_VERSION = LooseVersion('.'.join(ansible_version_raw.split('.')[:3]))


def _get_expr_name(node):
    """Funciton to get either ``attrname`` or ``name`` from ``node.func.expr``

    Created specifically for the case of ``display.deprecated`` or ``self._display.deprecated``
    """
    try:
        return node.func.expr.attrname
    except AttributeError:
        # If this fails too, we'll let it raise, the caller should catch it
        return node.func.expr.name


class AnsibleDeprecatedChecker(BaseChecker):
Ejemplo n.º 6
0
def get_ansible_version():
    """Return current ansible-core version"""
    from ansible.release import __version__

    return LooseVersion('.'.join(__version__.split('.')[:3]))
Ejemplo n.º 7
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import os
import time

from collections import defaultdict

from ansible.release import __version__ as ansible_version

ansible_major_version = '.'.join(ansible_version.split('.')[:2])

try:
    from github3 import GitHub
except ImportError:
    raise SystemExit(
        'This script needs the github3.py library installed to work')

if not os.getenv('GITHUB_TOKEN'):
    raise SystemExit(
        'Please set the GITHUB_TOKEN env var with your github oauth token')

deprecated = defaultdict(list)

parser = argparse.ArgumentParser()
parser.add_argument('--template',
Ejemplo n.º 8
0
import os
import re
import sys

from ansible.module_utils.compat.version import StrictVersion

import yaml

import ansible.config

from ansible.plugins.loader import fragment_loader
from ansible.release import __version__ as ansible_version
from ansible.utils.plugin_docs import get_docstring

DOC_RE = re.compile(b'^DOCUMENTATION', flags=re.M)
ANSIBLE_MAJOR = StrictVersion('.'.join(ansible_version.split('.')[:2]))


def find_deprecations(obj, path=None):
    if not isinstance(obj, (list, dict)):
        return

    try:
        items = obj.items()
    except AttributeError:
        items = enumerate(obj)

    for key, value in items:
        if path is None:
            this_path = []
        else:
Ejemplo n.º 9
0
    'E9502': ("Display.deprecated call without a version",
              "ansible-deprecated-no-version",
              "Used when a call to Display.deprecated does not specify a "
              "version", {
                  'minversion': (2, 6)
              }),
    'E9503': ("Invalid deprecated version (%r) found in call to "
              "Display.deprecated or AnsibleModule.deprecate",
              "ansible-invalid-deprecated-version",
              "Used when a call to Display.deprecated specifies an invalid "
              "version number", {
                  'minversion': (2, 6)
              }),
}

ANSIBLE_VERSION = StrictVersion('.'.join(ansible_version_raw.split('.')[:3]))


def _get_expr_name(node):
    """Funciton to get either ``attrname`` or ``name`` from ``node.func.expr``

    Created specifically for the case of ``display.deprecated`` or ``self._display.deprecated``
    """
    try:
        return node.func.expr.attrname
    except AttributeError:
        # If this fails too, we'll let it raise, the caller should catch it
        return node.func.expr.name


class AnsibleDeprecatedChecker(BaseChecker):
Ejemplo n.º 10
0
__metaclass__ = type

import argparse
import os
import time

from collections import defaultdict

from ansible.release import __version__ as ansible_version

# Pylint doesn't understand Python3 namespace modules.
from ..commands import Command  # pylint: disable=relative-beyond-top-level
from .. import errors  # pylint: disable=relative-beyond-top-level

ANSIBLE_MAJOR_VERSION = '.'.join(ansible_version.split('.')[:2])


def get_token(token_file):
    if token_file:
        return token_file.read().strip()

    token = os.getenv('GITHUB_TOKEN').strip()
    if not token:
        raise errors.MissingUserInput(
            'Please provide a file containing a github oauth token with public_repo scope'
            ' via the --github-token argument or set the GITHUB_TOKEN env var with your'
            ' github oauth token')
    return token

import dataclasses
import os
import re
import subprocess
import sys
import typing as t

try:
    # noinspection PyPackageRequirements
    import argcomplete
except ImportError:
    argcomplete = None

from ansible.release import __version__

MAJOR_MINOR_VERSION = '.'.join(__version__.split('.')[:2])
PROJECT = f'ansible-core {MAJOR_MINOR_VERSION}'


@dataclasses.dataclass(frozen=True)
class Issue:
    title: str
    summary: str
    body: str
    project: str

    def create(self) -> str:
        cmd = ['gh', 'issue', 'create', '--title', self.title, '--body', self.body, '--project', self.project]
        process = subprocess.run(cmd, capture_output=True, check=True)
        url = process.stdout.decode().strip()
        return url
Ejemplo n.º 12
0
from ast import literal_eval
from jinja2 import Template
from string import ascii_letters, digits

from ansible.config.manager import ConfigManager, ensure_type
from ansible.module_utils._text import to_text
from ansible.module_utils.common.collections import Sequence
from ansible.module_utils.parsing.convert_bool import BOOLEANS_TRUE
from ansible.module_utils.six import string_types
from ansible.release import __version__
from ansible.utils.fqcn import add_internal_fqcns

# 4 versions above current
default_deprecated = to_text(
    float('.'.join(__version__.split('.')[0:2])) + 0.04)


def _warning(msg):
    ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
    try:
        from ansible.utils.display import Display
        Display().warning(msg)
    except Exception:
        import sys
        sys.stderr.write(' [WARNING] %s\n' % (msg))


def _deprecated(msg, version=default_deprecated):
    ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
    try: