<commit_before>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os

from robot import utils
from robot.errors import DataError, FrameworkError
from robot.output import LOGGER


def get_title(type_, name):
    endings = { 'Log' : 'Test Log',
                'Report' : 'Test Report',
                'Summary' : 'Summary Report' }
    return '%s %s' % (name, endings[type_])


class _BaseSettings:

    _cli_opts = { 'Name'             : ('name', None),
                  'Doc'              : ('doc', None),
                  'Metadata'         : ('metadata', []),
                  'TestNames'        : ('test', []),
                  'SuiteNames'       : ('suite', []),
                  'SetTag'           : ('settag', []),
                  'Include'          : ('include', []),
                  'Exclude'          : ('exclude', []),
                  'Critical'         : ('critical', None),
                  'NonCritical'      : ('noncritical', None),
                  'OutputDir'        : ('outputdir', '.'),
                  'Log'              : ('log', 'log.html'),
                  'Report'           : ('report', 'report.html'),
                  'Summary'          : ('summary', 'NONE'),
                  'SplitOutputs'     : ('splitoutputs', -1),
                  'TimestampOutputs' : ('timestampoutputs', False),
                  'LogTitle'         : ('logtitle', None),
                  'ReportTitle'      : ('reporttitle', None),
                  'SummaryTitle'     : ('summarytitle', None),
                  'SuiteStatLevel'   : ('suitestatlevel', -1),
                  'TagStatInclude'   : ('tagstatinclude', []),
                  'TagStatExclude'   : ('tagstatexclude', []),
                  'TagStatCombine'   : ('tagstatcombine', []),
                  'TagDoc'           : ('tagdoc', []),
                  'TagStatLink'      : ('tagstatlink', []),
                  'LogLevel'         : ('loglevel', 'INFO'),
                  'MonitorWidth'     : ('monitorwidth', 78),
                  'MonitorColors'    : ('monitorcolors', 'ON') }

    _deprecated = {}

    def __init__(self, options={}, log=True):
        self._opts = {}
        self._cli_opts.update(self._extra_cli_opts)
        self._process_deprecated_cli_opts(options)
        self._process_cli_opts(options)
        if log: LOGGER.info('Settings:\n%s' % self)

    def _process_cli_opts(self, opts):
        for name, (cli_name, default) in self._cli_opts.items():
            try:
                value = opts[cli_name]
                if value in [None, []]:
                    raise KeyError
            except KeyError:
                value = default
            self[name] = value

    def _process_deprecated_cli_opts(self, opts):
        for oldname, newname in self._deprecated.items():
            if oldname not in opts or opts[oldname] in [None, []]:
                continue
            if newname:
                LOGGER.warn("Option '--%s' is deprecated. Use '--%s' instead."
                            % (oldname, newname))
                opts[newname] = opts[oldname]
            else:
                LOGGER.error("Option '--%s' has been removed." % oldname)

    def __setitem__(self, name, value):
        if not self._cli_opts.has_key(name):
            raise KeyError("Non-existing settings '%s'" % name)
        elif name in ['Name', 'Doc'] and value:
            value = value.replace('_', ' ')
        elif name == 'Metadata' and value:
            value = [v.replace('_', ' ') for v in value]
        elif name == 'TagDoc':
            value = [ item.replace('_', ' ') for item in value ]
        elif name in ['Include', 'Exclude', 'TagStatCombine']:
            value = [ item.replace('AND','&')  for item in value ]
        elif name in self._optional_outputs and utils.eq(value, 'NONE'):
            value = 'NONE'
        elif name == 'OutputDir':
            value = utils.normpath(value)
        elif name in ['SplitOutputs', 'SuiteStatLevel', 'MonitorWidth']:
            value = self._convert_to_integer(name, value)
        elif name in ['Listeners', 'VariableFiles']:
            value = [ self._split_args_from_name(item) for item in value ]
        elif name == 'TagStatLink':
            value = self._process_tag_stat_link(value)
        elif name == 'RemoveKeywords':
            value = value.upper()
        elif name == 'MonitorColors':
            value = (utils.eq(value, 'ON') and not utils.is_windows) \
                         or utils.eq(value, 'FORCE')
        self._opts[name] = value

    def __getitem__(self, name):
        if not self._cli_opts.has_key(name):
            raise KeyError("Non-existing setting '%s'" % name)
        elif name in ['Output', 'Log', 'Report', 'Summary', 'DebugFile']:
            return self._get_output_file(name)
        elif name in ['LogTitle', 'ReportTitle', 'SummaryTitle']:
            return self._get_output_title(name)
        return self._opts[name]

    def _get_output_title(self, type_):
        value = self._opts[type_]
        if value is not None:
            return value.replace('_', ' ')
        return get_title(type_.replace('Title',''), self['Name'])

    def _get_output_file(self, type_):
        """Returns path of the requested ouput file and creates needed dirs.

        Type can be 'Output', 'Log', 'Report' or 'Summary'.<commit_msg>inlined<commit_after>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os

from robot import utils
from robot.errors import DataError, FrameworkError
from robot.output import LOGGER


def get_title(type_, name):
    endings = { 'Log' : 'Test Log',
                'Report' : 'Test Report',
                'Summary' : 'Summary Report' }
    return '%s %s' % (name, endings[type_])


class _BaseSettings:

    _cli_opts = { 'Name'             : ('name', None),
                  'Doc'              : ('doc', None),
                  'Metadata'         : ('metadata', []),
                  'TestNames'        : ('test', []),
                  'SuiteNames'       : ('suite', []),
                  'SetTag'           : ('settag', []),
                  'Include'          : ('include', []),
                  'Exclude'          : ('exclude', []),
                  'Critical'         : ('critical', None),
                  'NonCritical'      : ('noncritical', None),
                  'OutputDir'        : ('outputdir', '.'),
                  'Log'              : ('log', 'log.html'),
                  'Report'           : ('report', 'report.html'),
                  'Summary'          : ('summary', 'NONE'),
                  'SplitOutputs'     : ('splitoutputs', -1),
                  'TimestampOutputs' : ('timestampoutputs', False),
                  'LogTitle'         : ('logtitle', None),
                  'ReportTitle'      : ('reporttitle', None),
                  'SummaryTitle'     : ('summarytitle', None),
                  'SuiteStatLevel'   : ('suitestatlevel', -1),
                  'TagStatInclude'   : ('tagstatinclude', []),
                  'TagStatExclude'   : ('tagstatexclude', []),
                  'TagStatCombine'   : ('tagstatcombine', []),
                  'TagDoc'           : ('tagdoc', []),
                  'TagStatLink'      : ('tagstatlink', []),
                  'LogLevel'         : ('loglevel', 'INFO'),
                  'MonitorWidth'     : ('monitorwidth', 78),
                  'MonitorColors'    : ('monitorcolors', 'ON') }

    _deprecated = {}

    def __init__(self, options={}, log=True):
        self._opts = {}
        self._cli_opts.update(self._extra_cli_opts)
        self._process_deprecated_cli_opts(options)
        self._process_cli_opts(options)
        if log: LOGGER.info('Settings:\n%s' % self)

    def _process_cli_opts(self, opts):
        for name, (cli_name, default) in self._cli_opts.items():
            try:
                value = opts[cli_name]
                if value in [None, []]:
                    raise KeyError
            except KeyError:
                value = default
            self[name] = value

    def _process_deprecated_cli_opts(self, opts):
        for oldname, newname in self._deprecated.items():
            if oldname not in opts or opts[oldname] in [None, []]:
                continue
            if newname:
                LOGGER.warn("Option '--%s' is deprecated. Use '--%s' instead."
                            % (oldname, newname))
                opts[newname] = opts[oldname]
            else:
                LOGGER.error("Option '--%s' has been removed." % oldname)

    def __setitem__(self, name, value):
        if not self._cli_opts.has_key(name):
            raise KeyError("Non-existing settings '%s'" % name)
        elif name in ['Name', 'Doc'] and value:
            value = value.replace('_', ' ')
        elif name == 'Metadata' and value:
            value = [v.replace('_', ' ') for v in value]
        elif name == 'TagDoc':
            value = [ item.replace('_', ' ') for item in value ]
        elif name in ['Include', 'Exclude', 'TagStatCombine']:
            value = [ item.replace('AND','&')  for item in value ]
        elif name in self._optional_outputs and utils.eq(value, 'NONE'):
            value = 'NONE'
        elif name == 'OutputDir':
            value = utils.normpath(value)
        elif name in ['SplitOutputs', 'SuiteStatLevel', 'MonitorWidth']:
            value = self._convert_to_integer(name, value)
        elif name in ['Listeners', 'VariableFiles']:
            value = [ self._split_args_from_name(item) for item in value ]
        elif name == 'TagStatLink':
            value = self._process_tag_stat_link(value)
        elif name == 'RemoveKeywords':
            value = value.upper()
        elif name == 'MonitorColors':
            value = (utils.eq(value, 'ON') and (not os.sep == '\\')) \
                         or utils.eq(value, 'FORCE')
        self._opts[name] = value

    def __getitem__(self, name):
        if not self._cli_opts.has_key(name):
            raise KeyError("Non-existing setting '%s'" % name)
        elif name in ['Output', 'Log', 'Report', 'Summary', 'DebugFile']:
            return self._get_output_file(name)
        elif name in ['LogTitle', 'ReportTitle', 'SummaryTitle']:
            return self._get_output_title(name)
        return self._opts[name]

    def _get_output_title(self, type_):
        value = self._opts[type_]
        if value is not None:
            return value.replace('_', ' ')
        return get_title(type_.replace('Title',''), self['Name'])

    def _get_output_file(self, type_):
        """Returns path of the requested ouput file and creates needed dirs.

        Type can be 'Output', 'Log', 'Report' or 'Summary'.
{'fraction_non_alphanumeric': 0.13358133243151843, 'fraction_numerical': 0.002705444707473791, 'mean_word_length': 1.8278747310542673, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '487616', 'n_tokens_mistral': 3326, 'n_tokens_neox': 3220, 'n_words': 893}