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

import os

from ansible.module_utils.basic import *

"""
Ansible module to manage elasticsearch plugins
(c) 2015, <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: elasticsearch_plugin
short_description: Manage Elasticsearch plugins
description:
    - Manages Elasticsearch plugins.
version_added: ""
author: <NAME> (@ThePixelDeveloper)
options:
    name:
        description:
            - Name of the plugin to install
        required: True
    state:
        description:
            - Desired state of a plugin.
        required: False
        choices: [present, absent]
        default: present
    url:
        description:
            - Set exact URL to download the plugin from
        required: False
        default: None
    timeout:
        description:
            - Timeout setting: 30s, 1m, 1h...
        required: False
        default: 1m
    plugin_bin:
        description:
            - Location of the plugin binary
        required: False
        default: /usr/share/elasticsearch/bin/plugin
    plugin_dir:
        description:
            - Your configured plugin directory specified in Elasticsearch
        required: False
        default: /usr/share/elasticsearch/plugins/
    version:
        description: 
            - Version of the plugin to be installed.
        required: False
        default: None
'''

EXAMPLES = '''
# Install Elasticsearch head plugin
- elasticsearch_plugin: state=present name="mobz/elasticsearch-head"
'''


def parse_plugin_repo(string):
    elements = string.split("/")

    # We first consider the simplest form: pluginname
    repo = elements[0]

    # We consider the form: username/pluginname
    if len(elements) > 1:
        repo = elements[1]

    # remove elasticsearch- prefix
    # remove es- prefix
    for string in ("elasticsearch-", "es-"):
        if repo.startswith(string):
            return repo[len(string):]

    return repo


def is_plugin_present(plugin_dir, working_dir):
    return os.path.isdir(os.path.join(working_dir, plugin_dir))


def parse_error(string):
    reason = "reason: "
    return string[string.index(reason) + len(reason):].strip()


def main():

    package_state_map = dict(
        present="--install",
        absent="--remove"
    )

    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            state=dict(default="present", choices=package_state_map.keys()),
            url=dict(default=None),
            timeout=dict(default="1m"),
            plugin_bin=dict(default="/usr/share/elasticsearch/bin/plugin"),
            plugin_dir=dict(default="/usr/share/elasticsearch/plugins/"),
            version=dict(default=None)
        )
    )

    plugin_bin = module.params["plugin_bin"]
    plugin_dir = module.params["plugin_dir"]
    name = module.params["name"]
    state = module.params["state"]
    url = module.params["url"]
    timeout = module.params["timeout"]
    version = module.params["version"]

    present = is_plugin_present(parse_plugin_repo(name), plugin_dir)

    # skip if the state is correct
    if (present and state == "present") or (state == "absent" and not present):
        module.exit_json(changed=False, name=name)
        
    if (version):
       name = name + '/' + version

    cmd_args = [plugin_bin, package_state_map[state], name]

    if url:
        cmd_args.append("--url %s" % url)

    if timeout:
        cmd_args.append("--timeout %s" % timeout)

    cmd = " ".join(cmd_args)

    rc, out, err = module.run_command(cmd)

    if rc != 0:
        reason = parse_error(out)
        module.fail_json(msg=reason)

    module.exit_json(changed=True, cmd=cmd, name=name, state=state, url=url, timeout=timeout, stdout=out, stderr=err)

if __name__ == "__main__":
    main()<commit_msg>Move ansible util import to the bottom of the module<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os

"""
Ansible module to manage elasticsearch plugins
(c) 2015, <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: elasticsearch_plugin
short_description: Manage Elasticsearch plugins
description:
    - Manages Elasticsearch plugins.
version_added: ""
author: <NAME> (@ThePixelDeveloper)
options:
    name:
        description:
            - Name of the plugin to install
        required: True
    state:
        description:
            - Desired state of a plugin.
        required: False
        choices: [present, absent]
        default: present
    url:
        description:
            - Set exact URL to download the plugin from
        required: False
        default: None
    timeout:
        description:
            - Timeout setting: 30s, 1m, 1h...
        required: False
        default: 1m
    plugin_bin:
        description:
            - Location of the plugin binary
        required: False
        default: /usr/share/elasticsearch/bin/plugin
    plugin_dir:
        description:
            - Your configured plugin directory specified in Elasticsearch
        required: False
        default: /usr/share/elasticsearch/plugins/
    version:
        description: 
            - Version of the plugin to be installed.
        required: False
        default: None
'''

EXAMPLES = '''
# Install Elasticsearch head plugin
- elasticsearch_plugin: state=present name="mobz/elasticsearch-head"
'''


def parse_plugin_repo(string):
    elements = string.split("/")

    # We first consider the simplest form: pluginname
    repo = elements[0]

    # We consider the form: username/pluginname
    if len(elements) > 1:
        repo = elements[1]

    # remove elasticsearch- prefix
    # remove es- prefix
    for string in ("elasticsearch-", "es-"):
        if repo.startswith(string):
            return repo[len(string):]

    return repo


def is_plugin_present(plugin_dir, working_dir):
    return os.path.isdir(os.path.join(working_dir, plugin_dir))


def parse_error(string):
    reason = "reason: "
    return string[string.index(reason) + len(reason):].strip()


def main():

    package_state_map = dict(
        present="--install",
        absent="--remove"
    )

    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            state=dict(default="present", choices=package_state_map.keys()),
            url=dict(default=None),
            timeout=dict(default="1m"),
            plugin_bin=dict(default="/usr/share/elasticsearch/bin/plugin"),
            plugin_dir=dict(default="/usr/share/elasticsearch/plugins/"),
            version=dict(default=None)
        )
    )

    plugin_bin = module.params["plugin_bin"]
    plugin_dir = module.params["plugin_dir"]
    name = module.params["name"]
    state = module.params["state"]
    url = module.params["url"]
    timeout = module.params["timeout"]
    version = module.params["version"]

    present = is_plugin_present(parse_plugin_repo(name), plugin_dir)

    # skip if the state is correct
    if (present and state == "present") or (state == "absent" and not present):
        module.exit_json(changed=False, name=name)
        
    if (version):
       name = name + '/' + version

    cmd_args = [plugin_bin, package_state_map[state], name]

    if url:
        cmd_args.append("--url %s" % url)

    if timeout:
        cmd_args.append("--timeout %s" % timeout)

    cmd = " ".join(cmd_args)

    rc, out, err = module.run_command(cmd)

    if rc != 0:
        reason = parse_error(out)
        module.fail_json(msg=reason)

    module.exit_json(changed=True, cmd=cmd, name=name, state=state, url=url, timeout=timeout, stdout=out, stderr=err)

from ansible.module_utils.basic import *

main()
{'fraction_non_alphanumeric': 0.10376091336467427, 'fraction_numerical': 0.003581822252070741, 'mean_word_length': 2.7136325852036576, 'pattern_counts': {'":': 1, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '676163', 'n_tokens_mistral': 2564, 'n_tokens_neox': 2496, 'n_words': 763}