def _configure_logger(verbose=0, log_config=None, log_file=None):

    if log_config:
        with open(log_config, 'r') as f:
            logging.Logger.manager = debug_tools.Debugger.manager
            logging.Logger.manager.setLoggerClass(debug_tools.Debugger)

            logging.config.dictConfig(json.load(f))
    else:
        log = debug_tools.getLogger(1,
                                    "pyls",
                                    file=log_file,
                                    mode=10,
                                    rotation=50,
                                    level=True)

        if verbose == 0:
            level = "WARNING"
        elif verbose == 1:
            level = "INFO"
        elif verbose >= 2:
            level = "DEBUG"

        log.setLevel(level)
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import re
import os

import datetime
import unittest

from debug_tools import getLogger
log = getLogger(os.environ.get('REACT_APP_GITHUB_RESEARCHER_DEBUG_LEVEL', 1),
                __name__)


class TimeSpentTestCase(unittest.TestCase):
    """
        https://stackoverflow.com/questions/9502516/how-to-know-time-spent-on-each-test-when-using-unittest
    """
    def setUp(self):
        # https://stackoverflow.com/questions/4219717/how-to-assert-output-with-nosetest-unittest-in-python
        self.maxDiff = None
        log.newline()
        super().setUp()
        self.startTime = datetime.datetime.now()

    def tearDown(self):
        timespent = datetime.datetime.now() - self.startTime
        # log.clean( "%s: %s seconds", self.id(), timespent )
        log.clean("%s seconds", timespent)
        super().tearDown()
"""
Iterates through all subdirectories of the current directory where this script file is on, but do not
recurse into them.

1. https://stackoverflow.com/questions/23937436/add-subdirectory-of-remote-repo-with-git-subtree
1. https://stackoverflow.com/questions/20102594/git-subtree-push-squash-does-not-squash
1. https://stackoverflow.com/questions/9614255/git-subtree-push-squash-needs-a-long-time-and-it-is-getting-longer-over-time
1. https://stackoverflow.com/questions/16134975/reduce-increasing-time-to-push-a-subtree
1. https://stackoverflow.com/questions/10081681/git-subtree-push-changes-back-to-subtree-project
1. https://stackoverflow.com/questions/26928299/why-does-git-subtree-push-always-list-hundreds-of-commits
1. https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt
1. https://github.com/git/git/blob/master/contrib/subtree/git-subtree.sh
"""

from debug_tools import getLogger
log = getLogger( __name__ )

current_directory = os.path.dirname( os.path.realpath(__file__) )
log( 1, 'directory walk %s', current_directory )


# If `TYPE` is equals to ProcessType.CREATE_README, it will not git for subtree operations but will
# create `README.md` and `LICENSE` on all repositories. Notice, an existing `README.md` will be
# overridden.
TYPE = 1

# The maximum count of repositories to to process when calling this batch script.
maximum_process_limit = 1000

# GitHub token with full repository access
token = "Authorization: token 1231231241231231251231231232131231223123"
from channel_manager import channel_installer

# When there is an ImportError, means that Package Control is installed instead of PackagesManager,
# or vice-versa. Which means we cannot do nothing as this is only compatible with PackagesManager.
try:
    from package_control.thread_progress import ThreadProgress

except ImportError:
    from PackagesManager.package_control.thread_progress import ThreadProgress

from debug_tools import getLogger
from debug_tools.utilities import wrap_text

# Debugger settings: 0 - disabled, 127 - enabled
log = getLogger(127, __name__)

# log( 2, "..." )
# log( 2, "..." )
# log( 2, "Debugging" )
# log( 2, "PACKAGE_ROOT_DIRECTORY: " + g_settings.PACKAGE_ROOT_DIRECTORY )


def main(channel_settings):
    """
        Before calling this installer, the `Package Control` user settings file, must have the
        Studio Channel file set before the default channel key `channels`.

        Also the current `Package Control` cache must be cleaned, ensuring it is downloading and
        using the Studio Channel repositories/channel list.
    """
# Copyright 2017 Palantir Technologies, Inc.
import debug_tools
import os
from pyls._utils import find_parents
from .source import ConfigSource

log = debug_tools.getLogger(__name__)

CONFIG_KEY = 'flake8'
PROJECT_CONFIGS = ['.flake8', 'setup.cfg', 'tox.ini']

OPTIONS = [
    # mccabe
    ('max-complexity', 'plugins.mccabe.threshold', int),
    # pycodestyle
    ('exclude', 'plugins.pycodestyle.exclude', list),
    ('filename', 'plugins.pycodestyle.filename', list),
    ('hang-closing', 'plugins.pycodestyle.hangClosing', bool),
    ('ignore', 'plugins.pycodestyle.ignore', list),
    ('max-line-length', 'plugins.pycodestyle.maxLineLength', int),
    ('select', 'plugins.pycodestyle.select', list),
]


class Flake8Config(ConfigSource):
    """Parse flake8 configurations."""
    def user_config(self):
        config_file = self._user_config_file()
        config = self.read_config_from_files([config_file])
        return self.parse_config(config, CONFIG_KEY, OPTIONS)
try:
    # To run this file, run on the Sublime Text console:
    # import imp; import AmxxEditor.tests.stock_functions_include; imp.reload( AmxxEditor.tests.stock_functions_include )
    import sublime_api

except (ImportError):
    assert_path(
        os.path.join(
            os.path.dirname(
                os.path.dirname(os.path.dirname(os.path.realpath(__file__))))))

# Import and reload
from AmxxEditor.AmxxEditor import PawnParse
from AmxxEditor.AmxxEditor import Node

log = getLogger(__name__.split('.')[-1], 127)

current_directory = os.path.dirname(__file__)
file_name = os.path.join(current_directory, 'testing',
                         'stock_functions_include.inc')
log(1, "file_name: %s", file_name)

node = Node(file_name)
pawnParse = PawnParse()

with open(node.file_name) as file:
    pawnParse.start(file, node)

log(1, "func_list: \n%s", pprint.pformat(node.funcs_list))
log(1, "words_list: \n%s", pprint.pformat(node.words_list))
Beispiel #7
0
# Copyright 2017 Palantir Technologies, Inc.
import contextlib
import debug_tools
import os
import re
import sys

import pydocstyle
from pyls import hookimpl, lsp

log = debug_tools.getLogger(__name__)

# PyDocstyle is a little verbose in debug message
pydocstyle_logger = debug_tools.getLogger("pyls." + pydocstyle.utils.__name__)
pydocstyle_logger.setLevel("INFO")

DEFAULT_MATCH_RE = pydocstyle.config.ConfigurationParser.DEFAULT_MATCH_RE
DEFAULT_MATCH_DIR_RE = pydocstyle.config.ConfigurationParser.DEFAULT_MATCH_DIR_RE


@hookimpl
def pyls_settings():
    # Default pydocstyle to disabled
    return {'plugins': {'pydocstyle': {'enabled': False}}}


@hookimpl
def pyls_lint(config, document):
    settings = config.plugin_settings('pydocstyle')
    log.debug("Got pydocstyle settings: %s", settings)
Beispiel #8
0
import os
import re
import time

import sublime
import sublime_plugin
import threading

from sublime_plugin import TextCommand
from sublime import error_message, version

import plantuml_connection

from debug_tools import getLogger
log = getLogger(1, __package__)

try:
    from .diagram import setup, process
except ValueError:
    from diagram import setup, process

g_is_there_new_changes = False

try:
    all_views_active

except NameError:
    all_views_active = {}

#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################################
#

import re
import pprint
import pushdown
import dominate
import debug_tools

from pushdown import Tree
from collections import OrderedDict

from debug_tools import getLogger
log = getLogger(1, __name__, time=0, tick=0, msecs=0)


def escape_html(input_text):
    return dominate.util.escape(input_text,
                                quote=False).replace("\n", "<br />")


def get_div_doc(input_text):
    return '<span grammar_scope="none" theme_scope="none">%s</span>' % escape_html(
        input_text)


def get_font_doc(input_text, color, grammar_scope, theme_scope):
    return '<font color="%s" grammar_scope="%s" theme_scope="%s">%s</font>' % (
        color, grammar_scope, theme_scope, escape_html(input_text))
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os

from PyQt5 import QtGui
from PyQt5 import QtCore

from PyQt5.QtCore import Qt
from debug_tools import getLogger

from .utilities import ignore_exceptions

# level 4 - Abstract Syntax Tree Parsing
log = getLogger(127 - 4, __name__)


class RunFunctionAsyncThread(QtCore.QThread):
    """
        Dynamically updates the user interface with new sentences generated by the program.
    """

    ## Send the given `function` full or partial results to the `results_dialog` window
    send_string_signal = QtCore.pyqtSignal([str])

    ## Disables the `results_dialog` window stop button when the function has finished it given task
    disable_stop_button_signal = QtCore.pyqtSignal()

    ## Save the current caret/cursor position to restore it later
    save_cursor_position_signal = QtCore.pyqtSignal()
Beispiel #11
0
Delete the default main menu for the `Amxmodx` package, because when it updates
we would get duplicated menu entries as the default menu for that package is set
on the `User/Main.sublime-menu` file.

"""

import os
import sublime
import sublime_plugin

from debug_tools import getLogger
from debug_tools.third_part import load_package_file_as_binary

# Debugger settings: 0 - disabled, 127 - enabled
log = getLogger(1, __name__)

AMXX_CHANNEL = "AmxxChannel"
MENU_FILE_NAME = "Main.sublime-menu"

CURRENT_PACKAGE_NAME = __package__
PACKAGE_ROOT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))


def plugin_loaded():
    global USER_MENU_FILES_DIRECTORY
    USER_MENU_FILES_DIRECTORY = os.path.join(sublime.packages_path(), "User",
                                             CURRENT_PACKAGE_NAME)
    install_amxx_editor_menu_on_first_run()

Beispiel #12
0
import os
import json
import requests

import sys
import traceback
import functools

import flask
import flask_cors

from debug_tools import getLogger
from debug_tools.utilities import wrap_text

log = getLogger(os.environ.get('REACT_APP_GITHUB_RESEARCHER_DEBUG_LEVEL'),
                'researcher')

# https://gist.github.com/gbaman/b3137e18c739e0cf98539bf4ec4366ad
graphql_url = "https://api.github.com/graphql"
headers = {
    "Authorization":
    f"Bearer {os.environ.get( 'REACT_APP_GITHUB_RESEARCHER_TOKEN' )}"
}

# https://stackoverflow.com/questions/15117416/capture-arbitrary-path-in-flask-route
# https://stackoverflow.com/questions/44209978/serving-a-front-end-created-with-create-react-app-with-flask
APP = flask.Flask(
    "github_repository_researcher",
    static_folder="reactfrontend/build/static",
    template_folder="reactfrontend/build",
)
Beispiel #13
0
from user_interface.integer_input_dialog import IntegerInputDialog

from user_interface.utilities import trimMessage
from user_interface.utilities import ignore_exceptions
from user_interface.utilities import get_screen_center
from user_interface.utilities import setTextWithoutCleaningHistory

from user_interface.run_function_async import run_function_async
from debug_tools import getLogger

# Enable debug messages: ( bitwise )
# 0   - Disabled debugging
# 1   - Basic logging messages
# 32  - Boxes geometries
# 127 - All debugging levels at the same time.
log = getLogger(127 - 32,
                os.path.basename(os.path.dirname(os.path.abspath(__file__))))
log(1, "Importing " + __name__)


def main():
    app = QtWidgets.QApplication(sys.argv)
    programWindow = ProgramWindow()

    log(1, "Opening main window...")
    programWindow.show()
    exit_code = app.exec_()

    log(1, "Closing main window...")
    log(1, "exit_code: %s", exit_code)
    sys.exit(exit_code)

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import os
import shlex
import subprocess

"""
Iterates through all subdirectories of the current directory where this script file is on, but do not
recurse into them. Then, replace the last commit message, if matches the defined pattern.
"""

from debug_tools import getLogger
log = getLogger( __name__ )

current_directory = os.path.dirname( os.path.realpath(__file__) )
# current_directory = os.path.join( current_directory, '..', 'Packages' )

log( 1, 'directory walk %s', current_directory )
maximum_process_limit = 1000


def run_command(absolute_path, command_name):
    log( 1, "Running", command_name, absolute_path )
    command = shlex.split( command_name )

    command_line_interface = subprocess.Popen( command, stdout=subprocess.PIPE, cwd=absolute_path )
    output = command_line_interface.communicate()[0]
Beispiel #15
0
# from channel_manager import channel_manager_tests; channel_manager_tests.main()

# # How to reload a Sublime Text dependency?
# # https://github.com/randy3k/AutomaticPackageReloader/issues/12
# sublime_plugin.reload_plugin( "channel_manager.channel_installer" )
# sublime_plugin.reload_plugin( "channel_manager.channel_utilities" )
# sublime_plugin.reload_plugin( "channel_manager.channel_manager" )
# sublime_plugin.reload_plugin( "channel_manager.channel_manager_tests" )

from debug_tools import getLogger
from debug_tools.third_part import load_data_file
from debug_tools.third_part import write_data_file

# Debugger settings: 0 - disabled, 127 - enabled
log = getLogger(
    1, g_settings.CURRENT_PACKAGE_NAME + "." +
    os.path.basename(__file__).split(".")[0])

log(2, "...")
log(2, "...")
log(2, "Debugging")
log(2, "PACKAGE_ROOT_DIRECTORY: " + g_settings.PACKAGE_ROOT_DIRECTORY)


class DevelopmentVersionBaseCommand(sublime_plugin.ApplicationCommand):
    def is_enabled(self):
        return is_channel_installed() and is_development_version()


class StudioChannelExtractDefaultPackages(DevelopmentVersionBaseCommand):
    def run(self):
Beispiel #16
0
"""
Utilities for parsing text position in python code, through AST,
and returning a test class/method name.
"""
from __future__ import print_function
import os
import subprocess

import sublime
from debug_tools import getLogger

from .. import test_parser

log = getLogger(1, __name__, trimname=__package__)


def DEBUG(value=None):
    settings = sublime.load_settings("TestPlier.sublime-settings")
    if value is None:
        return settings.get('debug', False)

    settings['debug'] = value
    settings = sublime.save_settings("TestPlier.sublime-settings")


def get_first_selection(view):
    view.settings().set('__vi_external_disable', True)
    selection = list(view.sel())
    view.settings().set('__vi_external_disable', False)
    if not selection:
        # cursor not in view
except:
    print(
        "Please, install the Python 3 packages `pushdown` and `debug_tools`!")
    print("You can run these commands:")
    print("    pip3 install pushdown")
    print("    pip3 install debug_tools")
    print("")
    exit(1)

from pushdown import Lark
from pushdown import Tree

from debug_tools import getLogger
from debug_tools.utilities import wrap_text

log = getLogger(3)


def main():
    sys.setrecursionlimit(10000)
    # unittest.main()

    current_directory = os.path.dirname(os.path.realpath(__file__))
    parent_directory = os.path.dirname(current_directory)
    parse_all_files(parent_directory)


class BasicUnitTests(unittest.TestCase):
    def test_simplest_valid_input(self):
        results = remove_lang_tag(r"\lang{some}{thing}")
        self.assertEqual(wrap_text("""