<commit_before># -*- coding: utf-8 -*-
'''
Support for RallyDev

Requires a ``username`` and a ``password`` in ``/etc/salt/minion``:

.. code-block: yaml

    rallydev:
      username: <EMAIL>
      password: <PASSWORD>
'''

# Import python libs
from __future__ import absolute_import, print_function
import json
import logging

# Import salt libs
from salt.exceptions import SaltException
from salt.exceptions import SaltInvocationError
import salt.utils.http

log = logging.getLogger(__name__)


def __virtual__():
    '''
    Only load the module if apache is installed
    '''
    if not __opts__.get('rallydev', {}).get('username', None):
        return False
    if not __opts__.get('rallydev', {}).get('password', None):
        return False
    return True


def _get_token():
    '''
    Get an auth token
    '''
    username = __opts__.get('rallydev', {}).get('username', None)
    password = __opts__.get('rallydev', {}).get('password', None)
    path = 'https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize'
    result = salt.utils.http.query(
        path,
        decode=True,
        decode_type='json',
        text=True,
        status=True,
        username=username,
        password=password,
        cookies=True,
        persist_session=True,
        opts=__opts__,
    )
    if not 'dict' in result:
        return None

    return result['dict']['OperationResult']['SecurityToken']


def _query(action=None,
           command=None,
           args=None,
           method='GET',
           header_dict=None,
           data=None):
    '''
    Make a web call to Stormpath

    .. versionadded:: Beryllium
    '''
    token = _get_token()
    username = __opts__.get('rallydev', {}).get('username', None)
    password = __opts__.get('r<PASSWORD>dev', {}).get('password', None)
    path = 'https://rally1.rallydev.com/slm/webservice/v2.0/'

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('RallyDev URL: {0}'.format(path))

    if not isinstance(args, dict):
        args = {}

    args['key'] = token

    if header_dict is None:
        header_dict = {'Content-type': 'application/json'}

    if method != 'POST':
        header_dict['Accept'] = 'application/json'

    decode = True
    if method == 'DELETE':
        decode = False

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        data=data,
        header_dict=header_dict,
        decode=decode,
        decode_type='json',
        text=True,
        status=True,
        username=username,
        password=password,
        cookies=True,
        persist_session=True,
        opts=__opts__,
    )
    log.debug('RallyDev Response Status Code: {0}'.format( result['status']))
    if 'error' in result:
        log.error(result['error'])
        return [result['status'], result['error']]

    return [result['status'], result.get('dict', {})]


def list_items(name):
    '''
    List items of a particular type

    CLI Examples:

    .. code-block:: bash

        salt myminion rallydev.list_<item name>s
        salt myminion rallydev.list_users
        salt myminion rallydev.list_artifacts
    '''
    status, result = _query(action=name)
    return result


def query_item(name, query_string, order='Rank'):
    '''
    Query a type of record for one or more items. Requires a valid query string.
    See https://rally1.rallydev.com/slm/doc/webservice/introduction.jsp for
    information on query syntax.<commit_msg>Linting<commit_after># -*- coding: utf-8 -*-
'''
Support for RallyDev

Requires a ``username`` and a ``password`` in ``/etc/salt/minion``:

.. code-block: yaml

    rallydev:
      username: <EMAIL>
      password: <PASSWORD>
'''

# Import python libs
from __future__ import absolute_import, print_function
import json
import logging

# Import salt libs
from salt.exceptions import SaltInvocationError
import salt.utils.http

log = logging.getLogger(__name__)


def __virtual__():
    '''
    Only load the module if apache is installed
    '''
    if not __opts__.get('rallydev', {}).get('username', None):
        return False
    if not __opts__.get('rallydev', {}).get('password', None):
        return False
    return True


def _get_token():
    '''
    Get an auth token
    '''
    username = __opts__.get('rallydev', {}).get('username', None)
    password = __opts__.get('rallydev', {}).get('password', None)
    path = 'https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize'
    result = salt.utils.http.query(
        path,
        decode=True,
        decode_type='json',
        text=True,
        status=True,
        username=username,
        password=password,
        cookies=True,
        persist_session=True,
        opts=__opts__,
    )
    if 'dict' not in result:
        return None

    return result['dict']['OperationResult']['SecurityToken']


def _query(action=None,
           command=None,
           args=None,
           method='GET',
           header_dict=None,
           data=None):
    '''
    Make a web call to Stormpath

    .. versionadded:: Beryllium
    '''
    token = _get_token()
    username = __opts__.get('rallydev', {}).get('username', None)
    password = __opts__.get('r<PASSWORD>', {}).get('password', None)
    path = 'https://rally1.rallydev.com/slm/webservice/v2.0/'

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('RallyDev URL: {0}'.format(path))

    if not isinstance(args, dict):
        args = {}

    args['key'] = token

    if header_dict is None:
        header_dict = {'Content-type': 'application/json'}

    if method != 'POST':
        header_dict['Accept'] = 'application/json'

    decode = True
    if method == 'DELETE':
        decode = False

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        data=data,
        header_dict=header_dict,
        decode=decode,
        decode_type='json',
        text=True,
        status=True,
        username=username,
        password=password,
        cookies=True,
        persist_session=True,
        opts=__opts__,
    )
    log.debug('RallyDev Response Status Code: {0}'.format(result['status']))
    if 'error' in result:
        log.error(result['error'])
        return [result['status'], result['error']]

    return [result['status'], result.get('dict', {})]


def list_items(name):
    '''
    List items of a particular type

    CLI Examples:

    .. code-block:: bash

        salt myminion rallydev.list_<item name>s
        salt myminion rallydev.list_users
        salt myminion rallydev.list_artifacts
    '''
    status, result = _query(action=name)
    return result


def query_item(name, query_string, order='Rank'):
    '''
    Query a type of record for one or more items. Requires a valid query string.
    See https://rally1.rallydev.com/slm/doc/webservice/introduction.jsp for
    information on query syntax.
{'fraction_non_alphanumeric': 0.13234042553191488, 'fraction_numerical': 0.003120567375886525, 'mean_word_length': 2.548565676899849, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6167222', 'n_tokens_mistral': 2171, 'n_tokens_neox': 2127, 'n_words': 520}