<commit_before>#!/usr/bin/python
# encoding: utf-8

# (c) 2013, <NAME> <<EMAIL>>
# (c) 2014, <NAME> <<EMAIL>>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# 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/>.


DOCUMENTATION = '''
---
module: zypper_repository
author: "<NAME> (@matze)"
version_added: "1.4"
short_description: Add and remove Zypper repositories
description:
    - Add or remove Zypper repositories on SUSE and openSUSE
options:
    name:
        required: false
        default: none
        description:
            - A name for the repository. Not required when adding repofiles.
    repo:
        required: false
        default: none
        description:
            - URI of the repository or .repo file. Required when state=present.
    state:
        required: false
        choices: [ "absent", "present" ]
        default: "present"
        description:
            - A source string state.
    description:
        required: false
        default: none
        description:
            - A description of the repository
    disable_gpg_check:
        description:
            - Whether to disable GPG signature checking of
              all packages. Has an effect only if state is
              I(present).
        required: false
        default: "no"
        choices: [ "yes", "no" ]
    refresh:
        description:
            - Enable autorefresh of the repository.
        required: false
        default: "yes"
        choices: [ "yes", "no" ]
    priority:
        description:
            - Set priority of repository. Packages will always be installed
              from the repository with the smallest priority number.
        required: false
        version_added: "2.1"
    overwrite_multiple:
        description:
            - Overwrite multiple repository entries, if repositories with both name and
              URL already exist.
        required: false
        default: "no"
        choices: [ "yes", "no" ]
        version_added: "2.1"
requirements: 
    - "zypper >= 1.0  # included in openSuSE >= 11.1 or SuSE Linux Enterprise Server/Desktop >= 11.0"
'''

EXAMPLES = '''
# Add NVIDIA repository for graphics drivers
- zypper_repository: name=nvidia-repo repo='ftp://download.nvidia.com/opensuse/12.2' state=present

# Remove NVIDIA repository
- zypper_repository: name=nvidia-repo repo='ftp://download.nvidia.com/opensuse/12.2' state=absent

# Add python development repository
- zypper_repository: repo=http://download.opensuse.org/repositories/devel:/languages:/python/SLE_11_SP3/devel:languages:python.repo
'''

REPO_OPTS = ['alias', 'name', 'priority', 'enabled', 'autorefresh', 'gpgcheck']

def _parse_repos(module):
    """parses the output of zypper -x lr and return a parse repo dictionary"""
    cmd = ['/usr/bin/zypper', '-x', 'lr']

    from xml.dom.minidom import parseString as parseXML
    rc, stdout, stderr = module.run_command(cmd, check_rc=False)
    if rc == 0:
        repos = []
        dom = parseXML(stdout)
        repo_list = dom.getElementsByTagName('repo')
        for repo in repo_list:
            opts = {}
            for o in REPO_OPTS:
                opts[o] = repo.getAttribute(o)
            opts['url'] = repo.getElementsByTagName('url')[0].firstChild.data
            # A repo can be uniquely identified by an alias + url
            repos.append(opts)
        return repos
    # exit code 6 is ZYPPER_EXIT_NO_REPOS (no repositories defined)
    elif rc == 6:
        return []
    else:
        d = { 'zypper_exit_code': rc }
        if stderr:
            d['stderr'] = stderr
        if stdout:
            d['stdout'] = stdout
        module.fail_json(msg='Failed to execute "%s"' % " ".join(cmd), **d)

def _repo_changes(realrepo, repocmp):
    for k in repocmp:
        if repocmp[k] and k not in realrepo:
            return True

    for k, v in realrepo.items():
        if k in repocmp and repocmp[k]:
            valold = str(repocmp[k] or "")
            valnew = v or ""
            if k == "url":
                valold, valnew = valold.rstrip("/"), valnew.rstrip("/")
            if valold != valnew:
                return True
    return False

def repo_exists(module, repodata, overwrite_multiple):
    existing_repos = _parse_repos(module)

    # look for repos that have matching alias or url to the one searched
    repos = []
    for kw in ['alias', 'url']:
        name = repodata[kw]
        for oldr in existing_repos:
            if repodata[kw] == oldr[kw] and oldr not in repos:
                repos.append(oldr)

    if len(repos) == 0:
        # Repo does not exist yet
        return (False, False, None)
    elif len(repos) == 1:
        # Found an existing repo, look for changes
        has_changes = _repo_changes(repos[0], repodata)
        return (True, has_changes, repos)
    elif len(repos) == 2 and overwrite_multiple:
        # Found two repos and want to overwrite_multiple
        return (True, True, repos)
    else:
        # either more than 2 repos (shouldn't happen)
        # or overwrite_multiple is not active
        module.fail_json(msg='More than one repo matched "%s": "%s"' % (name, repos))

def modify_repo(module, repodata, old_repos):
    repo = repodata['url']
    cmd = ['/usr/bin/zypper', 'ar', '--check']
    if repodata['name']:
        cmd.extend(['--name', repodata['name']])

    if repodata['priority']:
        cmd.extend(['--priority', str(repodata['priority'])])

    if repodata['enabled'] == '0':
        cmd.append('--disable')

    if repodata['gpgcheck'] == '1':
        cmd.append('--gpgcheck')
    else:
        cmd.append('--no-gpgcheck')

    if repodata['autorefresh'] == '1':
        cmd.append('--refresh')
<commit_msg>allow overwrite_multiple with more than 2 repos (#2481)<commit_after>#!/usr/bin/python
# encoding: utf-8

# (c) 2013, <NAME> <<EMAIL>>
# (c) 2014, <NAME> <<EMAIL>>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# 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/>.


DOCUMENTATION = '''
---
module: zypper_repository
author: "<NAME> (@matze)"
version_added: "1.4"
short_description: Add and remove Zypper repositories
description:
    - Add or remove Zypper repositories on SUSE and openSUSE
options:
    name:
        required: false
        default: none
        description:
            - A name for the repository. Not required when adding repofiles.
    repo:
        required: false
        default: none
        description:
            - URI of the repository or .repo file. Required when state=present.
    state:
        required: false
        choices: [ "absent", "present" ]
        default: "present"
        description:
            - A source string state.
    description:
        required: false
        default: none
        description:
            - A description of the repository
    disable_gpg_check:
        description:
            - Whether to disable GPG signature checking of
              all packages. Has an effect only if state is
              I(present).
        required: false
        default: "no"
        choices: [ "yes", "no" ]
    refresh:
        description:
            - Enable autorefresh of the repository.
        required: false
        default: "yes"
        choices: [ "yes", "no" ]
    priority:
        description:
            - Set priority of repository. Packages will always be installed
              from the repository with the smallest priority number.
        required: false
        version_added: "2.1"
    overwrite_multiple:
        description:
            - Overwrite multiple repository entries, if repositories with both name and
              URL already exist.
        required: false
        default: "no"
        choices: [ "yes", "no" ]
        version_added: "2.1"
requirements: 
    - "zypper >= 1.0  # included in openSuSE >= 11.1 or SuSE Linux Enterprise Server/Desktop >= 11.0"
'''

EXAMPLES = '''
# Add NVIDIA repository for graphics drivers
- zypper_repository: name=nvidia-repo repo='ftp://download.nvidia.com/opensuse/12.2' state=present

# Remove NVIDIA repository
- zypper_repository: name=nvidia-repo repo='ftp://download.nvidia.com/opensuse/12.2' state=absent

# Add python development repository
- zypper_repository: repo=http://download.opensuse.org/repositories/devel:/languages:/python/SLE_11_SP3/devel:languages:python.repo
'''

REPO_OPTS = ['alias', 'name', 'priority', 'enabled', 'autorefresh', 'gpgcheck']

def _parse_repos(module):
    """parses the output of zypper -x lr and return a parse repo dictionary"""
    cmd = ['/usr/bin/zypper', '-x', 'lr']

    from xml.dom.minidom import parseString as parseXML
    rc, stdout, stderr = module.run_command(cmd, check_rc=False)
    if rc == 0:
        repos = []
        dom = parseXML(stdout)
        repo_list = dom.getElementsByTagName('repo')
        for repo in repo_list:
            opts = {}
            for o in REPO_OPTS:
                opts[o] = repo.getAttribute(o)
            opts['url'] = repo.getElementsByTagName('url')[0].firstChild.data
            # A repo can be uniquely identified by an alias + url
            repos.append(opts)
        return repos
    # exit code 6 is ZYPPER_EXIT_NO_REPOS (no repositories defined)
    elif rc == 6:
        return []
    else:
        d = { 'zypper_exit_code': rc }
        if stderr:
            d['stderr'] = stderr
        if stdout:
            d['stdout'] = stdout
        module.fail_json(msg='Failed to execute "%s"' % " ".join(cmd), **d)

def _repo_changes(realrepo, repocmp):
    for k in repocmp:
        if repocmp[k] and k not in realrepo:
            return True

    for k, v in realrepo.items():
        if k in repocmp and repocmp[k]:
            valold = str(repocmp[k] or "")
            valnew = v or ""
            if k == "url":
                valold, valnew = valold.rstrip("/"), valnew.rstrip("/")
            if valold != valnew:
                return True
    return False

def repo_exists(module, repodata, overwrite_multiple):
    existing_repos = _parse_repos(module)

    # look for repos that have matching alias or url to the one searched
    repos = []
    for kw in ['alias', 'url']:
        name = repodata[kw]
        for oldr in existing_repos:
            if repodata[kw] == oldr[kw] and oldr not in repos:
                repos.append(oldr)

    if len(repos) == 0:
        # Repo does not exist yet
        return (False, False, None)
    elif len(repos) == 1:
        # Found an existing repo, look for changes
        has_changes = _repo_changes(repos[0], repodata)
        return (True, has_changes, repos)
    elif len(repos) >= 2:
        if overwrite_multiple:
            # Found two repos and want to overwrite_multiple
            return (True, True, repos)
        else:
            errmsg = 'More than one repo matched "%s": "%s".' % (name, repos)
            errmsg += ' Use overwrite_multiple to allow more than one repo to be overwritten'
            module.fail_json(msg=errmsg)


def modify_repo(module, repodata, old_repos):
    repo = repodata['url']
    cmd = ['/usr/bin/zypper', 'ar', '--check']
    if repodata['name']:
        cmd.extend(['--name', repodata['name']])

    if repodata['priority']:
        cmd.extend(['--priority', str(repodata['priority'])])

    if repodata['enabled'] == '0':
        cmd.append('--disable')

    if repodata['gpgcheck'] == '1':
        cmd.append('--gpgcheck')
    else:
        cmd.append('--no-gpgcheck')

    if repodata['autorefresh'] == '1':
        cmd.append('--refresh')

{'fraction_non_alphanumeric': 0.10937251787132644, 'fraction_numerical': 0.007466243050039714, 'mean_word_length': 2.362082777036048, 'pattern_counts': {'":': 4, '<': 19, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6539237', 'n_tokens_mistral': 3848, 'n_tokens_neox': 3655, 'n_words': 1219}