id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,900
|
__init__.py
|
rpm-software-management_dnf/doc/__init__.py
|
# __init__.py
# DNF documentation package.
#
# Copyright (C) 2012-2013 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
| 1,005
|
Python
|
.py
| 19
| 51.894737
| 77
| 0.780933
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,901
|
install_extension.py
|
rpm-software-management_dnf/doc/examples/install_extension.py
|
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
"""An extension that ensures that given features are present."""
import sys
import dnf
import dnf.module
import dnf.rpm
if __name__ == '__main__':
FTR_SPECS = {'acpi-1.7-10.fc29.x86_64'} # <-- SET YOUR FEATURES HERE.
RPM_SPECS = {'./acpi-1.7-10.fc29.x86_64.rpm'} # <-- SET YOUR RPMS HERE.
GRP_SPECS = {'kde-desktop'} # <-- SET YOUR GROUPS HERE.
MODULE_SPEC = {"nodejs:10/default"} # <-- SET YOUR MODULES HERE.
with dnf.Base() as base:
# Substitutions are needed for correct interpretation of repo files.
RELEASEVER = dnf.rpm.detect_releasever(base.conf.installroot)
base.conf.substitutions['releasever'] = RELEASEVER
# Repositories are needed if we want to install anything.
base.read_all_repos()
# A sack is required by marking methods and dependency resolving.
base.fill_sack()
# Feature marking methods set the user request.
for ftr_spec in FTR_SPECS:
try:
base.install(ftr_spec)
except dnf.exceptions.MarkingError:
sys.exit('Feature(s) cannot be found: ' + ftr_spec)
# Package marking methods set the user request.
for pkg in base.add_remote_rpms(RPM_SPECS, strict=False):
try:
base.package_install(pkg, strict=False)
except dnf.exceptions.MarkingError:
sys.exit('RPM cannot be found: ' + pkg)
# Comps data reading initializes the base.comps attribute.
if GRP_SPECS:
base.read_comps(arch_filter=True)
# Group marking methods set the user request.
if MODULE_SPEC:
module_base = dnf.module.module_base.ModuleBase(base)
module_base.install(MODULE_SPEC, strict=False)
for grp_spec in GRP_SPECS:
group = base.comps.group_by_pattern(grp_spec)
if not group:
sys.exit('Group cannot be found: ' + grp_spec)
base.group_install(group.id, ['mandatory', 'default'])
# Resolving finds a transaction that allows the packages installation.
try:
base.resolve()
except dnf.exceptions.DepsolveError:
sys.exit('Dependencies cannot be resolved.')
# The packages to be installed must be downloaded first.
try:
base.download_packages(base.transaction.install_set)
except dnf.exceptions.DownloadError:
sys.exit('Required package cannot be downloaded.')
# The request can finally be fulfilled.
base.do_transaction()
| 3,519
|
Python
|
.py
| 69
| 43.231884
| 78
| 0.674121
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,902
|
install_plugin.py
|
rpm-software-management_dnf/doc/examples/install_plugin.py
|
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
"""A plugin that ensures that given features are present."""
import dnf.cli
from dnf.i18n import _
from dnf.cli.option_parser import OptionParser
# The parent class allows registration to the CLI manager.
class Command(dnf.cli.Command):
"""A command that ensures that given features are present."""
# An alias is needed to invoke the command from command line.
aliases = ['foo'] # <-- SET YOUR ALIAS HERE.
def configure(self):
"""Setup the demands."""
# Repositories are needed if we want to install anything.
self.cli.demands.available_repos = True
# A sack is required by marking methods and dependency resolving.
self.cli.demands.sack_activation = True
# Resolving performs a transaction that installs the packages.
self.cli.demands.resolving = True
# Based on the system, privileges are required to do an installation.
self.cli.demands.root_user = True # <-- SET YOUR FLAG HERE.
@staticmethod
def set_argparser(parser):
"""Parse command line arguments."""
parser.add_argument('package', nargs='+', metavar=_('PACKAGE'),
action=OptionParser.ParseSpecGroupFileCallback,
help=_('Package to install'))
def run(self):
"""Run the command."""
# Feature marking methods set the user request.
for ftr_spec in self.opts.pkg_specs:
try:
self.base.install(ftr_spec)
except dnf.exceptions.MarkingError:
raise dnf.exceptions.Error('feature(s) not found: ' + ftr_spec)
# Package marking methods set the user request.
for pkg in self.base.add_remote_rpms(self.opts.filenames, strict=False):
try:
self.base.package_install(pkg, strict=False)
except dnf.exceptions.MarkingError as e:
raise dnf.exceptions.Error(e)
# Comps data reading initializes the base.comps attribute.
if self.opts.grp_specs:
self.base.read_comps(arch_filter=True)
# Group marking methods set the user request.
for grp_spec in self.opts.grp_specs:
group = self.base.comps.group_by_pattern(grp_spec)
if not group:
raise dnf.exceptions.Error('group not found: ' + grp_spec)
self.base.group_install(group.id, ['mandatory', 'default'])
# Every plugin must be a subclass of dnf.Plugin.
class Plugin(dnf.Plugin):
"""A plugin that registers our custom command."""
# Every plugin must provide its name.
name = 'foo' # <-- SET YOUR NAME HERE.
# Every plugin must provide its own initialization function.
def __init__(self, base, cli):
"""Initialize the plugin."""
super(Plugin, self).__init__(base, cli)
if cli:
cli.register_command(Command)
| 3,836
|
Python
|
.py
| 74
| 44.216216
| 80
| 0.678495
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,903
|
list_obsoletes_plugin.py
|
rpm-software-management_dnf/doc/examples/list_obsoletes_plugin.py
|
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
"""A plugin that lists installed packages that are obsoleted by any available package"""
from dnf.i18n import _
import dnf
import dnf.cli
# If you only plan to create a new dnf subcommand in a plugin
# you can use @dnf.plugin.register_command decorator instead of creating
# a Plugin class which only registers the command
# (for full-fledged Plugin class see examples/install_plugin.py)
@dnf.plugin.register_command
class Command(dnf.cli.Command):
"""A command that lists packages installed on the system that are
obsoleted by packages in any known repository."""
# An alias is needed to invoke the command from command line.
aliases = ['foo'] # <-- SET YOUR ALIAS HERE.
@staticmethod
def set_argparser(parser):
parser.add_argument("package", nargs='*', metavar=_('PACKAGE'))
def configure(self):
"""Setup the demands."""
# Repositories serve as sources of information about packages.
self.cli.demands.available_repos = True
# A sack is needed for querying.
self.cli.demands.sack_activation = True
def run(self):
"""Run the command."""
obs_tuples = []
# A query matches all available packages
q = self.base.sack.query()
if not self.opts.package:
# Narrow down query to match only installed packages
inst = q.installed()
# A dictionary containing list of obsoleted packages
for new in q.filter(obsoletes=inst):
obs_reldeps = new.obsoletes
obsoleted = inst.filter(provides=obs_reldeps).run()
obs_tuples.extend([(new, old) for old in obsoleted])
else:
for pkg_spec in self.opts.package:
# A subject serves for parsing package format from user input
subj = dnf.subject.Subject(pkg_spec)
# A query restricted to installed packages matching given subject
inst = subj.get_best_query(self.base.sack).installed()
for new in q.filter(obsoletes=inst):
obs_reldeps = new.obsoletes
obsoleted = inst.filter(provides=obs_reldeps).run()
obs_tuples.extend([(new, old) for old in obsoleted])
if not obs_tuples:
raise dnf.exceptions.Error('No matching Packages to list')
for (new, old) in obs_tuples:
print('%s.%s obsoletes %s.%s' %
(new.name, new.arch, old.name, old.arch))
| 3,463
|
Python
|
.py
| 66
| 44.621212
| 88
| 0.678593
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,904
|
list_extras_extension.py
|
rpm-software-management_dnf/doc/examples/list_extras_extension.py
|
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
"""An extension that lists installed packages not available
in any remote repository.
"""
import dnf
if __name__ == '__main__':
with dnf.Base() as base:
# Repositories serve as sources of information about packages.
base.read_all_repos()
# A sack is needed for querying.
base.fill_sack()
# A query matches all packages in sack
q = base.sack.query()
# Derived query matches only available packages
q_avail = q.available()
# Derived query matches only installed packages
q_inst = q.installed()
available = q_avail.run()
for pkg in q_inst.run():
if pkg not in available:
print(str(pkg))
| 1,676
|
Python
|
.py
| 35
| 42.914286
| 77
| 0.714023
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,905
|
dnf_pylint
|
rpm-software-management_dnf/scripts/dnf_pylint
|
#!/usr/bin/bash
TEMP=`getopt -o s -n dnf_pylint -- "$@"`
[[ $? -eq 0 ]] || exit 1;
eval set -- "$TEMP"
TEMPLATE=--msg-template='{msg_id}: {module}:{line:3d},{column}: {msg}'
while true ; do
case "$1" in
-s) TEMPLATE=--msg-template='{msg_id}: {module}: {msg}'; shift ;;
--) shift ; break ;;
esac
done
THIS_DIR=$(readlink -f $(dirname $0))
FALSE_POSITIVES=$THIS_DIR/pylint_false_positives
DISABLED=""
function disable()
{
DISABLED="$DISABLED $1"
}
disable "-d C0111" # docstrings
disable "-d I0011" # locally disabled warnings
disable "-d R0801" # similar lines
disable "-d R0904" # too many public methods
disable "-d R0911" # too many return statements
disable "-d R0912" # too many branches
disable "-d R0913" # too many arguments
disable "-d R0903" # too few public methods
disable "-d W0141" # used builtin 'map' function
disable "-d W0142" # used star magic
disable "-d W0212" # access to a protected member
VAR_NAMES='--variable-rgx=[a-z_][a-z0-9_]*$'
DUMMY_NAMES='--dummy-variables-rgx=_.*'
MISC=--max-line-length=82
pylint --rcfile=/dev/null --reports=n $DISABLED "$VAR_NAMES" "$DUMMY_NAMES" $MISC $* \
"$TEMPLATE" \
| egrep -v -f $FALSE_POSITIVES
| 1,185
|
Python
|
.py
| 35
| 32
| 86
| 0.676883
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,906
|
sanitize_po_files.py
|
rpm-software-management_dnf/scripts/sanitize_po_files.py
|
#!/usr/bin/python3
# script to get rid of
# "'msgid' and 'msgstr' entries do not both begin/end with '\n'"
# error messages during .po to .mo files conversion via msgfmt tool
#
# 'polib' module is needed for run: https://pypi.python.org/pypi/polib
#
# usage: python3 sanitize_po_files.py [po_file...]
#
# in order to update translations from zanata, do:
# * cmake .
# * make gettext-update
# * git add po/*.po
# * ./scripts/sanitize_po_files.py po/*.po
# * git commit -m "zanata update"
import polib
import re
import sys
def sanitize_po_file(po_file):
print("Processing", po_file)
po = polib.pofile(po_file)
for entry in po:
msgid_without_indents = entry.msgid.strip()
msgstr_without_indents = entry.msgstr.strip()
entry.msgstr = entry.msgid.replace(
msgid_without_indents, msgstr_without_indents)
if re.match(r"^\s+$", entry.msgstr):
entry.msgstr = ""
if entry.msgid_plural:
msgid_plural_without_indents = entry.msgid_plural.strip()
for i in entry.msgstr_plural.keys():
msgstr_plural_without_indents = entry.msgstr_plural[i].strip()
entry.msgstr_plural[i] = entry.msgid_plural.replace(
msgid_plural_without_indents,
msgstr_plural_without_indents)
if re.match(r"^\s+$", entry.msgstr_plural[i]):
entry.msgstr_plural[i] = ""
po.save()
if __name__ == "__main__":
for po_file in sys.argv[1:]:
sanitize_po_file(po_file)
| 1,551
|
Python
|
.py
| 41
| 31.195122
| 78
| 0.625416
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,907
|
update_releasenotes.py
|
rpm-software-management_dnf/scripts/update_releasenotes.py
|
#!/usr/bin/python2
#
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
r"""A script intended to update release notes.
Works on Python >= 2.7 and < 3.0.
This module, when run as a script, provides a command line interface.
The interface usage is::
usage: prog [-h]
Extend the list of issues of the next version in release notes. It
updates the release notes found in the DNF repository which contains
this module. The module location is obtained from the __file__
variable. The version number is parsed from the spec file. If the
release notes already contains given issue, it is not added again.
Otherwise, it is added to the beginning of the list. If the release
notes does not contain the next version, a new section is appended
right before the first section. The diff between the new release
notes and the Git index is printed to the standard error stream. The
message starts with "INFO Update finished. See the diff to the Git
index: ".
optional arguments:
-h, --help show this help message and exit
If the version is already released or if another error occurs the
exit status is non-zero.
:var LOGGER: the logger used by this script
:type LOGGER: logging.Logger
:var SPEC_FN: a name of the DNF spec file relative to the working
directory of the Git repository which contains this script
:type SPEC_FN: str
:var TAG_PAT: a string pattern of DNF tags where the "{version}" field
should be replaced with the given version of DNF
:type TAG_PAT: str
:var ISSUE_RE: a regular expression matching numbers of resolved issues
in the first line of a commit message
:type ISSUE_RE: re.RegexObject
:var RELATED_RE: a regular expression matching numbers of related issues
in a commit message
:type RELATED_RE: re.RegexObject
:var SIMILAR_RE: a regular expression matching numbers which look like a
number of an issue referred in a commit message
:type SIMILAR_RE: re.RegexObject
:var NOTES_FN: a name of the DNF release notes file relative to the
working directory of the Git repository which contains this script
:type NOTES_FN: str
:var TITLE_PAT: a string pattern of a DNF release notes section title
(including a trailing "\n") where the "{version}" field should be
replaced with the given release version
:type TITLE_PAT: str
:var ISSUE_PAT: a string pattern of a reference to a resolved issue in
DNF release notes (including a trailing "\n") where the "{number}"
field should be replaced with the number of the given issue
:type ISSUE_PAT: str
:var OVERLINE_RE: a regular expression matching a section title overline
in a line of DNF release notes
:type OVERLINE_RE: re.RegexObject
:var TITLE_RE_PAT: a string pattern of a regular expression matching a
section title in a line of DNF release notes where the "{maxlen}"
field should be replaced with the maximum expected length of the
release version
:type TITLE_RE_PAT: str
"""
from __future__ import absolute_import
import argparse
import contextlib
import io
import itertools
import logging
import os
import re
import shutil
import sys
import tempfile
import unittest
import git
import rpm
import tests.mock
LOGGER = logging.getLogger(sys.argv[0])
SPEC_FN = 'dnf.spec'
TAG_PAT = 'dnf-{version}-1'
ISSUE_RE = re.compile(ur'(?<!Related: )RhBug:(\d+)')
RELATED_RE = re.compile(ur'Related: RhBug:(\d+)')
SIMILAR_RE = re.compile(ur'\d{6,}')
NOTES_FN = os.path.join('doc', 'release_notes.rst')
TITLE_PAT = '{version} Release Notes\n'
ISSUE_PAT = '* :rhbug:`{number}`\n'
OVERLINE_RE = re.compile('^(=+)\n$')
TITLE_RE_PAT = '^(.{{,{maxlen}}}) Release Notes\n$'
@contextlib.contextmanager
def _safe_overwrite(name):
"""Open a file in order to overwrite it safely.
Until the context manager successfully exits, the file remains
unchanged.
:param name: name of the file
:type name: str
:returns: a context manager that returns a readable text file object
intended to read the content of the file and a writable text
file object intended to write the new content of the file
:rtype: contextmanager[tuple[file, file]]
:raises exceptions.IOError: if the file cannot be opened
"""
with open(name, 'rt+') as file_, tempfile.TemporaryFile('wt+') as tmpfile:
yield file_, tmpfile
tmpfile.seek(0)
file_.seek(0)
shutil.copyfileobj(tmpfile, file_)
def detect_repository():
"""Detect the DNF Git repository which contains this module.
The module location is obtained from :const:`__file__`.
:returns: the repository
:rtype: git.Repo
"""
dirname = os.path.dirname(__file__)
# FIXME remove this once we can get rid of supporting GitPython < 0.3.5
try:
return git.Repo(dirname, search_parent_directories=True)
except TypeError:
return git.Repo(dirname)
def detect_version(repository):
"""Detect the DNF version from its spec file.
:param repository: a non-bare DNF repository which contains the spec
file
:type repository: git.Repo
:returns: the detected version
:rtype: str
"""
filename = os.path.join(repository.working_dir, SPEC_FN)
return rpm.spec(filename).sourceHeader[rpm.RPMTAG_VERSION]
def find_tag(repository, version):
"""Find the Git tag corresponding to a DNF version.
:param repository: a DNF repository
:type repository: git.Repo
:returns: the name of the tag
:rtype: str | None
"""
tagname = TAG_PAT.format(version=version)
return tagname if tagname in repository.tags else None
def iter_unreleased_commits(repository):
"""Iterate over the commits that were not tagged as a release.
:param repository: a repository
:type repository: git.Repo
:returns: a generator yielding the commits
:rtype: generator[git.Commit]
"""
tagshas = {tag.commit.hexsha for tag in repository.tags}
for commit in repository.iter_commits():
if commit.hexsha in tagshas:
# FIXME encode() once we get rid of supporting GitPython < 0.3.4
LOGGER.debug(
'Unreleased commits iteration stopped on the first tagged '
'commit: %s', commit.hexsha.encode())
break
yield commit
def parse_issues(commits):
"""Parse the numbers of the resolved DNF issues from commit messages.
:param commits: the DNF commits
:type commits: collections.Iterable[git.Commit]
:returns: a generator yielding the issue numbers
:rtype: generator[str]
"""
for commit in commits:
firstline = commit.message.splitlines()[0]
valid = {match.group(1) for match in ISSUE_RE.finditer(firstline)}
for issue in valid:
issue = issue.encode()
# FIXME decode() once we get rid of supporting GitPython < 0.3.4
LOGGER.debug(
'Recognized %s in commit %s.', issue,
commit.hexsha.decode().encode())
yield issue.encode()
valid |= {mat.group(1) for mat in RELATED_RE.finditer(commit.message)}
for match in SIMILAR_RE.finditer(commit.message):
if match.group(0) not in valid:
# FIXME decode once we get rid of supporting GitPython < 0.3.4
LOGGER.warning(
'Skipped %s in commit %s which looks like an issue '
'number.', match.group(0).encode(),
commit.hexsha.decode().encode())
def extend_releases(releases, version, issues):
r"""Extend the list of issues of a release version in release notes.
The issues are appended to the beginning of the list. If an issue is
already in the list of the release version, it is not added again.
If the release version is not found, the release version
(``version, '\n', issues, '\n'``) is yielded right before the first
release version in the release notes.
:param releases: the version, the description, the list of issue
numbers and the epilog for each release version in release notes
:type releases: collections.Iterable[tuple[str | None, str, list[str], str]]
:param version: the release version to be extended
:type version: str
:param issues: the issues to be added
:type issues: collections.Iterable[str]
:returns: a generator yielding the modified release notes
:rtype: generator[tuple[str | None, str, list[str], str]]
"""
releases, issues = list(releases), list(issues)
prepend = not any(release[0] == version for release in releases)
for version_, description, issues_, epilog in releases:
if prepend and version_ is not None:
yield version, '\n', issues, '\n'
prepend = False
elif version_ == version:
issues_ = issues_[:]
for issue in reversed(issues):
if issue not in issues_:
issues_.insert(0, issue)
yield version_, description, issues_, epilog
def format_release(version, description, issues, epilog):
"""Compose a string in form of DNF release notes from a release.
The order of issues is preserved.
:param version: the version of the release
:type version: str | None
:param description: the description of the release
:type description: str
:param issues: the list of issue numbers of the release
:type issues: list[str]
:param epilog: the epilog of the release
:type epilog: str
:returns: the formatted string
:rtype: str
"""
titlestr = ''
if version:
title = TITLE_PAT.format(version=version)
length = len(title) - 1
titlestr = '{}\n{}{}\n'.format('=' * length, title, '=' * length)
issuestr = ''.join(ISSUE_PAT.format(number=issue) for issue in issues)
return ''.join([titlestr, description, issuestr, epilog])
def update_notes():
r"""Extend the list of issues of the next version in release notes.
It updates the release notes found in the DNF repository which
contains this module. The module location is obtained from
:const:`__file__`. The version number is parsed from the spec file.
If the release notes already contains given issue, it is not added
again. Otherwise, it is added to the beginning of the list. If the
release notes does not contain the next version, a new section is
appended right before the first section. The diff between the new
release notes and the Git index is logged to :const:`.LOGGER` with
level :const:`INFO`. The message starts with "Update finished. See
the diff to the Git index:\n".
:raises exceptions.ValueError: if the version is already released
"""
repository = detect_repository()
LOGGER.info('Detected the repository at: %s', repository.working_dir)
notesfn = os.path.join(repository.working_dir, NOTES_FN)
version = detect_version(repository)
LOGGER.info('Detected DNF version (from the spec file): %s', version)
issues = parse_issues(iter_unreleased_commits(repository))
parser = ReleaseNotesParser()
tagname = find_tag(repository, version)
if tagname:
LOGGER.warning('Found a tag matching the current version: %s', tagname)
LOGGER.error('Extending an already released version is not allowed!')
raise ValueError('version already released')
with _safe_overwrite(notesfn) as (source, destination):
releases = extend_releases(parser.parse_lines(source), version, issues)
for version_, desc, issues_, epilog in releases:
destination.write(format_release(version_, desc, issues_, epilog))
diff = repository.index.diff(None, NOTES_FN, create_patch=True)[0].diff
LOGGER.info(
'Update finished. See the diff to the Git index:\n%s',
re.sub(r'^', ' ', diff, flags=re.M))
def main():
"""Start the main loop of the command line interface.
The root logger is configured to write DEBUG+ messages into the
directory where is this module located if not configured otherwise.
A handler that writes INFO+ messages to :data:`sys.stderr` is added
to :const:`.LOGGER`.
The interface usage is::
usage: prog [-h]
Extend the list of issues of the next version in release notes.
It updates the release notes found in the DNF repository which
contains this module. The module location is obtained from the
__file__ variable. The version number is parsed from the spec
file. If the release notes already contains given issue, it is
not added again. Otherwise, it is added to the beginning of the
list. If the release notes does not contain the next version, a
new section is appended right before the first section. The diff
between the new release notes and the Git index is printed to
the standard error stream. The message starts with "INFO Update
finished. See the diff to the Git index: ".
optional arguments:
-h, --help show this help message and exit
If the version is already released or if another error occurs
the exit status is non-zero.
:raises exceptions.SystemExit: with a non-zero exit status if an
error occurs
"""
logging.basicConfig(
filename='{}.log'.format(__file__),
filemode='wt',
format='%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:%(message)s',
datefmt='%Y%m%dT%H%M%S',
level=logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(levelname)s %(message)s'))
LOGGER.addHandler(handler)
argparser = argparse.ArgumentParser(
description='Extend the list of issues of the next version in release '
'notes. It updates the release notes found in the DNF '
'repository which contains this module. The module '
'location is obtained from the __file__ variable. The '
'version number is parsed from the spec file. If the '
'release notes already contains given issue, it is not '
'added again. Otherwise, it is added to the beginning of '
'the list. If the release notes does not contain the next '
'version, a new section is appended right before the first'
' section. The diff between the new release notes and the '
'Git index is printed to the standard error stream. The '
'message starts with "INFO Update finished. See the diff '
'to the Git index:\n".',
epilog='If the version is already released or if another error occurs '
'the exit status is non-zero.')
argparser.parse_args()
try:
update_notes()
except ValueError:
sys.exit(1)
class ReleaseNotesParser(object):
"""A class able to parse DNF release notes.
:ivar _needline: an expected line which represents the end of a
section title
:type _needline: str | None
:ivar _version: a version parsed from a potential next section title
:type _version: str | None
:ivar version: a version parsed from the last section title
:type version: str | None
:ivar description: lines parsed from the last section description
:type description: list[str]
:ivar issues: numbers of resolved issues parsed from the last
section
:type issues: list[str]
:ivar epilog: lines parsed from the last section epilog
:type epilog: list[str]
"""
def __init__(self):
"""Initialize the parser."""
super(ReleaseNotesParser, self).__init__()
self._needline = None
self._version = None
self.version = None
self.description = []
self.issues = []
self.epilog = []
@property
def _last_version(self):
"""The last parsed release version.
:returns: the version, the description, the list of issue
numbers and the epilog of the release
:rtype: tuple[str | None, str, list[str], str]
"""
return (
self.version,
''.join(self.description),
self.issues,
''.join(self.epilog))
def _cancel_title(self):
"""Cancel expectations of a next section title.
It modifies :attr:`_needline` and :attr:`_version`.
:returns: the old values of :attr:`_needline` and
:attr:`_version`
:rtype: tuple[str | None, str | None]
"""
needline, version = self._needline, self._version
self._needline = self._version = None
return needline, version
def _parse_overline(self, line):
"""Parse the overline of the next section title from a line.
It changes the state of the parser.
:param line: the line to be parsed
:type line: str
:returns: returns :data:`True` if the line contains an
overline, otherwise it returns :data:`False`
:rtype: bool
"""
match = OVERLINE_RE.match(line)
if not match:
return False
self._cancel_title()
self._needline = match.group(1)
return True
def _parse_title(self, line):
"""Parse the title from a line.
It changes the state of the parser even if the line does not
contain a title.
:param line: the line to be parsed
:type line: str
:returns: returns :data:`True` if the line contains a title,
otherwise it returns :data:`False`
:rtype: bool
"""
maxlen = len(self._needline) - len(' Release Notes')
match = re.match(TITLE_RE_PAT.format(maxlen=maxlen), line)
if not match:
self._cancel_title()
return False
self._version = match.group(1)
return True
def _parse_underline(self, line):
"""Parse the underline of the next section title from a line.
It changes the state of the parser.
:param line: the line to be parsed
:type line: str
:returns: the version, the description, the list of issue
numbers and the epilog of the previous release
:rtype: tuple[str | None, str, list[str], str] | None
"""
needline, version = self._cancel_title()
if line != '{}\n'.format(needline):
return None
previous_version = self._last_version
self.version = version
self.description, self.issues, self.epilog = [], [], []
return previous_version
def _parse_issue(self, line):
"""Parse an issue number from a line.
It changes the state of the parser.
:param line: the line to be parsed
:type line: str
:returns: returns :data:`True` if the line refers to an issue,
otherwise it returns :data:`False`
:rtype: bool
"""
match = re.match(r'^\* :rhbug:`(\d+)`\n$', line)
if not match:
return False
self.issues.append(match.group(1))
return True
def _parse_line(self, line):
"""Parse a line of DNF release notes.
It changes the state of the parser.
:param line: the line to be parsed
:type line: str
:returns: the version, the description, the list of issue
numbers and the epilog of the previous release
:rtype: tuple[str | None, str, list[str], str] | None
"""
needtitle = self._needline and self._version
if not needtitle and self._parse_overline(line):
return None
if self._needline and not self._version and self._parse_title(line):
return None
if self._needline and self._version:
previous_version = self._parse_underline(line)
if previous_version:
return previous_version
if not self.epilog and self._parse_issue(line):
return None
if not self.issues:
self.description.append(line)
return None
self.epilog.append(line)
def parse_lines(self, lines):
"""Parse the lines of DNF release notes.
:param lines: the line to be parsed
:type lines: collections.Iterable[str]
:returns: a generator yielding the version, the description, the
list of issue numbers and the epilog of each release version
:rtype: generator[tuple[str | None, str, list[str], str]]
"""
self._needline = None
self._version = None
self.version = None
self.description = []
self.issues = []
self.epilog = []
for line in lines:
previous_version = self._parse_line(line)
if previous_version:
yield previous_version
yield self._last_version
class TestCase(unittest.TestCase):
"""A test fixture common to all tests.
Among other things, the fixture contains a non-bare DNF repository
with a spec file specifying an unreleased version, a tag dnf-1.0.1-1
matching the version 1.0.1, one extra commit which resolves an issue
and release notes matching the revision 9110490 of DNF.
:cvar VERSION: the unreleased version specified in the spec file
:type VERSION: str
:cvar ISSUE: the number of the issue resolved by the extra commit
:type ISSUE: str
:ivar repository: the testing repository
:type repository: git.Repo
:ivar commit: the extra commit
:type commit: unicode
"""
VERSION = '999.9.9'
ISSUE = '123456'
def setUp(self):
"""Prepare the test fixture.
:const:`__file__` is needed to prepare the fixture.
"""
dirname = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, dirname)
self.repository = detect_repository().clone(dirname)
self.repository.head.reset(
'9110490d690bbad10977b86e7ffbe1feeae26e03', working_tree=True)
with open(os.path.join(dirname, SPEC_FN), 'wt') as specfile:
specfile.write(
'Name: dnf\n' +
'Version: {}\n'.format(self.VERSION) +
'Release: 1\n'
'Summary: Package manager forked from Yum\n'
'License: GPLv2+ and GPLv2 and GPL\n'
'%description\n'
'Package manager forked from Yum, using libsolv.\n'
'%files\n')
self.repository.index.add([SPEC_FN])
self.commit = self.repository.index.commit(
u'Version (RhBug:{})'.format(self.ISSUE.decode()))
@staticmethod
@contextlib.contextmanager
def _read_copy(name):
"""Create and open a readable copy of a file.
:param name: name of the file
:type name: str
:returns: the readable copy
:rtype: file
:raises exceptions.IOError: if the file cannot be opened
"""
with tempfile.TemporaryFile('wt+') as copy:
with open(name, 'rt') as original:
shutil.copyfileobj(original, copy)
copy.seek(0)
yield copy
@contextlib.contextmanager
def _patch_file(self):
"""Temporarily set :const:`__file__` to point to the testing repo.
:returns: a context manager
:rtype: contextmanager
"""
filename = os.path.join(
self.repository.working_dir, 'scripts', 'update_releasenotes.py')
original = __file__
with tests.mock.patch('update_releasenotes.__file__', filename):
assert __file__ != original, 'double check that the patch works'
yield
@contextlib.contextmanager
def _assert_logs(self, level, regex):
"""Test whether a message matching an expression is logged.
:param level: the level of the message
:type level: int
:param regex: the regular expression to be matched
:type regex: re.RegexObject
:returns: a context manager which represents the block in which
the message should be logged
:rtype: contextmanager
:raises exceptions.AssertionError: if the test fails
"""
class Handler(logging.Handler):
def __init__(self, regex):
super(Handler, self).__init__()
self.regex = regex
self.found = False
def emit(self, record):
if not self.found:
self.found = self.regex.match(record.getMessage())
handler = Handler(regex)
LOGGER.setLevel(level)
LOGGER.addHandler(handler)
yield
self.assertTrue(handler.found)
@contextlib.contextmanager
def _assert_prints(self, regex, stream):
"""Test whether a message matching an expression is printed.
:param regex: the regular expression to be matched
:type regex: re.RegexObject
:param stream: a name of the stream to be matched
:type stream: str
:returns: a context manager which represents the block in which
the message should be printed
:rtype: contextmanager
:raises exceptions.AssertionError: if the test fails
"""
with tests.mock.patch(stream, io.BytesIO()) as mock:
yield
self.assertRegex(mock.getvalue(), regex)
def _assert_iter_equal(self, actual, expected):
"""Test whether two iterables are equal.
:param actual: one of the iterables
:type actual: collections.Iterable[object]
:param expected: the other iterable
:type expected: collections.Iterable[object]
:raises exceptions.AssertionError: if the test fails
"""
self.assertTrue(all(
actual_ == expected_ for actual_, expected_ in
itertools.izip_longest(actual, expected, fillvalue=object())))
def test_detect_repository(self):
"""Test whether correct repository is detected.
:raises exceptions.AssertionError: if the test fails
"""
with self._patch_file():
self.assertEqual(
detect_repository().working_dir, self.repository.working_dir)
def test_detect_version(self):
"""Test whether correct version is detected.
:raises exceptions.AssertionError: if the test fails
"""
self.assertEqual(detect_version(self.repository), self.VERSION)
def test_find_tag_name(self):
"""Test whether correct tag is detected.
:raises exceptions.AssertionError: if the test fails
"""
self.assertEqual(find_tag(self.repository, '1.0.1'), 'dnf-1.0.1-1')
def test_find_tag_none(self):
"""Test whether correct tag is detected.
:raises exceptions.AssertionError: if the test fails
"""
self.assertIsNone(find_tag(self.repository, '9999'))
def test_iter_unreleased_commits(self):
"""Test whether correct commits are yielded.
:raises exceptions.AssertionError: if the test fails
"""
commits = iter_unreleased_commits(self.repository)
self.assertItemsEqual(
(commit.hexsha for commit in commits), [self.commit.hexsha])
def test_parse_issues(self):
"""Test whether correct issues are yielded.
:raises exceptions.AssertionError: if the test fails
"""
self.assertItemsEqual(parse_issues([self.commit]), [self.ISSUE])
def test_extend_releases_extend(self):
"""Test whether the release version is extended.
:raises exceptions.AssertionError: if the test fails
"""
releases = [
(None, 'd1\n', [], ''),
('1.0.1', '\nd2\n', ['234567'], '\n'),
('999.9.9', '\nd3\n', ['345678'], '\n')]
expected = [
(None, 'd1\n', [], ''),
('1.0.1', '\nd2\n', ['456789', '234567'], '\n'),
('999.9.9', '\nd3\n', ['345678'], '\n')]
self.assertItemsEqual(
extend_releases(releases, '1.0.1', ['456789']), expected)
def test_extend_releases_skip(self):
"""Test whether the already present issues are skipped.
:raises exceptions.AssertionError: if the test fails
"""
releases = [
(None, 'd1\n', [], ''),
('1.0.1', '\nd2\n', ['234567'], '\n'),
('999.9.9', '\nd3\n', ['345678'], '\n')]
expected = [
(None, 'd1\n', [], ''),
('1.0.1', '\nd2\n', ['234567'], '\n'),
('999.9.9', '\nd3\n', ['345678'], '\n')]
self.assertItemsEqual(
extend_releases(releases, '1.0.1', ['234567']), expected)
def test_extend_releases_append(self):
"""Test whether the rel. version is appended to the beginning.
:raises exceptions.AssertionError: if the test fails
"""
releases = [
(None, 'd1\n', [], ''),
('1.0.1', '\nd2\n', ['234567'], '\n')]
expected = [
(None, 'd1\n', [], ''),
('999.9.9', '\n', ['345678'], '\n'),
('1.0.1', '\nd2\n', ['234567'], '\n')]
self.assertItemsEqual(
extend_releases(releases, '999.9.9', ['345678']), expected)
def test_format_release_version(self):
"""Test whether correct string is returned.
:raises exceptions.AssertionError: if the test fails
"""
self.assertEqual(
format_release('1.0.1', '\ndesc\n', ['123456', '234567'], '\ne\n'),
'===================\n'
'1.0.1 Release Notes\n'
'===================\n'
'\n'
'desc\n'
'* :rhbug:`123456`\n'
'* :rhbug:`234567`\n'
'\n'
'e\n')
def test_format_release_none(self):
"""Test whether no version is handled properly.
:raises exceptions.AssertionError: if the test fails
"""
self.assertEqual(format_release(None, 'l1\nl2\n', [], ''), 'l1\nl2\n')
def test_update_notes_append(self):
"""Test whether the rel. version is appended to the beginning.
:raises exceptions.AssertionError: if the test fails
"""
regex = re.compile(
'^Update finished. See the diff to the Git index:\n.+')
notesfn = os.path.join(self.repository.working_dir, NOTES_FN)
title = TITLE_PAT.format(version=self.VERSION)
extra = [
'\n',
'{}\n'.format('=' * (len(title) - 1)),
title,
'{}\n'.format('=' * (len(title) - 1)),
'\n',
ISSUE_PAT.format(number=self.ISSUE)]
with self._read_copy(notesfn) as original:
# Insert the extra lines right after the 22nd line.
expected = itertools.chain(
itertools.islice(original, 0, 22), extra, original)
with self._patch_file(), self._assert_logs(logging.INFO, regex):
update_notes()
with open(notesfn, 'rt') as actual:
self._assert_iter_equal(actual, expected)
def test_update_notes_released(self):
"""Test whether the released version is detected.
:raises exceptions.AssertionError: if the test fails
"""
self.repository.create_tag(TAG_PAT.format(version=self.VERSION))
with self._patch_file():
self.assertRaises(ValueError, update_notes)
def test_main_append(self):
"""Test whether the release version is appended to the end.
:raises exceptions.AssertionError: if the test fails
"""
regex = re.compile(
'^INFO Update finished. See the diff to the Git index:\n.+', re.M)
notesfn = os.path.join(self.repository.working_dir, NOTES_FN)
title = TITLE_PAT.format(version=self.VERSION)
extra = [
'\n',
'{}\n'.format('=' * (len(title) - 1)),
title,
'{}\n'.format('=' * (len(title) - 1)),
'\n',
ISSUE_PAT.format(number=self.ISSUE)]
with self._read_copy(notesfn) as original:
# Insert the extra lines right after the 22nd line.
expected = itertools.chain(
itertools.islice(original, 0, 22), extra, original)
with \
tests.mock.patch('sys.argv', ['prog']), \
self._patch_file(), \
self._assert_prints(regex, 'sys.stderr'):
main()
with open(notesfn, 'rt') as actual:
self._assert_iter_equal(actual, expected)
def test_main_released(self):
"""Test whether the released version is detected.
:raises exceptions.AssertionError: if the test fails
"""
self.repository.create_tag(TAG_PAT.format(version=self.VERSION))
with \
tests.mock.patch('sys.argv', ['prog']), self._patch_file(), \
self.assertRaises(SystemExit) as context:
main()
self.assertNotEqual(context.exception.code, 0)
def test_releasenotesparser(self):
"""Test whether correct release notes are yielded.
:raises exceptions.AssertionError: if the test fails
"""
notesfn = os.path.join(self.repository.working_dir, NOTES_FN)
parser = ReleaseNotesParser()
descriptions = [
# None
'..\n'
' Copyright (C) 2014 Red Hat, Inc.\n'
'\n'
' This copyrighted material is made available to anyone wishing '
'to use,\n modify, copy, or redistribute it subject to the terms '
'and conditions of\n the GNU General Public License v.2, or (at '
'your option) any later version.\n This program is distributed in'
' the hope that it will be useful, but WITHOUT\n ANY WARRANTY '
'expressed or implied, including the implied warranties of\n '
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU'
' General\n Public License for more details. You should have '
'received a copy of the\n GNU General Public License along with '
'this program; if not, write to the\n Free Software Foundation, '
'Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, '
'USA. Any Red Hat trademarks that are incorporated in the\n '
'source code or documentation are not subject to the GNU General '
'Public\n License and may only be used or replicated with the '
'express permission of\n Red Hat, Inc.\n'
'\n'
'###################\n'
' DNF Release Notes\n'
'###################\n'
'\n'
'.. contents::\n'
'\n',
# 0.3.1
'\n0.3.1 brings mainly changes to the automatic metadata '
'synchronization. In\nFedora, ``dnf makecache`` is triggered via '
'SystemD timers now and takes an\noptional ``background`` '
'extra-argument to run in resource-considerate mode (no\nsyncing '
'when running on laptop battery, only actually performing the '
'check at\nmost once every three hours). Also, the IO and CPU '
'priorities of the\ntimer-triggered process are lowered now and '
"shouldn't as noticeably impact the\nsystem's performance.\n\nThe "
'administrator can also easily disable the automatic metadata '
'updates by\nsetting :ref:`metadata_timer_sync '
'<metadata_timer_sync-label>` to 0.\n\nThe default value of '
':ref:`metadata_expire <metadata_expire-label>` was\nincreased '
'from 6 hours to 48 hours. In Fedora, the repos usually set this\n'
'explicitly so this change is not going to cause much impact.\n\n'
'The following reported issues are fixed in this release:\n\n',
# 0.3.2
'\nThe major improvement in this version is in speeding up syncing'
' of repositories\nusing metalink by looking at the repomd.xml '
'checksums. This effectively lets DNF\ncheaply refresh expired '
'repositories in cases where the original has not\nchanged\\: for '
'instance the main Fedora repository is refreshed with one 30 kB\n'
'HTTP download. This functionality is present in the current Yum '
"but hasn't\nworked in DNF since 3.0.0.\n\nOtherwise this is "
'mainly a release fixing bugs and tracebacks. The following\n'
'reported bugs are fixed:\n\n',
# 0.3.3
'\nThe improvements in 0.3.3 are only API changes to the logging. '
'There is a new\nmodule ``dnf.logging`` that defines simplified '
'logging structure compared to\nYum, with fewer logging levels and'
' `simpler usage for the developers\n<https://github.com/'
'rpm-software-management/dnf/wiki/Hacking#logging>`_. The RPM '
'transaction logs are\nno longer in ``/var/log/dnf.transaction.log'
'`` but in ``/var/log/dnf.rpm.log`` by\ndefault.\n\nThe exception '
'classes were simplified and moved to ``dnf.exceptions``.\n\nThe '
'following bugs are fixed in 0.3.3:\n\n',
# 0.3.4
'\n0.3.4 is the first DNF version since the fork from Yum that is '
'able to\nmanipulate the comps data. In practice, ``dnf group '
'install <group name>`` works\nagain. No other group commands are '
'supported yet.\n\nSupport for ``librepo-0.0.4`` and related '
'cleanups and extensions this new\nversion allows are included '
'(see the buglist below)\n\nThis version has also improved '
'reporting of obsoleted packages in the CLI (the\nYum-style '
'"replacing <package-nevra>" appears in the textual transaction\n'
'overview).\n\nThe following bugfixes are included in 0.3.4:\n\n',
# 0.3.5
'\nBesides few fixed bugs this version should not present any '
'differences for the\nuser. On the inside, the transaction '
'managing mechanisms have changed\ndrastically, bringing code '
'simplification, better maintainability and better\ntestability.\n'
'\nIn Fedora, there is a change in the spec file effectively '
'preventing the\nmakecache timer from running *immediately after '
'installation*. The timer\nservice is still enabled by default, '
'but unless the user starts it manually with\n``systemctl start '
'dnf-makecache.timer`` it will not run until after the first\n'
'reboot. This is in alignment with Fedora packaging best '
'practices.\n\nThe following bugfixes are included in 0.3.5:\n\n',
# 0.3.6
'\nThis is a bugfix release, including the following fixes:\n\n',
# 0.3.7
'\nThis is a bugfix release:\n\n',
# 0.3.8
'\nA new locking module has been integrated in this version, '
'clients should see the\nmessage about DNF lock being taken less '
'often.\n\nPanu Matilainen has submitted many patches to this '
'release to cleanup the RPM\ninterfacing modules.\n\nThe following'
' bugs are fixed in this release:\n\n',
# 0.3.9
'\nThis is a quick bugfix release dealing with reported bugs and '
'tracebacks:\n\n',
# 0.3.10
'\nThe only major change is that ``skip_if_unavailable`` is '
':ref:`enabled by\ndefault now <skip_if_unavailable_default>`.\n\n'
'A minor release otherwise, mainly to get a new version of DNF out'
' that uses a\nfresh librepo. The following issues are now a thing'
' of the past:\n\n',
# 0.3.11
'\nThe default multilib policy configuration value is ``best`` '
'now. This does not\npose any change for the Fedora users because '
'exactly the same default had been\npreviously achieved by a '
'setting in ``/etc/dnf/dnf.conf`` shipped with the\nFedora '
'package.\n\nAn important fix to the repo module speeds up package'
' downloads again is present\nin this release. The full list of '
'fixes is:\n\n',
# 0.4.0
'\nThe new minor version brings many internal changes to the comps'
' code, most comps\nparsing and processing is now delegated to '
'`libcomps\n<https://github.com/midnightercz/libcomps>`_ by '
'Jind\xc5\x99ich Lu\xc5\xbea.\n\nThe ``overwrite_groups`` config '
'option has been dropped in this version and DNF\nacts if it was '
'0, that is groups with the same name are merged together.\n\nThe '
'currently supported groups commands (``group list`` and '
'``group install``)\nare documented on the manpage now.\n\nThe '
'0.4.0 version is the first one supported by the DNF Payload for '
'Anaconda and\nmany changes since 0.3.11 make that possible by '
'cleaning up the API and making\nit more sane (cleanup of '
'``yumvars`` initialization API, unifying the RPM\ntransaction '
'callback objects hierarchy, slimming down ``dnf.rpmUtils.arch``,'
'\nimproved logging).\n\nFixes for the following are contained in '
'this version:\n\n',
# 0.4.1
'\nThe focus of this release was to support our efforts in '
'implementing the DNF\nPayload for Anaconda, with changes on the '
'API side of things (better logging,\nnew ``Base.reset()`` '
'method).\n\nSupport for some irrelevant config options has been '
'dropped (``kernelpkgnames``,\n``exactarch``, '
'``rpm_check_debug``). We also no longer detect metalinks in the\n'
'``mirrorlist`` option (see `Fedora bug 948788\n'
'<https://bugzilla.redhat.com/show_bug.cgi?id=948788>`_).\n\nDNF '
'is on its way to drop the urlgrabber dependency and the first set'
' of patches\ntowards this goal is already in.\n\nExpect the '
'following bugs to go away with upgrade to 0.4.1:\n\n',
# 0.4.2
'\nDNF now downloads packages for the transaction in parallel with'
' progress bars\nupdated to effectively represent this. Since so '
'many things in the downloading\ncode were changing, we figured it'
' was a good idea to finally drop urlgrabber\ndependency at the '
"same time. Indeed, this is the first version that doesn't\n"
'require urlgrabber for neither build nor run.\n\nSimilarly, since'
' `librepo started to support this\n<https://github.com/Tojaj/'
'librepo/commit/acf458f29f7234d2d8d93a68391334343beae4b9>`_,\n'
'downloads in DNF now use the fastests mirrors available by '
"default.\n\nThe option to :ref:`specify repositories' costs "
'<repo_cost-label>` has been\nreadded.\n\nInternally, DNF has seen'
' first part of ongoing refactorings of the basic\noperations '
'(install, update) as well as a couple of new API methods '
'supporting\ndevelopment of extensions.\n\nThese bugzillas are '
'fixed in 0.4.2:\n\n',
# 0.4.3
'\nThis is an early release to get the latest DNF out with the '
'latest librepo\nfixing the `Too many open files\n'
'<https://bugzilla.redhat.com/show_bug.cgi?id=1015957>`_ bug.\n\n'
'In Fedora, the spec file has been updated to no longer depend on '
'precise\nversions of the libraries so in the future they can be '
'released\nindependently.\n\nThis release sees the finished '
'refactoring in error handling during basic\noperations and adds '
'support for ``group remove`` and ``group info`` commands,\ni.e. '
'the following two bugs:\n\n',
# 0.4.4
'\nThe initial support for Python 3 in DNF has been merged in this'
' version. In\npractice one can not yet run the ``dnf`` command in'
' Py3 but the unit tests\nalready pass there. We expect to give '
'Py3 and DNF heavy testing during the\nFedora 21 development cycle'
' and eventually switch to it as the default. The plan\nis to drop'
' Python 2 support as soon as Anaconda is running in Python 3.\n\n'
'Minor adjustments to allow Anaconda support also happened during '
'the last week,\nas well as a fix to a possibly severe bug that '
'one is however not really likely\nto see with non-devel Fedora '
'repos:\n\n',
# 0.4.5
'\nA serious bug causing `tracebacks during package downloads\n'
'<https://bugzilla.redhat.com/show_bug.cgi?id=1021087>`_ made it '
'into 0.4.4 and\nthis release contains a fix for that. Also, a '
'basic proxy support has been\nreadded now.\n\nBugs fixed in '
'0.4.5:\n\n',
# 0.4.6
'\n0.4.6 brings two new major features. Firstly, it is the revival'
' of ``history\nundo``, so transactions can be reverted now. '
'Secondly, DNF will now limit the\nnumber of installed kernels and'
' *installonly* packages in general to the number\nspecified by '
':ref:`installonly_limit <installonly-limit-label>` configuration'
'\noption.\n\nDNF now supports the ``group summary`` command and '
'one-word group commands no\nlonger cause tracebacks, e.g. '
'``dnf grouplist``.\n\nThere are vast internal changes to '
'``dnf.cli``, the subpackage that provides CLI\nto DNF. In '
'particular, it is now better separated from the core.\n\nThe '
'hawkey library used against DNF from with this versions uses a '
'`recent RPMDB\nloading optimization in libsolv\n'
'<https://github.com/openSUSE/libsolv/commit/843dc7e1>`_ that '
'shortens DNF\nstartup by seconds when the cached RPMDB is '
'invalid.\n\nWe have also added further fixes to support Python 3 '
"and enabled `librepo's\nfastestmirror caching optimization\n"
'<https://github.com/Tojaj/librepo/commit/'
'b8a063763ccd8a84b8ec21a643461eaace9b9c08>`_\nto tighten the '
'download times even more.\n\nBugs fixed in 0.4.6:\n\n',
# 0.4.7
'\nWe start to publish the :doc:`api` with this release. It is '
'largely\nincomprehensive at the moment, yet outlines the shape of'
' the documentation and\nthe process the project is going to use '
'to maintain it.\n\nThere are two Yum configuration options that '
'were dropped: :ref:`group_package_types '
'<group_package_types_dropped>` and '
':ref:`upgrade_requirements_on_install '
'<upgrade_requirements_on_install_dropped>`.\n\nBugs fixed in '
'0.4.7:\n\n',
# 0.4.8
'\nThere are mainly internal changes, new API functions and '
'bugfixes in this release.\n\nPython 3 is fully supported now, the'
' Fedora builds include the Py3 variant. The DNF program still '
'runs under Python 2.7 but the extension authors can now choose '
'what Python they prefer to use.\n\nThis is the first version of '
'DNF that deprecates some of its API. Clients using deprecated '
'code will see a message emitted to stderr using the standard '
'`Python warnings module '
'<http://docs.python.org/3.3/library/warnings.html>`_. You can '
'filter out :exc:`dnf.exceptions.DeprecationWarning` to suppress '
'them.\n\nAPI additions in 0.4.8:\n\n* :attr:`dnf.Base.sack`\n* '
':attr:`dnf.conf.Conf.cachedir`\n* '
':attr:`dnf.conf.Conf.config_file_path`\n* '
':attr:`dnf.conf.Conf.persistdir`\n* :meth:`dnf.conf.Conf.read`\n*'
' :class:`dnf.package.Package`\n* :class:`dnf.query.Query`\n* '
':class:`dnf.subject.Subject`\n* :meth:`dnf.repo.Repo.__init__`\n*'
' :class:`dnf.sack.Sack`\n* :class:`dnf.selector.Selector`\n* '
':class:`dnf.transaction.Transaction`\n\nAPI deprecations in '
'0.4.8:\n\n* :mod:`dnf.queries` is deprecated now. If you need to '
'create instances of :class:`.Subject`, import it from '
':mod:`dnf.subject`. To create :class:`.Query` instances it is '
'recommended to use :meth:`sack.query() <dnf.sack.Sack.query>`.\n'
'\nBugs fixed in 0.4.8:\n\n',
# 0.4.9
'\nSeveral Yum features are revived in this release. '
'``dnf history rollback`` now works again. The '
'``history userinstalled`` has been added, it displays a list of '
'ackages that the user manually selected for installation on an '
'installed system and does not include those packages that got '
"installed as dependencies.\n\nWe're happy to announce that the "
'API in 0.4.9 has been extended to finally support plugins. There '
'is a limited set of plugin hooks now, we will carefully add new '
'ones in the following releases. New marking operations have ben '
'added to the API and also some configuration options.\n\nAn '
'alternative to ``yum shell`` is provided now for its most common '
'use case: :ref:`replacing a non-leaf package with a conflicting '
'package <allowerasing_instead_of_shell>` is achieved by using the'
' ``--allowerasing`` switch now.\n\nAPI additions in 0.4.9:\n\n* '
':doc:`api_plugins`\n* :ref:`logging_label`\n* '
':meth:`.Base.read_all_repos`\n* :meth:`.Base.reset`\n* '
':meth:`.Base.downgrade`\n* :meth:`.Base.remove`\n* '
':meth:`.Base.upgrade`\n* :meth:`.Base.upgrade_all`\n* '
':attr:`.Conf.pluginpath`\n* :attr:`.Conf.reposdir`\n\nAPI '
'deprecations in 0.4.9:\n\n* :exc:`.PackageNotFoundError` is '
'deprecated for public use. Please catch :exc:`.MarkingError` '
'instead.\n* It is deprecated to use :meth:`.Base.install` return '
'value for anything. The method either returns or raises an '
'exception.\n\nBugs fixed in 0.4.9:\n\n',
# 0.4.10
'\n0.4.10 is a bugfix release that also adds some long-requested '
'CLI features and extends the plugin support with two new plugin '
'hooks. An important feature for plugin developers is going to be '
"the possibility to register plugin's own CLI command, available "
'from this version.\n\n``dnf history`` now recognizes ``last`` as '
'a special argument, just like other history commands.\n\n'
'``dnf install`` now accepts group specifications via the ``@`` '
'character.\n\nSupport for the ``--setopt`` option has been '
'readded from Yum.\n\nAPI additions in 0.4.10:\n\n* '
':doc:`api_cli`\n* :attr:`.Plugin.name`\n* '
':meth:`.Plugin.__init__` now specifies the second parameter as an'
' instance of `.cli.Cli`\n* :meth:`.Plugin.sack`\n* '
':meth:`.Plugin.transaction`\n* :func:`.repo.repo_id_invalid`\n\n'
'API changes in 0.4.10:\n\n* Plugin authors must specify '
':attr:`.Plugin.name` when authoring a plugin.\n\nBugs fixed in '
'0.4.10:\n\n',
# 0.4.11
'\nThis is mostly a bugfix release following quickly after 0.4.10,'
' with many updates to documentation.\n\nAPI additions in 0.4.11:'
'\n\n* :meth:`.Plugin.read_config`\n* :class:`.repo.Metadata`\n* '
':attr:`.repo.Repo.metadata`\n\nAPI changes in 0.4.11:\n\n* '
':attr:`.Conf.pluginpath` is no longer hard coded but depends on '
'the major Python version.\n\nBugs fixed in 0.4.11:\n\n',
# 0.4.12
'\nThis release disables fastestmirror by default as we received '
'many complains about it. There are also several bugfixes, most '
'importantly an issue has been fixed that caused packages '
'installed by Anaconda be removed together with a depending '
'package. It is now possible to use ``bandwidth`` and ``throttle``'
' config values too.\n\nBugs fixed in 0.4.12:\n\n',
# 0.4.13
'\n0.4.13 finally ships support for `delta RPMS '
'<https://gitorious.org/deltarpm>`_. Enabling this can save some '
'bandwidth (and use some CPU time) when downloading packages for '
'updates.\n\nSupport for bash completion is also included in this '
'version. It is recommended to use the '
'``generate_completion_cache`` plugin to have the completion work '
'fast. This plugin will be also shipped with '
'``dnf-plugins-core-0.0.3``.\n\nThe '
':ref:`keepcache <keepcache-label>` config option has been '
'readded.\n\nBugs fixed in 0.4.13:\n\n',
# 0.4.14
'\nThis quickly follows 0.4.13 to address the issue of crashes '
'when DNF output is piped into another program.\n\nAPI additions '
'in 0.4.14:\n\n* :attr:`.Repo.pkgdir`\n\nBugs fixed in 0.4.14:\n'
'\n',
# 0.4.15
'\nMassive refactoring of the downloads handling to provide better'
' API for reporting download progress and fixed bugs are the main '
'things brought in 0.4.15.\n\nAPI additions in 0.4.15:\n\n* '
':exc:`dnf.exceptions.DownloadError`\n* '
':meth:`dnf.Base.download_packages` now takes the optional '
'`progress` parameter and can raise :exc:`.DownloadError`.\n* '
':class:`dnf.callback.Payload`\n* '
':class:`dnf.callback.DownloadProgress`\n* '
':meth:`dnf.query.Query.filter` now also recognizes ``provides`` '
'as a filter name.\n\nBugs fixed in 0.4.15:\n\n',
# 0.4.16
'\nThe refactorings from 0.4.15 are introducing breakage causing '
'the background ``dnf makecache`` runs traceback. This release '
'fixes that.\n\nBugs fixed in 0.4.16:\n\n',
# 0.4.17
'\nThis release fixes many bugs in the downloads/DRPM CLI area. A '
'bug got fixed preventing a regular user from running read-only '
'operations using ``--cacheonly``. Another fix ensures that '
'``metadata_expire=never`` setting is respected. Lastly, the '
'release provides three requested API calls in the repo management'
' area.\n\nAPI additions in 0.4.17:\n\n* '
':meth:`dnf.repodict.RepoDict.all`\n* '
':meth:`dnf.repodict.RepoDict.get_matching`\n* '
':meth:`dnf.repo.Repo.set_progress_bar`\n\nBugs fixed in 0.4.17:\n'
'\n',
# 0.4.18
'\nSupport for ``dnf distro-sync <spec>`` finally arrives in this '
'version.\n\nDNF has moved to handling groups as objects, tagged '
'installed/uninstalled independently from the actual installed '
'packages. This has been in Yum as the ``group_command=objects`` '
'setting and the default in recent Fedora releases. There are API '
'extensions related to this change as well as two new CLI '
'commands: ``group mark install`` and ``group mark remove``.\n\n'
'API items deprecated in 0.4.8 and 0.4.9 have been dropped in '
'0.4.18, in accordance with our :ref:`deprecating-label`.\n\nAPI '
'changes in 0.4.18:\n\n* :mod:`dnf.queries` has been dropped as '
'announced in `0.4.8 Release Notes`_\n* '
':exc:`dnf.exceptions.PackageNotFoundError` has been dropped from '
'API as announced in `0.4.9 Release Notes`_\n* '
':meth:`dnf.Base.install` no longer has to return the number of '
'marked packages as announced in `0.4.9 Release Notes`_\n\nAPI '
'deprecations in 0.4.18:\n\n* :meth:`dnf.Base.select_group` is '
'deprecated now. Please use :meth:`~.Base.group_install` instead.'
'\n\nAPI additions in 0.4.18:\n\n* :meth:`dnf.Base.group_install`'
'\n* :meth:`dnf.Base.group_remove`\n\nBugs fixed in 0.4.18:\n\n',
# 0.4.19
'\nArriving one week after 0.4.18, the 0.4.19 mainly provides a '
'fix to a traceback in group operations under non-root users.\n\n'
'DNF starts to ship separate translation files (.mo) starting with'
' this release.\n\nBugs fixed in 0.4.19:\n\n',
# 0.5.0
'\nThe biggest improvement in 0.5.0 is complete support for groups'
' `and environments '
'<https://bugzilla.redhat.com/show_bug.cgi?id=1063666>`_, '
'including internal database of installed groups independent of '
'the actual packages (concept known as groups-as-objects from '
'Yum). Upgrading groups is supported now with ``group upgrade`` '
'too.\n\nTo force refreshing of metadata before an operation (even'
' if the data is not expired yet), `the refresh option has been '
'added <https://bugzilla.redhat.com/show_bug.cgi?id=1064226>`_.\n'
'\nInternally, the CLI went through several changes to allow for '
'better API accessibility like `granular requesting of root '
'permissions '
'<https://bugzilla.redhat.com/show_bug.cgi?id=1062889>`_.\n\nAPI '
'has got many more extensions, focusing on better manipulation '
'with comps and packages. There are new entries in '
':doc:`cli_vs_yum` and :doc:`user_faq` too.\n\nSeveral resource '
'leaks (file descriptors, noncollectable Python objects) were '
'found and fixed.\n\nAPI changes in 0.5.0:\n\n* it is now '
'recommended that either :meth:`dnf.Base.close` is used, or that '
':class:`dnf.Base` instances are treated as a context manager.\n\n'
'API extensions in 0.5.0:\n\n* :meth:`dnf.Base.add_remote_rpms`\n* '
':meth:`dnf.Base.close`\n* :meth:`dnf.Base.group_upgrade`\n* '
':meth:`dnf.Base.resolve` optionally accepts `allow_erasing` '
'arguments now.\n* :meth:`dnf.Base.package_downgrade`\n* '
':meth:`dnf.Base.package_install`\n* '
':meth:`dnf.Base.package_upgrade`\n* '
':class:`dnf.cli.demand.DemandSheet`\n* '
':attr:`dnf.cli.Command.base`\n* :attr:`dnf.cli.Command.cli`\n* '
':attr:`dnf.cli.Command.summary`\n* :attr:`dnf.cli.Command.usage`'
'\n* :meth:`dnf.cli.Command.configure`\n* '
':attr:`dnf.cli.Cli.demands`\n* :class:`dnf.comps.Package`\n* '
':meth:`dnf.comps.Group.packages_iter`\n* '
':data:`dnf.comps.MANDATORY` etc.\n\nBugs fixed in 0.5.0:\n\n',
# 0.5.1
'\nBugfix release with several internal cleanups. One outstanding '
'change for CLI users is that DNF is a lot less verbose now during'
' the dependency resolving phase.\n\nBugs fixed in 0.5.1:\n\n',
# 0.5.2
'\nThis release brings `autoremove command '
'<https://bugzilla.redhat.com/show_bug.cgi?id=963345>`_ that '
'removes any package that was originally installed as a dependency'
' (e.g. had not been specified as an explicit argument to the '
'install command) and is no longer needed.\n\nEnforced '
'verification of SSL connections can now be disabled with the '
':ref:`sslverify setting <sslverify-label>`.\n\nWe have been '
'plagued with many crashes related to Unicode and encodings since '
"the 0.5.0 release. These have been cleared out now.\n\nThere's "
'more: improvement in startup time, `extended globbing semantics '
'for input arguments '
'<https://bugzilla.redhat.com/show_bug.cgi?id=1083679>`_ and '
'`better search relevance sorting '
'<https://bugzilla.redhat.com/show_bug.cgi?id=1093888>`_.\n\nBugs '
'fixed in 0.5.2:\n\n',
# 0.5.3
'\nA set of bugfixes related to i18n and Unicode handling. There '
'is a ``-4/-6`` switch and a corresponding :ref:`ip_resolve '
'<ip-resolve-label>` configuration option (both known from Yum) to'
' force DNS resolving of hosts to IPv4 or IPv6 addresses.\n\n0.5.3'
' comes with several extensions and clarifications in the API: '
'notably :class:`~.dnf.transaction.Transaction` is introspectible '
'now, :class:`Query.filter <dnf.query.Query.filter>` is more '
"useful with new types of arguments and we've hopefully shed more"
' light on how a client is expected to setup the configuration '
':attr:`~dnf.conf.Conf.substitutions`.\n\nFinally, plugin authors '
'can now use a new :meth:`~dnf.Plugin.resolved` hook.\n\nAPI '
'changes in 0.5.3:\n\n* extended description given for '
':meth:`dnf.Base.fill_sack`\n* :meth:`dnf.Base.select_group` has '
'been dropped as announced in `0.4.18 Release Notes`_\n\nAPI '
'additions in 0.5.3:\n\n* :attr:`dnf.conf.Conf.substitutions`\n* '
':attr:`dnf.package.Package.arch`\n* '
':attr:`dnf.package.Package.buildtime`\n* '
':attr:`dnf.package.Package.epoch`\n* '
':attr:`dnf.package.Package.installtime`\n* '
':attr:`dnf.package.Package.name`\n* '
':attr:`dnf.package.Package.release`\n* '
':attr:`dnf.package.Package.sourcerpm`\n* '
':attr:`dnf.package.Package.version`\n* '
':meth:`dnf.Plugin.resolved`\n* :meth:`dnf.query.Query.filter` '
'accepts suffixes for its argument keys now which change the '
'filter semantics.\n* :mod:`dnf.rpm`\n* '
':class:`dnf.transaction.TransactionItem`\n* '
':class:`dnf.transaction.Transaction` is iterable now.\n\nBugs '
'fixed in 0.5.3:\n\n',
# 0.5.4
'\nSeveral encodings bugs were fixed in this release, along with '
'some packaging issues and updates to :doc:`conf_ref`.\n\n'
'Repository :ref:`priority <repo_priority-label>` configuration '
'setting has been added, providing similar functionality to Yum '
"Utils' Priorities plugin.\n\nBugs fixed in 0.5.4:\n\n",
# 0.5.5
'\nThe full proxy configuration, API extensions and several '
'bugfixes are provided in this release.\n\nAPI changes in 0.5.5:\n'
'\n* `cachedir`, the second parameter of '
':meth:`dnf.repo.Repo.__init__` is not optional (the method has '
'always been this way but the documentation was not matching)\n\n'
'API additions in 0.5.5:\n\n* extended description and an example '
'provided for :meth:`dnf.Base.fill_sack`\n* '
':attr:`dnf.conf.Conf.proxy`\n* '
':attr:`dnf.conf.Conf.proxy_username`\n* '
':attr:`dnf.conf.Conf.proxy_password`\n* '
':attr:`dnf.repo.Repo.proxy`\n* '
':attr:`dnf.repo.Repo.proxy_username`\n* '
':attr:`dnf.repo.Repo.proxy_password`\n\nBugs fixed in 0.5.5:\n\n',
# 0.6.0
'\n0.6.0 marks a new minor version of DNF and the first release to'
' support advisories listing with the :ref:`udpateinfo command '
'<updateinfo_command-label>`.\n\nSupport for the :ref:`include '
'configuration directive <include-label>` has been added. Its '
"functionality reflects Yum's ``includepkgs`` but it has been "
'renamed to make it consistent with the ``exclude`` setting.\n\n'
'Group operations now produce a list of proposed marking changes '
'to group objects and the user is given a chance to accept or '
'reject them just like with an ordinary package transaction.\n\n'
'Bugs fixed in 0.6.0:\n\n',
# 0.6.1
'\nNew release adds :ref:`upgrade-type command '
'<upgrade_type_automatic-label>` to `dnf-automatic` for choosing '
'specific advisory type updates.\n\nImplemented missing '
':ref:`history redo command <history_redo_command-label>` for '
'repeating transactions.\n\nSupports :ref:`gpgkey '
'<repo_gpgkey-label>` repo config, :ref:`repo_gpgcheck '
'<repo_gpgcheck-label>` and :ref:`gpgcheck <gpgcheck-label>` '
'[main] and Repo configs.\n\nDistributing new package '
':ref:`dnf-yum <dnf_yum_package-label>` that provides '
'`/usr/bin/yum` as a symlink to `/usr/bin/dnf`.\n\nAPI additions '
'in 0.6.1:\n\n* `exclude`, the third parameter of '
':meth:`dnf.Base.group_install` now also accepts glob patterns of '
'package names.\n\nBugs fixed in 0.6.1:\n\n',
# 0.6.2
'\nAPI additions in 0.6.2:\n\n* Now '
':meth:`dnf.Base.package_install` method ignores already installed'
' packages\n* `CliError` exception from :mod:`dnf.cli` documented'
'\n* `Autoerase`, `History`, `Info`, `List`, `Provides`, '
'`Repolist` commands do not force a sync of expired :ref:`metadata'
' <metadata_synchronization-label>`\n* `Install` command does '
'installation only\n\nBugs fixed in 0.6.2:\n\n',
# 0.6.3
'\n:ref:`Deltarpm <deltarpm-label>` configuration option is set on'
' by default.\n\nAPI additions in 0.6.3:\n\n* dnf-automatic adds '
':ref:`motd emitter <emit_via_automatic-label>` as an alternative '
'output\n\nBugs fixed in 0.6.3:\n\n',
# 0.6.4
'\nAdded example code snippets into :doc:`use_cases`.\n\nShows '
'ordered groups/environments by `display_order` tag from :ref:`cli'
' <grouplist_command-label>` and :doc:`api_comps` DNF API.\n\nIn '
'commands the environment group is specified the same as '
':ref:`group <specifying_groups-label>`.\n\n'
':ref:`skip_if_unavailable <skip_if_unavailable-label>` '
'configuration option affects the metadata only.\n\nadded '
'`enablegroups`, `minrate` and `timeout` :doc:`configuration '
'options <conf_ref>`\n\nAPI additions in 0.6.4:\n\nDocumented '
'`install_set` and `remove_set attributes` from '
':doc:`api_transaction`.\n\nExposed `downloadsize`, `files`, '
'`installsize` attributes from :doc:`api_package`.\n\nBugs fixed '
'in 0.6.4:\n\n',
# 0.6.5
'\nPython 3 version of DNF is now default in Fedora 23 and later.'
'\n\nyum-dnf package does not conflict with yum package.\n\n'
'`dnf erase` was deprecated in favor of `dnf remove`.\n\nExtended '
'documentation of handling non-existent packages and YUM to DNF '
'transition in :doc:`cli_vs_yum`.\n\nAPI additions in 0.6.5:\n\n'
'Newly added `pluginconfpath` option in :doc:`configuration '
'<conf_ref>`.\n\nExposed `skip_if_unavailable` attribute from '
':doc:`api_repos`.\n\nDocumented `IOError` exception of method '
'`fill_sack` from :class:`dnf.Base`.\n\nBugs fixed in 0.6.5:\n\n',
# 1.0.0
'\nImproved documentation of YUM to DNF transition in '
':doc:`cli_vs_yum`.\n\n:ref:`Auto remove command '
'<autoremove_command-label>` does not remove `installonly` '
'packages.\n\n:ref:`Downgrade command <downgrade_command-label>` '
'downgrades to specified package version if that is lower than '
'currently installed one.\n\nDNF now uses :attr:`dnf.repo.Repo.id`'
' as a default value for :attr:`dnf.repo.Repo.name`.\n\nAdded '
'support of repositories which use basic HTTP authentication.\n\n'
'API additions in 1.0.0:\n\n:doc:`configuration <conf_ref>` '
'options `username` and `password` (HTTP authentication)\n\n'
':attr:`dnf.repo.Repo.username` and :attr:`dnf.repo.Repo.password`'
' (HTTP authentication)\n\nBugs fixed in 1.0.0:\n\n',
# 1.0.1
'\nDNF follows the Semantic Versioning as defined at '
'`<http://semver.org/>`_.\n\nDocumented SSL '
':doc:`configuration <conf_ref>` and :doc:`repository <api_repos>`'
' options.\n\nAdded virtual provides allowing installation of DNF'
' commands by their name in the form of\n'
'``dnf install dnf-command(name)``.\n\n'
':doc:`dnf-automatic <automatic>` now by default waits random '
'interval between 0 and 300 seconds before any network '
'communication is performed.\n\n\nBugs fixed in 1.0.1:\n\n'
]
rest = [
(None, [], ''),
('0.3.1',
['916657', '921294', '922521', '926871', '878826', '922664',
'892064', '919769'],
'\n'),
('0.3.2', ['947258', '889202', '923384'], '\n'),
('0.3.3', ['950722', '903775'], '\n'),
('0.3.4', ['887317', '914919', '922667'], '\n'),
('0.3.5', ['958452', '959990', '961549', '962188'], '\n'),
('0.3.6',
['966372', '965410', '963627', '965114', '964467', '963680',
'963133'],
'\n'),
('0.3.7', ['916662', '967732'], '\n'),
('0.3.8',
['908491', '968159', '974427', '974866', '976652', '975858'],
'\n'),
('0.3.9', ['964584', '979942', '980227', '981310'], '\n'),
('0.3.10', ['977661', '984483', '986545'], '\n'),
('0.3.11', ['979042', '977753', '996138', '993916'], '\n'),
('0.4.0', ['997403', '1002508', '1002798'], '\n'),
('0.4.1', ['998859', '1006366', '1008444', '1003220'], '\n'),
('0.4.2', ['909744', '984529', '967798', '995459'], '\n'),
('0.4.3', ['1013764', '1013773'], '\n'),
('0.4.4', ['1017278'], '\n'),
('0.4.5', ['1021087'], '\n'),
('0.4.6',
['878348', '880524', '1019957', '1020101', '1020934', '1023486'],
'\n'),
('0.4.7', ['1019170', '1024776', '1025650'], '\n'),
('0.4.8',
['1014563', '1029948', '1030998', '1030297', '1030980'],
'\n'),
('0.4.9',
['884615', '963137', '991038', '1032455', '1034607', '1036116'],
'\n'),
('0.4.10',
['967264', '1018284', '1035164', '1036147', '1036211', '1038403',
'1038937', '1040255', '1044502', '1044981', '1044999'],
'\n'),
('0.4.11',
['1048402', '1048572', '1048716', '1048719', '1048988'],
'\n'),
('0.4.12',
['1045737', '1048468', '1048488', '1049025', '1051554'],
'\n'),
('0.4.13',
['909468', '1030440', '1046244', '1055051', '1056400'],
'\n'),
('0.4.14', ['1062390', '1062847', '1063022', '1064148'],
'\n'),
('0.4.15',
['1048788', '1065728', '1065879', '1065959', '1066743'],
'\n'),
('0.4.16', ['1069996'], '\n'),
('0.4.17',
['1059704', '1058224', '1069538', '1070598', '1070710', '1071323',
'1071455', '1071501', '1071518', '1071677'],
'\n'),
('0.4.18', ['963710', '1067136', '1071212', '1071501'], '\n'),
('0.4.19', ['1077173', '1078832', '1079621'], '\n'),
('0.5.0',
['1029022', '1051869', '1061780', '1062884', '1062889', '1063666',
'1064211', '1064226', '1073859', '1076884', '1079519', '1079932',
'1080331', '1080489', '1082230', '1083432', '1083767', '1084139',
'1084553', '1088166'],
'\n'),
('0.5.1', ['1065882', '1081753', '1089864'], '\n'),
('0.5.2',
['963345', '1073457', '1076045', '1083679', '1092006', '1092777',
'1093888', '1094594', '1095580', '1095861', '1096506'],
'\n'),
('0.5.3',
['1047049', '1067156', '1093420', '1104757', '1105009', '1110800',
'1111569', '1111997', '1112669', '1112704'],
'\n'),
('0.5.4',
['1048973', '1108908', '1116544', '1116839', '1116845', '1117102',
'1117293', '1117678', '1118178', '1118796', '1119032'],
'\n'),
('0.5.5',
['1100946', '1117789', '1120583', '1121280', '1122900',
'1123688'],
'\n'),
('0.6.0',
['850912', '1055910', '1116666', '1118272', '1127206'],
'\n'),
('0.6.1',
['1132335', '1071854', '1131969', '908764', '1130878', '1130432',
'1118236', '1109915'],
'\n'),
('0.6.2',
['909856', '1134893', '1138700', '1070902', '1124316', '1136584',
'1135861', '1136223', '1122617', '1133830', '1121184'],
'\n'),
('0.6.3',
['1153543', '1151231', '1163063', '1151854', '1151740', '1110780',
'1149972', '1150474', '995537', '1149952', '1149350', '1170232',
'1147523', '1148208', '1109927'],
'\n'),
('0.6.4',
['1155877', '1175466', '1175466', '1186461', '1170156', '1184943',
'1177002', '1169165', '1167982', '1157233', '1138096', '1181189',
'1181397', '1175434', '1162887', '1156084', '1175098', '1174136',
'1055910', '1155918', '1119030', '1177394', '1154476'],
'\n'),
('0.6.5',
['1203151', '1187579', '1185977', '1195240', '1193914', '1195385',
'1160806', '1186710', '1207726', '1157233', '1190671', '1191579',
'1195325', '1154202', '1189083', '1193915', '1195661', '1190458',
'1194685', '1160950'],
'\n'),
('1.0.0',
['1215560', '1199648', '1208773', '1208018', '1207861', '1201445',
'1210275', '1191275', '1207965', '1215289'],
'\n'),
('1.0.1',
['1214968', '1222694', '1225246', '1213985', '1225277', '1223932',
'1223614', '1203661', '1187741'],
'')]
expected = (
(version, desc, issues, epilog)
for desc, (version, issues, epilog) in zip(descriptions, rest))
with open(notesfn) as notesfile:
self.assertItemsEqual(parser.parse_lines(notesfile), expected)
if __name__ == '__main__':
main()
| 76,794
|
Python
|
.py
| 1,447
| 42.475466
| 80
| 0.604753
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,908
|
update-copyright-years.sh
|
rpm-software-management_dnf/scripts/update-copyright-years.sh
|
#!/bin/bash
YEAR=$1
if [ -z "$YEAR" ] ; then
echo "$0 <year>" >&2
exit 1
fi
PREV_YEAR=$(($YEAR-1))
PREV_YEARS=$(seq -s '|' 2000 $PREV_YEAR)
git log --pretty=format: --name-only --author='redhat\.com' \
--after "$YEAR-01-01" --before "$YEAR-12-31" \
| xargs perl -i -pe 's!^(#|--| \*|<source>| *) *Copyright (\([c]\)|©|\&(?:amp;)?#169;) ('"$PREV_YEARS"')(?:(-?|\&(?:amp;)?#x'"$YEAR"';)('"$PREV_YEARS"'))?,? +Red Hat,? Inc\.!$1Copyright $2 $3@{[($4 eq "") ? "-" : ${4}]}'"$YEAR"' Red Hat, Inc.!i and s!^(#|--| \*) *Copyright!$1 Copyright!;'
| 578
|
Python
|
.py
| 11
| 48.181818
| 299
| 0.487365
|
rpm-software-management/dnf
| 1,227
| 411
| 56
|
GPL-2.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,909
|
setup.py
|
nojhan_colout/setup.py
|
#!/usr/bin/env python3
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py bdist_wheel --universal upload')
sys.exit()
packages = ['colout']
requires = ['pygments', 'babel']
setup_requires = ['setuptools_scm']
classifiers = """
Environment :: Console
Development Status :: 5 - Production/Stable
License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Operating System :: POSIX
Operating System :: POSIX :: Linux
Programming Language :: Python :: 3
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Topic :: Utilities
Topic :: Text Processing
Topic :: Text Processing :: Filters
""".strip().split('\n')
setup(
name='colout',
use_scm_version=True,
classifiers=classifiers,
description='Color Up Arbitrary Command Output.',
entry_points={
'console_scripts': ['colout=colout.colout:main'],
},
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type='text/markdown;variant=CommonMark',
author='nojhan',
author_email='nojhan@nojhan.net',
url='http://nojhan.github.com/colout/',
packages=packages,
package_data={'': ['LICENSE', 'README.md']},
package_dir={'colout': 'colout'},
python_requires='>=3.5',
setup_requires=setup_requires,
include_package_data=True,
install_requires=requires,
license='GPLv3',
zip_safe=False,
)
| 1,609
|
Python
|
.py
| 51
| 28.352941
| 87
| 0.704516
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,910
|
colout_catch2.py
|
nojhan_colout/colout/colout_catch2.py
|
def theme(context):
return context,[
["^ (Start)(.*): (.*):(.*)$", "yellow", "normal,normal,normal,bold"], # Test start.
# path file ext:line :
["^(tests): (/.*?)/([^/:]+):([0-9]+): (.*)", "yellow,none,white,yellow,red", "bold,normal,bold,normal,bold"],
["(`)(.*)('.*)", "red,Cpp,red", "bold,normal,bold"],
[r"^\.+$", "yellow", "bold"],
["^=+$", "yellow", "bold"],
["(/.*?)/([^/:]+):([0-9]+): (FAILED):", "white,white,yellow,red", "normal,bold,normal,bold"],
[r"(REQUIRE\(|CHECK\(|REQUIRE_THAT\()(.*)(\))$","yellow,Cpp,yellow","bold,normal,bold"],
# Hide uninteresting stuff:
["[0-9]+/[0-9]+ Test.*","blue"],
["^Filters:.*","blue"],
["^Randomness seeded to:.*","blue"],
["^tests is a Catch2.*","blue"],
["^Run with.*", "blue"],
["^~+$","blue"],
["^-+$","blue"],
[r"^\s*(Scenario:|Given:|When:|Then:).*","blue"],
["^(/.*?)/([^/:]+):([0-9]+)", "blue"],
["^(test cases|assertions)(.*)", "blue"],
]
| 1,072
|
Python
|
.py
| 22
| 40.409091
| 117
| 0.42326
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,911
|
colout_clang.py
|
nojhan_colout/colout/colout_clang.py
|
#encoding: utf-8
def default_gettext( msg ):
return msg
def theme(context):
import os
import gettext
import locale
section="blue"
# get g++ version
gv = os.popen("g++ -dumpversion").read().strip()
# get the current translations of gcc
try:
t = gettext.translation("gcc-"+gv)
except IOError:
_ = default_gettext
else:
_ = t.gettext
# _("msg") will return the given message, translated
# if the locale is unicode
enc = locale.getpreferredencoding()
if "UTF" in enc:
# gcc will use unicode quotes
qo = "[‘`]"
qc = "[’']"
else:
# rather than ascii ones
qo = "['`]"
qc = "'"
return context,[
# Command line
[ r"[/\s]([cg]\+\+-*[0-9]*\.*[0-9]*)", "white", "bold" ],
[ r"\s(\-D)(\s*[^\s]+)", "none,green", "normal,bold" ],
[ r"\s(-g)", "green", "normal" ],
[ r"\s-O[0-4]", "green", "normal" ],
[ r"\s-[Wf][^\s]*", "magenta", "normal" ],
[ r"\s-pedantic", "magenta", "normal" ],
[ r"\s(-I)(/*[^\s]+/)([^/\s]+)", "none,blue", "normal,normal,bold" ],
[ r"\s(-L)(/*[^\s]+/)([^/\s]+)", "none,cyan", "normal,normal,bold" ],
[ r"\s(-l)([^/\s]+)", "none,cyan", "normal,bold" ],
[ r"\s-[oc]", "red", "bold" ],
[ r"\s(-+std(?:lib)?)=?([^\s]+)", "red", "normal,bold" ],
# Important messages
[ _("error: "), "red", "bold" ],
[ _("fatal error: "), "red", "bold" ],
[ _("warning: "), "magenta", "bold" ],
[ _("undefined reference to "), "red", "bold" ],
# [-Wflag]
[ r"\[-W.*\]", "magenta"],
# Highlight message start:
# path file ext : line : col …
[ "(/.*?)/([^/:]+): (In .*)"+qo,
section,
"normal,normal,bold" ],
[ "(/.*?)/([^/:]+): (At .*)",
section,
"normal,normal,bold" ],
[ _("In file included from"), section ],
# Highlight locations:
# path file ext : line : col …
[ "(/.*?)/([^/:]+):([0-9]+):*([0-9]*)(.*)",
"none,white,yellow,none,none",
"normal,normal,normal,normal" ],
# source code in single quotes
[ qo+"(.*?)"+qc, "Cpp", "monokai" ],
# source code after a "note: candidate are/is:"
[ _("note: ")+"((?!.*("+qo+"|"+qc+")).*)$", "Cpp", "monokai" ],
# [ _("note: ")+"(candidate:)(.*)$", "green,Cpp", "normal,monokai" ],
# after the code part, to avoid matching ANSI escape chars
[ _("note: "), "green", "normal" ]
]
| 2,640
|
Python
|
.py
| 70
| 29.585714
| 77
| 0.443659
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,912
|
colout_perm.py
|
nojhan_colout/colout/colout_perm.py
|
def theme(context):
p="([-rwxsStT])"
reg=r"^([-dpcCDlMmpPs?])"+p*9+r"\s.*$"
colors="blue"+",green"*3+",yellow"*3+",red"*3
styles="normal"+ ",normal,italic,bold"*3
return context,[ [reg, colors, styles] ]
| 226
|
Python
|
.py
| 6
| 33
| 49
| 0.577982
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,913
|
colout_configure.py
|
nojhan_colout/colout/colout_configure.py
|
#encoding: utf-8
def theme(context):
return context, [
["^(checking .*)(yes|found|ok)$","green", "normal,bold"],
["^(checking .*)(no|none)$", "yellow", "normal,bold"],
["^(configure:) (error:)(.*)", "red","normal,bold"],
["^(configure:)(.*)", "magenta","normal,bold"],
["^(checking .*)", "blue",""],
["^(config.status:) (creating|linking)(.*)", "cyan,blue","normal,normal,bold"],
["^(config.status:) (executing )(.*)", "cyan,green","normal,normal,bold"],
["^(config.status:) (.*)(is unchanged)", "cyan,green","normal,normal,bold"],
[r"^\s*(Build.*)(yes)$","green", "normal,bold"],
[r"^\s*(Build.*)(no)$","yellow", "normal,bold"],
]
| 778
|
Python
|
.py
| 14
| 45
| 92
| 0.476378
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,914
|
colout_django.py
|
nojhan_colout/colout/colout_django.py
|
def theme(context):
return context,[
# Waiting
["^Waiting for .*$", "red", "bold"],
[".*Sending.*", "green"],
# Watches
[r"^(Watching) (\S*) (.*)", "yellow", "bold,bold,normal"],
[".*reloading.$","yellow"],
# File from python/lib
[r"^(File) (/.*/lib/python[^/]*/site-packages/)([^/]*)\S* (first seen) (with mtime [0-9]*.*)$",
"blue,blue,white,blue,blue", "bold,normal,bold,bold,normal"],
# File from app (last 3 name highlighted)
[r"^(File) (/\S*/)(\S*/\S*/)(\S*) (first seen) (with mtime [0-9]*.*)$",
"magenta,magenta,white,white,magenta,magenta", "bold,normal,normal,bold,bold,normal"],
# SQL
["(.*)(SELECT)(.*)(FROM)(.*)",
"green", "normal,bold,normal,bold,normal"],
["(.*)(SELECT)(.*)(FROM)(.*)(WHERE)(.*)",
"green", "normal,bold,normal,bold,normal,bold,normal"],
# HTTP
[r"\"(GET) (\S*) (HTTP\S*)\" ([0-9]+) (.*)$",
"green,white,green,green,green", "bold,bold,normal,bold,normal"],
# Errors
["(Exception) (while .*) '(.*)' (in) (.*) '(.*)'", "red,red,white,red,red,white", "bold,normal,bold,bold,normal,bold"],
["(.*Error): (.*) '(.*)'", "red,red,white", "bold,normal,bold"],
[r"(django[^:\s]*)\.([^.:\s]*): (.*)", "red","normal,bold,normal"],
["Traceback.*:","yellow"],
["During handling.*","yellow"],
# File, line, in
[
r"^\s{2}(File \")(/*.*?/)*([^/:]+)(\", line) ([0-9]+)(, in) (.*)$",
"blue, none, white,blue, yellow,blue",
"normal,normal,bold, normal,normal,bold"
],
]
| 1,808
|
Python
|
.py
| 35
| 38.514286
| 131
| 0.432844
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,915
|
colout_vivado.py
|
nojhan_colout/colout/colout_vivado.py
|
def theme(context):
# Theme for coloring AMD/Xilinx Vivado IDE synthesis and implementation output
return context,[
[ r"^\s*\*+.+$", "green" ],
[ "^#.+", "green" ],
[ "^.+ Checksum: .+$", "green" ],
[ r"^.+Time \(s\).+", "green" ],
[ r"^Time \(s\).+", "green" ],
[ r"Estimated Timing Summary \|.+\|.+\|", "cyan", "bold" ],
[ r"Intermediate Timing Summary \|.+\|.+\|", "cyan", "bold" ],
[ "^INFO:", "white", "bold" ],
[ "^WARNING:.+$", "yellow" ],
[ "^CRITICAL WARNING:.+$", "red" ],
[ "^ERROR:.+$", "red" ],
[ "^Phase [0-9]+.[0-9]+.[0-9]+.[0-9]+.+$", "magenta", "bold" ],
[ "^Phase [0-9]+.[0-9]+.[0-9]+.+$", "magenta", "bold" ],
[ "^Phase [0-9]+.[0-9]+.+$", "magenta", "bold" ],
[ "^Phase [0-9]+.+$", "magenta", "bold" ]
]
| 904
|
Python
|
.py
| 19
| 39.263158
| 82
| 0.389522
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,916
|
colout_javac.py
|
nojhan_colout/colout/colout_javac.py
|
#encoding: utf-8
def theme(context):
style="monokai"
return context,[
[ r"^(.*\.java):([0-9]+):\s*(warning:.*)$", "white,yellow,magenta", "normal,normal,bold" ],
[ r"^(.*\.java):([0-9]+):(.*)$", "white,yellow,red", "normal,normal,bold" ],
[ r"^(symbol|location)\s*:\s*(.*)$", "blue,Java", "bold,"+style ],
[ r"^(found)\s*:\s*(.*)", "red,Java", "bold,"+style ],
[ r"^(required)\s*:\s*(.*)", "green,Java", "bold,"+style ],
[ r"^\s*\^$", "cyan", "bold" ],
[ r"^\s+.*$", "Java", style ],
[ "[0-9]+ error[s]*", "red", "bold" ],
[ "[0-9]+ warning[s]*", "magenta", "bold" ],
]
| 695
|
Python
|
.py
| 14
| 39.714286
| 103
| 0.414706
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,917
|
colout_ctest.py
|
nojhan_colout/colout/colout_ctest.py
|
def theme(context):
# CTest theme:
passed="green"
notrun="yellow"
notpassed="red"
# If the user do not ask for his own colormap
# if not context["user_defined_colormaps"]:
# # A palette that goes: purple, orange, white
# percs = [45, 39, 33, 27, 21, 57, 63, 62, 98, 97, 133, 132, 138, 173, 172, 208, 214, 220, 226, 228, 229, 230, 231, 255]
# context["colormaps"]["Scale"] = percs
return context,[
# Passed
[ r"^\s*[0-9]+/[0-9]+ Test\s+#[0-9]+: (.*)\s+\.+\s+(Passed)", "blue,"+passed],
[ r"^\s*[0-9]+/[0-9]+ Test\s+#[0-9]+: (.*)\s+\.+(\*{3}Not Run.*)\s+.*", "blue,"+notrun],
[ r"^\s*[0-9]+/[0-9]+ Test\s+#[0-9]+: (.*)\s+\.+(.*\*{3}.*)\s+.*", "blue,"+notpassed],
]
| 754
|
Python
|
.py
| 16
| 41.1875
| 128
| 0.493878
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,918
|
colout_ninja.py
|
nojhan_colout/colout/colout_ninja.py
|
import colout_cmake
def theme(context):
# Ninja theme
# Inherit from the CMake theme
context,th = colout_cmake.theme(context)
# Because Ninja note progress as a fraction, we do not want the scale of a percentage
context["scale"] = (0,1)
# Link (ninja)
th.append( [ r"^\[[0-9/]+\]\s?(Linking .* )(library|executable) (.*/)*(.+(\.[aso]+)*)$",
"blue", "normal,normal,bold" ] )
# progress percentage (ninja)
th.append( [ r"^(\[[0-9]+/[0-9]+\])","Scale" ] )
return context,th
| 527
|
Python
|
.py
| 13
| 35.230769
| 92
| 0.596457
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,919
|
colout_latex.py
|
nojhan_colout/colout/colout_latex.py
|
def theme(context):
return context,[
# LaTeX
["This is .*TeX.*$", "white", "bold"],
["(LaTeX Warning): (.*) `(.*)' on page [0-9] (.*) on input line [0-9]+.$",
"magenta,magenta,white,magenta", "normal,bold,normal" ],
["(LaTeX Warning): (.*)", "magenta", "normal,bold" ],
["(LaTeX Error): (.*)", "red", "normal,bold" ],
[r"^(.*\.tex):([0-9]+): (.*)", "white,yellow,red", "normal,normal,bold" ],
# ["on (page [0-9]+)", "yellow", "normal" ],
["on input (line [0-9]+)", "yellow", "normal" ],
["^! .*$", "red", "bold"],
[r"(.*erfull) ([^\s]+).* in [^\s]+ at (lines [0-9]+--[0-9]+)",
"magenta,magenta,yellow", "normal"],
[r"\\[^\s]+\s", "white", "bold"],
[r"^l\.([0-9]+) (.*)", "yellow,tex"],
[r"^\s+(.*)", "tex"],
[r"(Output written on) (.*) \(([0-9]+ pages), [0-9]+ bytes\).",
"blue,white,blue", "normal,bold,normal"],
["WARNING.*", "magenta", "normal"],
["[wW]arning.*", "magenta", "normal"],
["No pages of output", "red", "bold"],
# BiBTeX
["^(I couldn't) (.*)", "red", "normal,bold"],
["(I found) no (.*)", "red"],
["^---(line [0-9]+) of file (.*)", "yellow,white", "normal"],
]
| 1,392
|
Python
|
.py
| 27
| 38.888889
| 86
| 0.391336
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,920
|
colout.py
|
nojhan_colout/colout/colout.py
|
#!/usr/bin/env python3
#encoding: utf-8
# Color Up Arbitrary Command Output
# Licensed under the GPL version 3
# 2012 (c) nojhan <nojhan@nojhan.net>
import os
import re
import sys
import copy
import glob
import math
import pprint
import random
import signal
import string
import hashlib
import logging
import argparse
import importlib
import functools
import babel.numbers as bn
# set the SIGPIPE handler to kill the program instead of
# ending in a write error when a broken pipe occurs
signal.signal( signal.SIGPIPE, signal.SIG_DFL )
###############################################################################
# Global variable(s)
###############################################################################
context = {}
debug = False
# Available styles
context["styles"] = {
"normal": 0, "bold": 1, "faint": 2, "italic": 3, "underline": 4,
"blink": 5, "rapid_blink": 6,
"reverse": 7, "conceal": 8
}
error_codes = {"UnknownColor": 1, "DuplicatedPalette": 2, "MixedModes": 3, "UnknownLexer": 4, "UnknownResource": 5}
# Available color names in 8-colors mode.
eight_colors = ["black","red","green","yellow","blue","magenta","cyan","white"]
# Given in that order, the ASCII code is the index.
eight_color_codes = {n:i for i,n in enumerate(eight_colors)}
# One can add synonyms.
eight_color_codes["orange"] = eight_color_codes["yellow"]
eight_color_codes["purple"] = eight_color_codes["magenta"]
# Foreground colors has a special "none" item.
# Note: use copy to avoid having the same reference over fore/background.
context["colors"] = copy.copy(eight_color_codes)
context["colors"]["none"] = -1
# Background has the same colors than foreground, but without the none code.
context["backgrounds"] = copy.copy(eight_color_codes)
context["themes"] = {}
# pre-defined colormaps
# 8-colors mode should start with a lower-case letter (and can contains either named or indexed colors)
# 256-colors mode should start with an upper-case letter (and should contains indexed colors)
context["colormaps"] = {
# Rainbows
"rainbow" : ["magenta", "blue", "cyan", "green", "yellow", "red"],
"Rainbow" : [92, 93, 57, 21, 27, 33, 39, 45, 51, 50, 49, 48, 47, 46, 82, 118, 154, 190, 226, 220, 214, 208, 202, 196],
# From magenta to red, with white in the middle
"spectrum" : ["magenta", "blue", "cyan", "white", "green", "yellow", "red"],
"Spectrum" : [91, 92, 56, 57, 21, 27, 26, 32, 31, 37, 36, 35, 41, 40, 41, 77, 83, 84, 120, 121, 157, 194, 231, 254, 255, 231, 230, 229, 228, 227, 226, 220, 214, 208, 202, 196],
# All the colors are available for the default `random` special
"random" : context["colors"],
"Random" : list(range(256))
} # colormaps
context["colormaps"]["scale"] = context["colormaps"]["spectrum"]
context["colormaps"]["Scale"] = context["colormaps"]["Spectrum"]
context["colormaps"]["hash"] = context["colormaps"]["rainbow"]
context["colormaps"]["Hash"] = context["colormaps"]["Rainbow"]
context["colormaps"]["default"] = context["colormaps"]["spectrum"]
context["colormaps"]["Default"] = context["colormaps"]["Spectrum"]
context["user_defined_colormaps"] = False
context["colormap_idx"] = 0
context["scale"] = (0,100)
context["lexers"] = []
# Character use as a delimiter
# between foreground and background.
context["sep_pair"]="."
context["sep_list"]=","
class UnknownColor(Exception):
pass
class DuplicatedPalette(Exception):
pass
class DuplicatedTheme(Exception):
pass
class MixedModes(Exception):
pass
###############################################################################
# Ressource parsing helpers
###############################################################################
def make_colormap( colors, sep_list = context["sep_list"] ):
cmap = colors.split(sep_list)
# Check unicity of mode.
modes = [mode(c) for c in cmap]
if len(uniq(modes)) > 1:
# Format a list of color:mode, for error display.
raise MixedModes(", ".join(["%s:%s" % cm for cm in zip(cmap,modes)]))
return cmap
def set_special_colormaps( cmap, sep_list = context["sep_list"] ):
"""Change all the special colors to a single colormap (which must be a list of colors)."""
global context
context["colormaps"]["scale"] = cmap
context["colormaps"]["Scale"] = cmap
context["colormaps"]["hash"] = cmap
context["colormaps"]["Hash"] = cmap
context["colormaps"]["default"] = cmap
context["colormaps"]["Default"] = cmap
context["colormaps"]["random"] = cmap
context["colormaps"]["Random"] = cmap
context["user_defined_colormaps"] = True
logging.debug("user-defined special colormap: %s" % sep_list.join([str(i) for i in cmap]) )
def parse_gimp_palette( filename ):
"""
Parse the given filename as a GIMP palette (.gpl)
Return the filename (without path and extension) and a list of ordered
colors.
Generally, the colors are RGB triplets, thus this function returns:
(name, [ [R0,G0,B0], [R1,G1,B1], ... , [RN,GN,BN] ])
"""
logging.debug("parse GIMP palette file: %s" % filename)
fd = open(filename)
# remove path and extension, only keep the file name itself
name = os.path.splitext( os.path.basename(filename ))[0]
# The first .gpl line is a header
assert( fd.readline().strip() == "GIMP Palette" )
# Then the full name of the palette
long_name = fd.readline().strip()
# Then the columns number.
# split on colon, take the second argument as an int
line = fd.readline()
if "Columns:" in line:
columns = int( line.strip().split(":")[1].strip() )
lines = fd.readlines()
else:
columns=3
lines = [line] + fd.readlines()
# Then the colors themselves.
palette = []
for line in lines:
# skip lines with only a comment
if re.match(r"^\s*#.*$", line ):
continue
# decode the columns-ths codes. Generally [R G B] followed by a comment
colors = [ int(c) for c in line.split()[:columns] ]
palette.append( colors )
logging.debug("parsed %i RGB colors from palette %s" % (len(palette), name) )
return name,palette
def uniq( lst ):
"""Build a list with uniques consecutive elements in the argument.
>>> uniq([1,1,2,2,2,3])
[1,2,3]
>>> uniq([0,1,1,2,3,3,3])
[0,1,2,3]
"""
assert( len(lst) > 0 )
uniq = [ lst[0] ]
for i in range(1,len(lst)):
if lst[i] != lst[i-1]:
uniq.append(lst[i])
return uniq
def rgb_to_ansi( r, g, b ):
"""Convert a RGB color to its closest 256-colors ANSI index"""
# Range limits for the *colored* section of ANSI,
# this does not include the *gray* section.
ansi_min = 16
ansi_max = 234
# ansi_max is the higher possible RGB value for ANSI *colors*
# limit RGB values to ansi_max
red,green,blue = tuple([ansi_max if c>ansi_max else c for c in (r,g,b)])
offset = 42.5
is_gray = True
while is_gray:
if red < offset or green < offset or blue < offset:
all_gray = red < offset and green < offset and blue < offset
is_gray = False
offset += 42.5
if all_gray:
val = ansi_max + round( (red + green + blue)/33.0 )
res = int(val)
else:
val = ansi_min
for color,modulo in zip( [red, green, blue], [6*6, 6, 1] ):
val += round(6.0 * (color / 256.0)) * modulo
res = int(val)
return res
def hex_to_rgb(h):
assert( h[0] == "#" )
h = h.lstrip('#')
lh = len(h)
return tuple( int(h[i:i+lh//3], 16) for i in range(0, lh, lh//3) )
###############################################################################
# Load available extern resources
###############################################################################
def load_themes( themes_dir):
global context
logging.debug("search for themes in: %s" % themes_dir)
sys.path.append( themes_dir )
# load available themes
for f in glob.iglob(os.path.join(themes_dir, "colout_*.py")):
basename = os.path.basename(f) # Remove path.
module = os.path.splitext(basename)[0] # Remove extension.
name = "_".join(module.split("_")[1:]) # Remove the 'colout_' prefix.
if name in context["themes"]:
raise DuplicatedTheme(name)
logging.debug("load theme %s" % name)
context["themes"][name] = importlib.import_module(module)
def load_palettes( palettes_dir, ignore_duplicates = True ):
global context
logging.debug("search for palettes in: %s" % palettes_dir)
# load available colormaps (GIMP palettes format)
for p in glob.iglob(os.path.join(palettes_dir, "*.gpl")):
try:
name,palette = parse_gimp_palette(p)
except Exception as e:
logging.warning("error while parsing palette %s: %s" % ( p,e ) )
continue
if name in context["colormaps"]:
if ignore_duplicates:
logging.warning("ignore this duplicated palette name: %s" % name)
else:
raise DuplicatedPalette(name)
# Convert the palette to ANSI
ansi_palette = [ rgb_to_ansi(r,g,b) for r,g,b in palette ]
# Compress it so that there isn't two consecutive identical colors
compressed = uniq(ansi_palette)
logging.debug("load %i ANSI colors in palette %s: %s" % (len(compressed), name, compressed))
context["colormaps"][name] = compressed
def load_lexers():
global context
# load available pygments lexers
lexers = []
global get_lexer_by_name
from pygments.lexers import get_lexer_by_name
global highlight
from pygments import highlight
global Terminal256Formatter
from pygments.formatters import Terminal256Formatter
global TerminalFormatter
from pygments.formatters import TerminalFormatter
from pygments.lexers import get_all_lexers
try:
for lexer in get_all_lexers():
l = None
# If the tuple has one-word aliases
# (which are usually a better option than the long names
# for a command line argument).
if lexer[1]:
l = lexer[1][0] # Take the first one.
else:
assert(lexer[0])
l = lexer[0] # Take the long name, which should alway exists.
if not l:
logging.warning("cannot load lexer: %s" % lexer[1][0])
pass # Forget about this lexer.
else:
assert(" " not in l) # Should be very rare, but probably a source of bugs.
lexers.append(l)
except:
logging.warning("error while executing the pygment module, syntax coloring is not available")
lexers.sort()
logging.debug("loaded %i lexers: %s" % (len(lexers), ", ".join(lexers)))
context["lexers"] = lexers
def load_resources( themes_dir, palettes_dir ):
load_themes( themes_dir )
load_palettes( palettes_dir )
load_lexers()
###############################################################################
# Library
###############################################################################
def mode( color ):
global context
if type(color) is int:
if 0 <= color and color <= 255 :
return 256
else:
raise UnknownColor(color)
elif color in context["colors"]:
return 8
elif color in context["colormaps"].keys():
if color[0].islower():
return 8
elif color[0].isupper():
return 256
elif color.lower() in ("scale","hash","random") or color.lower() in context["lexers"]:
if color[0].islower():
return 8
elif color[0].isupper():
return 256
elif color[0] == "#":
return 256
elif color.isdigit() and (0 <= int(color) and int(color) <= 255) :
return 256
else:
raise UnknownColor(color)
def next_in_map( name ):
global context
# loop over indices in colormap
return (context["colormap_idx"]+1) % len(context["colormaps"][name])
def color_random( color ):
global context
m = mode(color)
if m == 8:
color_name = random.choice(list(context["colormaps"]["random"]))
color_code = context["colors"][color_name]
color_code = str(30 + color_code)
elif m == 256:
color_nb = random.choice(context["colormaps"]["Random"])
color_code = str(color_nb)
return color_code
def color_in_colormaps( color ):
global context
m = mode(color)
if m == 8:
c = context["colormaps"][color][context["colormap_idx"]]
if c.isdigit():
color_code = str(30 + c)
else:
color_code = str(30 + context["colors"][c])
else:
color_nb = context["colormaps"][color][context["colormap_idx"]]
color_code = str( color_nb )
context["colormap_idx"] = next_in_map(color)
return color_code
def color_scale( name, text ):
# filter out everything that does not seem to be necessary to interpret the string as a number
# this permits to transform "[ 95%]" to "95" before number conversion,
# and thus allows to color a group larger than the matched number
chars_in_numbers = "-+.,e/*"
allowed = string.digits + chars_in_numbers
nb = "".join([i for i in filter(allowed.__contains__, text)])
# interpret as decimal
f = None
try:
f = float(bn.parse_decimal(nb))
except bn.NumberFormatError:
pass
if f is not None:
# normalize with scale if it's a number
f = (f - context["scale"][0]) / (context["scale"][1]-context["scale"][0])
else:
# interpret as float between 0 and 1 otherwise
f = eval(nb)
# if out of scale, do not color
if f < 0 or f > 1:
return None
# normalize and scale over the nb of colors in cmap
colormap = context["colormaps"][name]
i = int( math.ceil( f * (len(colormap)-1) ) )
color = colormap[i]
# infer mode from the color in the colormap
m = mode(color)
if m == 8:
color_code = str(30 + context["colors"][color])
else:
color_code = str(color)
return color_code
def color_hash( name, text ):
hasher = hashlib.md5()
hasher.update(text.encode('utf-8'))
hash = hasher.hexdigest()
f = float(functools.reduce(lambda x, y: x+ord(y), hash, 0) % 101)
# normalize and scale over the nb of colors in cmap
colormap = context["colormaps"][name]
i = int( math.ceil( (f - context["scale"][0]) / (context["scale"][1]-context["scale"][0]) * (len(colormap)-1) ) )
color = colormap[i]
# infer mode from the color in the colormap
m = mode(color)
if m == 8:
color_code = str(30 + context["colors"][color])
else:
color_code = str(color)
return color_code
def color_map(name):
global context
# current color
color = context["colormaps"][name][ context["colormap_idx"] ]
m = mode(color)
if m == 8:
color_code = str(30 + context["colors"][color])
else:
color_nb = int(color)
assert( 0 <= color_nb <= 255 )
color_code = str(color_nb)
context["colormap_idx"] = next_in_map(name)
return color,color_code
def color_lexer( name, style, text ):
lexer = get_lexer_by_name(name.lower())
# Python => 256 colors, python => 8 colors
m = mode(name)
if m == 256:
try:
formatter = Terminal256Formatter(style=style)
except: # style not found
formatter = Terminal256Formatter()
else:
if style not in ("light","dark"):
style = "dark" # dark color scheme by default
formatter = TerminalFormatter(bg=style)
# We should return all but the last character,
# because Pygments adds a newline char.
if not debug:
return highlight(text, lexer, formatter)[:-1]
else:
return "<"+name+">"+ highlight(text, lexer, formatter)[:-1] + "</"+name+">"
def colorin(text, color="red", style="normal", sep_pair=context["sep_pair"]):
"""
Return the given text, surrounded by the given color ASCII markers.
The given color may be either a single name, encoding the foreground color,
or a pair of names, delimited by the given sep_pair,
encoding foreground and background, e.g. "red.blue".
If the given color is a name that exists in available colors,
a 8-colors mode is assumed, else, a 256-colors mode.
The given style must exists in the available styles.
>>> colorin("Fetchez la vache", "red", "bold")
'\x1b[1;31mFetchez la vache\x1b[0m'
>>> colout.colorin("Faites chier la vache", 41, "normal")
'\x1b[0;38;5;41mFaites chier la vache\x1b[0m'
"""
assert( type(color) is str )
global debug
# Special characters.
start = "\033["
stop = "\033[0m"
# Escaped end markers for given color modes
endmarks = {8: ";", 256: ";38;5;"}
color_code = ""
style_code = ""
background_code = ""
style_codes = []
# Convert the style code
if style == "random" or style == "Random":
style = random.choice(list(context["styles"].keys()))
else:
styles = style.split(sep_pair)
for astyle in styles:
if astyle in context["styles"]:
style_codes.append(str(context["styles"][astyle]))
style_code = ";".join(style_codes)
color_pair = color.strip().split(sep_pair)
color = color_pair[0]
background = color_pair[1] if len(color_pair) == 2 else "none"
if color == "none" and background == "none":
# if no color, style cannot be applied
if not debug:
return text
else:
return "<none>"+text+"</none>"
elif color.lower() == "random":
color_code = color_random( color )
elif color.lower() == "scale": # "scale" or "Scale"
color_code = color_scale( color, text )
# "hash" or "Hash"; useful to randomly but consistently color strings
elif color.lower() == "hash":
color_code = color_hash( color, text )
# The user can change the "colormap" variable to its favorite one before calling colorin.
elif color == "colormap":
# "default" should have been set to the user-defined colormap.
color,color_code = color_map("default")
# Registered colormaps should be tested after special colors,
# because special tags are also registered as colormaps,
# but do not have the same simple behavior.
elif color in context["colormaps"].keys():
color_code = color_in_colormaps( color )
# 8 colors modes
elif color in context["colors"]:
color_code = str(30 + context["colors"][color])
# hexadecimal color
elif color[0] == "#":
color_nb = rgb_to_ansi(*hex_to_rgb(color))
assert(0 <= color_nb <= 255)
color_code = str(color_nb)
# 256 colors mode
elif color.isdigit():
color_nb = int(color)
assert(0 <= color_nb <= 255)
color_code = str(color_nb)
# programming language
elif color.lower() in context["lexers"]:
# bypass color encoding and return text colored by the lexer
return color_lexer(color,style,text)
# unrecognized
else:
raise UnknownColor(color)
m = mode(color)
if background in context["backgrounds"] and m == 8:
background_code = endmarks[m] + str(40 + context["backgrounds"][background])
elif background == "none":
background_code = ""
else:
raise UnknownColor(background)
if color_code is not None:
if not debug:
return start + style_code + endmarks[m] + color_code + background_code + "m" + text + stop
else:
return start + style_code + endmarks[m] + color_code + background_code + "m" \
+ "<color name=" + str(color) \
+ " code=" + color_code \
+ " style=" + str(style) \
+ " stylecode=" + style_code \
+ " background=" + str(background) \
+ " backgroundcode=" + background_code.strip(endmarks[m]) \
+ " mode=" + str(m) \
+ ">" \
+ text + "</color>" + stop
else:
if not debug:
return text
else:
return "<none>" + text + "</none>"
def colorout(text, match, prev_end, color="red", style="normal", group=0):
"""
Build the text from the previous re.match to the current one,
coloring up the matching characters.
"""
start = match.start(group)
colored_text = text[prev_end:start]
end = match.end(group)
colored_text += colorin(text[start:end], color, style)
return colored_text, end
def colorup(text, pattern, color="red", style="normal", on_groups=False, sep_list=context["sep_list"]):
"""
Color up every characters that match the given regexp patterns.
If groups are specified, only color up them and not the whole pattern.
Colors and styles may be specified as a list of comma-separated values,
in which case the different matching groups may be formatted differently.
If there is less colors/styles than groups, the last format is used
for the additional groups.
"""
global context
global debug
if not debug:
regex = re.compile(pattern)
else:
regex = re.compile(pattern, re.DEBUG)
# Prepare the colored text.
colored_text = ""
end = 0
for match in regex.finditer(text):
# If no groups are specified
if not match.groups():
# Color the previous partial line,
partial, end = colorout(text, match, end, color, style)
# add it to the final text.
colored_text += partial
else:
nb_groups = len(match.groups())
# Build a list of colors that match the number of grouped,
# if there is not enough colors, duplicate the last one.
colors_l = color.split(sep_list)
group_colors = colors_l + [colors_l[-1]] * (nb_groups - len(colors_l))
# Same for styles
styles_l = style.split(sep_list)
group_styles = styles_l + [styles_l[-1]] * (nb_groups - len(styles_l))
# If we want to iterate colormaps on groups instead of patterns
if on_groups:
# Reset the counter at the beginning of each match
context["colormap_idx"] = 0
# For each group index.
# Note that match.groups returns a tuple (thus being indexed in [0,n[),
# but that match.start(0) refers to the whole match, the groups being indexed in [1,n].
# Thus, we need to range in [1,n+1[.
for group in range(1, nb_groups+1):
# If a group didn't match, there's nothing to color
if match.group(group) is not None:
partial, end = colorout(text, match, end, group_colors[group-1], group_styles[group-1], group)
colored_text += partial
# Append the remaining part of the text, if any.
colored_text += text[end:]
return colored_text
###########
# Helpers #
###########
def colortheme(item, theme):
"""
Take a list of list of args to colorup, and color the given item with sequential calls to colorup.
Used to read themes, which can be something like:
[ [ pattern, colors, styles ], [ pattern ], [ pattern, colors ] ]
"""
# logging.debug("use a theme with %i arguments" % len(theme))
for args in theme:
item = colorup(item, *args)
return item
def write(colored, stream = sys.stdout):
"""
Write "colored" on sys.stdout, then flush.
"""
try:
stream.write(colored)
stream.flush()
# Silently handle broken pipes
except IOError:
try:
stream.close()
except IOError:
pass
def map_write( stream_in, stream_out, function, *args ):
"""
Read the given file-like object as a non-blocking stream
and call the function on each item (line),
with the given extra arguments.
A call to "map_write(sys.stdin, colorup, pattern, colors)" will translate to the
non-blocking equivalent of:
for item in sys.stdin.readlines():
write( colorup( item, pattern, colors ) )
"""
while True:
try:
item = stream_in.readline()
except UnicodeDecodeError:
continue
except KeyboardInterrupt:
break
if not item:
break
write( function(item, *args), stream_out )
def colorgen(stream, pattern, color="red", style="normal", on_groups=False, sep_list=context["sep_list"]):
"""
A generator that colors the items given in an iterable input.
>>> import math
>>> list(colorgen([str(i) for i in [math.pi,math.e]],"1","red"))
['3.\x1b[0;31m1\x1b[0m4\x1b[0;31m1\x1b[0m59265359',
'2.7\x1b[0;31m1\x1b[0m828\x1b[0;31m1\x1b[0m82846']
"""
while True:
try:
item = stream.readline()
except KeyboardInterrupt:
break
if not item:
break
yield colorup(item, pattern, color, style, on_groups, sep_list)
######################
# Command line tools #
######################
def _args_parse(argv, usage=""):
"""
Parse command line arguments with the argparse library.
Returns a tuple of (pattern,color,style,on_stderr).
"""
parser = argparse.ArgumentParser(
description=usage)
parser.add_argument("pattern", metavar="REGEX", type=str, nargs=1,
help="A regular expression")
pygments_warn=" You can use a language name to activate syntax coloring (see `-r all` for a list)."
parser.add_argument("color", metavar="COLOR", type=str, nargs='?',
default="red",
help="A number in [0…255], a color name, a colormap name, \
a palette or a comma-separated list of those values." + pygments_warn)
parser.add_argument("style", metavar="STYLE", type=str, nargs='?',
default="bold",
help="One of the available styles or a comma-separated list of styles.")
parser.add_argument("-g", "--groups", action="store_true",
help="For color maps (random, rainbow, etc.), iterate over matching groups \
in the pattern instead of over patterns")
parser.add_argument("-c", "--colormap", action="store_true",
help="Interpret the given COLOR comma-separated list of colors as a colormap \
(cycle the colors at each match)")
babel_warn=" (numbers will be parsed according to your locale)"
parser.add_argument("-l", "--scale", metavar="SCALE",
help="When using the 'scale' colormap, parse matches as decimal numbers \
and apply the rainbow colormap linearly between the given SCALE=min,max" + babel_warn)
parser.add_argument("-a", "--all", action="store_true",
help="Color the whole input at once instead of line per line \
(really useful for coloring a source code file with strings \
on multiple lines).")
parser.add_argument("-t", "--theme", action="store_true",
help="Interpret REGEX as a theme.")
parser.add_argument("-T", "--themes-dir", metavar="DIR", action="append",
help="Search for additional themes (colout_*.py files) in the given directory")
parser.add_argument("-P", "--palettes-dir", metavar="DIR", action="append",
help="Search for additional palettes (*.gpl files) in the given directory")
parser.add_argument("-d", "--default", metavar="COLORMAP", default=None,
help="When using special colormaps (`random`, `scale` or `hash`), use this COLORMAP. \
This can be either one of the available colormaps or a comma-separated list of colors. \
WARNING: be sure to specify a default colormap that is compatible with the special colormap's mode \
(8 or 256 colors).")
# This normally should be an option with an argument, but this would end in an error,
# as no regexp is supposed to be passed after calling this option,
# we use it as the argument to this option.
# The only drawback is that the help message lacks a metavar...
parser.add_argument("-r", "--resources", action="store_true",
help="Print the names of available resources. Use a comma-separated list of resources names \
(styles, colors, special, themes, palettes, colormaps or lexers), \
use 'all' to print everything.")
parser.add_argument("-s", "--source", action="store_true",
help="Interpret REGEX as a source code readable by the Pygments library. \
If the first letter of PATTERN is upper case, use the 256 colors mode, \
if it is lower case, use the 8 colors mode. \
Interpret COLOR as a Pygments style." + pygments_warn)
parser.add_argument("-e", "--sep-list", metavar="CHAR", default=",", type=str,
help="Use this character as a separator for list of colors/resources/numbers (instead of comma).")
parser.add_argument("-E", "--sep-pair", metavar="CHAR", default=".", type=str,
help="Use this character as a separator for foreground/background pairs (instead of period).")
parser.add_argument("--debug", action="store_true",
help="Debug mode: print what's going on internally, useful if you want to check what features are available.")
# HACK: Mock up "--resources ALL" if just "--resources" on command line
if (len(sys.argv) == 2 and (sys.argv[1] in ["-r", "--resources"])):
sys.argv.append("ALL")
args = parser.parse_args()
return args.pattern[0], args.color, args.style, args.groups, \
args.colormap, args.theme, args.source, args.all, args.scale, args.debug, args.resources, args.palettes_dir, \
args.themes_dir, args.default, args.sep_list, args.sep_pair
def write_all( as_all, stream_in, stream_out, function, *args ):
"""
If as_all, print function(*args) on the whole stream,
else, print it for each line.
"""
if as_all:
write( function( stream_in.read(), *args ), stream_out )
else:
map_write( stream_in, stream_out, function, *args )
def main():
global context
usage = "A regular expression based formatter that color up an arbitrary text stream."
#####################
# Arguments parsing #
#####################
pattern, color, style, on_groups, as_colormap, as_theme, as_source, as_all, myscale, \
debug, resources, palettes_dirs, themes_dirs, default_colormap, sep_list, sep_pair \
= _args_parse(sys.argv, usage)
if debug:
lvl = logging.DEBUG
else:
lvl = logging.ERROR
logging.basicConfig(format='[colout] %(levelname)s: %(message)s', level=lvl)
##################
# Load resources #
##################
context["sep_list"] = sep_list
logging.debug("Color list separator: '%s'" % context["sep_list"])
context["sep_pair"] = sep_pair
logging.debug("Color pair separator: '%s'" % context["sep_pair"])
try:
# Search for available resources files (themes, palettes)
# in the same dir as the colout.py script
res_dir = os.path.dirname(os.path.realpath(__file__))
# this must be called before args parsing, because the help can list available resources
load_resources( res_dir, res_dir )
# try additional directories if asked
if palettes_dirs:
for adir in palettes_dirs:
if os.path.isdir(adir):
load_palettes( adir )
else:
logging.warning("cannot read palettes directory %s, ignore it" % adir)
if themes_dirs:
for adir in themes_dirs:
if os.path.isdir(adir):
load_themes( adir )
else:
logging.warning("cannot read themes directory %s, ignore it" % adir)
except DuplicatedPalette as e:
logging.error( "duplicated palette file name: %s" % e )
sys.exit( error_codes["DuplicatedPalette"] )
# if debug:
# setting = pprint.pformat(context, depth=2)
# logging.debug(setting)
if resources:
asked=[r.lower() for r in pattern.split(context["sep_list"])]
def join_sort( l ):
"""
Sort the given list in lexicographical order,
with upper-cases first, then lower cases
join the list with a comma.
>>> join_sort(["a","B","A","b"])
'A, a, B, b'
"""
return ", ".join(sorted(l, key=lambda s: s.lower()+s))
# print("Available resources:")
resources_not_found = []
for res in asked:
resource_found = False
if "style" in res or "all" in res:
print("STYLES: %s" % join_sort(context["styles"]) )
resource_found = True
if "color" in res or "all" in res:
print("COLORS: %s" % join_sort(context["colors"]) )
resource_found = True
if "special" in res or "all" in res:
print("SPECIAL: %s" % join_sort(["random", "Random", "scale", "Scale", "hash", "Hash", "colormap"]) )
resource_found = True
if "theme" in res or "all" in res:
if len(context["themes"]) > 0:
print("THEMES: %s" % join_sort(context["themes"].keys()) )
else:
print("NO THEME")
resource_found = True
if "colormap" in res or "all" in res:
if len(context["colormaps"]) > 0:
print("COLORMAPS: %s" % join_sort(context["colormaps"]) )
else:
print("NO COLORMAPS")
resource_found = True
if "lexer" in res or "all" in res:
if len(context["lexers"]) > 0:
print("SYNTAX COLORING: %s" % join_sort(context["lexers"]) )
else:
print("NO SYNTAX COLORING (check that python3-pygments is installed)")
resource_found = True
if not resource_found:
resources_not_found.append(res)
if resources_not_found:
logging.error( "Unknown resources: %s" % ", ".join(resources_not_found) )
sys.exit( error_codes["UnknownResource"] )
sys.exit(0) # not an error, we asked for help
############
# Coloring #
############
try:
if myscale:
context["scale"] = tuple([float(i) for i in myscale.split(context["sep_list"])])
logging.debug("user-defined scale: %f,%f" % context["scale"])
# Default color maps
if default_colormap:
if default_colormap not in context["colormaps"]:
cmap = make_colormap(default_colormap,context["sep_list"])
elif default_colormap in context["colormaps"]:
cmap = context["colormaps"][default_colormap]
set_special_colormaps( cmap, context["sep_list"] )
# explicit color map
if as_colormap is True and color not in context["colormaps"]:
context["colormaps"]["Default"] = make_colormap(color,context["sep_list"]) # replace the colormap by the given colors
context["colormaps"]["default"] = make_colormap(color,context["sep_list"]) # replace the colormap by the given colors
color = "colormap" # use the keyword to switch to colormap instead of list of colors
logging.debug("used-defined default colormap: %s" % context["sep_list"].join(context["colormaps"]["Default"]) )
# if theme
if as_theme:
logging.debug( "asked for theme: %s" % pattern )
assert(pattern in context["themes"].keys())
context,theme = context["themes"][pattern].theme(context)
write_all( as_all, sys.stdin, sys.stdout, colortheme, theme )
# if pygments
elif as_source:
logging.debug("asked for lexer: %s" % pattern.lower())
if pattern.lower() not in context["lexers"]:
logging.error("Lexer %r is not available. Run with \"--resources all\" to see the options.")
sys.exit(error_codes["UnknownLexer"])
lexer = get_lexer_by_name(pattern.lower())
# Python => 256 colors, python => 8 colors
ask_256 = pattern[0].isupper()
if ask_256:
logging.debug("256 colors mode")
try:
formatter = Terminal256Formatter(style=color)
except: # style not found
logging.warning("style %s not found, fallback to default style" % color)
formatter = Terminal256Formatter()
else:
logging.debug("8 colors mode")
formatter = TerminalFormatter()
write_all( as_all, sys.stdin, sys.stdout, highlight, lexer, formatter )
# if color
else:
write_all( as_all, sys.stdin, sys.stdout, colorup, pattern, color, style, on_groups, context["sep_list"] )
except UnknownColor as e:
if debug:
import traceback
print(traceback.format_exc())
logging.error("Unknown color: %s (maybe you forgot to install python3-pygments?)" % e )
sys.exit( error_codes["UnknownColor"] )
except MixedModes as e:
logging.error("You cannot mix up color modes when defining your own colormap." \
+ " Check the following 'color:mode' pairs: %s." % e )
sys.exit( error_codes["MixedModes"] )
if __name__ == "__main__":
main()
| 38,080
|
Python
|
.py
| 865
| 36.052023
| 180
| 0.600135
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,921
|
colout_valgrind.py
|
nojhan_colout/colout/colout_valgrind.py
|
#encoding: utf-8
def theme(context):
return context, [
# section title
[r"^(==[0-9]+==\s{1})(Memcheck|Copyright|Using)(.*)$","blue",""],
[r"^(==[0-9]+==\s{1})(Warning)(.*)$","magenta",""],
[r"^(==[0-9]+==\s{1}Command: )(\S*)(.*)$","green,white","normal,bold,normal"],
[r"^(==[0-9]+==\s{1})(HEAP SUMMARY:)(.*)$","green",""],
[r"^(==[0-9]+==\s{1})(All heap blocks were freed)(.*)$","green",""],
[r"^(==[0-9]+==\s{1})(.*[rR]erun.*)$","blue",""],
[r"^(==[0-9]+==\s{1})(Use --.*)$","blue",""],
[r"^(==[0-9]+==\s{1}\S+.*)$","red",""],
# section explanation
[r"^==[0-9]+==\s{2}(\S+.*)$","orange",""],
# locations adresses
[r"^==[0-9]+==\s{4}([atby]{2}) (0x0): (\?{3})",
"blue,yellow,red", "normal,normal,bold"],
[r"^==[0-9]+==\s{4}([atby]{2}) (0x)([^:]*:) (\S+)",
"blue,blue,blue,none", "normal"],
# locations: library
[r"\(in (.*)\)", "cyan", "normal"],
# locations: file
[r"\(([^\.]*\.[^:]+):([0-9]+)\)", "white,yellow", "bold,normal"],
# leak summary
[r"^==[0-9]+==\s{4}(definitely lost): .* (in) .*","red","bold"],
[r"^==[0-9]+==\s{4}(indirectly lost): .* (in) .*","orange","bold"],
[r"^==[0-9]+==\s{6}(possibly lost): .* (in) .*","yellow","bold"],
[r"^==[0-9]+==\s{4}(still reachable): .* (in) .*","green","bold"],
[r"^==[0-9]+==\s{9}(suppressed): .* (in) .*","cyan","bold"],
]
| 1,611
|
Python
|
.py
| 30
| 41.533333
| 90
| 0.364385
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,922
|
colout_python.py
|
nojhan_colout/colout/colout_python.py
|
def theme(context):
return context,[
# traceback header
["^Traceback .*$", "blue" ],
# File, line, in
[
r"^\s{2}(File \")(/*.*?/)*([^/:]+)(\", line) ([0-9]+)(, in) (.*)$",
"blue, none, white,blue, yellow,blue",
"normal,normal,bold, normal,normal,bold"
],
# [r"^\s{2}File \"(.*)\", line ([0-9]+), in (.*)$", "white,yellow,white", "normal,normal,bold" ],
# Error name
["^([A-Za-z]*Error):*", "red", "bold" ],
["^([A-Za-z]*Exception):*", "red", "bold" ],
# any quoted things
[r"Error.*['\"](.*)['\"]", "magenta" ],
# python code
[r"^\s{4}.*$", "Python", "monokai" ],
]
| 786
|
Python
|
.py
| 19
| 28.947368
| 109
| 0.373368
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,923
|
colout_json.py
|
nojhan_colout/colout/colout_json.py
|
def theme(context):
# This theme expect a formatted JSON input, with items spread across lines.
# See tools like "python -m json.tool" or "json_xs"
return context,[
[ r'[\[\]{}],*\s*\n' ],
[ '" (:) ', "yellow" ],
[ r'[\]}"](,)', "yellow" ],
[ r"\"(-*[0-9]+\.*[0-9]*e*-*[0-9]*)\"", "blue" ],
[ '"(.*)"', "green" ],
[ """["']""", "cyan" ]
]
| 405
|
Python
|
.py
| 11
| 29.818182
| 79
| 0.408163
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,924
|
colout_cmake.py
|
nojhan_colout/colout/colout_cmake.py
|
def theme(context):
# CMake theme:
# actions performing in cyan
performing="cyan"
# actions performed in green
performed="green"
# actions taking an unknown time
untimed="blue"
# If the user do not ask for his own colormap
if not context["user_defined_colormaps"]:
# A palette that goes: purple, orange, white
percs = [45, 39, 33, 27, 21, 57, 63, 62, 98, 97, 133, 132, 138, 173, 172, 208, 214, 220, 226, 228, 229, 230, 231, 255]
context["colormaps"]["Scale"] = percs
return context,[
# Configure...
[ "^--.*works", performed ],
[ "^--.*done", performed ],
[ "^-- Found.*NO", "red" ],
[ "^-- Found.*", performed ],
[ "^--.*broken", "red" ],
[ "^-- Coult NOT find.*", "red" ],
[ "^-- Configuring incomplete, errors occurred!", "red" ],
[ "^--.*", performing ],
# Errors
[ "CMake Error", "red" ],
[ "CMake Warning", "magenta" ],
[ "CMake Deprecation Warning", "magenta" ],
# Scan
[ "^(Scanning dependencies of target)(.*)$",
performing, "normal,bold" ],
# Link (make)
# [ "^(Linking .* )(library|executable) (.*/)*(.+(\.[aso]+)*)$",
[ "^(Linking .* )(library|executable) (.*)$",
untimed, "normal,normal,bold" ],
# [percent] Creating something
[ r"^\[\s*[0-9/]+%?\]\s(.*Creating.*)$",
performing, "normal" ],
# [percent] Built
[ r"^\[\s*[0-9/]+%?\]\s(Built target)(\s.*)$",
performed, "normal,bold" ],
# [percent] Building
[ r"^\[\s*[0-9/]+%?\]\s(Building \w* object)\s+(.*)(\.dir)(.*/)([-\w]+).c.*.o$",
performing+","+performing+","+performing+",Hash,"+performing, "normal,normal,normal,normal,bold"],
# [percent] Generating
[ r"^\[\s*[0-9/]+%?\]\s(Generating)(\s+.*)$",
performing, "normal,bold"],
# make errors
[ r"make\[[0-9]+\].*", "yellow"],
[ r"(make: \*\*\* \[.+\] )(.* [0-9]+)", "red", "normal,bold"],
# progress percentage (make)
[ r"^(\[\s*[0-9]+%\])","Scale" ]
]
| 2,157
|
Python
|
.py
| 52
| 33.115385
| 126
| 0.483825
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,925
|
colout_g++.py
|
nojhan_colout/colout/colout_g++.py
|
#encoding: utf-8
def default_gettext( msg ):
return msg
def theme(context):
import os
import gettext
import locale
section="blue"
# get g++ version
gv = os.popen("g++ -dumpversion").read().strip()
# get the current translations of gcc
try:
t = gettext.translation("gcc-"+gv)
except IOError:
_ = default_gettext
else:
_ = t.gettext
# _("msg") will return the given message, translated
# if the locale is unicode
enc = locale.getpreferredencoding()
if "UTF" in enc:
# gcc will use unicode quotes
qo = "[‘`]"
qc = "[’']"
else:
# rather than ascii ones
qo = "['`]"
qc = "'"
return context,[
# Command line
[ r"[/\s]([cg]\+\+-*[0-9]*\.*[0-9]*)", "white", "bold" ],
[ r"\s(\-D)(\s*[^\s]+)", "none,green", "normal,bold" ],
[ r"\s(-g)", "green", "normal" ],
[ r"\s-O[0-4]", "green", "normal" ],
[ r"\s-[Wf][^\s]*", "magenta", "normal" ],
[ r"\s-pedantic", "magenta", "normal" ],
[ r"\s(-I)(/*[^\s]+/)([^/\s]+)", "none,blue", "normal,normal,bold" ],
[ r"\s(-L)(/*[^\s]+/)([^/\s]+)", "none,cyan", "normal,normal,bold" ],
[ r"\s(-l)([^/\s]+)", "none,cyan", "normal,bold" ],
[ r"\s-[oc]", "red", "bold" ],
[ r"\s(-+std(?:lib)?)=?([^\s]+)", "red", "normal,bold" ],
# Important messages
[ _("error: "), "red", "bold" ],
[ _("fatal error: "), "red", "bold" ],
[ _("warning: "), "magenta", "bold" ],
[ _("undefined reference to "), "red", "bold" ],
# [-Wflag]
[ r"\[-W.*\]", "magenta"],
# Highlight message start:
# path file ext : line : col …
[ "(/.*?)/([^/:]+): (In .*)"+qo,
section,
"normal,normal,bold" ],
[ "(/.*?)/([^/:]+): (At .*)",
section,
"normal,normal,bold" ],
[ _("In file included from"), section ],
# Highlight locations:
# path file ext : line : col …
[ "(/.*?)/([^/:]+):([0-9]+):*([0-9]*)(.*)",
"none,white,yellow,none,none",
"normal,normal,normal,normal" ],
# source code in single quotes
[ qo+"(.*?)"+qc, "Cpp", "monokai" ],
# source code after a "note: candidate are/is:"
[ _("note: ")+"((?!.*("+qo+"|"+qc+")).*)$", "Cpp", "monokai" ],
# [ _("note: ")+"(candidate:)(.*)$", "green,Cpp", "normal,monokai" ],
# after the code part, to avoid matching ANSI escape chars
[ _("note: "), "green", "normal" ]
]
| 2,640
|
Python
|
.py
| 70
| 29.585714
| 77
| 0.443659
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,926
|
colout_slurm.py
|
nojhan_colout/colout/colout_slurm.py
|
def theme(context):
# SLURM's states (from squeue manual).
col_width = 9
COMPLETED =r"\bCOMPLETED"
PENDING =r"\bPENDING"
RUNNING =r"\bRUNNING"
CONFIGURING =r"\bCONFIGURING"
COMPLETING =r"\bCOMPLETING"
FAILED =r"\bFAILED"
DEADLINE =r"\bDEADLINE"
OUT_OF_MEMORY=r"\bOUT_OF_MEMORY"
TIMEOUT =r"\bTIMEOUT"
CANCELLED =r"\bCANCELLED"
BOOT_FAIL =r"\bBOOT_FAIL"
NODE_FAIL =r"\bNODE_FAIL"
PREEMPTED =r"\bPREEMPTED"
RESV_DEL_HOLD=r"\bRESV_DEL_HOLD"
REQUEUE_FED =r"\bREQUEUE_FED"
REQUEUE_HOLD =r"\bREQUEUE_HOLD"
REQUEUED =r"\bREQUEUED"
RESIZING =r"\bRESIZING"
REVOKED =r"\bREVOKED"
SIGNALING =r"\bSIGNALING"
SPECIAL_EXIT =r"\bSPECIAL_EXIT"
STAGE_OUT =r"\bSTAGE_OUT"
STOPPED =r"\bSTOPPED"
SUSPENDED =r"\bSUSPENDED"
return context,[
## No problem: greens
#Job has terminated all processes on all nodes with an exit code of zero.
[r"\bCD\b", "22"],
[COMPLETED[0:col_width]+r"\w*\b", "22"],
#Job is awaiting resource allocation.
[r"\bPD\b", "28"],
[PENDING[0:col_width]+r"\w*\b", "28"],
#Job currently has an allocation.
[r"\bR\b", "34"],
[RUNNING[0:col_width]+r"\w*\b", "34"],
#Job has been allocated resources, but are waiting for them to become ready for use (e.g. booting).
[r"\bCF\b", "58"],
[CONFIGURING[0:col_width]+r"\w*\b", "58"],
#Job is in the process of completing. Some processes on some nodes may still be active.
[r"\bCG\b", "23"],
[COMPLETING[0:col_width]+r"\w*\b", "23"],
## Problem for the user: bold reds
#Job terminated with non-zero exit code or other failure condition.
[r"\bF\b", "196"],
[FAILED[0:col_width]+r"\w*\b", "196", "bold"],
#Job terminated on deadline.
[r"\bDL\b", "160"],
[DEADLINE[0:col_width]+r"\w*\b", "160", "bold"],
#Job experienced out of memory error.
[r"\bOO\b", "197"],
[OUT_OF_MEMORY[0:col_width]+r"\w*\b", "197", "bold"],
#Job terminated upon reaching its time limit.
[r"\bTO\b", "161"],
[TIMEOUT[0:col_width]+r"\w*\b", "161", "bold"],
## Problem for the sysadmin: oranges
#Job was explicitly cancelled by the user or system administrator. The job may or may not have been initiated.
[r"\bCA\b", "202"],
[CANCELLED[0:col_width]+r"\w*\b", "202", "bold"],
#Job terminated due to launch failure, typically due to a hardware failure (e.g. unable to boot the node or block and the job can not be requeued).
[r"\bBF\b", "166"],
[BOOT_FAIL[0:col_width]+r"\w*\b", "166"],
#Job terminated due to failure of one or more allocated nodes.
[r"\bNF\b", "208"],
[NODE_FAIL[0:col_width]+r"\w*\b", "208"],
## Non-blocking events: blues
#Job terminated due to preemption.
[r"\bPR\b", "105"],
[PREEMPTED[0:col_width]+r"\w*\b", "105", "bold"],
#Job is being held after requested reservation was deleted.
[r"\bRD\b", "25"],
[RESV_DEL_HOLD[0:col_width]+r"\w*\b", "25"],
#Job is being requeued by a federation.
[r"\bRF\b", "26"],
[REQUEUE_FED[0:col_width]+r"\w*\b", "26"],
#Held job is being requeued.
[r"\bRH\b", "27"],
[REQUEUE_HOLD[0:col_width]+r"\w*\b", "27"],
#Completing job is being requeued.
[r"\bRQ\b", "31"],
[REQUEUED[0:col_width]+r"\w*\b", "31"],
#Job is about to change size.
[r"\bRS\b", "32"],
[RESIZING[0:col_width]+r"\w*\b", "32"],
#Sibling was removed from cluster due to other cluster starting the job.
[r"\bRV\b", "33"],
[REVOKED[0:col_width]+r"\w*\b", "33"],
#Job is being signaled.
[r"\bSI\b", "37"],
[SIGNALING[0:col_width]+r"\w*\b", "37"],
#The job was requeued in a special state. This state can be set by users, typically in EpilogSlurmctld, if the job has terminated with a particular exit value.
[r"\bSE\b", "38"],
[SPECIAL_EXIT[0:col_width]+r"\w*\b", "38"],
#Job is staging out files.
[r"\bSO\b", "39"],
[STAGE_OUT[0:col_width]+r"\w*\b", "39"],
#Job has an allocation, but execution has been stopped with SIGSTOP signal. CPUS have been retained by this job.
[r"\bST\b", "44"],
[STOPPED[0:col_width]+r"\w*\b", "44"],
#Job has an allocation, but execution has been suspended and CPUs have been released for other jobs.
[r"\bS\b", "45"],
[SUSPENDED[0:col_width]+r"\w*\b", "45"],
]
| 4,715
|
Python
|
.py
| 105
| 36.933333
| 167
| 0.566551
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,927
|
colout_python.py
|
nojhan_colout/colout/colout_python.py
|
def theme(context):
return context,[
# traceback header
["^Traceback .*$", "blue" ],
# File, line, in
[
r"^\s{2}(File \")(/*.*?/)*([^/:]+)(\", line) ([0-9]+)(, in) (.*)$",
"blue, none, white,blue, yellow,blue",
"normal,normal,bold, normal,normal,bold"
],
# [r"^\s{2}File \"(.*)\", line ([0-9]+), in (.*)$", "white,yellow,white", "normal,normal,bold" ],
# Error name
["^([A-Za-z]*Error):*", "red", "bold" ],
["^([A-Za-z]*Exception):*", "red", "bold" ],
# any quoted things
[r"Error.*['\"](.*)['\"]", "magenta" ],
# python code
[r"^\s{4}.*$", "Python", "monokai" ],
]
| 786
|
Python
|
.pyt
| 19
| 28.947368
| 109
| 0.373368
|
nojhan/colout
| 1,123
| 60
| 16
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,928
|
run_tests.py
|
ycm-core_YouCompleteMe/run_tests.py
|
#!/usr/bin/env python3
import argparse
import glob
import os
import os.path as p
import subprocess
import sys
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
# We don't include python-future (not to be confused with pythonfutures) because
# it needs to be inserted in sys.path AFTER the standard library imports but we
# can't do that with PYTHONPATH because the std lib paths are always appended to
# PYTHONPATH. We do it correctly inside Vim because we have access to the right
# sys.path. So for dev, we rely on python-future being installed correctly with
#
# pip install -r python/test_requirements.txt
#
# Pip knows how to install this correctly so that it doesn't matter where in
# sys.path the path is.
python_path = [ p.join( DIR_OF_THIS_SCRIPT, 'python' ),
p.join( DIR_OF_THIRD_PARTY, 'ycmd' ) ]
if os.environ.get( 'PYTHONPATH' ):
python_path.append( os.environ[ 'PYTHONPATH' ] )
os.environ[ 'PYTHONPATH' ] = os.pathsep.join( python_path )
def RunFlake8():
print( 'Running flake8' )
args = [ sys.executable,
'-m',
'flake8',
p.join( DIR_OF_THIS_SCRIPT, 'python' ) ]
root_dir_scripts = glob.glob( p.join( DIR_OF_THIS_SCRIPT, '*.py' ) )
args.extend( root_dir_scripts )
subprocess.check_call( args )
def ParseArguments():
parser = argparse.ArgumentParser()
parser.add_argument( '--skip-build', action = 'store_true',
help = 'Do not build ycmd before testing' )
parser.add_argument( '--coverage', action = 'store_true',
help = 'Enable coverage report' )
parser.add_argument( '--no-flake8', action = 'store_true',
help = 'Do not run flake8' )
parser.add_argument( '--dump-path', action = 'store_true',
help = 'Dump the PYTHONPATH required to run tests '
'manually, then exit.' )
parsed_args, unittest_args = parser.parse_known_args()
if 'COVERAGE' in os.environ:
parsed_args.coverage = ( os.environ[ 'COVERAGE' ] == 'true' )
return parsed_args, unittest_args
def BuildYcmdLibs( args ):
if not args.skip_build:
subprocess.check_call( [
sys.executable,
p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ),
'--quiet'
] )
def UnittestTests( parsed_args, extra_unittest_args ):
# if any extra arg is a specific file, or the '--' token, then assume the
# arguments are unittest-aware test selection:
# - don't use discover
# - don't set the pattern to search for
unittest_args = [ '-cb' ]
prefer_regular = any( arg == '--' or p.isfile( arg )
for arg in extra_unittest_args )
if not prefer_regular:
unittest_args += [ '-p', '*_test.py' ]
if extra_unittest_args:
unittest_args.extend( extra_unittest_args )
if not ( prefer_regular and extra_unittest_args ):
unittest_args.append( '-s' )
test_directory = p.join( DIR_OF_THIS_SCRIPT, 'python', 'ycm', 'tests' )
unittest_args.append( test_directory )
if parsed_args.coverage:
executable = [ sys.executable,
'-m',
'coverage',
'run' ]
else:
executable = [ sys.executable, '-We' ]
unittest = [ '-m', 'unittest' ]
if not prefer_regular:
unittest.append( 'discover' )
subprocess.check_call( executable + unittest + unittest_args )
def Main():
( parsed_args, unittest_args ) = ParseArguments()
if parsed_args.dump_path:
print( os.environ[ 'PYTHONPATH' ] )
sys.exit()
if not parsed_args.no_flake8:
RunFlake8()
BuildYcmdLibs( parsed_args )
UnittestTests( parsed_args, unittest_args )
if __name__ == "__main__":
Main()
| 3,761
|
Python
|
.py
| 93
| 34.935484
| 80
| 0.649383
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,929
|
install.py
|
ycm-core_YouCompleteMe/install.py
|
#!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import subprocess
import sys
import os.path as p
import glob
version = sys.version_info[ 0 : 3 ]
if version < ( 3, 6, 0 ):
sys.exit( 'YouCompleteMe requires Python >= 3.6.0; '
'your version of Python is ' + sys.version )
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_OLD_LIBS = p.join( DIR_OF_THIS_SCRIPT, 'python' )
def CheckCall( args, **kwargs ):
try:
subprocess.check_call( args, **kwargs )
except subprocess.CalledProcessError as error:
sys.exit( error.returncode )
def Main():
build_file = p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' )
if not p.isfile( build_file ):
sys.exit(
'File {0} does not exist; you probably forgot to run:\n'
'\tgit submodule update --init --recursive\n'.format( build_file ) )
CheckCall( [ sys.executable, build_file ] + sys.argv[ 1: ] )
# Remove old YCM libs if present so that YCM can start.
old_libs = (
glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_core.*' ) ) +
glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_client_support.*' ) ) +
glob.glob( p.join( DIR_OF_OLD_LIBS, '*clang*.*' ) ) )
for lib in old_libs:
os.remove( lib )
if __name__ == "__main__":
Main()
| 1,389
|
Python
|
.py
| 37
| 34.243243
| 78
| 0.660941
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,930
|
.ycm_extra_conf.py
|
ycm-core_YouCompleteMe/.ycm_extra_conf.py
|
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
import os.path as p
import subprocess
DIR_OF_THIS_SCRIPT = p.abspath( p.dirname( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
def GetStandardLibraryIndexInSysPath( sys_path ):
for index, path in enumerate( sys_path ):
if p.isfile( p.join( path, 'os.py' ) ):
return index
raise RuntimeError( 'Could not find standard library path in Python path.' )
def PythonSysPath( **kwargs ):
sys_path = kwargs[ 'sys_path' ]
dependencies = [ p.join( DIR_OF_THIS_SCRIPT, 'python' ),
p.join( DIR_OF_THIRD_PARTY, 'requests-futures' ),
p.join( DIR_OF_THIRD_PARTY, 'ycmd' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'idna' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'chardet' ),
p.join( DIR_OF_THIRD_PARTY,
'requests_deps',
'urllib3',
'src' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'certifi' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'requests' ) ]
# The concurrent.futures module is part of the standard library on Python 3.
interpreter_path = kwargs[ 'interpreter_path' ]
major_version = int( subprocess.check_output( [
interpreter_path, '-c', 'import sys; print( sys.version_info[ 0 ] )' ]
).rstrip().decode( 'utf8' ) )
if major_version == 2:
dependencies.append( p.join( DIR_OF_THIRD_PARTY, 'pythonfutures' ) )
sys_path[ 0:0 ] = dependencies
sys_path.insert( GetStandardLibraryIndexInSysPath( sys_path ) + 1,
p.join( DIR_OF_THIRD_PARTY, 'python-future', 'src' ) )
return sys_path
| 3,104
|
Python
|
.py
| 62
| 44.467742
| 78
| 0.683047
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,931
|
doc.py
|
ycm-core_YouCompleteMe/test/testdata/python/doc.py
|
# Comment
def Test_OneLine():
"""This is the one line output."""
pass
def Test_MultiLine():
"""This is the one line output.
This is second line."""
pass
def Main():
Test_OneLine()
Test_MultiLine()
def Really_Long_Method( which, has, some, param, that, take, the, whole, line ):
"""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum egestas libero urna, vel sagittis felis condimentum in. Nulla arcu eros, aliquet vel mollis vitae, semper eu ex. Donec posuere quam et ornare sagittis. Curabitur nunc ex, fringilla quis lorem sed, dignissim congue felis. Integer vestibulum ac elit vel blandit. Nam non dui urna. Integer eu semper massa. Nullam ac elit interdum, aliquet elit nec, porttitor orci. Duis tempus justo lorem, ac fringilla ante viverra egestas. Etiam eleifend enim ac libero dapibus, quis condimentum lectus tristique. Fusce feugiat, lorem et faucibus eleifend, ipsum nisi maximus justo, at consectetur ligula leo vitae justo."""
# Really long one-line
pass
def Really_Long_Method_2():
"""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum egestas
libero urna, vel sagittis felis condimentum in. Nulla arcu eros, aliquet vel
mollis vitae, semper eu ex. Donec posuere quam et ornare sagittis. Curabitur
nunc ex, fringilla quis lorem sed, dignissim congue felis. Integer vestibulum
ac elit vel blandit. Nam non dui urna. Integer eu semper massa. Nullam ac elit
interdum, aliquet elit nec, porttitor orci. Duis tempus justo lorem, ac
fringilla ante viverra egestas. Etiam eleifend enim ac libero dapibus, quis
condimentum lectus tristique. Fusce feugiat, lorem et faucibus eleifend, ipsum
nisi maximus justo, at consectetur ligula leo vitae justo."""
# Really long one para
pass
def Moan():
Really_Long_Method()
Really_Long_Method_2()
| 1,830
|
Python
|
.py
| 30
| 58.2
| 680
| 0.774554
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,932
|
syntax_parse.py
|
ycm-core_YouCompleteMe/python/ycm/syntax_parse.py
|
# Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import re
from ycm import vimsupport
SYNTAX_GROUP_REGEX = re.compile(
r"""^
(?P<group_name>\w+)
\s+
xxx
\s+
(?P<content>.+?)
$""",
re.VERBOSE )
KEYWORD_REGEX = re.compile( r'^(\w+),?$' )
SYNTAX_ARGUMENT_REGEX = re.compile(
r"^\w+=.*$" )
SYNTAX_REGION_ARGUMENT_REGEX = re.compile(
r"^(?:matchgroup|start)=.*$" )
# See ":h syn-nextgroup".
SYNTAX_NEXTGROUP_ARGUMENTS = {
'skipwhite',
'skipnl',
'skipempty'
}
# These are the parent groups from which we want to extract keywords.
ROOT_GROUPS = {
'Boolean',
'Identifier',
'Statement',
'PreProc',
'Type'
}
class SyntaxGroup:
def __init__( self, name, lines = None ):
self.name = name
self.lines = lines if lines else []
self.children = []
def SyntaxKeywordsForCurrentBuffer():
syntax_output = vimsupport.CaptureVimCommand( 'syntax list' )
return _KeywordsFromSyntaxListOutput( syntax_output )
def _KeywordsFromSyntaxListOutput( syntax_output ):
group_name_to_group = _SyntaxGroupsFromOutput( syntax_output )
_ConnectGroupChildren( group_name_to_group )
groups_with_keywords = []
for root_group in ROOT_GROUPS:
groups_with_keywords.extend(
_GetAllDescendentats( group_name_to_group[ root_group ] ) )
keywords = []
for group in groups_with_keywords:
keywords.extend( _ExtractKeywordsFromGroup( group ) )
return set( keywords )
def _SyntaxGroupsFromOutput( syntax_output ):
group_name_to_group = _CreateInitialGroupMap()
lines = syntax_output.split( '\n' )
looking_for_group = True
current_group = None
for line in lines:
if not line:
continue
match = SYNTAX_GROUP_REGEX.search( line )
if match:
if looking_for_group:
looking_for_group = False
else:
group_name_to_group[ current_group.name ] = current_group
current_group = SyntaxGroup( match.group( 'group_name' ),
[ match.group( 'content' ).strip() ] )
else:
if looking_for_group:
continue
if line[ 0 ] == ' ' or line[ 0 ] == '\t':
current_group.lines.append( line.strip() )
if current_group:
group_name_to_group[ current_group.name ] = current_group
return group_name_to_group
def _CreateInitialGroupMap():
def AddToGroupMap( name, parent ):
new_group = SyntaxGroup( name )
group_name_to_group[ name ] = new_group
parent.children.append( new_group )
identifier_group = SyntaxGroup( 'Identifier' )
statement_group = SyntaxGroup( 'Statement' )
type_group = SyntaxGroup( 'Type' )
preproc_group = SyntaxGroup( 'PreProc' )
# See ":h group-name" for details on how the initial group hierarchy is built.
group_name_to_group = {
'Boolean': SyntaxGroup( 'Boolean' ),
'Identifier': identifier_group,
'Statement': statement_group,
'PreProc': preproc_group,
'Type': type_group
}
AddToGroupMap( 'Function', identifier_group )
AddToGroupMap( 'Conditional', statement_group )
AddToGroupMap( 'Repeat' , statement_group )
AddToGroupMap( 'Label' , statement_group )
AddToGroupMap( 'Operator' , statement_group )
AddToGroupMap( 'Keyword' , statement_group )
AddToGroupMap( 'Exception' , statement_group )
AddToGroupMap( 'StorageClass', type_group )
AddToGroupMap( 'Structure' , type_group )
AddToGroupMap( 'Typedef' , type_group )
AddToGroupMap( 'Include' , preproc_group )
AddToGroupMap( 'Define' , preproc_group )
AddToGroupMap( 'Macro' , preproc_group )
AddToGroupMap( 'PreCondit', preproc_group )
return group_name_to_group
def _ConnectGroupChildren( group_name_to_group ):
def GetParentNames( group ):
links_to = 'links to '
parent_names = []
for line in group.lines:
if line.startswith( links_to ):
parent_names.append( line[ len( links_to ): ] )
return parent_names
for group in group_name_to_group.values():
parent_names = GetParentNames( group )
for parent_name in parent_names:
try:
parent_group = group_name_to_group[ parent_name ]
except KeyError:
continue
parent_group.children.append( group )
def _GetAllDescendentats( root_group ):
descendants = []
for child in root_group.children:
descendants.append( child )
descendants.extend( _GetAllDescendentats( child ) )
return descendants
def _ExtractKeywordsFromLine( line ):
if line.startswith( 'links to ' ):
return []
# Ignore "syntax match" lines (see ":h syn-match").
if line.startswith( 'match ' ):
return []
words = line.split()
if not words:
return []
# Ignore "syntax region" lines (see ":h syn-region"). They always start
# with matchgroup= or start= in the syntax list.
if SYNTAX_REGION_ARGUMENT_REGEX.match( words[ 0 ] ):
return []
# Ignore "nextgroup=" argument in first position and the arguments
# "skipwhite", "skipnl", and "skipempty" that immediately come after.
nextgroup_at_start = False
if words[ 0 ].startswith( 'nextgroup=' ):
nextgroup_at_start = True
words = words[ 1: ]
# Ignore "contained" argument in first position.
if words[ 0 ] == 'contained':
words = words[ 1: ]
keywords = []
for word in words:
if nextgroup_at_start and word in SYNTAX_NEXTGROUP_ARGUMENTS:
continue
nextgroup_at_start = False
keyword_matched = KEYWORD_REGEX.match( word )
if keyword_matched:
keywords.append( keyword_matched.group( 1 ) )
return keywords
def _ExtractKeywordsFromGroup( group ):
keywords = []
for line in group.lines:
keywords.extend( _ExtractKeywordsFromLine( line ) )
return keywords
| 6,371
|
Python
|
.py
| 179
| 31.463687
| 80
| 0.688751
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,933
|
vimsupport.py
|
ycm-core_YouCompleteMe/python/ycm/vimsupport.py
|
# Copyright (C) 2011-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import vim
import os
import json
import re
from collections import defaultdict, namedtuple
from functools import lru_cache as memoize
from ycmd.utils import ( ByteOffsetToCodepointOffset,
GetCurrentDirectory,
JoinLinesAsUnicode,
OnMac,
OnWindows,
ToBytes,
ToUnicode )
BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
'split' : 'split',
# These commands are obsolete. :vertical or :tab should
# be used with the 'split' command instead.
'horizontal-split' : 'split',
'vertical-split' : 'vsplit',
'new-tab' : 'tabedit' }
FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT = (
'The requested operation will apply changes to {0} files which are not '
'currently open. This will therefore open {0} new files in the hidden '
'buffers. The quickfix list can then be used to review the changes. No '
'files will be written to disk. Do you wish to continue?' )
NO_SELECTION_MADE_MSG = "No valid selection was made; aborting."
# When we're in a buffer without a file name associated with it, we need to
# invent a file name. We do so by the means of $CWD/$BUFNR.
# However, that causes problems with diagnostics - we also need a way to map
# those same file names back to their originating buffer numbers.
MADEUP_FILENAME_TO_BUFFER_NUMBER = {}
NO_COMPLETIONS = {
'line': -1,
'column': -1,
'completion_start_column': -1,
'completions': []
}
YCM_NEOVIM_NS_ID = vim.eval( 'g:ycm_neovim_ns_id' )
def CurrentLineAndColumn():
"""Returns the 0-based current line and 0-based current column."""
# See the comment in CurrentColumn about the calculation for the line and
# column number
line, column = vim.current.window.cursor
line -= 1
return line, column
def SetCurrentLineAndColumn( line, column ):
"""Sets the cursor position to the 0-based line and 0-based column."""
# Line from vim.current.window.cursor is 1-based.
vim.current.window.cursor = ( line + 1, column )
def CurrentColumn():
"""Returns the 0-based current column. Do NOT access the CurrentColumn in
vim.current.line. It doesn't exist yet when the cursor is at the end of the
line. Only the chars before the current column exist in vim.current.line."""
# vim's columns are 1-based while vim.current.line columns are 0-based
# ... but vim.current.window.cursor (which returns a (line, column) tuple)
# columns are 0-based, while the line from that same tuple is 1-based.
# vim.buffers buffer objects OTOH have 0-based lines and columns.
# Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
return vim.current.window.cursor[ 1 ]
def CurrentLineContents():
return ToUnicode( vim.current.line )
def CurrentLineContentsAndCodepointColumn():
"""Returns the line contents as a unicode string and the 0-based current
column as a codepoint offset. If the current column is outside the line,
returns the column position at the end of the line."""
line = CurrentLineContents()
byte_column = CurrentColumn()
# ByteOffsetToCodepointOffset expects 1-based offset.
column = ByteOffsetToCodepointOffset( line, byte_column + 1 ) - 1
return line, column
def TextAfterCursor():
"""Returns the text after CurrentColumn."""
return ToUnicode( vim.current.line[ CurrentColumn(): ] )
def TextBeforeCursor():
"""Returns the text before CurrentColumn."""
return ToUnicode( vim.current.line[ :CurrentColumn() ] )
def BufferModified( buffer_object ):
return buffer_object.options[ 'mod' ]
def GetBufferData( buffer_object ):
return {
# Add a newline to match what gets saved to disk. See #1455 for details.
'contents': JoinLinesAsUnicode( buffer_object ) + '\n',
'filetypes': FiletypesForBuffer( buffer_object )
}
def GetUnsavedAndSpecifiedBufferData( included_buffer, included_filepath ):
"""Build part of the request containing the contents and filetypes of all
dirty buffers as well as the buffer |included_buffer| with its filepath
|included_filepath|."""
buffers_data = { included_filepath: GetBufferData( included_buffer ) }
for buffer_object in vim.buffers:
if not BufferModified( buffer_object ):
continue
filepath = GetBufferFilepath( buffer_object )
if filepath in buffers_data:
continue
buffers_data[ filepath ] = GetBufferData( buffer_object )
return buffers_data
def GetBufferNumberForFilename( filename, create_buffer_if_needed = False ):
realpath = os.path.realpath( filename )
return MADEUP_FILENAME_TO_BUFFER_NUMBER.get( realpath, GetIntValue(
f"bufnr( '{ EscapeForVim( realpath ) }', "
f"{ int( create_buffer_if_needed ) } )" ) )
def GetCurrentBufferFilepath():
return GetBufferFilepath( vim.current.buffer )
def BufferIsVisible( buffer_number ):
if buffer_number < 0:
return False
window_number = GetIntValue( f"bufwinnr( { buffer_number } )" )
return window_number != -1
def GetBufferFilepath( buffer_object ):
if buffer_object.name:
return os.path.abspath( ToUnicode( buffer_object.name ) )
# Buffers that have just been created by a command like :enew don't have any
# buffer name so we use the buffer number for that.
name = os.path.join( GetCurrentDirectory(), str( buffer_object.number ) )
MADEUP_FILENAME_TO_BUFFER_NUMBER[ name ] = buffer_object.number
return name
def GetCurrentBufferNumber():
return vim.current.buffer.number
def GetBufferChangedTick( bufnr ):
try:
return GetIntValue( f'getbufvar({ bufnr }, "changedtick")' )
except ValueError:
# For some reason, occasionally changedtick returns '' and causes an error.
# In that case, just return 0 rather than spamming an error to the console.
return 0
# Returns a range covering the earliest and latest lines visible in the current
# tab page for the supplied buffer number. By default this range is then
# extended by half of the resulting range size
def RangeVisibleInBuffer( bufnr, grow_factor=0.5 ):
windows = [ w for w in vim.eval( f'win_findbuf( { bufnr } )' )
if GetIntValue( vim.eval( f'win_id2tabwin( { w } )[ 0 ]' ) ) ==
vim.current.tabpage.number ]
class Location:
line: int = None
col: int = None
class Range:
start: Location = Location()
end: Location = Location()
try:
buffer = vim.buffers[ bufnr ]
except KeyError:
return None
if not windows:
return None
r = Range()
# Note, for this we ignore horizontal scrolling
for winid in windows:
win_info = vim.eval( f'getwininfo( { winid } )[ 0 ]' )
if r.start.line is None or r.start.line > int( win_info[ 'topline' ] ):
r.start.line = int( win_info[ 'topline' ] )
if r.end.line is None or r.end.line < int( win_info[ 'botline' ] ):
r.end.line = int( win_info[ 'botline' ] )
# Extend the range by 1 factor, and calculate the columns
num_lines = r.end.line - r.start.line + 1
r.start.line = max( r.start.line - int( num_lines * grow_factor ), 1 )
r.start.col = 1
r.end.line = min( r.end.line + int( num_lines * grow_factor ), len( buffer ) )
r.end.col = len( buffer[ r.end.line - 1 ] )
filepath = GetBufferFilepath( buffer )
return {
'start': {
'line_num': r.start.line,
'column_num': r.start.col,
'filepath': filepath,
},
'end': {
'line_num': r.end.line,
'column_num': r.end.col,
'filepath': filepath,
}
}
def VisibleRangeOfBufferOverlaps( bufnr, expanded_range ):
visible_range = RangeVisibleInBuffer( bufnr, 0 )
# As above, we ignore horizontal scroll and only check lines
return (
expanded_range is not None and
visible_range is not None and
visible_range[ 'start' ][ 'line_num' ]
>= expanded_range[ 'start' ][ 'line_num' ] and
visible_range[ 'end' ][ 'line_num' ]
<= expanded_range[ 'end' ][ 'line_num' ]
)
def CaptureVimCommand( command ):
return vim.eval( f"execute( '{ EscapeForVim( command ) }', 'silent!' )" )
def GetSignsInBuffer( buffer_number ):
return vim.eval(
f'sign_getplaced( { buffer_number }, {{ "group": "ycm_signs" }} )'
)[ 0 ][ 'signs' ]
class DiagnosticProperty( namedtuple( 'DiagnosticProperty', [ 'id',
'type',
'line',
'column',
'length' ] ) ):
def __eq__( self, other ):
return ( self.type == other.type and
self.line == other.line and
self.column == other.column and
self.length == other.length )
def GetTextPropertyForDiag( buffer_number, line_number, diag ):
range = diag[ 'location_extent' ]
start = range[ 'start' ]
end = range[ 'end' ]
start_line = start[ 'line_num' ]
end_line = end[ 'line_num' ]
if start_line == end_line:
length = end[ 'column_num' ] - start[ 'column_num' ]
column = start[ 'column_num' ]
elif start_line == line_number:
# -1 switches to 0-based indexing.
current_line_len = len( vim.buffers[ buffer_number ][ line_number - 1 ] )
# +2 includes the start columnand accounts for properties at the end of line
# covering \n as well.
length = current_line_len - start[ 'column_num' ] + 2
column = start[ 'column_num' ]
elif end_line == line_number:
length = end[ 'column_num' ] - 1
column = 1
else:
# -1 switches to 0-based indexing.
# +1 accounts for properties at the end of line covering \n as well.
length = len( vim.buffers[ buffer_number ][ line_number - 1 ] ) + 1
column = 1
if diag[ 'kind' ] == 'ERROR':
property_name = 'YcmErrorProperty'
else:
property_name = 'YcmWarningProperty'
vim_props = vim.eval( f'prop_list( { line_number }, '
f'{{ "bufnr": { buffer_number }, '
f'"types": [ "{ property_name }" ] }} )' )
return next( filter(
lambda p: column == int( p[ 'col' ] ) and
length == int( p[ 'length' ] ),
vim_props ) )
def GetTextProperties( buffer_number ):
if not VimIsNeovim():
return [
DiagnosticProperty(
int( p[ 'id' ] ),
p[ 'type' ],
int( p[ 'lnum' ] ),
int( p[ 'col' ] ),
int( p[ 'length' ] ) )
for p in vim.eval(
f'prop_list( 1, '
f'{{ "bufnr": { buffer_number }, '
'"end_lnum": -1, '
'"types": [ "YcmErrorProperty", '
'"YcmWarningProperty" ] } )' ) ]
else:
ext_marks = vim.eval(
f'nvim_buf_get_extmarks( { buffer_number }, '
f'{ YCM_NEOVIM_NS_ID }, '
'0, '
'-1, '
'{ "details": 1 } )' )
return [ DiagnosticProperty(
int( id ),
extra_args[ 'hl_group' ],
int( line ) + 1, # Neovim uses 0-based lines and columns
int( column ) + 1,
int( extra_args[ 'end_col' ] ) - int( column ) )
for id, line, column, extra_args in ext_marks ]
def AddTextProperty( buffer_number,
line,
column,
prop_type,
extra_args ):
if not VimIsNeovim():
extra_args.update( {
'type': prop_type,
'bufnr': buffer_number
} )
return GetIntValue( f'prop_add( { line }, '
f'{ column }, '
f'{ json.dumps( extra_args ) } )' )
else:
extra_args[ 'hl_group' ] = prop_type
# Neovim uses 0-based offsets
if 'end_lnum' in extra_args:
extra_args[ 'end_line' ] = extra_args.pop( 'end_lnum' ) - 1
if 'end_col' in extra_args:
extra_args[ 'end_col' ] = extra_args.pop( 'end_col' ) - 1
line -= 1
column -= 1
return GetIntValue( f'nvim_buf_set_extmark( { buffer_number }, '
f'{ YCM_NEOVIM_NS_ID }, '
f'{ line }, '
f'{ column }, '
f'{ extra_args } )' )
def RemoveDiagnosticProperty( buffer_number: int, prop: DiagnosticProperty ):
RemoveTextProperty( buffer_number,
prop.line,
prop.id,
prop.type )
def RemoveTextProperty( buffer_number, line_num, prop_id, prop_type ):
if not VimIsNeovim():
p = {
'bufnr': buffer_number,
'id': prop_id,
'type': prop_type,
'both': 1,
'all': 1
}
vim.eval( f'prop_remove( { p }, { line_num } )' )
else:
vim.eval( f'nvim_buf_del_extmark( { buffer_number }, '
f'{ YCM_NEOVIM_NS_ID }, '
f'{ prop_id } )' )
# Clamps the line and column numbers so that they are not past the contents of
# the buffer. Numbers are 1-based byte offsets.
def LineAndColumnNumbersClamped( bufnr, line_num, column_num ):
vim_buffer = vim.buffers[ bufnr ]
line_num = max( min( line_num, len( vim_buffer ) ), 1 )
# Vim buffers are lists Unicode objects on Python 3.
max_column = len( ToBytes( vim_buffer[ line_num - 1 ] ) ) + 1
return line_num, max( min( column_num, max_column ), 1 )
def SetLocationList( diagnostics ):
"""Set the location list for the current window to the supplied diagnostics"""
SetLocationListForWindow( vim.current.window, diagnostics )
def GetWindowsForBufferNumber( buffer_number ):
"""Return the list of windows containing the buffer with number
|buffer_number| for the current tab page."""
return [ window for window in vim.windows
if window.buffer.number == buffer_number ]
def SetLocationListsForBuffer( buffer_number,
diagnostics,
open_on_edit = False ):
"""Populate location lists for all windows containing the buffer with number
|buffer_number|. See SetLocationListForWindow for format of diagnostics."""
for window in GetWindowsForBufferNumber( buffer_number ):
SetLocationListForWindow( window, diagnostics, open_on_edit )
def SetLocationListForWindow( window,
diagnostics,
open_on_edit = False ):
window_id = WinIDForWindow( window )
"""Populate the location list with diagnostics. Diagnostics should be in
qflist format; see ":h setqflist" for details."""
ycm_loc_id = window.vars.get( 'ycm_loc_id' )
# User may have made a bunch of `:lgrep` calls and we do not own the
# location list with the ID we remember any more.
if ( ycm_loc_id is not None and
vim.eval( f'getloclist( { window_id }, '
f'{{ "id": { ycm_loc_id }, '
'"title": 0 } ).title' ) == 'ycm_loc' ):
ycm_loc_id = None
if ycm_loc_id is None:
# Create new and populate
vim.eval( f'setloclist( { window_id }, '
'[], '
'" ", '
'{ "title": "ycm_loc", '
f'"items": { json.dumps( diagnostics ) } }} )' )
window.vars[ 'ycm_loc_id' ] = GetIntValue(
f'getloclist( { window_id }, {{ "nr": "$", "id": 0 }} ).id' )
elif open_on_edit:
# Remove old and create new list
vim.eval( f'setloclist( { window_id }, '
'[], '
'"r", '
f'{{ "id": { ycm_loc_id }, '
'"items": [], "title": "" } )' )
vim.eval( f'setloclist( { window_id }, '
'[], '
'" ", '
'{ "title": "ycm_loc", '
f'"items": { json.dumps( diagnostics ) } }} )' )
window.vars[ 'ycm_loc_id' ] = GetIntValue(
f'getloclist( { window_id }, {{ "nr": "$", "id": 0 }} ).id' )
else:
# Just populate the old one
vim.eval( f'setloclist( { window_id }, '
'[], '
'"r", '
f'{{ "id": { ycm_loc_id }, '
f'"items": { json.dumps( diagnostics ) } }} )' )
def OpenLocationList( focus = False, autoclose = False ):
"""Open the location list to the bottom of the current window with its
height automatically set to fit all entries. This behavior can be overridden
by using the YcmLocationOpened autocommand. When focus is set to True, the
location list window becomes the active window. When autoclose is set to True,
the location list window is automatically closed after an entry is
selected."""
vim.command( 'lopen' )
SetFittingHeightForCurrentWindow()
if autoclose:
AutoCloseOnCurrentBuffer( 'ycmlocation' )
if VariableExists( '#User#YcmLocationOpened' ):
vim.command( 'doautocmd User YcmLocationOpened' )
if not focus:
JumpToPreviousWindow()
def SetQuickFixList( quickfix_list ):
"""Populate the quickfix list and open it. List should be in qflist format:
see ":h setqflist" for details."""
vim.eval( f'setqflist( { json.dumps( quickfix_list ) } )' )
def OpenQuickFixList( focus = False, autoclose = False ):
"""Open the quickfix list to full width at the bottom of the screen with its
height automatically set to fit all entries. This behavior can be overridden
by using the YcmQuickFixOpened autocommand.
See the OpenLocationList function for the focus and autoclose options."""
vim.command( 'botright copen' )
SetFittingHeightForCurrentWindow()
if autoclose:
AutoCloseOnCurrentBuffer( 'ycmquickfix' )
if VariableExists( '#User#YcmQuickFixOpened' ):
vim.command( 'doautocmd User YcmQuickFixOpened' )
if not focus:
JumpToPreviousWindow()
def ComputeFittingHeightForCurrentWindow():
current_window = vim.current.window
if not current_window.options[ 'wrap' ]:
return len( vim.current.buffer )
window_width = current_window.width
fitting_height = 0
for line in vim.current.buffer:
fitting_height += len( line ) // window_width + 1
return fitting_height
def SetFittingHeightForCurrentWindow():
if int( vim.current.buffer.vars.get( 'ycm_no_resize', 0 ) ):
return
vim.command( f'{ ComputeFittingHeightForCurrentWindow() }wincmd _' )
def ConvertDiagnosticsToQfList( diagnostics ):
def ConvertDiagnosticToQfFormat( diagnostic ):
# See :h getqflist for a description of the dictionary fields.
# Note that, as usual, Vim is completely inconsistent about whether
# line/column numbers are 1 or 0 based in its various APIs. Here, it wants
# them to be 1-based. The documentation states quite clearly that it
# expects a byte offset, by which it means "1-based column number" as
# described in :h getqflist ("the first column is 1").
location = diagnostic[ 'location' ]
line_num = location[ 'line_num' ]
# libclang can give us diagnostics that point "outside" the file; Vim borks
# on these.
if line_num < 1:
line_num = 1
text = diagnostic[ 'text' ]
if diagnostic.get( 'fixit_available', False ):
text += ' (FixIt available)'
return {
'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ],
create_buffer_if_needed = True ),
'lnum' : line_num,
'col' : location[ 'column_num' ],
'text' : text,
'type' : diagnostic[ 'kind' ][ 0 ],
'valid' : 1
}
return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
def GetVimGlobalsKeys():
return vim.eval( 'keys( g: )' )
def VimExpressionToPythonType( vim_expression ):
"""Returns a Python type from the return value of the supplied Vim expression.
If the expression returns a list, dict or other non-string type, then it is
returned unmodified. If the string return can be converted to an
integer, returns an integer, otherwise returns the result converted to a
Unicode string."""
result = vim.eval( vim_expression )
if not ( isinstance( result, str ) or isinstance( result, bytes ) ):
return result
try:
return int( result )
except ValueError:
return ToUnicode( result )
def HiddenEnabled( buffer_object ):
if buffer_object.options[ 'bh' ] == "hide":
return True
return GetBoolValue( '&hidden' )
def BufferIsUsable( buffer_object ):
return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
def EscapeFilepathForVimCommand( filepath ):
return GetVariableValue( f"fnameescape('{ EscapeForVim( filepath ) }')" )
def ComparePaths( path1, path2 ):
# Assume that the file system is case-insensitive on Windows and macOS and
# case-sensitive on other platforms. While this is not necessarily true, being
# completely correct here is not worth the trouble as this assumption
# represents the overwhelming use case and detecting the case sensitivity of a
# file system is tricky.
if OnWindows() or OnMac():
return path1.lower() == path2.lower()
return path1 == path2
# Both |line| and |column| need to be 1-based
def TryJumpLocationInTab( tab, filename, line, column ):
for win in tab.windows:
if ComparePaths( GetBufferFilepath( win.buffer ), filename ):
vim.current.tabpage = tab
vim.current.window = win
if line is not None and column is not None:
vim.current.window.cursor = ( line, column - 1 )
# Open possible folding at location
vim.command( 'normal! zv' )
# Center the screen on the jumped-to location
vim.command( 'normal! zz' )
return True
# 'filename' is not opened in this tab page
return False
# Both |line| and |column| need to be 1-based
def TryJumpLocationInTabs( filename, line, column ):
for tab in vim.tabpages:
if TryJumpLocationInTab( tab, filename, line, column ):
return True
# 'filename' is not opened in any tab pages
return False
# Maps User command to vim command
def GetVimCommand( user_command, default = 'edit' ):
vim_command = BUFFER_COMMAND_MAP.get( user_command, default )
if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
vim_command = 'split'
return vim_command
def JumpToFile( filename, command, modifiers ):
vim_command = GetVimCommand( command )
try:
escaped_filename = EscapeFilepathForVimCommand( filename )
vim.command(
f'keepjumps { modifiers } { vim_command } { escaped_filename }' )
# When the file we are trying to jump to has a swap file
# Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
# or KeyboardInterrupt after user selects one of the options.
except vim.error as e:
if 'E325' not in str( e ):
raise
# Do nothing if the target file is still not opened (user chose (Q)uit).
if filename != GetCurrentBufferFilepath():
return False
# Thrown when user chooses (A)bort in .swp message box.
except KeyboardInterrupt:
return False
return True
# Both |line| and |column| need to be 1-based
def JumpToLocation( filename, line, column, modifiers, command ):
# Add an entry to the jumplist
vim.command( "normal! m'" )
if filename != GetCurrentBufferFilepath():
# We prefix the command with 'keepjumps' so that opening the file is not
# recorded in the jumplist. So when we open the file and move the cursor to
# a location in it, the user can use CTRL-O to jump back to the original
# location, not to the start of the newly opened file.
# Sadly this fails on random occasions and the undesired jump remains in the
# jumplist.
if command == 'split-or-existing-window':
if 'tab' in modifiers:
if TryJumpLocationInTabs( filename, line, column ):
return
elif TryJumpLocationInTab( vim.current.tabpage, filename, line, column ):
return
command = 'split'
# This command is kept for backward compatibility. :tab should be used with
# the 'split-or-existing-window' command instead.
if command == 'new-or-existing-tab':
if TryJumpLocationInTabs( filename, line, column ):
return
command = 'new-tab'
if not JumpToFile( filename, command, modifiers ):
return
if line is not None and column is not None:
vim.current.window.cursor = ( line, column - 1 )
# Open possible folding at location
vim.command( 'normal! zv' )
# Center the screen on the jumped-to location
vim.command( 'normal! zz' )
def NumLinesInBuffer( buffer_object ):
# This is actually less than obvious, that's why it's wrapped in a function
return len( buffer_object )
# Calling this function from the non-GUI thread will sometimes crash Vim. At
# the time of writing, YCM only uses the GUI thread inside Vim (this used to
# not be the case).
def PostVimMessage( message, warning = True, truncate = False ):
"""Display a message on the Vim status line. By default, the message is
highlighted and logged to Vim command-line history (see :h history).
Unset the |warning| parameter to disable this behavior. Set the |truncate|
parameter to avoid hit-enter prompts (see :h hit-enter) when the message is
longer than the window width."""
echo_command = 'echom' if warning else 'echo'
# Displaying a new message while previous ones are still on the status line
# might lead to a hit-enter prompt or the message appearing without a
# newline so we do a redraw first.
vim.command( 'redraw' )
if warning:
vim.command( 'echohl WarningMsg' )
message = ToUnicode( message )
if truncate:
vim_width = GetIntValue( '&columns' )
message = message.replace( '\n', ' ' )
message = message.replace( '\t', ' ' )
if len( message ) >= vim_width:
message = message[ : vim_width - 4 ] + '...'
old_ruler = GetIntValue( '&ruler' )
old_showcmd = GetIntValue( '&showcmd' )
vim.command( 'set noruler noshowcmd' )
vim.command( f"{ echo_command } '{ EscapeForVim( message ) }'" )
SetVariableValue( '&ruler', old_ruler )
SetVariableValue( '&showcmd', old_showcmd )
else:
for line in message.split( '\n' ):
vim.command( f"{ echo_command } '{ EscapeForVim( line ) }'" )
if warning:
vim.command( 'echohl None' )
def PresentDialog( message, choices, default_choice_index = 0 ):
"""Presents the user with a dialog where a choice can be made.
This will be a dialog for gvim users or a question in the message buffer
for vim users or if `set guioptions+=c` was used.
choices is list of alternatives.
default_choice_index is the 0-based index of the default element
that will get choosen if the user hits <CR>. Use -1 for no default.
PresentDialog will return a 0-based index into the list
or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
If you are presenting a list of options for the user to choose from, such as
a list of imports, or lines to insert (etc.), SelectFromList is a better
option.
See also:
:help confirm() in vim (Note that vim uses 1-based indexes)
Example call:
PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
Is this a nice example?
[Y]es, (N)o, May(b)e:"""
message = EscapeForVim( ToUnicode( message ) )
choices = EscapeForVim( ToUnicode( '\n'.join( choices ) ) )
to_eval = ( f"confirm( '{ message }', "
f"'{ choices }', "
f"{ default_choice_index + 1 } )" )
try:
return GetIntValue( to_eval ) - 1
except KeyboardInterrupt:
return -1
def Confirm( message ):
"""Display |message| with Ok/Cancel operations. Returns True if the user
selects Ok"""
return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
def SelectFromList( prompt, items ):
"""Ask the user to select an item from the list |items|.
Presents the user with |prompt| followed by a numbered list of |items|,
from which they select one. The user is asked to enter the number of an
item or click it.
|items| should not contain leading ordinals: they are added automatically.
Returns the 0-based index in the list |items| that the user selected, or an
exception if no valid item was selected.
See also :help inputlist()."""
vim_items = [ prompt ]
vim_items.extend( [ f"{ i + 1 }: { item }"
for i, item in enumerate( items ) ] )
# The vim documentation warns not to present lists larger than the number of
# lines of display. This is sound advice, but there really isn't any sensible
# thing we can do in that scenario. Testing shows that Vim just pages the
# message; that behaviour is as good as any, so we don't manipulate the list,
# or attempt to page it.
# For an explanation of the purpose of inputsave() / inputrestore(),
# see :help input(). Briefly, it makes inputlist() work as part of a mapping.
vim.eval( 'inputsave()' )
try:
# Vim returns the number the user entered, or the line number the user
# clicked. This may be wildly out of range for our list. It might even be
# negative.
#
# The first item is index 0, and this maps to our "prompt", so we subtract 1
# from the result and return that, assuming it is within the range of the
# supplied list. If not, we return negative.
#
# See :help input() for explanation of the use of inputsave() and inpput
# restore(). It is done in try/finally in case vim.eval ever throws an
# exception (such as KeyboardInterrupt)
selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1
except KeyboardInterrupt:
selected = -1
finally:
vim.eval( 'inputrestore()' )
if selected < 0 or selected >= len( items ):
# User selected something outside of the range
raise RuntimeError( NO_SELECTION_MADE_MSG )
return selected
def EscapeForVim( text ):
return ToUnicode( text.replace( "'", "''" ) )
def AllOpenedFiletypes():
"""Returns a dict mapping filetype to list of buffer numbers for all open
buffers"""
filetypes = defaultdict( list )
for buffer in vim.buffers:
for filetype in FiletypesForBuffer( buffer ):
filetypes[ filetype ].append( buffer.number )
return filetypes
def CurrentFiletypes():
filetypes = vim.eval( "&filetype" )
if not filetypes:
filetypes = 'ycm_nofiletype'
return ToUnicode( filetypes ).split( '.' )
def CurrentFiletypesEnabled( disabled_filetypes ):
"""Return False if one of the current filetypes is disabled, True otherwise.
|disabled_filetypes| must be a dictionary where keys are the disabled
filetypes and values are unimportant. The special key '*' matches all
filetypes."""
return ( '*' not in disabled_filetypes and
not any( x in disabled_filetypes for x in CurrentFiletypes() ) )
def GetBufferFiletypes( bufnr ):
command = f'getbufvar({ bufnr }, "&ft")'
filetypes = vim.eval( command )
if not filetypes:
filetypes = 'ycm_nofiletype'
return ToUnicode( filetypes ).split( '.' )
def FiletypesForBuffer( buffer_object ):
# NOTE: Getting &ft for other buffers only works when the buffer has been
# visited by the user at least once, which is true for modified buffers
# We don't use
#
# buffer_object.options[ 'ft' ]
#
# to get the filetypes because this causes annoying flickering when the buffer
# is hidden.
return GetBufferFiletypes( buffer_object.number )
def VariableExists( variable ):
return GetBoolValue( f"exists( '{ EscapeForVim( variable ) }' )" )
def SetVariableValue( variable, value ):
vim.command( f"let { variable } = { json.dumps( value ) }" )
def GetVariableValue( variable ):
return vim.eval( variable )
def GetBoolValue( variable ):
return bool( int( vim.eval( variable ) ) )
def GetIntValue( variable ):
return int( vim.eval( variable ) or 0 )
def _SortChunksByFile( chunks ):
"""Sort the members of the list |chunks| (which must be a list of dictionaries
conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new
list in arbitrary order."""
chunks_by_file = defaultdict( list )
for chunk in chunks:
filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ]
chunks_by_file[ filepath ].append( chunk )
return chunks_by_file
def _GetNumNonVisibleFiles( file_list ):
"""Returns the number of file in the iterable list of files |file_list| which
are not curerntly open in visible windows"""
return len(
[ f for f in file_list
if not BufferIsVisible( GetBufferNumberForFilename( f ) ) ] )
def _OpenFileInSplitIfNeeded( filepath ):
"""Ensure that the supplied filepath is open in a visible window, opening a
new split if required. Returns the buffer number of the file and an indication
of whether or not a new split was opened.
If the supplied filename is already open in a visible window, return just
return its buffer number. If the supplied file is not visible in a window
in the current tab, opens it in a new vertical split.
Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer
number and whether or not this method created a new split. If the user opts
not to open a file, or if opening fails, this method raises RuntimeError,
otherwise, guarantees to return a visible buffer number in buffer_num."""
buffer_num = GetBufferNumberForFilename( filepath )
# We only apply changes in the current tab page (i.e. "visible" windows).
# Applying changes in tabs does not lead to a better user experience, as the
# quickfix list no longer works as you might expect (doesn't jump into other
# tabs), and the complexity of choosing where to apply edits is significant.
if BufferIsVisible( buffer_num ):
# file is already open and visible, just return that buffer number (and an
# idicator that we *didn't* open a split)
return ( buffer_num, False )
# The file is not open in a visible window, so we open it in a split.
# We open the file with a small, fixed height. This means that we don't
# make the current buffer the smallest after a series of splits.
OpenFilename( filepath, {
'focus': True,
'fix': True,
'size': GetIntValue( '&previewheight' ),
} )
# OpenFilename returns us to the original cursor location. This is what we
# want, because we don't want to disorientate the user, but we do need to
# know the (now open) buffer number for the filename
buffer_num = GetBufferNumberForFilename( filepath )
if not BufferIsVisible( buffer_num ):
# This happens, for example, if there is a swap file and the user
# selects the "Quit" or "Abort" options. We just raise an exception to
# make it clear to the user that the abort has left potentially
# partially-applied changes.
raise RuntimeError(
f'Unable to open file: { filepath }\nFixIt/Refactor operation '
'aborted prior to completion. Your files have not been '
'fully updated. Please use undo commands to revert the '
'applied changes.' )
# We opened this file in a split
return ( buffer_num, True )
def ReplaceChunks( chunks, silent=False ):
"""Apply the source file deltas supplied in |chunks| to arbitrary files.
|chunks| is a list of changes defined by ycmd.responses.FixItChunk,
which may apply arbitrary modifications to arbitrary files.
If a file specified in a particular chunk is not currently open in a visible
buffer (i.e., one in a window visible in the current tab), we:
- issue a warning to the user that we're going to open new files (and offer
her the option to abort cleanly)
- open the file in a new split, make the changes, then hide the buffer.
If for some reason a file could not be opened or changed, raises RuntimeError.
Otherwise, returns no meaningful value."""
# We apply the edits file-wise for efficiency.
chunks_by_file = _SortChunksByFile( chunks )
# We sort the file list simply to enable repeatable testing.
sorted_file_list = sorted( chunks_by_file.keys() )
if not silent:
# Make sure the user is prepared to have her screen mutilated by the new
# buffers.
num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list )
if num_files_to_open > 0:
if not Confirm(
FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ):
return
# Store the list of locations where we applied changes. We use this to display
# the quickfix window showing the user where we applied changes.
locations = []
for filepath in sorted_file_list:
buffer_num, close_window = _OpenFileInSplitIfNeeded( filepath )
locations.extend( ReplaceChunksInBuffer( chunks_by_file[ filepath ],
vim.buffers[ buffer_num ] ) )
# When opening tons of files, we don't want to have a split for each new
# file, as this simply does not scale, so we open the window, make the
# edits, then hide the window.
if close_window:
# Some plugins (I'm looking at you, syntastic) might open a location list
# for the window we just opened. We don't want that location list hanging
# around, so we close it. lclose is a no-op if there is no location list.
vim.command( 'lclose' )
# Note that this doesn't lose our changes. It simply "hides" the buffer,
# which can later be re-accessed via the quickfix list or `:ls`
vim.command( 'hide' )
# Open the quickfix list, populated with entries for each location we changed.
if not silent:
if locations:
SetQuickFixList( locations )
PostVimMessage( f'Applied { len( chunks ) } changes', warning = False )
def ReplaceChunksInBuffer( chunks, vim_buffer ):
"""Apply changes in |chunks| to the buffer-like object |buffer| and return the
locations for that buffer."""
# We apply the chunks from the bottom to the top of the buffer so that we
# don't need to adjust the position of the remaining chunks due to text
# changes. This assumes that chunks are not overlapping. However, we still
# allow multiple chunks to share the same starting position (because of the
# language server protocol specs). These chunks must be applied in their order
# of appareance. Since Python sorting is stable, if we sort the whole list in
# reverse order of location, these chunks will be reversed. Therefore, we
# need to fully reverse the list then sort it on the starting position in
# reverse order.
chunks.reverse()
chunks.sort( key = lambda chunk: (
chunk[ 'range' ][ 'start' ][ 'line_num' ],
chunk[ 'range' ][ 'start' ][ 'column_num' ]
), reverse = True )
# However, we still want to display the locations from the top of the buffer
# to its bottom.
return reversed( [ ReplaceChunk( chunk[ 'range' ][ 'start' ],
chunk[ 'range' ][ 'end' ],
chunk[ 'replacement_text' ],
vim_buffer )
for chunk in chunks ] )
def SplitLines( contents ):
"""Return a list of each of the lines in the byte string |contents|.
Behavior is equivalent to str.splitlines with the following exceptions:
- empty strings are returned as [ '' ];
- a trailing newline is not ignored (i.e. SplitLines( '\n' )
returns [ '', '' ], not [ '' ] )."""
if contents == b'':
return [ b'' ]
lines = contents.splitlines()
if contents.endswith( b'\r' ) or contents.endswith( b'\n' ):
lines.append( b'' )
return lines
# Replace the chunk of text specified by a contiguous range with the supplied
# text and return the location.
# * start and end are objects with line_num and column_num properties
# * the range is inclusive
# * indices are all 1-based
#
# NOTE: Works exclusively with bytes() instances and byte offsets as returned
# by ycmd and used within the Vim buffers
def ReplaceChunk( start, end, replacement_text, vim_buffer ):
# ycmd's results are all 1-based, but vim's/python's are all 0-based
# (so we do -1 on all of the values)
start_line = start[ 'line_num' ] - 1
end_line = end[ 'line_num' ] - 1
start_column = start[ 'column_num' ] - 1
end_column = end[ 'column_num' ] - 1
# When sending a request to the server, a newline is added to the buffer
# contents to match what gets saved to disk. If the server generates a chunk
# containing that newline, this chunk goes past the Vim buffer contents since
# there is actually no new line. When this happens, recompute the end position
# of where the chunk is applied and remove all trailing characters in the
# chunk.
if end_line >= len( vim_buffer ):
end_column = len( ToBytes( vim_buffer[ -1 ] ) )
end_line = len( vim_buffer ) - 1
replacement_text = replacement_text.rstrip()
# NOTE: replacement_text is unicode, but all our offsets are byte offsets,
# so we convert to bytes
replacement_lines = SplitLines( ToBytes( replacement_text ) )
# NOTE: Vim buffers are a list of unicode objects on Python 3.
start_existing_text = ToBytes( vim_buffer[ start_line ] )[ : start_column ]
end_line_text = ToBytes( vim_buffer[ end_line ] )
end_existing_text = end_line_text[ end_column : ]
replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
cursor_line, cursor_column = CurrentLineAndColumn()
vim_buffer[ start_line : end_line + 1 ] = replacement_lines[ : ]
# When the cursor position is on the last line in the replaced area, and ends
# up somewhere after the end of the new text, we need to reset the cursor
# position. This is because Vim doesn't know where to put it, and guesses
# badly. We put it at the end of the new text.
if cursor_line == end_line and cursor_column >= end_column:
cursor_line = start_line + len( replacement_lines ) - 1
cursor_column += len( replacement_lines[ - 1 ] ) - len( end_line_text )
SetCurrentLineAndColumn( cursor_line, cursor_column )
return {
'bufnr': vim_buffer.number,
'filename': vim_buffer.name,
# line and column numbers are 1-based in qflist
'lnum': start_line + 1,
'col': start_column + 1,
'text': replacement_text,
'type': 'F',
}
def InsertNamespace( namespace ):
if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
if expr:
SetVariableValue( "g:ycm_namespace_to_insert", namespace )
vim.eval( expr )
return
pattern = r'^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
existing_indent = ''
line = SearchInCurrentBuffer( pattern )
if line:
existing_line = LineTextInCurrentBuffer( line )
existing_indent = re.sub( r'\S.*', '', existing_line )
new_line = f'{ existing_indent }using { namespace };\n'
replace_pos = { 'line_num': line + 1, 'column_num': 1 }
ReplaceChunk( replace_pos, replace_pos, new_line, vim.current.buffer )
PostVimMessage( f'Add namespace: { namespace }', warning = False )
def SearchInCurrentBuffer( pattern ):
""" Returns the 1-indexed line on which the pattern matches
(going UP from the current position) or 0 if not found """
return GetIntValue( f"search('{ EscapeForVim( pattern ) }', 'Wcnb')" )
def LineTextInCurrentBuffer( line_number ):
""" Returns the text on the 1-indexed line (NOT 0-indexed) """
return vim.current.buffer[ line_number - 1 ]
def ClosePreviewWindow():
""" Close the preview window if it is present, otherwise do nothing """
vim.command( 'silent! pclose!' )
def JumpToPreviewWindow():
""" Jump the vim cursor to the preview window, which must be active. Returns
boolean indicating if the cursor ended up in the preview window """
vim.command( 'silent! wincmd P' )
return vim.current.window.options[ 'previewwindow' ]
def JumpToPreviousWindow():
""" Jump the vim cursor to its previous window position """
vim.command( 'silent! wincmd p' )
def JumpToTab( tab_number ):
"""Jump to Vim tab with corresponding number """
vim.command( f'silent! tabn { tab_number }' )
def OpenFileInPreviewWindow( filename, modifiers ):
""" Open the supplied filename in the preview window """
if modifiers:
modifiers = ' ' + modifiers
vim.command( f'silent!{ modifiers } pedit! { filename }' )
def WriteToPreviewWindow( message, modifiers ):
""" Display the supplied message in the preview window """
# This isn't something that comes naturally to Vim. Vim only wants to show
# tags and/or actual files in the preview window, so we have to hack it a
# little bit. We generate a temporary file name and "open" that, then write
# the data to it. We make sure the buffer can't be edited or saved. Other
# approaches include simply opening a split, but we want to take advantage of
# the existing Vim options for preview window height, etc.
ClosePreviewWindow()
OpenFileInPreviewWindow( vim.eval( 'tempname()' ), modifiers )
if JumpToPreviewWindow():
# We actually got to the preview window. By default the preview window can't
# be changed, so we make it writable, write to it, then make it read only
# again.
vim.current.buffer.options[ 'modifiable' ] = True
vim.current.buffer.options[ 'readonly' ] = False
vim.current.buffer[ : ] = message.splitlines()
vim.current.buffer.options[ 'buftype' ] = 'nofile'
vim.current.buffer.options[ 'bufhidden' ] = 'wipe'
vim.current.buffer.options[ 'buflisted' ] = False
vim.current.buffer.options[ 'swapfile' ] = False
vim.current.buffer.options[ 'modifiable' ] = False
vim.current.buffer.options[ 'readonly' ] = True
# We need to prevent closing the window causing a warning about unsaved
# file, so we pretend to Vim that the buffer has not been changed.
vim.current.buffer.options[ 'modified' ] = False
JumpToPreviousWindow()
else:
# We couldn't get to the preview window, but we still want to give the user
# the information we have. The only remaining option is to echo to the
# status area.
PostVimMessage( message, warning = False )
def BufferIsVisibleForFilename( filename ):
"""Check if a buffer exists for a specific file."""
buffer_number = GetBufferNumberForFilename( filename )
return BufferIsVisible( buffer_number )
def CloseBuffersForFilename( filename ):
"""Close all buffers for a specific file."""
buffer_number = GetBufferNumberForFilename( filename )
while buffer_number != -1:
vim.command( f'silent! bwipeout! { buffer_number }' )
new_buffer_number = GetBufferNumberForFilename( filename )
if buffer_number == new_buffer_number:
raise RuntimeError( f"Buffer { buffer_number } for filename "
f"'{ filename }' should already be wiped out." )
buffer_number = new_buffer_number
def OpenFilename( filename, options = {} ):
"""Open a file in Vim. Following options are available:
- command: specify which Vim command is used to open the file. Choices
are same-buffer, horizontal-split, vertical-split, and new-tab (default:
horizontal-split);
- size: set the height of the window for a horizontal split or the width for
a vertical one (default: '');
- fix: set the winfixheight option for a horizontal split or winfixwidth for
a vertical one (default: False). See :h winfix for details;
- focus: focus the opened file (default: False);
- watch: automatically watch for changes (default: False). This is useful
for logs;
- position: set the position where the file is opened (default: start).
Choices are 'start' and 'end'.
- mods: The vim <mods> for the command, such as :vertical"""
# Set the options.
command = GetVimCommand( options.get( 'command', 'horizontal-split' ),
'horizontal-split' )
size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else
'' )
focus = options.get( 'focus', False )
# There is no command in Vim to return to the previous tab so we need to
# remember the current tab if needed.
if not focus and command == 'tabedit':
previous_tab = GetIntValue( 'tabpagenr()' )
else:
previous_tab = None
# Open the file.
try:
vim.command( f'{ options.get( "mods", "" ) }'
f'{ size }'
f'{ command } '
f'{ filename }' )
# When the file we are trying to jump to has a swap file,
# Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
# or KeyboardInterrupt after user selects one of the options which actually
# opens the file (Open read-only/Edit anyway).
except vim.error as e:
if 'E325' not in str( e ):
raise
# Otherwise, the user might have chosen Quit. This is detectable by the
# current file not being the target file
if filename != GetCurrentBufferFilepath():
return
except KeyboardInterrupt:
# Raised when the user selects "Abort" after swap-exists-choices
return
_SetUpLoadedBuffer( command,
filename,
options.get( 'fix', False ),
options.get( 'position', 'start' ),
options.get( 'watch', False ) )
# Vim automatically set the focus to the opened file so we need to get the
# focus back (if the focus option is disabled) when opening a new tab or
# window.
if not focus:
if command == 'tabedit':
JumpToTab( previous_tab )
if command in [ 'split', 'vsplit' ]:
JumpToPreviousWindow()
def _SetUpLoadedBuffer( command, filename, fix, position, watch ):
"""After opening a buffer, configure it according to the supplied options,
which are as defined by the OpenFilename method."""
if command == 'split':
vim.current.window.options[ 'winfixheight' ] = fix
if command == 'vsplit':
vim.current.window.options[ 'winfixwidth' ] = fix
if watch:
vim.current.buffer.options[ 'autoread' ] = True
vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'"
.format( filename ) )
if position == 'end':
vim.command( 'silent! normal! Gzz' )
def BuildRange( start_line, end_line ):
# Vim only returns the starting and ending lines of the range of a command.
# Check if those lines correspond to a previous visual selection and if they
# do, use the columns of that selection to build the range.
start = vim.current.buffer.mark( '<' )
end = vim.current.buffer.mark( '>' )
if not start or not end or start_line != start[ 0 ] or end_line != end[ 0 ]:
start = [ start_line, 0 ]
end = [ end_line, len( vim.current.buffer[ end_line - 1 ] ) ]
# Vim Python API returns 1-based lines and 0-based columns while ycmd expects
# 1-based lines and columns.
return {
'range': {
'start': {
'line_num': start[ 0 ],
'column_num': start[ 1 ] + 1
},
'end': {
'line_num': end[ 0 ],
# Vim returns the maximum 32-bit integer value when a whole line is
# selected. Use the end of line instead.
'column_num': min( end[ 1 ],
len( vim.current.buffer[ end[ 0 ] - 1 ] ) ) + 1
}
}
}
# Expects version_string in 'MAJOR.MINOR.PATCH' format, e.g. '8.1.278'
def VimVersionAtLeast( version_string ):
major, minor, patch = ( int( x ) for x in version_string.split( '.' ) )
# For Vim 8.1.278, v:version is '801'
actual_major_and_minor = GetIntValue( 'v:version' )
matching_major_and_minor = major * 100 + minor
if actual_major_and_minor != matching_major_and_minor:
return actual_major_and_minor > matching_major_and_minor
return GetBoolValue( f"has( 'patch{ patch }' )" )
def AutoCloseOnCurrentBuffer( name ):
"""Create an autocommand group with name |name| on the current buffer that
automatically closes it when leaving its window."""
vim.command( f'augroup { name }' )
vim.command( 'autocmd! * <buffer>' )
vim.command( 'autocmd WinLeave <buffer> '
'if bufnr( "%" ) == expand( "<abuf>" ) | q | endif '
f'| autocmd! { name }' )
vim.command( 'augroup END' )
@memoize()
def VimIsNeovim():
return GetBoolValue( 'has( "nvim" )' )
@memoize()
def VimSupportsPopupWindows():
return VimHasFunctions( 'popup_create',
'popup_atcursor',
'popup_move',
'popup_hide',
'popup_settext',
'popup_show',
'popup_close' )
@memoize()
def VimHasFunction( func ):
return bool( GetIntValue( f"exists( '*{ EscapeForVim( func ) }' )" ) )
def VimHasFunctions( *functions ):
return all( VimHasFunction( f ) for f in functions )
def WinIDForWindow( window ):
return GetIntValue( f'win_getid( { window.number }, '
f'{ window.tabpage.number } )' )
def ScreenPositionForLineColumnInWindow( window, line, column ):
return vim.eval( f'screenpos( { WinIDForWindow( window ) }, '
f'{ line }, '
f'{ column } )' )
def UsingPreviewPopup():
return 'popup' in ToUnicode( vim.options[ 'completeopt' ] ).split( ',' )
def DisplayWidth():
return GetIntValue( '&columns' )
def DisplayWidthOfString( s ):
return GetIntValue( f"strdisplaywidth( '{ EscapeForVim( s ) }' )" )
def BuildQfListItem( goto_data_item ):
qf_item = {}
if 'filepath' in goto_data_item:
qf_item[ 'filename' ] = ToUnicode( goto_data_item[ 'filepath' ] )
if 'description' in goto_data_item:
qf_item[ 'text' ] = ToUnicode( goto_data_item[ 'description' ] )
if 'line_num' in goto_data_item:
qf_item[ 'lnum' ] = goto_data_item[ 'line_num' ]
if 'column_num' in goto_data_item:
# ycmd returns columns 1-based, and QuickFix lists require "byte offsets".
# See :help getqflist and equivalent comment in
# vimsupport.ConvertDiagnosticsToQfList.
#
# When the Vim help says "byte index", it really means "1-based column
# number" (which is somewhat confusing). :help getqflist states "first
# column is 1".
qf_item[ 'col' ] = goto_data_item[ 'column_num' ]
return qf_item
| 55,215
|
Python
|
.py
| 1,180
| 40.576271
| 80
| 0.663061
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,934
|
signature_help.py
|
ycm-core_YouCompleteMe/python/ycm/signature_help.py
|
# Copyright (C) 2011-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import vim
import json
from ycm import vimsupport
from ycmd import utils
from ycm.vimsupport import memoize, GetIntValue
class SignatureHelpState:
ACTIVE = 'ACTIVE'
INACTIVE = 'INACTIVE'
ACTIVE_SUPPRESSED = 'ACTIVE_SUPPRESSED'
def __init__( self,
popup_win_id = None,
state = INACTIVE ):
self.popup_win_id = popup_win_id
self.state = state
self.anchor = None
def ToggleVisibility( self ):
if self.state == 'ACTIVE':
self.state = 'ACTIVE_SUPPRESSED'
vim.eval( f'popup_hide( { self.popup_win_id } )' )
elif self.state == 'ACTIVE_SUPPRESSED':
self.state = 'ACTIVE'
vim.eval( f'popup_show( { self.popup_win_id } )' )
def IsActive( self ):
if self.state in ( 'ACTIVE', 'ACTIVE_SUPPRESSED' ):
return 'ACTIVE'
return 'INACTIVE'
def _MakeSignatureHelpBuffer( signature_info ):
active_parameter = int( signature_info.get( 'activeParameter', 0 ) )
lines = []
signatures = ( signature_info.get( 'signatures' ) or [] )
for sig_index, signature in enumerate( signatures ):
props = []
sig_label = signature[ 'label' ]
parameters = ( signature.get( 'parameters' ) or [] )
for param_index, parameter in enumerate( parameters ):
param_label = parameter[ 'label' ]
begin = int( param_label[ 0 ] )
end = int( param_label[ 1 ] )
if param_index == active_parameter:
props.append( {
'col': begin + 1, # 1-based
'length': end - begin,
'type': 'YCM-signature-help-current-argument'
} )
lines.append( {
'text': sig_label,
'props': props
} )
return lines
@memoize()
def ShouldUseSignatureHelp():
return ( vimsupport.VimHasFunctions( 'screenpos', 'pum_getpos' ) and
vimsupport.VimSupportsPopupWindows() )
def UpdateSignatureHelp( state, signature_info ): # noqa
if not ShouldUseSignatureHelp():
return state
signatures = signature_info.get( 'signatures' ) or []
if not signatures:
if state.popup_win_id:
# TODO/FIXME: Should we use popup_hide() instead ?
vim.eval( f"popup_close( { state.popup_win_id } )" )
return SignatureHelpState( None, SignatureHelpState.INACTIVE )
if state.state == SignatureHelpState.INACTIVE:
state.anchor = vimsupport.CurrentLineAndColumn()
state.state = SignatureHelpState.ACTIVE
# Generate the buffer as a list of lines
buf_lines = _MakeSignatureHelpBuffer( signature_info )
screen_pos = vimsupport.ScreenPositionForLineColumnInWindow(
vim.current.window,
state.anchor[ 0 ] + 1, # anchor 0-based
state.anchor[ 1 ] + 1 ) # anchor 0-based
# Simulate 'flip' at the screen boundaries by using screenpos and hiding the
# signature help menu if it overlaps the completion popup (pum).
#
# FIXME: revert to cursor-relative positioning and the 'flip' option when that
# is implemented (if that is indeed better).
# By default display above the anchor
line = int( screen_pos[ 'row' ] ) - 1 # -1 to display above the cur line
pos = "botleft"
cursor_line = vimsupport.CurrentLineAndColumn()[ 0 ] + 1
if int( screen_pos[ 'row' ] ) <= len( buf_lines ):
# No room at the top, display below
line = int( screen_pos[ 'row' ] ) + 1
pos = "topleft"
# Don't allow the popup to overlap the cursor
if ( pos == 'topleft' and
line < cursor_line and
line + len( buf_lines ) >= cursor_line ):
line = 0
# Don't allow the popup to overlap the pum
if line > 0 and GetIntValue( 'pumvisible()' ):
pum_line = GetIntValue( 'pum_getpos().row' ) + 1
if pos == 'botleft' and pum_line <= line:
line = 0
elif ( pos == 'topleft' and
pum_line >= line and
pum_line < ( line + len( buf_lines ) ) ):
line = 0
if line <= 0:
# Nowhere to put it so hide it
if state.popup_win_id:
# TODO/FIXME: Should we use popup_hide() instead ?
vim.eval( f"popup_close( { state.popup_win_id } )" )
return SignatureHelpState( None, SignatureHelpState.INACTIVE )
if int( screen_pos[ 'curscol' ] ) <= 1:
col = 1
else:
# -1 for padding,
# -1 for the trigger character inserted (the anchor is set _after_ the
# character is inserted, so we remove it).
# FIXME: multi-byte characters would be wrong. Need to set anchor before
# inserting the char ?
col = int( screen_pos[ 'curscol' ] ) - 2
if col <= 0:
col = 1
options = {
"line": line,
"col": col,
"pos": pos,
"wrap": 0,
# NOTE: We *dont'* use "cursorline" here - that actually uses PMenuSel,
# which is just too invasive for us (it's more selected item than actual
# cursorline. So instead, we manually set 'cursorline' in the popup window
# and enable syntax based on the current file syntax)
"flip": 1,
"padding": [ 0, 1, 0, 1 ], # Pad 1 char in X axis to match completion menu
"hidden": int( state.state == SignatureHelpState.ACTIVE_SUPPRESSED )
}
if not state.popup_win_id:
state.popup_win_id = GetIntValue(
f'popup_create( { json.dumps( buf_lines ) }, '
f'{ json.dumps( options ) } )' )
else:
vim.eval( f'popup_settext( { state.popup_win_id }, '
f'{ json.dumps( buf_lines ) } )' )
# Should do nothing if already visible
vim.eval( f'popup_move( { state.popup_win_id }, { json.dumps( options ) } )' )
if state.state == SignatureHelpState.ACTIVE:
vim.eval( f'popup_show( { state.popup_win_id } )' )
if vim.vars.get( 'ycm_signature_help_disable_syntax', False ):
syntax = ''
else:
syntax = utils.ToUnicode( vim.current.buffer.options[ 'syntax' ] )
active_signature = int( signature_info.get( 'activeSignature', 0 ) )
vim.eval( f"win_execute( { state.popup_win_id }, "
f"'set syntax={ syntax } cursorline | "
f"call cursor( [ { active_signature + 1 }, 1 ] )' )" )
return state
| 6,659
|
Python
|
.py
| 164
| 35.567073
| 80
| 0.659594
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,935
|
hierarchy_tree.py
|
ycm-core_YouCompleteMe/python/ycm/hierarchy_tree.py
|
# Copyright (C) 2024 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from typing import Optional, List
from ycm import vimsupport
import os
class HierarchyNode:
def __init__( self, data, distance : int ):
self._references : Optional[ List[ int ] ] = None
self._data = data
self._distance_from_root = distance
def ToRootLocation( self, subindex : int ):
location = self._data.get( 'root_location' )
if location:
file = location[ 'filepath' ]
line = location[ 'line_num' ]
column = location[ 'column_num' ]
return file, line, column
else:
return self.ToLocation( subindex )
def ToLocation( self, subindex : int ):
location = self._data[ 'locations' ][ subindex ]
line = location[ 'line_num' ]
column = location[ 'column_num' ]
file = location[ 'filepath' ]
return file, line, column
MAX_HANDLES_PER_INDEX = 1000000
def handle_to_index( handle : int ):
return abs( handle ) // MAX_HANDLES_PER_INDEX
def handle_to_location_index( handle : int ):
return abs( handle ) % MAX_HANDLES_PER_INDEX
def make_handle( index : int, location_index : int ):
return index * MAX_HANDLES_PER_INDEX + location_index
class HierarchyTree:
def __init__( self ):
self._up_nodes : List[ HierarchyNode ] = []
self._down_nodes : List[ HierarchyNode ] = []
self._kind : str = ''
def SetRootNode( self, items, kind : str ):
if items:
assert len( items ) == 1
self._root_node_indices = [ 0 ]
self._down_nodes.append( HierarchyNode( items[ 0 ], 0 ) )
self._up_nodes.append( HierarchyNode( items[ 0 ], 0 ) )
self._kind = kind
return self.HierarchyToLines()
return []
def UpdateHierarchy( self, handle : int, items, direction : str ):
current_index = handle_to_index( handle )
nodes = self._down_nodes if direction == 'down' else self._up_nodes
if items:
nodes.extend( [
HierarchyNode( item,
nodes[ current_index ]._distance_from_root + 1 )
for item in items ] )
nodes[ current_index ]._references = list(
range( len( nodes ) - len( items ), len( nodes ) ) )
else:
nodes[ current_index ]._references = []
def Reset( self ):
self._down_nodes = []
self._up_nodes = []
self._kind = ''
def _HierarchyToLinesHelper( self, refs, use_down_nodes ):
partial_result = []
nodes = self._down_nodes if use_down_nodes else self._up_nodes
for index in refs:
next_node = nodes[ index ]
indent = 2 * next_node._distance_from_root
if index == 0:
can_expand = ( self._down_nodes[ 0 ]._references is None or
self._up_nodes[ 0 ]._references is None )
else:
can_expand = next_node._references is None
symbol = '+' if can_expand else '-'
name = next_node._data[ 'name' ]
kind = next_node._data[ 'kind' ]
if use_down_nodes:
partial_result.extend( [
(
{
'indent': indent,
'icon': symbol,
'symbol': name,
'kind': kind,
'filepath': os.path.split( l[ 'filepath' ] )[ 1 ],
'line_num': str( l[ 'line_num' ] ),
'description': l.get( 'description', '' ).strip(),
},
make_handle( index, location_index )
)
for location_index, l in enumerate( next_node._data[ 'locations' ] )
] )
else:
partial_result.extend( [
(
{
'indent': indent,
'icon': symbol,
'symbol': name,
'kind': kind,
'filepath': os.path.split( l[ 'filepath' ] )[ 1 ],
'line_num': str( l[ 'line_num' ] ),
'description': l.get( 'description', '' ).strip(),
},
make_handle( index, location_index ) * -1
)
for location_index, l in enumerate( next_node._data[ 'locations' ] )
] )
if next_node._references:
partial_result.extend(
self._HierarchyToLinesHelper(
next_node._references, use_down_nodes ) )
return partial_result
def HierarchyToLines( self ):
down_lines = self._HierarchyToLinesHelper( [ 0 ], True )
up_lines = self._HierarchyToLinesHelper( [ 0 ], False )
up_lines.reverse()
return up_lines + down_lines[ 1: ]
def JumpToItem( self, handle : int, command ):
node_index = handle_to_index( handle )
location_index = handle_to_location_index( handle )
if handle >= 0:
node = self._down_nodes[ node_index ]
else:
node = self._up_nodes[ node_index ]
file, line, column = node.ToLocation( location_index )
vimsupport.JumpToLocation( file, line, column, '', command )
def ShouldResolveItem( self, handle : int, direction : str ):
node_index = handle_to_index( handle )
if ( ( handle >= 0 and direction == 'down' ) or
( handle <= 0 and direction == 'up' ) ):
if direction == 'down':
node = self._down_nodes[ node_index ]
else:
node = self._up_nodes[ node_index ]
return node._references is None
return True
def ResolveArguments( self, handle : int, direction : str ):
node_index = handle_to_index( handle )
if self._kind == 'call':
direction = 'outgoing' if direction == 'up' else 'incoming'
else:
direction = 'supertypes' if direction == 'up' else 'subtypes'
if handle >= 0:
node = self._down_nodes[ node_index ]
else:
node = self._up_nodes[ node_index ]
return [
f'Resolve{ self._kind.title() }HierarchyItem',
node._data,
direction
]
def HandleToRootLocation( self, handle : int ):
node_index = handle_to_index( handle )
if handle >= 0:
node = self._down_nodes[ node_index ]
else:
node = self._up_nodes[ node_index ]
location_index = handle_to_location_index( handle )
return node.ToRootLocation( location_index )
def UpdateChangesRoot( self, handle : int, direction : str ):
return ( ( handle < 0 and direction == 'down' ) or
( handle > 0 and direction == 'up' ) )
| 6,843
|
Python
|
.py
| 177
| 31.858757
| 78
| 0.610198
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,936
|
inlay_hints.py
|
ycm-core_YouCompleteMe/python/ycm/inlay_hints.py
|
# Copyright (C) 2022, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.inlay_hints_request import InlayHintsRequest
from ycm.client.base_request import BuildRequestData
from ycm import vimsupport
from ycm import text_properties as tp
from ycm import scrolling_range as sr
HIGHLIGHT_GROUP = {
'Type': 'YcmInlayHint',
'Parameter': 'YcmInlayHint',
'Enum': 'YcmInlayHint',
}
REPORTED_MISSING_TYPES = set()
def Initialise():
if vimsupport.VimIsNeovim():
return False
props = tp.GetTextPropertyTypes()
if 'YCM_INLAY_UNKNOWN' not in props:
tp.AddTextPropertyType( 'YCM_INLAY_UNKNOWN',
highlight = 'YcmInlayHint',
start_incl = 1 )
if 'YCM_INLAY_PADDING' not in props:
tp.AddTextPropertyType( 'YCM_INLAY_PADDING',
highlight = 'YcmInvisible',
start_incl = 1 )
for token_type, group in HIGHLIGHT_GROUP.items():
prop = f'YCM_INLAY_{ token_type }'
if prop not in props and vimsupport.GetIntValue(
f"hlexists( '{ vimsupport.EscapeForVim( group ) }' )" ):
tp.AddTextPropertyType( prop,
highlight = group,
start_incl = 1 )
return True
class InlayHints( sr.ScrollingBufferRange ):
"""Stores the inlay hints state for a Vim buffer"""
def _NewRequest( self, request_range ):
request_data = BuildRequestData( self._bufnr )
request_data[ 'range' ] = request_range
return InlayHintsRequest( request_data )
def Clear( self ):
types = [ 'YCM_INLAY_UNKNOWN', 'YCM_INLAY_PADDING' ] + [
f'YCM_INLAY_{ prop_type }' for prop_type in HIGHLIGHT_GROUP.keys()
]
tp.ClearTextProperties( self._bufnr, prop_types = types )
def _Draw( self ):
self.Clear()
for inlay_hint in self._latest_response:
if 'kind' not in inlay_hint:
prop_type = 'YCM_INLAY_UNKNOWN'
elif inlay_hint[ 'kind' ] not in HIGHLIGHT_GROUP:
prop_type = 'YCM_INLAY_UNKNOWN'
else:
prop_type = 'YCM_INLAY_' + inlay_hint[ 'kind' ]
self.GrowRangeIfNeeded( {
'start': inlay_hint[ 'position' ],
'end': {
'line_num': inlay_hint[ 'position' ][ 'line_num' ],
'column_num': inlay_hint[ 'position' ][ 'column_num' ] + len(
inlay_hint[ 'label' ] )
}
} )
if inlay_hint.get( 'paddingLeft', False ):
tp.AddTextProperty( self._bufnr,
None,
'YCM_INLAY_PADDING',
{
'start': inlay_hint[ 'position' ],
},
{
'text': ' '
} )
tp.AddTextProperty( self._bufnr,
None,
prop_type,
{
'start': inlay_hint[ 'position' ],
},
{
'text': inlay_hint[ 'label' ]
} )
if inlay_hint.get( 'paddingRight', False ):
tp.AddTextProperty( self._bufnr,
None,
'YCM_INLAY_PADDING',
{
'start': inlay_hint[ 'position' ],
},
{
'text': ' '
} )
| 4,208
|
Python
|
.py
| 104
| 28.836538
| 72
| 0.545945
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,937
|
buffer.py
|
ycm-core_YouCompleteMe/python/ycm/buffer.py
|
# Copyright (C) 2016, Davit Samvelyan
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm import vimsupport
from ycm.client.event_notification import EventNotification
from ycm.diagnostic_interface import DiagnosticInterface
from ycm.semantic_highlighting import SemanticHighlighting
from ycm.inlay_hints import InlayHints
# Emulates Vim buffer
# Used to store buffer related information like diagnostics, latest parse
# request. Stores buffer change tick at the parse request moment, allowing
# to effectively determine whether reparse is needed for the buffer.
class Buffer:
def __init__( self, bufnr, user_options, filetypes ):
self._number = bufnr
self._parse_tick = 0
self._handled_tick = 0
self._parse_request = None
self._should_resend = False
self._diag_interface = DiagnosticInterface( bufnr, user_options )
self._open_loclist_on_ycm_diags = user_options[
'open_loclist_on_ycm_diags' ]
self.semantic_highlighting = SemanticHighlighting( bufnr )
self.inlay_hints = InlayHints( bufnr )
self.UpdateFromFileTypes( filetypes )
def FileParseRequestReady( self, block = False ):
return ( bool( self._parse_request ) and
( block or self._parse_request.Done() ) )
def SendParseRequest( self, extra_data ):
# Don't send a parse request if one is in progress
if self._parse_request is not None and not self._parse_request.Done():
self._should_resend = True
return
self._should_resend = False
self._parse_request = EventNotification( 'FileReadyToParse',
extra_data = extra_data )
self._parse_request.Start()
# Decrement handled tick to ensure correct handling when we are forcing
# reparse on buffer visit and changed tick remains the same.
self._handled_tick -= 1
self._parse_tick = self._ChangedTick()
def ParseRequestPending( self ):
return bool( self._parse_request ) and not self._parse_request.Done()
def NeedsReparse( self ):
return self._parse_tick != self._ChangedTick()
def ShouldResendParseRequest( self ):
return ( self._should_resend
or ( bool( self._parse_request )
and self._parse_request.ShouldResend() ) )
def UpdateDiagnostics( self, force = False ):
if force or not self._async_diags:
self.UpdateWithNewDiagnostics( self._parse_request.Response(), False )
else:
# We need to call the response method, because it might throw an exception
# or require extra config confirmation, even if we don't actually use the
# diagnostics.
self._parse_request.Response()
def UpdateWithNewDiagnostics( self, diagnostics, async_message ):
self._async_diags = async_message
self._diag_interface.UpdateWithNewDiagnostics(
diagnostics,
not self._async_diags and self._open_loclist_on_ycm_diags )
def UpdateMatches( self ):
self._diag_interface.UpdateMatches()
def PopulateLocationList( self, open_on_edit = False ):
return self._diag_interface.PopulateLocationList( open_on_edit )
def GetResponse( self ):
return self._parse_request.Response()
def IsResponseHandled( self ):
return self._handled_tick == self._parse_tick
def MarkResponseHandled( self ):
self._handled_tick = self._parse_tick
def OnCursorMoved( self ):
self._diag_interface.OnCursorMoved()
def GetErrorCount( self ):
return self._diag_interface.GetErrorCount()
def GetWarningCount( self ):
return self._diag_interface.GetWarningCount()
def RefreshDiagnosticsUI( self ):
return self._diag_interface.RefreshDiagnosticsUI()
def ClearDiagnosticsUI( self ):
return self._diag_interface.ClearDiagnosticsUI()
def DiagnosticsForLine( self, line_number ):
return self._diag_interface.DiagnosticsForLine( line_number )
def UpdateFromFileTypes( self, filetypes ):
self._filetypes = filetypes
# We will set this to true if we ever receive any diagnostics asyncronously.
self._async_diags = False
def _ChangedTick( self ):
return vimsupport.GetBufferChangedTick( self._number )
class BufferDict( dict ):
def __init__( self, user_options ):
self._user_options = user_options
def __missing__( self, key ):
# Python does not allow to return assignment operation result directly
new_value = self[ key ] = Buffer(
key,
self._user_options,
vimsupport.GetBufferFiletypes( key ) )
return new_value
| 5,163
|
Python
|
.py
| 113
| 40.380531
| 80
| 0.72409
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,938
|
text_properties.py
|
ycm-core_YouCompleteMe/python/ycm/text_properties.py
|
# Copyright (C) 2020, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm import vimsupport
from ycm.vimsupport import GetIntValue
from ycmd import utils
import vim
import json
import typing
# FIXME/TODO: Merge this with vimsupport funcitons, added after these were
# written. It's not trivial, as those vimsupport functions are a bit fiddly.
# They also support neovim, but we don't.
def AddTextPropertyType( name, **kwargs ):
props = {
'highlight': 'Ignore',
'combine': 0,
'override': 0,
'start_incl': 0,
'end_incl': 0,
'priority': 10
}
props.update( kwargs )
vim.eval( f"prop_type_add( '{ vimsupport.EscapeForVim( name ) }', "
f" { json.dumps( props ) } )" )
def GetTextPropertyTypes( *args, **kwargs ):
return [ utils.ToUnicode( p ) for p in vim.eval( 'prop_type_list()' ) ]
def AddTextProperty( bufnr,
prop_id,
prop_type,
range,
extra_args: dict = None ):
props = {
'bufnr': bufnr,
'type': prop_type
}
if prop_id is not None:
props[ 'id' ] = prop_id
if extra_args:
props.update( extra_args )
if 'end' in range:
props.update( {
'end_lnum': range[ 'end' ][ 'line_num' ],
'end_col': range[ 'end' ][ 'column_num' ],
} )
return vim.eval( f"prop_add( { range[ 'start' ][ 'line_num' ] },"
f" { range[ 'start' ][ 'column_num' ] },"
f" { json.dumps( props ) } )" )
def ClearTextProperties(
bufnr,
prop_id = None,
prop_types: typing.Union[ typing.List[ str ], str ] = None,
first_line = None,
last_line = None ):
props = {
'bufnr': bufnr,
'all': 1,
}
if prop_id is not None:
props[ 'id' ] = prop_id
if prop_id is not None and prop_types is not None:
props[ 'both' ] = 1
def prop_remove():
if last_line is not None:
return GetIntValue( f"prop_remove( { json.dumps( props ) },"
f" { first_line },"
f" { last_line } )" )
elif first_line is not None:
return GetIntValue( f"prop_remove( { json.dumps( props ) },"
f" { first_line } )" )
else:
return GetIntValue( f"prop_remove( { json.dumps( props ) } )" )
if prop_types is None:
return prop_remove()
if not isinstance( prop_types, list ):
prop_types = [ prop_types ]
props[ 'types' ] = prop_types
return prop_remove()
| 3,184
|
Python
|
.py
| 90
| 29.6
| 76
| 0.612159
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,939
|
diagnostic_filter.py
|
ycm-core_YouCompleteMe/python/ycm/diagnostic_filter.py
|
# Copyright (C) 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import re
class DiagnosticFilter:
def __init__( self, config_or_filters ):
self._filters : list = config_or_filters
def IsAllowed( self, diagnostic ):
return not any( filterMatches( diagnostic )
for filterMatches in self._filters )
@staticmethod
def CreateFromOptions( user_options ):
all_filters = user_options[ 'filter_diagnostics' ]
compiled_by_type = {}
for type_spec, filter_value in all_filters.items():
filetypes = type_spec.split( ',' )
for filetype in filetypes:
compiled_by_type[ filetype ] = _CompileFilters( filter_value )
return _MasterDiagnosticFilter( compiled_by_type )
class _MasterDiagnosticFilter:
def __init__( self, all_filters ):
self._all_filters = all_filters
self._cache = {}
def SubsetForTypes( self, filetypes ):
# check cache
cache_key = ','.join( filetypes )
cached = self._cache.get( cache_key )
if cached is not None:
return cached
# build a new DiagnosticFilter merging all filters
# for the provided filetypes
spec = []
for filetype in filetypes:
type_specific = self._all_filters.get( filetype, [] )
spec.extend( type_specific )
new_filter = DiagnosticFilter( spec )
self._cache[ cache_key ] = new_filter
return new_filter
def _ListOf( config_entry ):
if isinstance( config_entry, list ):
return config_entry
return [ config_entry ]
def CompileRegex( raw_regex ):
pattern = re.compile( raw_regex, re.IGNORECASE )
def FilterRegex( diagnostic ):
return pattern.search( diagnostic[ 'text' ] ) is not None
return FilterRegex
def CompileLevel( level ):
# valid kinds are WARNING and ERROR;
# expected input levels are `warning` and `error`
# NOTE: we don't validate the input...
expected_kind = level.upper()
def FilterLevel( diagnostic ):
return diagnostic[ 'kind' ] == expected_kind
return FilterLevel
FILTER_COMPILERS = { 'regex' : CompileRegex,
'level' : CompileLevel }
def _CompileFilters( config ):
"""Given a filter config dictionary, return a list of compiled filters"""
filters = []
for filter_type, filter_pattern in config.items():
compiler = FILTER_COMPILERS.get( filter_type )
if compiler is not None:
for filter_config in _ListOf( filter_pattern ):
compiledFilter = compiler( filter_config )
filters.append( compiledFilter )
return filters
| 3,185
|
Python
|
.py
| 80
| 35.4125
| 75
| 0.711914
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,940
|
semantic_highlighting.py
|
ycm-core_YouCompleteMe/python/ycm/semantic_highlighting.py
|
# Copyright (C) 2020, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.semantic_tokens_request import SemanticTokensRequest
from ycm.client.base_request import BuildRequestData
from ycm import vimsupport
from ycm import text_properties as tp
from ycm import scrolling_range as sr
import vim
HIGHLIGHT_GROUP = {
'namespace': 'Type',
'type': 'Type',
'class': 'Structure',
'enum': 'Structure',
'interface': 'Structure',
'struct': 'Structure',
'typeParameter': 'Identifier',
'parameter': 'Identifier',
'variable': 'Identifier',
'property': 'Identifier',
'enumMember': 'Identifier',
'enumConstant': 'Constant',
'event': 'Identifier',
'function': 'Function',
'member': 'Identifier',
'macro': 'Macro',
'method': 'Function',
'keyword': 'Keyword',
'modifier': 'Keyword',
'comment': 'Comment',
'string': 'String',
'number': 'Number',
'regexp': 'String',
'operator': 'Operator',
'decorator': 'Special',
'unknown': 'Normal',
# These are not part of the spec, but are used by clangd
'bracket': 'Normal',
'concept': 'Type',
# These are not part of the spec, but are used by jdt.ls
'annotation': 'Macro',
}
REPORTED_MISSING_TYPES = set()
def Initialise():
if vimsupport.VimIsNeovim():
return
props = tp.GetTextPropertyTypes()
if 'YCM_HL_UNKNOWN' not in props:
tp.AddTextPropertyType( 'YCM_HL_UNKNOWN',
highlight = 'WarningMsg',
priority = 0 )
for token_type, group in HIGHLIGHT_GROUP.items():
prop = f'YCM_HL_{ token_type }'
if prop not in props and vimsupport.GetIntValue(
f"hlexists( '{ vimsupport.EscapeForVim( group ) }' )" ):
tp.AddTextPropertyType( prop,
highlight = group,
priority = 0 )
# "arbitrary" base id
NEXT_TEXT_PROP_ID = 70784
def NextPropID():
global NEXT_TEXT_PROP_ID
try:
return NEXT_TEXT_PROP_ID
finally:
NEXT_TEXT_PROP_ID += 1
class SemanticHighlighting( sr.ScrollingBufferRange ):
"""Stores the semantic highlighting state for a Vim buffer"""
def __init__( self, bufnr ):
self._prop_id = NextPropID()
super().__init__( bufnr )
def _NewRequest( self, request_range ):
request: dict = BuildRequestData( self._bufnr )
request[ 'range' ] = request_range
return SemanticTokensRequest( request )
def _Draw( self ):
# We requested a snapshot
tokens = self._latest_response.get( 'tokens', [] )
prev_prop_id = self._prop_id
self._prop_id = NextPropID()
for token in tokens:
prop_type = f"YCM_HL_{ token[ 'type' ] }"
rng = token[ 'range' ]
self.GrowRangeIfNeeded( rng )
try:
tp.AddTextProperty( self._bufnr, self._prop_id, prop_type, rng )
except vim.error as e:
if 'E971:' in str( e ): # Text property doesn't exist
if token[ 'type' ] not in REPORTED_MISSING_TYPES:
REPORTED_MISSING_TYPES.add( token[ 'type' ] )
vimsupport.PostVimMessage(
f"Token type { token[ 'type' ] } not supported. "
f"Define property type { prop_type }. "
f"See :help youcompleteme-customising-highlight-groups" )
else:
raise e
tp.ClearTextProperties( self._bufnr, prop_id = prev_prop_id )
| 3,982
|
Python
|
.py
| 110
| 31.127273
| 72
| 0.666407
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,941
|
omni_completer.py
|
ycm-core_YouCompleteMe/python/ycm/omni_completer.py
|
# Copyright (C) 2011-2019 ycmd contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import vim
from ycm import vimsupport
from ycmd import utils
from ycmd.completers.completer import Completer
from ycm.client.base_request import BaseRequest
OMNIFUNC_RETURNED_BAD_VALUE = 'Omnifunc returned bad value to YCM!'
OMNIFUNC_NOT_LIST = ( 'Omnifunc did not return a list or a dict with a "words" '
' list when expected.' )
class OmniCompleter( Completer ):
def __init__( self, user_options ):
super( OmniCompleter, self ).__init__( user_options )
self._omnifunc = None
def SupportedFiletypes( self ):
return []
def ShouldUseCache( self ):
return bool( self.user_options[ 'cache_omnifunc' ] )
def ShouldUseNow( self, request_data ):
self._omnifunc = utils.ToUnicode( vim.eval( '&omnifunc' ) )
if not self._omnifunc:
return False
if self.ShouldUseCache():
return super( OmniCompleter, self ).ShouldUseNow( request_data )
return self.ShouldUseNowInner( request_data )
def ShouldUseNowInner( self, request_data ):
if request_data[ 'force_semantic' ]:
return True
disabled_filetypes = self.user_options[
'filetype_specific_completion_to_disable' ]
if not vimsupport.CurrentFiletypesEnabled( disabled_filetypes ):
return False
return super( OmniCompleter, self ).ShouldUseNowInner( request_data )
def ComputeCandidates( self, request_data ):
if self.ShouldUseCache():
return super( OmniCompleter, self ).ComputeCandidates( request_data )
if self.ShouldUseNowInner( request_data ):
return self.ComputeCandidatesInner( request_data )
return []
def ComputeCandidatesInner( self, request_data ):
if not self._omnifunc:
return []
# Calling directly the omnifunc may move the cursor position. This is the
# case with the default Vim omnifunc for C-family languages
# (ccomplete#Complete) which calls searchdecl to find a declaration. This
# function is supposed to move the cursor to the found declaration but it
# doesn't when called through the omni completion mapping (CTRL-X CTRL-O).
# So, we restore the cursor position after the omnifunc calls.
line, column = vimsupport.CurrentLineAndColumn()
try:
start_column = vimsupport.GetIntValue( self._omnifunc + '(1,"")' )
# Vim only stops completion if the value returned by the omnifunc is -3 or
# -2. In other cases, if the value is negative or greater than the current
# column, the start column is set to the current column; otherwise, the
# value is used as the start column.
if start_column in ( -3, -2 ):
return []
if start_column < 0 or start_column > column:
start_column = column
# Use the start column calculated by the omnifunc, rather than our own
# interpretation. This is important for certain languages where our
# identifier detection is either incorrect or not compatible with the
# behaviour of the omnifunc. Note: do this before calling the omnifunc
# because it affects the value returned by 'query'.
request_data[ 'start_column' ] = start_column + 1
# Vim internally moves the cursor to the start column before calling again
# the omnifunc. Some omnifuncs like the one defined by the
# LanguageClient-neovim plugin depend on this behavior to compute the list
# of candidates.
vimsupport.SetCurrentLineAndColumn( line, start_column )
omnifunc_call = [ self._omnifunc,
"(0,'",
vimsupport.EscapeForVim( request_data[ 'query' ] ),
"')" ]
items = vim.eval( ''.join( omnifunc_call ) )
if isinstance( items, dict ) and 'words' in items:
items = items[ 'words' ]
if not hasattr( items, '__iter__' ):
raise TypeError( OMNIFUNC_NOT_LIST )
# Vim allows each item of the list to be either a string or a dictionary
# but ycmd only supports lists where items are all strings or all
# dictionaries. Convert all strings into dictionaries.
for index, item in enumerate( items ):
# Set the 'equal' field to 1 to disable Vim filtering.
if not isinstance( item, dict ):
items[ index ] = {
'word': item,
'equal': 1
}
else:
item[ 'equal' ] = 1
return items
except ( TypeError, ValueError, vim.error ) as error:
vimsupport.PostVimMessage(
OMNIFUNC_RETURNED_BAD_VALUE + ' ' + str( error ) )
return []
finally:
vimsupport.SetCurrentLineAndColumn( line, column )
def FilterAndSortCandidatesInner( self, candidates, sort_property, query ):
request_data = {
'candidates': candidates,
'sort_property': sort_property,
'query': query
}
response = BaseRequest().PostDataToHandler( request_data,
'filter_and_sort_candidates' )
return response if response is not None else []
| 5,705
|
Python
|
.py
| 121
| 40.595041
| 80
| 0.687736
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,942
|
base.py
|
ycm-core_YouCompleteMe/python/ycm/base.py
|
# Copyright (C) 2011, 2012 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import os
import json
from ycm import vimsupport, paths
from ycmd import identifier_utils
YCM_VAR_PREFIX = 'ycm_'
def GetUserOptions( default_options = {} ):
"""Builds a dictionary mapping YCM Vim user options to values. Option names
don't have the 'ycm_' prefix."""
user_options = {}
# First load the default settings from ycmd. We do this to ensure that any
# client-side code that assumes all options are loaded (such as the
# omnicompleter) don't have to constantly check for values being present, and
# so that we don't jave to dulicate the list of server settings in
# youcomplete.vim
defaults_file = os.path.join( paths.DIR_OF_YCMD,
'ycmd',
'default_settings.json' )
if os.path.exists( defaults_file ):
with open( defaults_file ) as defaults_file_handle:
user_options = json.load( defaults_file_handle )
# Override the server defaults with any client-generated defaults
user_options.update( default_options )
# Finally, override with any user-specified values in the g: dict
# We only evaluate the keys of the vim globals and not the whole dictionary
# to avoid unicode issues.
# See https://github.com/Valloric/YouCompleteMe/pull/2151 for details.
keys = vimsupport.GetVimGlobalsKeys()
for key in keys:
if not key.startswith( YCM_VAR_PREFIX ):
continue
new_key = key[ len( YCM_VAR_PREFIX ): ]
new_value = vimsupport.VimExpressionToPythonType( 'g:' + key )
user_options[ new_key ] = new_value
return user_options
def CurrentIdentifierFinished():
line, current_column = vimsupport.CurrentLineContentsAndCodepointColumn()
previous_char_index = current_column - 1
if previous_char_index < 0:
return True
filetype = vimsupport.CurrentFiletypes()[ 0 ]
regex = identifier_utils.IdentifierRegexForFiletype( filetype )
for match in regex.finditer( line ):
if match.end() == previous_char_index:
return True
# If the whole line is whitespace, that means the user probably finished an
# identifier on the previous line.
return line[ : current_column ].isspace()
def LastEnteredCharIsIdentifierChar():
line, current_column = vimsupport.CurrentLineContentsAndCodepointColumn()
if current_column - 1 < 0:
return False
filetype = vimsupport.CurrentFiletypes()[ 0 ]
return (
identifier_utils.StartOfLongestIdentifierEndingAtIndex(
line, current_column, filetype ) != current_column )
def AdjustCandidateInsertionText( candidates ):
"""This function adjusts the candidate insertion text to take into account the
text that's currently in front of the cursor.
For instance ('|' represents the cursor):
1. Buffer state: 'foo.|bar'
2. A completion candidate of 'zoobar' is shown and the user selects it.
3. Buffer state: 'foo.zoobar|bar' instead of 'foo.zoo|bar' which is what the
user wanted.
This function changes candidates to resolve that issue.
It could be argued that the user actually wants the final buffer state to be
'foo.zoobar|' (the cursor at the end), but that would be much more difficult
to implement and is probably not worth doing.
"""
def NewCandidateInsertionText( to_insert, text_after_cursor ):
overlap_len = OverlapLength( to_insert, text_after_cursor )
if overlap_len:
return to_insert[ :-overlap_len ]
return to_insert
text_after_cursor = vimsupport.TextAfterCursor()
if not text_after_cursor:
return candidates
new_candidates = []
for candidate in candidates:
new_candidate = candidate.copy()
if not new_candidate.get( 'abbr' ):
new_candidate[ 'abbr' ] = new_candidate[ 'word' ]
new_candidate[ 'word' ] = NewCandidateInsertionText(
new_candidate[ 'word' ],
text_after_cursor )
new_candidates.append( new_candidate )
return new_candidates
def OverlapLength( left_string, right_string ):
"""Returns the length of the overlap between two strings.
Example: "foo baro" and "baro zoo" -> 4
"""
left_string_length = len( left_string )
right_string_length = len( right_string )
if not left_string_length or not right_string_length:
return 0
# Truncate the longer string.
if left_string_length > right_string_length:
left_string = left_string[ -right_string_length: ]
elif left_string_length < right_string_length:
right_string = right_string[ :left_string_length ]
if left_string == right_string:
return min( left_string_length, right_string_length )
# Start by looking for a single character match
# and increase length until no match is found.
best = 0
length = 1
while True:
pattern = left_string[ -length: ]
found = right_string.find( pattern )
if found < 0:
return best
length += found
if left_string[ -length: ] == right_string[ :length ]:
best = length
length += 1
| 5,606
|
Python
|
.py
| 130
| 38.976923
| 80
| 0.727724
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,943
|
diagnostic_interface.py
|
ycm-core_YouCompleteMe/python/ycm/diagnostic_interface.py
|
# Copyright (C) 2013-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from collections import defaultdict
from ycm import vimsupport
from ycm.diagnostic_filter import DiagnosticFilter, CompileLevel
from ycm import text_properties as tp
import vim
YCM_VIM_PROPERTY_ID = 1
class DiagnosticInterface:
def __init__( self, bufnr, user_options ):
self._bufnr = bufnr
self._user_options = user_options
self._diagnostics = []
self._diag_filter = DiagnosticFilter.CreateFromOptions( user_options )
# Line and column numbers are 1-based
self._line_to_diags = defaultdict( list )
self._previous_diag_line_number = -1
self._diag_message_needs_clearing = False
def ShouldUpdateDiagnosticsUINow( self ):
return ( self._user_options[ 'update_diagnostics_in_insert_mode' ] or
'i' not in vim.eval( 'mode()' ) )
def OnCursorMoved( self ):
if self._user_options[ 'echo_current_diagnostic' ]:
line, _ = vimsupport.CurrentLineAndColumn()
line += 1 # Convert to 1-based
if not self.ShouldUpdateDiagnosticsUINow():
# Clear any previously echo'd diagnostic in insert mode
self._EchoDiagnosticText( line, None, None )
elif line != self._previous_diag_line_number:
self._EchoDiagnosticForLine( line )
def GetErrorCount( self ):
return self._DiagnosticsCount( _DiagnosticIsError )
def GetWarningCount( self ):
return self._DiagnosticsCount( _DiagnosticIsWarning )
def PopulateLocationList( self, open_on_edit = False ):
# Do nothing if loc list is already populated by diag_interface
if not self._user_options[ 'always_populate_location_list' ]:
self._UpdateLocationLists( open_on_edit )
return bool( self._diagnostics )
def UpdateWithNewDiagnostics( self, diags, open_on_edit = False ):
self._diagnostics = [ _NormalizeDiagnostic( x ) for x in
self._ApplyDiagnosticFilter( diags ) ]
self._ConvertDiagListToDict()
if self.ShouldUpdateDiagnosticsUINow():
self.RefreshDiagnosticsUI( open_on_edit )
def RefreshDiagnosticsUI( self, open_on_edit = False ):
if self._user_options[ 'echo_current_diagnostic' ]:
self._EchoDiagnostic()
if self._user_options[ 'enable_diagnostic_signs' ]:
self._UpdateSigns()
self.UpdateMatches()
if self._user_options[ 'always_populate_location_list' ]:
self._UpdateLocationLists( open_on_edit )
def ClearDiagnosticsUI( self ):
if self._user_options[ 'echo_current_diagnostic' ]:
self._ClearCurrentDiagnostic()
if self._user_options[ 'enable_diagnostic_signs' ]:
self._ClearSigns()
self._ClearMatches()
def DiagnosticsForLine( self, line_number ):
return self._line_to_diags[ line_number ]
def _ApplyDiagnosticFilter( self, diags ):
filetypes = vimsupport.GetBufferFiletypes( self._bufnr )
diag_filter = self._diag_filter.SubsetForTypes( filetypes )
return filter( diag_filter.IsAllowed, diags )
def _EchoDiagnostic( self ):
line, _ = vimsupport.CurrentLineAndColumn()
line += 1 # Convert to 1-based
self._EchoDiagnosticForLine( line )
def _EchoDiagnosticForLine( self, line_num ):
self._previous_diag_line_number = line_num
diags = self._line_to_diags[ line_num ]
text = None
first_diag = None
if diags:
first_diag = diags[ 0 ]
text = first_diag[ 'text' ]
if first_diag.get( 'fixit_available', False ):
text += ' (FixIt)'
self._EchoDiagnosticText( line_num, first_diag, text )
def _ClearCurrentDiagnostic( self, will_be_replaced=False ):
if not self._diag_message_needs_clearing:
return
if ( not vimsupport.VimIsNeovim() and
self._user_options[ 'echo_current_diagnostic' ] == 'virtual-text' ):
tp.ClearTextProperties( self._bufnr,
prop_types = [ 'YcmVirtDiagPadding',
'YcmVirtDiagError',
'YcmVirtDiagWarning' ] )
else:
if not will_be_replaced:
vimsupport.PostVimMessage( '', warning = False )
self._diag_message_needs_clearing = False
def _EchoDiagnosticText( self, line_num, first_diag, text ):
self._ClearCurrentDiagnostic( bool( text ) )
if ( not vimsupport.VimIsNeovim() and
self._user_options[ 'echo_current_diagnostic' ] == 'virtual-text' ):
if not text:
return
def MakeVritualTextProperty( prop_type, text, position='after' ):
vimsupport.AddTextProperty( self._bufnr,
line_num,
0,
prop_type,
{
'text': text,
'text_align': position,
'text_wrap': 'wrap'
} )
if vim.options[ 'ambiwidth' ] != 'double':
marker = 'âš '
else:
marker = '>'
MakeVritualTextProperty(
'YcmVirtDiagPadding',
' ' * vim.buffers[ self._bufnr ].options[ 'shiftwidth' ] ),
MakeVritualTextProperty(
'YcmVirtDiagError' if _DiagnosticIsError( first_diag )
else 'YcmVirtDiagWarning',
marker + ' ' + [ line for line in text.splitlines() if line ][ 0 ] )
else:
if not text:
# We already cleared it
return
vimsupport.PostVimMessage( text, warning = False, truncate = True )
self._diag_message_needs_clearing = True
def _DiagnosticsCount( self, predicate ):
count = 0
for diags in self._line_to_diags.values():
count += sum( 1 for d in diags if predicate( d ) )
return count
def _UpdateLocationLists( self, open_on_edit = False ):
vimsupport.SetLocationListsForBuffer(
self._bufnr,
vimsupport.ConvertDiagnosticsToQfList( self._diagnostics ),
open_on_edit )
def _ClearMatches( self ):
props_to_remove = vimsupport.GetTextProperties( self._bufnr )
for prop in props_to_remove:
vimsupport.RemoveDiagnosticProperty( self._bufnr, prop )
def UpdateMatches( self ):
if not self._user_options[ 'enable_diagnostic_highlighting' ]:
return
props_to_remove = vimsupport.GetTextProperties( self._bufnr )
for diags in self._line_to_diags.values():
# Insert squiggles in reverse order so that errors overlap warnings.
for diag in reversed( diags ):
for line, column, name, extras in _ConvertDiagnosticToTextProperties(
self._bufnr,
diag ):
global YCM_VIM_PROPERTY_ID
# Note the following .remove() works because the __eq__ on
# DiagnosticProperty does not actually check the IDs match...
diag_prop = vimsupport.DiagnosticProperty(
YCM_VIM_PROPERTY_ID,
name,
line,
column,
extras[ 'end_col' ] - column if 'end_col' in extras else column )
try:
props_to_remove.remove( diag_prop )
except ValueError:
extras.update( {
'id': YCM_VIM_PROPERTY_ID
} )
vimsupport.AddTextProperty( self._bufnr,
line,
column,
name,
extras )
YCM_VIM_PROPERTY_ID += 1
for prop in props_to_remove:
vimsupport.RemoveDiagnosticProperty( self._bufnr, prop )
def _ClearSigns( self ):
signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr )
vim.eval( f'sign_unplacelist( { signs_to_unplace } )' )
def _UpdateSigns( self ):
signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr )
signs_to_place = []
for line, diags in self._line_to_diags.items():
if not diags:
continue
# We always go for the first diagnostic on the line because diagnostics
# are sorted by errors in priority and Vim can only display one sign by
# line.
name = 'YcmError' if _DiagnosticIsError( diags[ 0 ] ) else 'YcmWarning'
sign = {
'lnum': line,
'name': name,
'buffer': self._bufnr,
'group': 'ycm_signs'
}
try:
signs_to_unplace.remove( sign )
except ValueError:
signs_to_place.append( sign )
vim.eval( f'sign_placelist( { signs_to_place } )' )
vim.eval( f'sign_unplacelist( { signs_to_unplace } )' )
def _ConvertDiagListToDict( self ):
self._line_to_diags = defaultdict( list )
for diag in self._diagnostics:
location_extent = diag[ 'location_extent' ]
start = location_extent[ 'start' ]
end = location_extent[ 'end' ]
bufnr = vimsupport.GetBufferNumberForFilename( start[ 'filepath' ] )
if bufnr == self._bufnr:
for line_number in range( start[ 'line_num' ], end[ 'line_num' ] + 1 ):
self._line_to_diags[ line_number ].append( diag )
for diags in self._line_to_diags.values():
# We also want errors to be listed before warnings so that errors aren't
# hidden by the warnings; Vim won't place a sign over an existing one.
diags.sort( key = lambda diag: ( diag[ 'kind' ],
diag[ 'location' ][ 'column_num' ] ) )
_DiagnosticIsError = CompileLevel( 'error' )
_DiagnosticIsWarning = CompileLevel( 'warning' )
def _NormalizeDiagnostic( diag ):
def ClampToOne( value ):
return value if value > 0 else 1
location = diag[ 'location' ]
location[ 'column_num' ] = ClampToOne( location[ 'column_num' ] )
location[ 'line_num' ] = ClampToOne( location[ 'line_num' ] )
return diag
def _ConvertDiagnosticToTextProperties( bufnr, diagnostic ):
properties = []
name = ( 'YcmErrorProperty' if _DiagnosticIsError( diagnostic ) else
'YcmWarningProperty' )
if vimsupport.VimIsNeovim():
name = name.replace( 'Property', 'Section' )
location_extent = diagnostic[ 'location_extent' ]
if location_extent[ 'start' ][ 'line_num' ] <= 0:
location = diagnostic[ 'location' ]
line, column = vimsupport.LineAndColumnNumbersClamped(
bufnr,
location[ 'line_num' ],
location[ 'column_num' ]
)
properties.append( ( line, column, name, {} ) )
else:
start_line, start_column = vimsupport.LineAndColumnNumbersClamped(
bufnr,
location_extent[ 'start' ][ 'line_num' ],
location_extent[ 'start' ][ 'column_num' ]
)
end_line, end_column = vimsupport.LineAndColumnNumbersClamped(
bufnr,
location_extent[ 'end' ][ 'line_num' ],
location_extent[ 'end' ][ 'column_num' ]
)
properties.append( (
start_line,
start_column,
name,
{ 'end_lnum': end_line,
'end_col': end_column } ) )
for diagnostic_range in diagnostic[ 'ranges' ]:
if ( diagnostic_range[ 'start' ][ 'line_num' ] == 0 or
diagnostic_range[ 'end' ][ 'line_num' ] == 0 ):
continue
start_line, start_column = vimsupport.LineAndColumnNumbersClamped(
bufnr,
diagnostic_range[ 'start' ][ 'line_num' ],
diagnostic_range[ 'start' ][ 'column_num' ]
)
end_line, end_column = vimsupport.LineAndColumnNumbersClamped(
bufnr,
diagnostic_range[ 'end' ][ 'line_num' ],
diagnostic_range[ 'end' ][ 'column_num' ]
)
if not _IsValidRange( start_line, start_column, end_line, end_column ):
continue
properties.append( (
start_line,
start_column,
name,
{ 'end_lnum': end_line,
'end_col': end_column } ) )
return properties
def _IsValidRange( start_line, start_column, end_line, end_column ):
# End line before start line - invalid
if start_line > end_line:
return False
# End line after start line - valid
if start_line < end_line:
return True
# Same line, start colum after end column - invalid
if start_column > end_column:
return False
# Same line, start column before or equal to end column - valid
return True
| 12,808
|
Python
|
.py
| 303
| 34.20462
| 79
| 0.6346
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,944
|
paths.py
|
ycm-core_YouCompleteMe/python/ycm/paths.py
|
# Copyright (C) 2015-2017 YouCompleteMe contributors.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import vim
import re
# Can't import these from setup.py because it makes nosetests go crazy.
DIR_OF_CURRENT_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_YCMD = os.path.join( DIR_OF_CURRENT_SCRIPT, '..', '..', 'third_party',
'ycmd' )
WIN_PYTHON_PATH = os.path.join( sys.exec_prefix, 'python.exe' )
PYTHON_BINARY_REGEX = re.compile(
r'python(3(\.[6-9])?)?(.exe)?$', re.IGNORECASE )
# Not caching the result of this function; users shouldn't have to restart Vim
# after running the install script or setting the
# `g:ycm_server_python_interpreter` option.
def PathToPythonInterpreter():
# Not calling the Python interpreter to check its version as it significantly
# impacts startup time.
from ycmd import utils
python_interpreter = vim.eval( 'g:ycm_server_python_interpreter' )
if python_interpreter:
python_interpreter = utils.FindExecutable( python_interpreter )
if python_interpreter:
return python_interpreter
raise RuntimeError( "Path in 'g:ycm_server_python_interpreter' option "
"does not point to a valid Python 3.6+." )
python_interpreter = _PathToPythonUsedDuringBuild()
if python_interpreter and utils.GetExecutable( python_interpreter ):
return python_interpreter
# On UNIX platforms, we use sys.executable as the Python interpreter path.
# We cannot use sys.executable on Windows because for unknown reasons, it
# returns the Vim executable. Instead, we use sys.exec_prefix to deduce the
# interpreter path.
python_interpreter = ( WIN_PYTHON_PATH if utils.OnWindows() else
sys.executable )
if _EndsWithPython( python_interpreter ):
return python_interpreter
python_interpreter = utils.PathToFirstExistingExecutable( [ 'python3',
'python' ] )
if python_interpreter:
return python_interpreter
raise RuntimeError( "Cannot find Python 3.6+. "
"Set the 'g:ycm_server_python_interpreter' option "
"to a Python interpreter path." )
def _PathToPythonUsedDuringBuild():
from ycmd import utils
try:
filepath = os.path.join( DIR_OF_YCMD, 'PYTHON_USED_DURING_BUILDING' )
return utils.ReadFile( filepath ).strip()
except OSError:
return None
def _EndsWithPython( path ):
"""Check if given path ends with a python 3.6+ name."""
return path and PYTHON_BINARY_REGEX.search( path ) is not None
def PathToServerScript():
return os.path.join( DIR_OF_YCMD, 'ycmd' )
| 3,317
|
Python
|
.py
| 71
| 41.661972
| 79
| 0.716631
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,945
|
youcompleteme.py
|
ycm-core_YouCompleteMe/python/ycm/youcompleteme.py
|
# Copyright (C) 2011-2024 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import base64
import json
import logging
import os
import signal
import vim
from subprocess import PIPE
from tempfile import NamedTemporaryFile
from ycm import base, paths, signature_help, vimsupport
from ycm.buffer import BufferDict
from ycmd import utils
from ycmd.request_wrap import RequestWrap
from ycm.omni_completer import OmniCompleter
from ycm import syntax_parse
from ycm.hierarchy_tree import HierarchyTree
from ycm.client.ycmd_keepalive import YcmdKeepalive
from ycm.client.base_request import BaseRequest, BuildRequestData
from ycm.client.completer_available_request import SendCompleterAvailableRequest
from ycm.client.command_request import ( SendCommandRequest,
SendCommandRequestAsync,
GetCommandResponse,
GetRawCommandResponse )
from ycm.client.completion_request import CompletionRequest
from ycm.client.resolve_completion_request import ResolveCompletionItem
from ycm.client.signature_help_request import ( SignatureHelpRequest,
SigHelpAvailableByFileType )
from ycm.client.debug_info_request import ( SendDebugInfoRequest,
FormatDebugInfoResponse )
from ycm.client.omni_completion_request import OmniCompletionRequest
from ycm.client.event_notification import SendEventNotificationAsync
from ycm.client.shutdown_request import SendShutdownRequest
from ycm.client.messages_request import MessagesPoll
def PatchNoProxy():
current_value = os.environ.get( 'no_proxy', '' )
additions = '127.0.0.1,localhost'
os.environ[ 'no_proxy' ] = ( additions if not current_value
else current_value + ',' + additions )
# We need this so that Requests doesn't end up using the local HTTP proxy when
# talking to ycmd. Users should actually be setting this themselves when
# configuring a proxy server on their machine, but most don't know they need to
# or how to do it, so we do it for them.
# Relevant issues:
# https://github.com/Valloric/YouCompleteMe/issues/641
# https://github.com/kennethreitz/requests/issues/879
PatchNoProxy()
# Force the Python interpreter embedded in Vim (in which we are running) to
# ignore the SIGINT signal. This helps reduce the fallout of a user pressing
# Ctrl-C in Vim.
signal.signal( signal.SIGINT, signal.SIG_IGN )
HMAC_SECRET_LENGTH = 16
SERVER_SHUTDOWN_MESSAGE = (
"The ycmd server SHUT DOWN (restart with ':YcmRestartServer')." )
EXIT_CODE_UNEXPECTED_MESSAGE = (
"Unexpected exit code {code}. "
"Type ':YcmToggleLogs {logfile}' to check the logs." )
CORE_UNEXPECTED_MESSAGE = (
"Unexpected error while loading the YCM core library. "
"Type ':YcmToggleLogs {logfile}' to check the logs." )
CORE_MISSING_MESSAGE = (
'YCM core library not detected; you need to compile YCM before using it. '
'Follow the instructions in the documentation.' )
CORE_OUTDATED_MESSAGE = (
'YCM core library too old; PLEASE RECOMPILE by running the install.py '
'script. See the documentation for more details.' )
PYTHON_TOO_OLD_MESSAGE = (
'Your python is too old to run YCM server. '
'Please see troubleshooting guide on YCM GitHub wiki.'
)
SERVER_IDLE_SUICIDE_SECONDS = 1800 # 30 minutes
CLIENT_LOGFILE_FORMAT = 'ycm_'
SERVER_LOGFILE_FORMAT = 'ycmd_{port}_{std}_'
# Flag to set a file handle inheritable by child processes on Windows. See
# https://msdn.microsoft.com/en-us/library/ms724935.aspx
HANDLE_FLAG_INHERIT = 0x00000001
class YouCompleteMe:
def __init__( self, default_options = {} ):
self._logger = logging.getLogger( 'ycm' )
self._client_logfile = None
self._server_stdout = None
self._server_stderr = None
self._server_popen = None
self._default_options = default_options
self._ycmd_keepalive = YcmdKeepalive()
self._SetUpLogging()
self._SetUpServer()
self._ycmd_keepalive.Start()
self._current_hierarchy = HierarchyTree()
def InitializeCurrentHierarchy( self, items, kind ):
return self._current_hierarchy.SetRootNode( items, kind )
def UpdateCurrentHierarchy( self, handle : int, direction : str ):
if not self._current_hierarchy.UpdateChangesRoot( handle, direction ):
items = self._ResolveHierarchyItem( handle, direction )
self._current_hierarchy.UpdateHierarchy( handle, items, direction )
if items is not None and direction == 'up':
offset = sum( len( item[ 'locations' ] ) for item in items )
else:
offset = 0
return self._current_hierarchy.HierarchyToLines(), offset
else:
location = self._current_hierarchy.HandleToRootLocation( handle )
kind = self._current_hierarchy._kind
self._current_hierarchy.Reset()
items = GetRawCommandResponse(
[ f'{ kind.title() }Hierarchy' ],
silent = False,
location = location
)
# [ 0 ] chooses the data for the 1st (and only) line.
# [ 1 ] chooses only the handle
handle = self.InitializeCurrentHierarchy( items, kind )[ 0 ][ 1 ]
return self.UpdateCurrentHierarchy( handle, direction )
def _ResolveHierarchyItem( self, handle : int, direction : str ):
return GetRawCommandResponse(
self._current_hierarchy.ResolveArguments( handle, direction ),
silent = False
)
def ShouldResolveItem( self, handle : int, direction : str ):
return self._current_hierarchy.ShouldResolveItem( handle, direction )
def ResetCurrentHierarchy( self ):
self._current_hierarchy.Reset()
def JumpToHierarchyItem( self, handle ):
self._current_hierarchy.JumpToItem(
handle,
self._user_options[ 'goto_buffer_command' ] )
def _SetUpServer( self ):
self._available_completers = {}
self._user_notified_about_crash = False
self._filetypes_with_keywords_loaded = set()
self._server_is_ready_with_cache = False
self._message_poll_requests = {}
self._latest_completion_request = None
self._latest_signature_help_request = None
self._signature_help_available_requests = SigHelpAvailableByFileType()
self._command_requests = {}
self._next_command_request_id = 0
self._signature_help_state = signature_help.SignatureHelpState()
self._user_options = base.GetUserOptions( self._default_options )
self._omnicomp = OmniCompleter( self._user_options )
self._buffers = BufferDict( self._user_options )
self._SetLogLevel()
hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
options_dict = dict( self._user_options )
options_dict[ 'hmac_secret' ] = utils.ToUnicode(
base64.b64encode( hmac_secret ) )
options_dict[ 'server_keep_logfiles' ] = self._user_options[
'keep_logfiles' ]
# The temp options file is deleted by ycmd during startup.
with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
json.dump( options_dict, options_file )
server_port = utils.GetUnusedLocalhostPort()
BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
BaseRequest.hmac_secret = hmac_secret
try:
python_interpreter = paths.PathToPythonInterpreter()
except RuntimeError as error:
error_message = (
f"Unable to start the ycmd server. { str( error ).rstrip( '.' ) }. "
"Correct the error then restart the server "
"with ':YcmRestartServer'." )
self._logger.exception( error_message )
vimsupport.PostVimMessage( error_message )
return
args = [ python_interpreter,
paths.PathToServerScript(),
f'--port={ server_port }',
f'--options_file={ options_file.name }',
f'--log={ self._user_options[ "log_level" ] }',
f'--idle_suicide_seconds={ SERVER_IDLE_SUICIDE_SECONDS }' ]
self._server_stdout = utils.CreateLogfile(
SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stdout' ) )
self._server_stderr = utils.CreateLogfile(
SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stderr' ) )
args.append( f'--stdout={ self._server_stdout }' )
args.append( f'--stderr={ self._server_stderr }' )
if self._user_options[ 'keep_logfiles' ]:
args.append( '--keep_logfiles' )
self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
stdout = PIPE, stderr = PIPE )
def _SetUpLogging( self ):
def FreeFileFromOtherProcesses( file_object ):
if utils.OnWindows():
from ctypes import windll
import msvcrt
file_handle = msvcrt.get_osfhandle( file_object.fileno() )
windll.kernel32.SetHandleInformation( file_handle,
HANDLE_FLAG_INHERIT,
0 )
self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )
handler = logging.FileHandler( self._client_logfile )
# On Windows and Python prior to 3.4, file handles are inherited by child
# processes started with at least one replaced standard stream, which is the
# case when we start the ycmd server (we are redirecting all standard
# outputs into a pipe). These files cannot be removed while the child
# processes are still up. This is not desirable for a logfile because we
# want to remove it at Vim exit without having to wait for the ycmd server
# to be completely shut down. We need to make the logfile handle
# non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
# details.
FreeFileFromOtherProcesses( handler.stream )
formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' )
handler.setFormatter( formatter )
self._logger.addHandler( handler )
def _SetLogLevel( self ):
log_level = self._user_options[ 'log_level' ]
numeric_level = getattr( logging, log_level.upper(), None )
if not isinstance( numeric_level, int ):
raise ValueError( f'Invalid log level: { log_level }' )
self._logger.setLevel( numeric_level )
def IsServerAlive( self ):
# When the process hasn't finished yet, poll() returns None.
return bool( self._server_popen ) and self._server_popen.poll() is None
def CheckIfServerIsReady( self ):
if not self._server_is_ready_with_cache and self.IsServerAlive():
self._server_is_ready_with_cache = BaseRequest().GetDataFromHandler(
'ready', display_message = False )
return self._server_is_ready_with_cache
def IsServerReady( self ):
return self._server_is_ready_with_cache
def NotifyUserIfServerCrashed( self ):
if ( not self._server_popen or self._user_notified_about_crash or
self.IsServerAlive() ):
return
self._user_notified_about_crash = True
return_code = self._server_popen.poll()
logfile = os.path.basename( self._server_stderr )
# See https://github.com/Valloric/ycmd#exit-codes for the list of exit
# codes.
if return_code == 3:
error_message = CORE_UNEXPECTED_MESSAGE.format( logfile = logfile )
elif return_code == 4:
error_message = CORE_MISSING_MESSAGE
elif return_code == 7:
error_message = CORE_OUTDATED_MESSAGE
elif return_code == 8:
# TODO: here we could retry but discard g:ycm_server_python_interpreter
error_message = PYTHON_TOO_OLD_MESSAGE
else:
error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format( code = return_code,
logfile = logfile )
if return_code != 8:
error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
self._logger.error( error_message )
vimsupport.PostVimMessage( error_message )
def ServerPid( self ):
if not self._server_popen:
return -1
return self._server_popen.pid
def _ShutdownServer( self ):
SendShutdownRequest()
def RestartServer( self ):
vimsupport.PostVimMessage( 'Restarting ycmd server...' )
self._ShutdownServer()
self._SetUpServer()
def SendCompletionRequest( self, force_semantic = False ):
request_data = BuildRequestData()
request_data[ 'force_semantic' ] = force_semantic
if not self.NativeFiletypeCompletionUsable():
wrapped_request_data = RequestWrap( request_data )
if self._omnicomp.ShouldUseNow( wrapped_request_data ):
self._latest_completion_request = OmniCompletionRequest(
self._omnicomp, wrapped_request_data )
self._latest_completion_request.Start()
return
self._AddExtraConfDataIfNeeded( request_data )
self._latest_completion_request = CompletionRequest( request_data )
self._latest_completion_request.Start()
def CompletionRequestReady( self ):
return bool( self._latest_completion_request and
self._latest_completion_request.Done() )
def GetCompletionResponse( self ):
return self._latest_completion_request.Response()
def SignatureHelpAvailableRequestComplete( self, filetype, send_new=True ):
"""Triggers or polls signature help available request. Returns whether or
not the request is complete. When send_new is False, won't send a new
request, only return the current status (This is used by the tests)"""
if not send_new and filetype not in self._signature_help_available_requests:
return False
return self._signature_help_available_requests[ filetype ].Done()
def SendSignatureHelpRequest( self ):
"""Send a signature help request, if we're ready to. Return whether or not a
request was sent (and should be checked later)"""
if not self.NativeFiletypeCompletionUsable():
return False
for filetype in vimsupport.CurrentFiletypes():
if not self.SignatureHelpAvailableRequestComplete( filetype ):
continue
sig_help_available = self._signature_help_available_requests[
filetype ].Response()
if sig_help_available == 'NO':
continue
if sig_help_available == 'PENDING':
# Send another /signature_help_available request
self._signature_help_available_requests[ filetype ].Start( filetype )
continue
if not self._latest_completion_request:
return False
request_data = self._latest_completion_request.request_data.copy()
request_data[ 'signature_help_state' ] = (
self._signature_help_state.IsActive()
)
self._AddExtraConfDataIfNeeded( request_data )
self._latest_signature_help_request = SignatureHelpRequest( request_data )
self._latest_signature_help_request.Start()
return True
return False
def SignatureHelpRequestReady( self ):
return bool( self._latest_signature_help_request and
self._latest_signature_help_request.Done() )
def GetSignatureHelpResponse( self ):
return self._latest_signature_help_request.Response()
def ClearSignatureHelp( self ):
self.UpdateSignatureHelp( {} )
if self._latest_signature_help_request:
self._latest_signature_help_request.Reset()
def UpdateSignatureHelp( self, signature_info ):
self._signature_help_state = signature_help.UpdateSignatureHelp(
self._signature_help_state,
signature_info )
def _GetCommandRequestArguments( self,
arguments,
has_range,
start_line,
end_line ):
extra_data = {
'options': {
'tab_size': vimsupport.GetIntValue( 'shiftwidth()' ),
'insert_spaces': vimsupport.GetBoolValue( '&expandtab' )
}
}
final_arguments = []
for argument in arguments:
if argument.startswith( 'ft=' ):
extra_data[ 'completer_target' ] = argument[ 3: ]
continue
elif argument.startswith( '--bufnr=' ):
extra_data[ 'bufnr' ] = int( argument[ len( '--bufnr=' ): ] )
continue
final_arguments.append( argument )
if has_range:
extra_data.update( vimsupport.BuildRange( start_line, end_line ) )
self._AddExtraConfDataIfNeeded( extra_data )
return final_arguments, extra_data
def SendCommandRequest( self,
arguments,
modifiers,
has_range,
start_line,
end_line ):
final_arguments, extra_data = self._GetCommandRequestArguments(
arguments,
has_range,
start_line,
end_line )
return SendCommandRequest(
final_arguments,
modifiers,
self._user_options[ 'goto_buffer_command' ],
extra_data )
def GetCommandResponse( self, arguments ):
final_arguments, extra_data = self._GetCommandRequestArguments(
arguments,
False,
0,
0 )
return GetCommandResponse( final_arguments, extra_data )
def SendCommandRequestAsync( self,
arguments,
silent = True,
location = None ):
final_arguments, extra_data = self._GetCommandRequestArguments(
arguments,
False,
0,
0 )
request_id = self._next_command_request_id
self._next_command_request_id += 1
self._command_requests[ request_id ] = SendCommandRequestAsync(
final_arguments,
extra_data,
silent,
location = location )
return request_id
def GetCommandRequest( self, request_id ):
return self._command_requests.get( request_id )
def FlushCommandRequest( self, request_id ):
self._command_requests.pop( request_id, None )
def GetDefinedSubcommands( self ):
request = BaseRequest()
subcommands = request.PostDataToHandler( BuildRequestData(),
'defined_subcommands' )
return subcommands if subcommands else []
def GetCurrentCompletionRequest( self ):
return self._latest_completion_request
def GetOmniCompleter( self ):
return self._omnicomp
def FiletypeCompleterExistsForFiletype( self, filetype ):
try:
return self._available_completers[ filetype ]
except KeyError:
pass
exists_completer = SendCompleterAvailableRequest( filetype )
if exists_completer is None:
return False
self._available_completers[ filetype ] = exists_completer
return exists_completer
def NativeFiletypeCompletionAvailable( self ):
return any( self.FiletypeCompleterExistsForFiletype( x ) for x in
vimsupport.CurrentFiletypes() )
def NativeFiletypeCompletionUsable( self ):
disabled_filetypes = self._user_options[
'filetype_specific_completion_to_disable' ]
return ( vimsupport.CurrentFiletypesEnabled( disabled_filetypes ) and
self.NativeFiletypeCompletionAvailable() )
def NeedsReparse( self ):
return self.CurrentBuffer().NeedsReparse()
def UpdateWithNewDiagnosticsForFile( self, filepath, diagnostics ):
if not self._user_options[ 'show_diagnostics_ui' ]:
return
bufnr = vimsupport.GetBufferNumberForFilename( filepath )
if bufnr in self._buffers and vimsupport.BufferIsVisible( bufnr ):
# Note: We only update location lists, etc. for visible buffers, because
# otherwise we default to using the current location list and the results
# are that non-visible buffer errors clobber visible ones.
self._buffers[ bufnr ].UpdateWithNewDiagnostics( diagnostics, True )
else:
# The project contains errors in file "filepath", but that file is not
# open in any buffer. This happens for Language Server Protocol-based
# completers, as they return diagnostics for the entire "project"
# asynchronously (rather than per-file in the response to the parse
# request).
#
# There are a number of possible approaches for
# this, but for now we simply ignore them. Other options include:
# - Use the QuickFix list to report project errors?
# - Use a special buffer for project errors
# - Put them in the location list of whatever the "current" buffer is
# - Store them in case the buffer is opened later
# - add a :YcmProjectDiags command
# - Add them to errror/warning _counts_ but not any actual location list
# or other
# - etc.
#
# However, none of those options are great, and lead to their own
# complexities. So for now, we just ignore these diagnostics for files not
# open in any buffer.
pass
def OnPeriodicTick( self ):
if not self.IsServerAlive():
# Server has died. We'll reset when the server is started again.
return False
elif not self.IsServerReady():
# Try again in a jiffy
return True
for w in vim.windows:
for filetype in vimsupport.FiletypesForBuffer( w.buffer ):
if filetype not in self._message_poll_requests:
self._message_poll_requests[ filetype ] = MessagesPoll( w.buffer )
# None means don't poll this filetype
if ( self._message_poll_requests[ filetype ] and
not self._message_poll_requests[ filetype ].Poll( self ) ):
self._message_poll_requests[ filetype ] = None
return any( self._message_poll_requests.values() )
def OnFileReadyToParse( self ):
if not self.IsServerAlive():
self.NotifyUserIfServerCrashed()
return
if not self.IsServerReady():
return
extra_data = {}
self._AddTagsFilesIfNeeded( extra_data )
self._AddSyntaxDataIfNeeded( extra_data )
self._AddExtraConfDataIfNeeded( extra_data )
self.CurrentBuffer().SendParseRequest( extra_data )
def OnFileSave( self, saved_buffer_number ):
SendEventNotificationAsync( 'FileSave', saved_buffer_number )
def OnBufferUnload( self, deleted_buffer_number ):
SendEventNotificationAsync( 'BufferUnload', deleted_buffer_number )
def UpdateMatches( self ):
self.CurrentBuffer().UpdateMatches()
def OnFileTypeSet( self ):
buffer_number = vimsupport.GetCurrentBufferNumber()
filetypes = vimsupport.CurrentFiletypes()
self._buffers[ buffer_number ].UpdateFromFileTypes( filetypes )
self.OnBufferVisit()
def OnBufferVisit( self ):
for filetype in vimsupport.CurrentFiletypes():
# Send the signature help available request for these filetypes if we need
# to (as a side effect of checking if it is complete)
self.SignatureHelpAvailableRequestComplete( filetype, True )
extra_data = {}
self._AddUltiSnipsDataIfNeeded( extra_data )
SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )
def CurrentBuffer( self ):
return self.Buffer( vimsupport.GetCurrentBufferNumber() )
def Buffer( self, bufnr ):
return self._buffers[ bufnr ]
def OnInsertEnter( self ):
if not self._user_options[ 'update_diagnostics_in_insert_mode' ]:
self.CurrentBuffer().ClearDiagnosticsUI()
def OnInsertLeave( self ):
async_diags = any( self._message_poll_requests.get( filetype )
for filetype in vimsupport.CurrentFiletypes() )
if ( not self._user_options[ 'update_diagnostics_in_insert_mode' ] and
( async_diags or not self.CurrentBuffer().ParseRequestPending() ) ):
self.CurrentBuffer().RefreshDiagnosticsUI()
SendEventNotificationAsync( 'InsertLeave' )
def OnCursorMoved( self ):
self.CurrentBuffer().OnCursorMoved()
def _CleanLogfile( self ):
logging.shutdown()
if not self._user_options[ 'keep_logfiles' ]:
if self._client_logfile:
utils.RemoveIfExists( self._client_logfile )
def OnVimLeave( self ):
self._ShutdownServer()
self._CleanLogfile()
def OnCurrentIdentifierFinished( self ):
SendEventNotificationAsync( 'CurrentIdentifierFinished' )
def OnCompleteDone( self ):
completion_request = self.GetCurrentCompletionRequest()
if completion_request:
completion_request.OnCompleteDone()
def ResolveCompletionItem( self, item ):
# Note: As mentioned elsewhere, we replace the current completion request
# with a resolve request. It's not valid to have simultaneous resolve and
# completion requests, because the resolve request uses the request data
# from the last completion request and is therefore dependent on it not
# having changed.
#
# The result of this is that self.GetCurrentCompletionRequest() might return
# either a completion request of a resolve request and it's the
# responsibility of the vimscript code to ensure that it only does one at a
# time. This is handled by re-using the same poller for completions and
# resolves.
completion_request = self.GetCurrentCompletionRequest()
if not completion_request:
return False
request = ResolveCompletionItem( completion_request, item )
if not request:
return False
self._latest_completion_request = request
return True
def GetErrorCount( self ):
return self.CurrentBuffer().GetErrorCount()
def GetWarningCount( self ):
return self.CurrentBuffer().GetWarningCount()
def _PopulateLocationListWithLatestDiagnostics( self ):
return self.CurrentBuffer().PopulateLocationList(
self._user_options[ 'open_loclist_on_ycm_diags' ] )
def FileParseRequestReady( self ):
# Return True if server is not ready yet, to stop repeating check timer.
return ( not self.IsServerReady() or
self.CurrentBuffer().FileParseRequestReady() )
def HandleFileParseRequest( self, block = False ):
if not self.IsServerReady():
return
current_buffer = self.CurrentBuffer()
# Order is important here:
# FileParseRequestReady has a low cost, while
# NativeFiletypeCompletionUsable is a blocking server request
if ( not current_buffer.IsResponseHandled() and
current_buffer.FileParseRequestReady( block ) and
self.NativeFiletypeCompletionUsable() ):
if self._user_options[ 'show_diagnostics_ui' ]:
# Forcefuly update the location list, etc. from the parse request when
# doing something like :YcmDiags
async_diags = any( self._message_poll_requests.get( filetype )
for filetype in vimsupport.CurrentFiletypes() )
current_buffer.UpdateDiagnostics( block or not async_diags )
else:
# If the user disabled diagnostics, we just want to check
# the _latest_file_parse_request for any exception or UnknownExtraConf
# response, to allow the server to raise configuration warnings, etc.
# to the user. We ignore any other supplied data.
current_buffer.GetResponse()
# We set the file parse request as handled because we want to prevent
# repeated issuing of the same warnings/errors/prompts. Setting this
# makes IsRequestHandled return True until the next request is created.
#
# Note: it is the server's responsibility to determine the frequency of
# error/warning/prompts when receiving a FileReadyToParse event, but
# it is our responsibility to ensure that we only apply the
# warning/error/prompt received once (for each event).
current_buffer.MarkResponseHandled()
def ShouldResendFileParseRequest( self ):
return self.CurrentBuffer().ShouldResendParseRequest()
def DebugInfo( self ):
debug_info = ''
if self._client_logfile:
debug_info += f'Client logfile: { self._client_logfile }\n'
extra_data = {}
self._AddExtraConfDataIfNeeded( extra_data )
debug_info += FormatDebugInfoResponse( SendDebugInfoRequest( extra_data ) )
debug_info += f'Server running at: { BaseRequest.server_location }\n'
if self._server_popen:
debug_info += f'Server process ID: { self._server_popen.pid }\n'
if self._server_stdout and self._server_stderr:
debug_info += ( 'Server logfiles:\n'
f' { self._server_stdout }\n'
f' { self._server_stderr }' )
debug_info += ( '\nSemantic highlighting supported: ' +
str( not vimsupport.VimIsNeovim() ) )
debug_info += ( '\nVirtual text supported: ' +
str( not vimsupport.VimIsNeovim() ) )
debug_info += ( '\nPopup windows supported: ' +
str( vimsupport.VimSupportsPopupWindows() ) )
return debug_info
def GetLogfiles( self ):
logfiles_list = [ self._client_logfile,
self._server_stdout,
self._server_stderr ]
extra_data = {}
self._AddExtraConfDataIfNeeded( extra_data )
debug_info = SendDebugInfoRequest( extra_data )
if debug_info:
completer = debug_info[ 'completer' ]
if completer:
for server in completer[ 'servers' ]:
logfiles_list.extend( server[ 'logfiles' ] )
logfiles = {}
for logfile in logfiles_list:
logfiles[ os.path.basename( logfile ) ] = logfile
return logfiles
def _OpenLogfile( self, size, mods, logfile ):
# Open log files in a horizontal window with the same behavior as the
# preview window (same height and winfixheight enabled). Automatically
# watch for changes. Set the cursor position at the end of the file.
if not size:
size = vimsupport.GetIntValue( '&previewheight' )
options = {
'size': size,
'fix': True,
'focus': False,
'watch': True,
'position': 'end',
'mods': mods
}
vimsupport.OpenFilename( logfile, options )
def _CloseLogfile( self, logfile ):
vimsupport.CloseBuffersForFilename( logfile )
def ToggleLogs( self, size, mods, *filenames ):
logfiles = self.GetLogfiles()
if not filenames:
sorted_logfiles = sorted( logfiles )
try:
logfile_index = vimsupport.SelectFromList(
'Which logfile do you wish to open (or close if already open)?',
sorted_logfiles )
except RuntimeError as e:
vimsupport.PostVimMessage( str( e ) )
return
logfile = logfiles[ sorted_logfiles[ logfile_index ] ]
if not vimsupport.BufferIsVisibleForFilename( logfile ):
self._OpenLogfile( size, mods, logfile )
else:
self._CloseLogfile( logfile )
return
for filename in set( filenames ):
if filename not in logfiles:
continue
logfile = logfiles[ filename ]
if not vimsupport.BufferIsVisibleForFilename( logfile ):
self._OpenLogfile( size, mods, logfile )
continue
self._CloseLogfile( logfile )
def ShowDetailedDiagnostic( self, message_in_popup ):
detailed_diagnostic = BaseRequest().PostDataToHandler(
BuildRequestData(), 'detailed_diagnostic' )
if detailed_diagnostic and 'message' in detailed_diagnostic:
message = detailed_diagnostic[ 'message' ]
if message_in_popup and vimsupport.VimSupportsPopupWindows():
window = vim.current.window
buffer_number = vimsupport.GetCurrentBufferNumber()
diags_on_this_line = self._buffers[ buffer_number ].DiagnosticsForLine(
window.cursor[ 0 ] )
lines = message.split( '\n' )
available_columns = vimsupport.GetIntValue( '&columns' )
col = window.cursor[ 1 ] + 1
if col > available_columns - 2: # -2 accounts for padding.
col = 0
options = {
'col': col,
'padding': [ 0, 1, 0, 1 ],
'maxwidth': available_columns,
'close': 'click',
'fixed': 0,
'highlight': 'YcmErrorPopup',
'border': [ 1, 1, 1, 1 ],
# Close when moving cursor
'moved': 'expr',
}
popup_func = 'popup_atcursor'
for diag in diags_on_this_line:
if message == diag[ 'text' ]:
popup_func = 'popup_create'
prop = vimsupport.GetTextPropertyForDiag( buffer_number,
window.cursor[ 0 ],
diag )
options.update( {
'textpropid': prop[ 'id' ],
'textprop': prop[ 'type' ],
} )
options.pop( 'col' )
break
vim.eval( f'{ popup_func }( { json.dumps( lines ) }, '
f'{ json.dumps( options ) } )' )
else:
vimsupport.PostVimMessage( message, warning = False )
def ForceCompileAndDiagnostics( self ):
if not self.NativeFiletypeCompletionUsable():
vimsupport.PostVimMessage(
'Native filetype completion not supported for current file, '
'cannot force recompilation.', warning = False )
return False
vimsupport.PostVimMessage(
'Forcing compilation, this will block Vim until done.',
warning = False )
self.OnFileReadyToParse()
self.HandleFileParseRequest( block = True )
vimsupport.PostVimMessage( 'Diagnostics refreshed', warning = False )
return True
def ShowDiagnostics( self ):
if not self.ForceCompileAndDiagnostics():
return
if not self._PopulateLocationListWithLatestDiagnostics():
vimsupport.PostVimMessage( 'No warnings or errors detected.',
warning = False )
return
if self._user_options[ 'open_loclist_on_ycm_diags' ]:
vimsupport.OpenLocationList( focus = True )
def FilterAndSortItems( self,
items,
sort_property,
query,
max_items = 0 ):
return BaseRequest().PostDataToHandler( {
'candidates': items,
'sort_property': sort_property,
'max_num_candidates': max_items,
'query': vimsupport.ToUnicode( query )
}, 'filter_and_sort_candidates' )
def ToggleSignatureHelp( self ):
self._signature_help_state.ToggleVisibility()
def _AddSyntaxDataIfNeeded( self, extra_data ):
if not self._user_options[ 'seed_identifiers_with_syntax' ]:
return
filetype = vimsupport.CurrentFiletypes()[ 0 ]
if filetype in self._filetypes_with_keywords_loaded:
return
if self.IsServerReady():
self._filetypes_with_keywords_loaded.add( filetype )
extra_data[ 'syntax_keywords' ] = list(
syntax_parse.SyntaxKeywordsForCurrentBuffer() )
def _AddTagsFilesIfNeeded( self, extra_data ):
def GetTagFiles():
tag_files = vim.eval( 'tagfiles()' )
return [ ( os.path.join( utils.GetCurrentDirectory(), tag_file )
if not os.path.isabs( tag_file ) else tag_file )
for tag_file in tag_files ]
if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
return
extra_data[ 'tag_files' ] = GetTagFiles()
def _AddExtraConfDataIfNeeded( self, extra_data ):
def BuildExtraConfData( extra_conf_vim_data ):
extra_conf_data = {}
for expr in extra_conf_vim_data:
try:
extra_conf_data[ expr ] = vimsupport.VimExpressionToPythonType( expr )
except vim.error:
message = (
f"Error evaluating '{ expr }' in the 'g:ycm_extra_conf_vim_data' "
"option." )
vimsupport.PostVimMessage( message, truncate = True )
self._logger.exception( message )
return extra_conf_data
extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
if extra_conf_vim_data:
extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
extra_conf_vim_data )
def _AddUltiSnipsDataIfNeeded( self, extra_data ):
# See :h UltiSnips#SnippetsInCurrentScope.
try:
vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
except vim.error:
return
snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
extra_data[ 'ultisnips_snippets' ] = [
{ 'trigger': trigger,
'description': snippet[ 'description' ] }
for trigger, snippet in snippets.items()
]
| 36,674
|
Python
|
.py
| 807
| 37.946716
| 80
| 0.677648
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,946
|
scrolling_range.py
|
ycm-core_YouCompleteMe/python/ycm/scrolling_range.py
|
# Copyright (C) 2023, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import abc
from ycm import vimsupport
class ScrollingBufferRange( object ):
"""Abstraction used by inlay hints and semantic tokens to only request visible
ranges"""
# FIXME: Send a request per-disjoint range for this buffer rather than the
# maximal range. then collaate the results when all responses are returned
def __init__( self, bufnr ):
self._bufnr = bufnr
self._tick = -1
self._request = None
self._last_requested_range = None
def Ready( self ):
return self._request is not None and self._request.Done()
def Request( self, force=False ):
if self._request and not self.Ready():
return True
# Check to see if the buffer ranges would actually change anything visible.
# This avoids a round-trip for every single line scroll event
if ( not force and
self._tick == vimsupport.GetBufferChangedTick( self._bufnr ) and
vimsupport.VisibleRangeOfBufferOverlaps(
self._bufnr,
self._last_requested_range ) ):
return False # don't poll
# FIXME: This call is duplicated in the call to VisibleRangeOfBufferOverlaps
# - remove the expansion param
# - look up the actual visible range, then call this function
# - if not overlapping, do the factor expansion and request
self._last_requested_range = vimsupport.RangeVisibleInBuffer( self._bufnr )
# If this is false, either the self._bufnr is not a valid buffer number or
# the buffer is not visible in any window.
# Since this is called asynchronously, a user may bwipeout a buffer with
# self._bufnr number between polls.
if self._last_requested_range is None:
return False
self._tick = vimsupport.GetBufferChangedTick( self._bufnr )
# We'll never use the last response again, so clear it
self._latest_response = None
self._request = self._NewRequest( self._last_requested_range )
self._request.Start()
return True
def Update( self ):
if not self._request:
# Nothing to update
return True
assert self.Ready()
# We're ready to use this response. Clear the request (to avoid repeatedly
# re-polling).
self._latest_response = self._request.Response()
self._request = None
if self._tick != vimsupport.GetBufferChangedTick( self._bufnr ):
# Buffer has changed, we should ignore the data and retry
self.Request( force=True )
return False # poll again
self._Draw()
# No need to re-poll
return True
def Refresh( self ):
if self._tick != vimsupport.GetBufferChangedTick( self._bufnr ):
# stale data
return
if self._request is not None:
# request in progress; we''l handle refreshing when it's done.
return
self._Draw()
def GrowRangeIfNeeded( self, rng ):
"""When processing results, we may receive a wider range than requested. In
that case, grow our 'last requested' range to minimise requesting more
frequently than we need to."""
# Note: references (pointers) so no need to re-assign
rmin = self._last_requested_range[ 'start' ]
rmax = self._last_requested_range[ 'end' ]
start = rng[ 'start' ]
end = rng[ 'end' ]
if rmin[ 'line_num' ] is None or start[ 'line_num' ] < rmin[ 'line_num' ]:
rmin[ 'line_num' ] = start[ 'line_num' ]
rmin[ 'column_num' ] = start[ 'column_num' ]
elif start[ 'line_num' ] == rmin[ 'line_num' ]:
rmin[ 'column_num' ] = min( start[ 'column_num' ],
rmin[ 'column_num' ] )
if rmax[ 'line_num' ] is None or end[ 'line_num' ] > rmax[ 'line_num' ]:
rmax[ 'line_num' ] = end[ 'line_num' ]
rmax[ 'column_num' ] = end[ 'column_num' ]
elif end[ 'line_num' ] == rmax[ 'line_num' ]:
rmax[ 'column_num' ] = max( end[ 'column_num' ], rmax[ 'column_num' ] )
# API; just implement the following, using self._bufnr and
# self._latest_response as required
@abc.abstractmethod
def _NewRequest( self, request_range ):
# prepare a new request_data and return it
pass
@abc.abstractmethod
def _Draw( self ):
# actuall paint the properties
pass
| 4,879
|
Python
|
.py
| 112
| 38.419643
| 80
| 0.685189
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,947
|
unsafe_thread_pool_executor.py
|
ycm-core_YouCompleteMe/python/ycm/unsafe_thread_pool_executor.py
|
# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
#
# Copyright (C) 2013 Google Inc.
# Changes to this file are licensed under the same terms as the original file
# (the Python Software Foundation License).
import threading
import weakref
import sys
from concurrent.futures import _base
try:
import queue
except ImportError:
import Queue as queue
# This file provides an UnsafeThreadPoolExecutor, which operates exactly like
# the upstream Python version of ThreadPoolExecutor with one exception: it
# doesn't wait for worker threads to finish before shutting down the Python
# interpreter.
#
# This is dangerous for many workloads, but fine for some (like when threads
# only send network requests). The YCM workload is one of those workloads where
# it's safe (the aforementioned network requests case).
class _WorkItem:
def __init__( self, future, fn, args, kwargs ):
self.future = future
self.fn = fn
self.args = args
self.kwargs = kwargs
def run( self ):
if not self.future.set_running_or_notify_cancel():
return
try:
result = self.fn( *self.args, **self.kwargs )
except BaseException:
e = sys.exc_info()[ 1 ]
self.future.set_exception( e )
else:
self.future.set_result( result )
def _worker( executor_reference, work_queue ):
try:
while True:
work_item = work_queue.get( block=True )
if work_item is not None:
work_item.run()
continue
executor = executor_reference()
# Exit if:
# - The executor that owns the worker has been collected OR
# - The executor that owns the worker has been shutdown.
if executor is None or executor._shutdown:
# Notice other workers
work_queue.put( None )
return
del executor
except BaseException:
_base.LOGGER.critical( 'Exception in worker', exc_info=True )
class UnsafeThreadPoolExecutor( _base.Executor ):
def __init__( self, max_workers ):
"""Initializes a new ThreadPoolExecutor instance.
Args:
max_workers: The maximum number of threads that can be used to
execute the given calls.
"""
self._max_workers = max_workers
self._work_queue = queue.Queue()
self._threads = set()
self._shutdown = False
self._shutdown_lock = threading.Lock()
def submit( self, fn, *args, **kwargs ):
with self._shutdown_lock:
if self._shutdown:
raise RuntimeError( 'cannot schedule new futures after shutdown' )
f = _base.Future()
w = _WorkItem( f, fn, args, kwargs )
self._work_queue.put( w )
self._adjust_thread_count()
return f
submit.__doc__ = _base.Executor.submit.__doc__
def _adjust_thread_count( self ):
# When the executor gets lost, the weakref callback will wake up
# the worker threads.
def weakref_cb( _, q=self._work_queue ):
q.put( None )
# TODO(bquinlan): Should avoid creating new threads if there are more
# idle threads than items in the work queue.
if len( self._threads ) < self._max_workers:
t = threading.Thread( target=_worker,
args=( weakref.ref( self, weakref_cb ),
self._work_queue ) )
t.daemon = True
t.start()
self._threads.add( t )
def shutdown( self, wait=True ):
with self._shutdown_lock:
self._shutdown = True
self._work_queue.put( None )
if wait:
for t in self._threads:
t.join()
shutdown.__doc__ = _base.Executor.shutdown.__doc__
| 3,597
|
Python
|
.py
| 100
| 30.45
| 79
| 0.667625
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,948
|
completer_available_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/completer_available_request.py
|
# Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.base_request import BaseRequest, BuildRequestData
class CompleterAvailableRequest( BaseRequest ):
def __init__( self, filetypes ):
super( CompleterAvailableRequest, self ).__init__()
self.filetypes = filetypes
self._response = None
def Start( self ):
request_data = BuildRequestData()
request_data.update( { 'filetypes': self.filetypes } )
self._response = self.PostDataToHandler( request_data,
'semantic_completion_available' )
def Response( self ):
return self._response
def SendCompleterAvailableRequest( filetypes ):
request = CompleterAvailableRequest( filetypes )
# This is a blocking call.
request.Start()
return request.Response()
| 1,464
|
Python
|
.py
| 34
| 39.235294
| 78
| 0.741731
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,949
|
ycmd_keepalive.py
|
ycm-core_YouCompleteMe/python/ycm/client/ycmd_keepalive.py
|
# Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import time
from threading import Thread
from ycm.client.base_request import BaseRequest
# This class can be used to keep the ycmd server alive for the duration of the
# life of the client. By default, ycmd shuts down if it doesn't see a request in
# a while.
class YcmdKeepalive:
def __init__( self, ping_interval_seconds = 60 * 10 ):
self._keepalive_thread = Thread( target = self._ThreadMain )
self._keepalive_thread.daemon = True
self._ping_interval_seconds = ping_interval_seconds
def Start( self ):
self._keepalive_thread.start()
def _ThreadMain( self ):
while True:
time.sleep( self._ping_interval_seconds )
BaseRequest().GetDataFromHandler( 'healthy', display_message = False )
| 1,445
|
Python
|
.py
| 33
| 41.393939
| 80
| 0.757835
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,950
|
messages_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/messages_request.py
|
# Copyright (C) 2017 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.base_request import BaseRequest, BuildRequestData
from ycm.vimsupport import PostVimMessage
import logging
_logger = logging.getLogger( __name__ )
# Looooong poll
TIMEOUT_SECONDS = 60
class MessagesPoll( BaseRequest ):
def __init__( self, buff ):
super( MessagesPoll, self ).__init__()
self._request_data = BuildRequestData( buff.number )
self._response_future = None
def _SendRequest( self ):
self._response_future = self.PostDataToHandlerAsync(
self._request_data,
'receive_messages',
timeout = TIMEOUT_SECONDS )
return
def Poll( self, diagnostics_handler ):
"""This should be called regularly to check for new messages in this buffer.
Returns True if Poll should be called again in a while. Returns False when
the completer or server indicated that further polling should not be done
for the requested file."""
if self._response_future is None:
# First poll
self._SendRequest()
return True
if not self._response_future.done():
# Nothing yet...
return True
response = self.HandleFuture( self._response_future,
display_message = False )
if response is None:
# Server returned an exception.
return False
poll_again = _HandlePollResponse( response, diagnostics_handler )
if poll_again:
self._SendRequest()
return True
return False
def _HandlePollResponse( response, diagnostics_handler ):
if isinstance( response, list ):
for notification in response:
if 'message' in notification:
PostVimMessage( notification[ 'message' ],
warning = False,
truncate = True )
elif 'diagnostics' in notification:
diagnostics_handler.UpdateWithNewDiagnosticsForFile(
notification[ 'filepath' ],
notification[ 'diagnostics' ] )
elif response is False:
# Don't keep polling for this file
return False
# else any truthy response means "nothing to see here; poll again in a
# while"
# Start the next poll (only if the last poll didn't raise an exception)
return True
| 2,901
|
Python
|
.py
| 73
| 34.438356
| 80
| 0.710676
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,951
|
inlay_hints_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/inlay_hints_request.py
|
# Copyright (C) 2022, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import logging
from ycm.client.base_request import ( BaseRequest, DisplayServerException,
MakeServerException )
_logger = logging.getLogger( __name__ )
# FIXME: This is copy/pasta from SemanticTokensRequest - abstract a
# SimpleAsyncRequest base that does all of this generically
class InlayHintsRequest( BaseRequest ):
def __init__( self, request_data ):
super().__init__()
self.request_data = request_data
self._response_future = None
def Start( self ):
self._response_future = self.PostDataToHandlerAsync( self.request_data,
'inlay_hints' )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def Reset( self ):
self._response_future = None
def Response( self ):
if not self._response_future:
return []
response = self.HandleFuture( self._response_future,
truncate_message = True )
if not response:
return []
# Vim may not be able to convert the 'errors' entry to its internal format
# so we remove it from the response.
errors = response.pop( 'errors', [] )
for e in errors:
exception = MakeServerException( e )
_logger.error( exception )
DisplayServerException( exception, truncate_message = True )
return response.get( 'inlay_hints' ) or []
| 2,151
|
Python
|
.py
| 49
| 38
| 78
| 0.69334
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,952
|
signature_help_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/signature_help_request.py
|
# Copyright (C) 2019 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import logging
from ycm.client.base_request import ( BaseRequest, DisplayServerException,
MakeServerException )
_logger = logging.getLogger( __name__ )
class SigHelpAvailableByFileType( dict ):
def __missing__( self, filetype ):
request = SignatureHelpAvailableRequest( filetype )
self[ filetype ] = request
return request
class SignatureHelpRequest( BaseRequest ):
def __init__( self, request_data ):
super( SignatureHelpRequest, self ).__init__()
self.request_data = request_data
self._response_future = None
self._response = None
def Start( self ):
self._response_future = self.PostDataToHandlerAsync( self.request_data,
'signature_help' )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def Reset( self ):
self._response_future = None
def Response( self ):
if self._response is None:
self._response = self._Response()
return self._response
def _Response( self ):
if not self._response_future:
return {}
response = self.HandleFuture( self._response_future,
truncate_message = True )
if not response:
return {}
# Vim may not be able to convert the 'errors' entry to its internal format
# so we remove it from the response.
errors = response.pop( 'errors', [] )
for e in errors:
exception = MakeServerException( e )
_logger.error( exception )
DisplayServerException( exception, truncate_message = True )
return response.get( 'signature_help' ) or {}
class SignatureHelpAvailableRequest( BaseRequest ):
def __init__( self, filetype ):
super( SignatureHelpAvailableRequest, self ).__init__()
self._response_future = None
self.Start( filetype )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def Response( self ):
if not self._response_future:
return None
response = self.HandleFuture( self._response_future,
truncate_message = True )
if not response:
return None
return response[ 'available' ]
def Start( self, filetype ):
self._response_future = self.GetDataFromHandlerAsync(
'signature_help_available',
payload = { 'subserver': filetype } )
| 3,141
|
Python
|
.py
| 76
| 35.184211
| 78
| 0.684349
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,953
|
omni_completion_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/omni_completion_request.py
|
# Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.completion_request import CompletionRequest
class OmniCompletionRequest( CompletionRequest ):
def __init__( self, omni_completer, request_data ):
super( OmniCompletionRequest, self ).__init__( request_data )
self._omni_completer = omni_completer
def Start( self ):
self._results = self._omni_completer.ComputeCandidates( self.request_data )
def Done( self ):
return True
def Response( self ):
return {
'line': self.request_data[ 'line_num' ],
'column': self.request_data[ 'column_num' ],
'completion_start_column': self.request_data[ 'start_column' ],
'completions': self._results
}
def OnCompleteDone( self ):
pass
| 1,418
|
Python
|
.py
| 34
| 38.558824
| 79
| 0.738529
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,954
|
command_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/command_request.py
|
# Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.base_request import ( BaseRequest,
BuildRequestData,
BuildRequestDataForLocation )
from ycm import vimsupport
DEFAULT_BUFFER_COMMAND = 'same-buffer'
def _EnsureBackwardsCompatibility( arguments ):
if arguments and arguments[ 0 ] == 'GoToDefinitionElseDeclaration':
arguments[ 0 ] = 'GoTo'
return arguments
class CommandRequest( BaseRequest ):
def __init__( self,
arguments,
extra_data = None,
silent = False,
location = None ):
super( CommandRequest, self ).__init__()
self._arguments = _EnsureBackwardsCompatibility( arguments )
self._command = arguments and arguments[ 0 ]
self._extra_data = extra_data
self._response = None
self._request_data = None
self._response_future = None
self._silent = silent
self._bufnr = extra_data.pop( 'bufnr', None ) if extra_data else None
self._location = location
def Start( self ):
if self._location is not None:
self._request_data = BuildRequestDataForLocation( *self._location )
elif self._bufnr is not None:
self._request_data = BuildRequestData( self._bufnr )
else:
self._request_data = BuildRequestData()
if self._extra_data:
self._request_data.update( self._extra_data )
self._request_data.update( {
'command_arguments': self._arguments
} )
self._response_future = self.PostDataToHandlerAsync(
self._request_data,
'run_completer_command' )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def Response( self ):
if self._response is None and self._response_future is not None:
# Block
self._response = self.HandleFuture( self._response_future,
display_message = not self._silent )
return self._response
def RunPostCommandActionsIfNeeded( self,
modifiers,
buffer_command = DEFAULT_BUFFER_COMMAND ):
# This is a blocking call if not Done()
self.Response()
if self._response is None:
# An exception was raised and handled.
return
# If not a dictionary or a list, the response is necessarily a
# scalar: boolean, number, string, etc. In this case, we print
# it to the user.
if not isinstance( self._response, ( dict, list ) ):
return self._HandleBasicResponse()
if 'fixits' in self._response:
return self._HandleFixitResponse()
if 'message' in self._response:
return self._HandleMessageResponse()
if 'detailed_info' in self._response:
return self._HandleDetailedInfoResponse( modifiers )
# The only other type of response we understand is GoTo, and that is the
# only one that we can't detect just by inspecting the response (it should
# either be a single location or a list)
return self._HandleGotoResponse( buffer_command, modifiers )
def StringResponse( self ):
# Retuns a supporable public API version of the response. The reason this
# exists is that the ycmd API here is wonky as it originally only supported
# text-responses and now has things like fixits and such.
#
# The supportable public API is basically any text-only response. All other
# response types are returned as empty strings
# This is a blocking call if not Done()
self.Response()
# Completer threw an error ?
if self._response is None:
return ""
# If not a dictionary or a list, the response is necessarily a
# scalar: boolean, number, string, etc. In this case, we print
# it to the user.
if not isinstance( self._response, ( dict, list ) ):
return str( self._response )
if 'message' in self._response:
return self._response[ 'message' ]
if 'detailed_info' in self._response:
return self._response[ 'detailed_info' ]
# The only other type of response we understand is 'fixits' and GoTo. We
# don't provide string versions of them.
return ""
def _HandleGotoResponse( self, buffer_command, modifiers ):
if isinstance( self._response, list ):
vimsupport.SetQuickFixList(
[ vimsupport.BuildQfListItem( x ) for x in self._response ] )
vimsupport.OpenQuickFixList( focus = True, autoclose = True )
elif self._response.get( 'file_only' ):
vimsupport.JumpToLocation( self._response[ 'filepath' ],
None,
None,
modifiers,
buffer_command )
else:
vimsupport.JumpToLocation( self._response[ 'filepath' ],
self._response[ 'line_num' ],
self._response[ 'column_num' ],
modifiers,
buffer_command )
def _HandleFixitResponse( self ):
if not len( self._response[ 'fixits' ] ):
vimsupport.PostVimMessage( 'No fixits found for current line',
warning = False )
else:
try:
fixit_index = 0
# If there is more than one fixit, we need to ask the user which one
# should be applied.
#
# If there's only one, triggered by the FixIt subcommand (as opposed to
# `RefactorRename`, for example) and whose `kind` is not `quicfix`, we
# still need to as the user for confirmation.
fixits = self._response[ 'fixits' ]
if ( len( fixits ) > 1 or
( len( fixits ) == 1 and
self._command == 'FixIt' and
fixits[ 0 ].get( 'kind' ) != 'quickfix' ) ):
fixit_index = vimsupport.SelectFromList(
"FixIt suggestion(s) available at this location. "
"Which one would you like to apply?",
[ fixit[ 'text' ] for fixit in fixits ] )
chosen_fixit = fixits[ fixit_index ]
if chosen_fixit[ 'resolve' ]:
self._request_data.update( { 'fixit': chosen_fixit } )
response = self.PostDataToHandler( self._request_data,
'resolve_fixit' )
if response is None:
return
fixits = response[ 'fixits' ]
assert len( fixits ) == 1
chosen_fixit = fixits[ 0 ]
vimsupport.ReplaceChunks(
chosen_fixit[ 'chunks' ],
silent = self._command == 'Format' )
except RuntimeError as e:
vimsupport.PostVimMessage( str( e ) )
def _HandleBasicResponse( self ):
vimsupport.PostVimMessage( self._response, warning = False )
def _HandleMessageResponse( self ):
vimsupport.PostVimMessage( self._response[ 'message' ], warning = False )
def _HandleDetailedInfoResponse( self, modifiers ):
vimsupport.WriteToPreviewWindow( self._response[ 'detailed_info' ],
modifiers )
def SendCommandRequestAsync( arguments,
extra_data = None,
silent = True,
location = None ):
request = CommandRequest( arguments,
extra_data = extra_data,
silent = silent,
location = location )
request.Start()
# Don't block
return request
def SendCommandRequest( arguments,
modifiers,
buffer_command = DEFAULT_BUFFER_COMMAND,
extra_data = None,
skip_post_command_action = False ):
request = SendCommandRequestAsync( arguments,
extra_data = extra_data,
silent = False )
# Block here to get the response
if not skip_post_command_action:
request.RunPostCommandActionsIfNeeded( modifiers, buffer_command )
return request.Response()
def GetCommandResponse( arguments, extra_data = None ):
request = SendCommandRequestAsync( arguments,
extra_data = extra_data,
silent = True )
# Block here to get the response
return request.StringResponse()
def GetRawCommandResponse( arguments, silent, location = None ):
request = SendCommandRequestAsync( arguments,
extra_data = None,
silent = silent,
location = location )
return request.Response()
| 9,355
|
Python
|
.py
| 207
| 34.700483
| 79
| 0.609652
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,955
|
event_notification.py
|
ycm-core_YouCompleteMe/python/ycm/client/event_notification.py
|
# Copyright (C) 2013-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.base_request import BaseRequest, BuildRequestData
class EventNotification( BaseRequest ):
def __init__( self, event_name, buffer_number = None, extra_data = None ):
super( EventNotification, self ).__init__()
self._event_name = event_name
self._buffer_number = buffer_number
self._extra_data = extra_data
self._response_future = None
self._cached_response = None
def Start( self ):
request_data = BuildRequestData( self._buffer_number )
if self._extra_data:
request_data.update( self._extra_data )
request_data[ 'event_name' ] = self._event_name
self._response_future = self.PostDataToHandlerAsync( request_data,
'event_notification' )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def Response( self ):
if self._cached_response:
return self._cached_response
if not self._response_future or self._event_name != 'FileReadyToParse':
return []
self._cached_response = self.HandleFuture( self._response_future,
truncate_message = True )
return self._cached_response if self._cached_response else []
def SendEventNotificationAsync( event_name,
buffer_number = None,
extra_data = None ):
event = EventNotification( event_name, buffer_number, extra_data )
event.Start()
| 2,226
|
Python
|
.py
| 47
| 40.553191
| 79
| 0.686229
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,956
|
debug_info_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/debug_info_request.py
|
# Copyright (C) 2016-2017 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.base_request import BaseRequest, BuildRequestData
class DebugInfoRequest( BaseRequest ):
def __init__( self, extra_data = None ):
super( DebugInfoRequest, self ).__init__()
self._extra_data = extra_data
self._response = None
def Start( self ):
request_data = BuildRequestData()
if self._extra_data:
request_data.update( self._extra_data )
self._response = self.PostDataToHandler( request_data,
'debug_info',
display_message = False )
def Response( self ):
return self._response
def FormatDebugInfoResponse( response ):
if not response:
return 'Server errored, no debug info from server\n'
message = _FormatYcmdDebugInfo( response )
completer = response[ 'completer' ]
if completer:
message += _FormatCompleterDebugInfo( completer )
return message
def _FormatYcmdDebugInfo( ycmd ):
python = ycmd[ 'python' ]
clang = ycmd[ 'clang' ]
message = (
f'Server Python interpreter: { python[ "executable" ] }\n'
f'Server Python version: { python[ "version" ] }\n'
f'Server has Clang support compiled in: { clang[ "has_support" ] }\n'
f'Clang version: { clang[ "version" ] }\n' )
extra_conf = ycmd[ 'extra_conf' ]
extra_conf_path = extra_conf[ 'path' ]
if not extra_conf_path:
message += 'No extra configuration file found\n'
elif not extra_conf[ 'is_loaded' ]:
message += ( 'Extra configuration file found but not loaded\n'
f'Extra configuration path: { extra_conf_path }\n' )
else:
message += ( 'Extra configuration file found and loaded\n'
f'Extra configuration path: { extra_conf_path }\n' )
return message
def _FormatCompleterDebugInfo( completer ):
message = f'{ completer[ "name" ] } completer debug information:\n'
for server in completer[ 'servers' ]:
name = server[ 'name' ]
if server[ 'is_running' ]:
address = server[ 'address' ]
port = server[ 'port' ]
if address and port:
message += f' { name } running at: http://{ address }:{ port }\n'
else:
message += f' { name } running\n'
message += f' { name } process ID: { server[ "pid" ] }\n'
else:
message += f' { name } not running\n'
message += f' { name } executable: { server[ "executable" ] }\n'
logfiles = server[ 'logfiles' ]
if logfiles:
message += f' { name } logfiles:\n'
for logfile in logfiles:
message += f' { logfile }\n'
else:
message += ' No logfiles available\n'
if 'extras' in server:
for extra in server[ 'extras' ]:
message += f' { name } { extra[ "key" ] }: { extra[ "value" ] }\n'
for item in completer[ 'items' ]:
message += f' { item[ "key" ].capitalize() }: { item[ "value" ] }\n'
return message
def SendDebugInfoRequest( extra_data = None ):
request = DebugInfoRequest( extra_data )
# This is a blocking call.
request.Start()
return request.Response()
| 3,773
|
Python
|
.py
| 91
| 36.208791
| 75
| 0.653122
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,957
|
base_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/base_request.py
|
# Copyright (C) 2013-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import logging
import json
import vim
from base64 import b64decode, b64encode
from hmac import compare_digest
from urllib.parse import urljoin, urlparse, urlencode
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from ycm import vimsupport
from ycmd.utils import ToBytes, GetCurrentDirectory, ToUnicode
from ycmd.hmac_utils import CreateRequestHmac, CreateHmac
from ycmd.responses import ServerError, UnknownExtraConf
HTTP_SERVER_ERROR = 500
_HEADERS = { 'content-type': 'application/json' }
_CONNECT_TIMEOUT_SEC = 0.01
# Setting this to None seems to screw up the Requests/urllib3 libs.
_READ_TIMEOUT_SEC = 30
_HMAC_HEADER = 'x-ycm-hmac'
_logger = logging.getLogger( __name__ )
class BaseRequest:
def __init__( self ):
self._should_resend = False
def Start( self ):
pass
def Done( self ):
return True
def Response( self ):
return {}
def ShouldResend( self ):
return self._should_resend
def HandleFuture( self,
future,
display_message = True,
truncate_message = False ):
"""Get the server response from a |future| object and catch any exception
while doing so. If an exception is raised because of a unknown
.ycm_extra_conf.py file, load the file or ignore it after asking the user.
An identical request should be sent again to the server. For other
exceptions, log the exception and display its message to the user on the Vim
status line. Unset the |display_message| parameter to hide the message from
the user. Set the |truncate_message| parameter to avoid hit-enter prompts
from this message."""
try:
try:
return _JsonFromFuture( future )
except UnknownExtraConf as e:
if vimsupport.Confirm( str( e ) ):
_LoadExtraConfFile( e.extra_conf_file )
else:
_IgnoreExtraConfFile( e.extra_conf_file )
self._should_resend = True
except URLError as e:
# We don't display this exception to the user since it is likely to happen
# for each subsequent request (typically if the server crashed) and we
# don't want to spam the user with it.
_logger.error( e )
except Exception as e:
_logger.exception( 'Error while handling server response' )
if display_message:
DisplayServerException( e, truncate_message )
return None
# This method blocks
# |timeout| is num seconds to tolerate no response from server before giving
# up; see Requests docs for details (we just pass the param along).
# See the HandleFuture method for the |display_message| and |truncate_message|
# parameters.
def GetDataFromHandler( self,
handler,
timeout = _READ_TIMEOUT_SEC,
display_message = True,
truncate_message = False,
payload = None ):
return self.HandleFuture(
self.GetDataFromHandlerAsync( handler, timeout, payload ),
display_message,
truncate_message )
def GetDataFromHandlerAsync( self,
handler,
timeout = _READ_TIMEOUT_SEC,
payload = None ):
return BaseRequest._TalkToHandlerAsync(
'', handler, 'GET', timeout, payload )
# This is the blocking version of the method. See below for async.
# |timeout| is num seconds to tolerate no response from server before giving
# up; see Requests docs for details (we just pass the param along).
# See the HandleFuture method for the |display_message| and |truncate_message|
# parameters.
def PostDataToHandler( self,
data,
handler,
timeout = _READ_TIMEOUT_SEC,
display_message = True,
truncate_message = False ):
return self.HandleFuture(
BaseRequest.PostDataToHandlerAsync( data, handler, timeout ),
display_message,
truncate_message )
# This returns a future! Use HandleFuture to get the value.
# |timeout| is num seconds to tolerate no response from server before giving
# up; see Requests docs for details (we just pass the param along).
@staticmethod
def PostDataToHandlerAsync( data, handler, timeout = _READ_TIMEOUT_SEC ):
return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout )
# This returns a future! Use HandleFuture to get the value.
# |method| is either 'POST' or 'GET'.
# |timeout| is num seconds to tolerate no response from server before giving
# up; see Requests docs for details (we just pass the param along).
@staticmethod
def _TalkToHandlerAsync( data,
handler,
method,
timeout = _READ_TIMEOUT_SEC,
payload = None ):
def _MakeRequest( data, handler, method, timeout, payload ):
request_uri = _BuildUri( handler )
if method == 'POST':
sent_data = _ToUtf8Json( data )
headers = BaseRequest._ExtraHeaders( method,
request_uri,
sent_data )
_logger.debug( 'POST %s\n%s\n%s', request_uri, headers, sent_data )
else:
headers = BaseRequest._ExtraHeaders( method, request_uri )
if payload:
request_uri += ToBytes( f'?{ urlencode( payload ) }' )
_logger.debug( 'GET %s (%s)\n%s', request_uri, payload, headers )
return urlopen(
Request(
ToUnicode( request_uri ),
data = sent_data if data else None,
headers = headers,
method = method ),
timeout = max( _CONNECT_TIMEOUT_SEC, timeout ) )
return BaseRequest.Executor().submit(
_MakeRequest,
data,
handler,
method,
timeout,
payload )
@staticmethod
def _ExtraHeaders( method, request_uri, request_body = None ):
if not request_body:
request_body = bytes( b'' )
headers = dict( _HEADERS )
headers[ _HMAC_HEADER ] = b64encode(
CreateRequestHmac( ToBytes( method ),
ToBytes( urlparse( request_uri ).path ),
request_body,
BaseRequest.hmac_secret ) )
return headers
# This method exists to avoid importing the requests module at startup;
# reducing loading time since this module is slow to import.
@classmethod
def Executor( cls ):
try:
return cls.executor
except AttributeError:
from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor
cls.executor = UnsafeThreadPoolExecutor( max_workers = 30 )
return cls.executor
server_location = ''
hmac_secret = ''
def BuildRequestData( buffer_number = None ):
"""Build request for the current buffer or the buffer with number
|buffer_number| if specified."""
working_dir = GetCurrentDirectory()
current_buffer = vim.current.buffer
if buffer_number and current_buffer.number != buffer_number:
# Cursor position is irrelevant when filepath is not the current buffer.
buffer_object = vim.buffers[ buffer_number ]
filepath = vimsupport.GetBufferFilepath( buffer_object )
return {
'filepath': filepath,
'line_num': 1,
'column_num': 1,
'working_dir': working_dir,
'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( buffer_object,
filepath )
}
current_filepath = vimsupport.GetBufferFilepath( current_buffer )
line, column = vimsupport.CurrentLineAndColumn()
return {
'filepath': current_filepath,
'line_num': line + 1,
'column_num': column + 1,
'working_dir': working_dir,
'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( current_buffer,
current_filepath )
}
def BuildRequestDataForLocation( file : str, line : int, column : int ):
buffer_number = vimsupport.GetBufferNumberForFilename(
file,
create_buffer_if_needed = True )
try:
vim.eval( f'bufload( "{ file }" )' )
except vim.error as e:
if 'E325' not in str( e ):
raise
buffer = vim.buffers[ buffer_number ]
file_data = vimsupport.GetUnsavedAndSpecifiedBufferData( buffer, file )
return {
'filepath': file,
'line_num': line,
'column_num': column,
'working_dir': GetCurrentDirectory(),
'file_data': file_data
}
def _JsonFromFuture( future ):
try:
response = future.result()
response_text = response.read()
_ValidateResponseObject( response, response_text )
response.close()
if response_text:
return json.loads( response_text )
return None
except HTTPError as response:
if response.code == HTTP_SERVER_ERROR:
response_text = response.read()
response.close()
if response_text:
raise MakeServerException( json.loads( response_text ) )
else:
return None
raise
def _LoadExtraConfFile( filepath ):
BaseRequest().PostDataToHandler( { 'filepath': filepath },
'load_extra_conf_file' )
def _IgnoreExtraConfFile( filepath ):
BaseRequest().PostDataToHandler( { 'filepath': filepath },
'ignore_extra_conf_file' )
def DisplayServerException( exception, truncate_message = False ):
serialized_exception = str( exception )
# We ignore the exception about the file already being parsed since it comes
# up often and isn't something that's actionable by the user.
if 'already being parsed' in serialized_exception:
return
vimsupport.PostVimMessage( serialized_exception, truncate = truncate_message )
def _ToUtf8Json( data ):
return ToBytes( json.dumps( data ) if data else None )
def _ValidateResponseObject( response, response_text ):
if not response_text:
return
our_hmac = CreateHmac( response_text, BaseRequest.hmac_secret )
their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )
if not compare_digest( our_hmac, their_hmac ):
raise RuntimeError( 'Received invalid HMAC for response!' )
def _BuildUri( handler ):
return ToBytes( urljoin( BaseRequest.server_location, handler ) )
def MakeServerException( data ):
_logger.debug( 'Server exception: %s', data )
if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__:
return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] )
return ServerError( f'{ data[ "exception" ][ "TYPE" ] }: '
f'{ data[ "message" ] }' )
| 11,461
|
Python
|
.py
| 272
| 34.463235
| 80
| 0.658876
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,958
|
shutdown_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/shutdown_request.py
|
# Copyright (C) 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.base_request import BaseRequest
TIMEOUT_SECONDS = 0.1
class ShutdownRequest( BaseRequest ):
def __init__( self ):
super( ShutdownRequest, self ).__init__()
def Start( self ):
self.PostDataToHandler( {},
'shutdown',
TIMEOUT_SECONDS,
display_message = False )
def SendShutdownRequest():
request = ShutdownRequest()
# This is a blocking call.
request.Start()
| 1,209
|
Python
|
.py
| 30
| 35.633333
| 72
| 0.71392
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,959
|
completion_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/completion_request.py
|
# Copyright (C) 2013-2019 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import json
import logging
from ycmd.utils import ToUnicode
from ycm.client.base_request import ( BaseRequest,
DisplayServerException,
MakeServerException )
from ycm import vimsupport, base
from ycm.vimsupport import NO_COMPLETIONS
_logger = logging.getLogger( __name__ )
class CompletionRequest( BaseRequest ):
def __init__( self, request_data ):
super().__init__()
self.request_data = request_data
self._response_future = None
def Start( self ):
self._response_future = self.PostDataToHandlerAsync( self.request_data,
'completions' )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def _RawResponse( self ):
if not self._response_future:
return NO_COMPLETIONS
response = self.HandleFuture( self._response_future,
truncate_message = True )
if not response:
return NO_COMPLETIONS
# Vim may not be able to convert the 'errors' entry to its internal format
# so we remove it from the response.
errors = response.pop( 'errors', [] )
for e in errors:
exception = MakeServerException( e )
_logger.error( exception )
DisplayServerException( exception, truncate_message = True )
response[ 'line' ] = self.request_data[ 'line_num' ]
response[ 'column' ] = self.request_data[ 'column_num' ]
return response
def Response( self ):
response = self._RawResponse()
response[ 'completions' ] = _ConvertCompletionDatasToVimDatas(
response[ 'completions' ] )
# FIXME: Do we really need to do this AdjustCandidateInsertionText ? I feel
# like Vim should do that for us
response[ 'completions' ] = base.AdjustCandidateInsertionText(
response[ 'completions' ] )
return response
def OnCompleteDone( self ):
if not self.Done():
return
if 'cs' in vimsupport.CurrentFiletypes():
self._OnCompleteDone_Csharp()
else:
self._OnCompleteDone_FixIt()
def _GetExtraDataUserMayHaveCompleted( self ):
completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
# If Vim supports user_data (8.0.1493 or later), we actually know the
# _exact_ element that was selected, having put its extra_data in the
# user_data field. Otherwise, we have to guess by matching the values in the
# completed item and the list of completions. Sometimes this returns
# multiple possibilities, which is essentially unresolvable.
if 'user_data' not in completed_item:
completions = self._RawResponse()[ 'completions' ]
return _FilterToMatchingCompletions( completed_item, completions )
if completed_item[ 'user_data' ]:
return [ json.loads( completed_item[ 'user_data' ] ) ]
return []
def _OnCompleteDone_Csharp( self ):
extra_datas = self._GetExtraDataUserMayHaveCompleted()
namespaces = [ _GetRequiredNamespaceImport( c ) for c in extra_datas ]
namespaces = [ n for n in namespaces if n ]
if not namespaces:
return
if len( namespaces ) > 1:
choices = [ f"{ i + 1 } { n }" for i, n in enumerate( namespaces ) ]
choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
if choice < 0:
return
namespace = namespaces[ choice ]
else:
namespace = namespaces[ 0 ]
vimsupport.InsertNamespace( namespace )
def _OnCompleteDone_FixIt( self ):
extra_datas = self._GetExtraDataUserMayHaveCompleted()
fixit_completions = [ _GetFixItCompletion( c ) for c in extra_datas ]
fixit_completions = [ f for f in fixit_completions if f ]
if not fixit_completions:
return
# If we have user_data in completions (8.0.1493 or later), then we would
# only ever return max. 1 completion here. However, if we had to guess, it
# is possible that we matched multiple completion items (e.g. for overloads,
# or similar classes in multiple packages). In any case, rather than
# prompting the user and disturbing her workflow, we just apply the first
# one. This might be wrong, but the solution is to use a (very) new version
# of Vim which supports user_data on completion items
fixit_completion = fixit_completions[ 0 ]
for fixit in fixit_completion:
vimsupport.ReplaceChunks( fixit[ 'chunks' ], silent=True )
def _GetRequiredNamespaceImport( extra_data ):
return extra_data.get( 'required_namespace_import' )
def _GetFixItCompletion( extra_data ):
return extra_data.get( 'fixits' )
def _FilterToMatchingCompletions( completed_item, completions ):
"""Filter to completions matching the item Vim said was completed"""
match_keys = [ 'word', 'abbr', 'menu', 'info' ]
matched_completions = []
for completion in completions:
item = ConvertCompletionDataToVimData( completion )
def matcher( key ):
return ( ToUnicode( completed_item.get( key, "" ) ) ==
ToUnicode( item.get( key, "" ) ) )
if all( matcher( i ) for i in match_keys ):
matched_completions.append( completion.get( 'extra_data', {} ) )
return matched_completions
def _GetCompletionInfoField( completion_data ):
info = completion_data.get( 'detailed_info', '' )
if 'extra_data' in completion_data:
docstring = completion_data[ 'extra_data' ].get( 'doc_string', '' )
if docstring:
if info:
info += '\n' + docstring
else:
info = docstring
# This field may contain null characters e.g. \x00 in Python docstrings. Vim
# cannot evaluate such characters so they are removed.
return info.replace( '\x00', '' )
def ConvertCompletionDataToVimData( completion_data ):
# See :h complete-items for a description of the dictionary fields.
extra_menu_info = completion_data.get( 'extra_menu_info', '' )
preview_info = _GetCompletionInfoField( completion_data )
# When we are using a popup for the preview_info, it needs to fit on the
# screen alongside the extra_menu_info. Let's use some heuristics. If the
# length of the extra_menu_info is more than, say, 1/3 of screen, truncate it
# and stick it in the preview_info.
if vimsupport.UsingPreviewPopup():
max_width = max( int( vimsupport.DisplayWidth() / 3 ), 3 )
extra_menu_info_width = vimsupport.DisplayWidthOfString( extra_menu_info )
if extra_menu_info_width > max_width:
if not preview_info.startswith( extra_menu_info ):
preview_info = extra_menu_info + '\n\n' + preview_info
extra_menu_info = extra_menu_info[ : ( max_width - 3 ) ] + '...'
return {
'word' : completion_data[ 'insertion_text' ],
'abbr' : completion_data.get( 'menu_text', '' ),
'menu' : extra_menu_info,
'info' : preview_info,
'kind' : ToUnicode( completion_data.get( 'kind', '' ) )[ :1 ].lower(),
# Disable Vim filtering.
'equal' : 1,
'dup' : 1,
'empty' : 1,
# We store the completion item extra_data as a string in the completion
# user_data. This allows us to identify the _exact_ item that was completed
# in the CompleteDone handler, by inspecting this item from v:completed_item
#
# We convert to string because completion user data items must be strings.
#
# Note: Not all versions of Vim support this (added in 8.0.1483), but adding
# the item to the dictionary is harmless in earlier Vims.
# Note: Since 8.2.0084 we don't need to use json.dumps() here.
'user_data': json.dumps( completion_data.get( 'extra_data', {} ) )
}
def _ConvertCompletionDatasToVimDatas( response_data ):
return [ ConvertCompletionDataToVimData( x ) for x in response_data ]
| 8,476
|
Python
|
.py
| 178
| 42.050562
| 80
| 0.689174
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,960
|
resolve_completion_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/resolve_completion_request.py
|
# Copyright (C) 2020 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.base_request import ( BaseRequest,
DisplayServerException,
MakeServerException )
from ycm.client.completion_request import ( CompletionRequest,
ConvertCompletionDataToVimData )
import logging
import json
_logger = logging.getLogger( __name__ )
class ResolveCompletionRequest( BaseRequest ):
def __init__( self,
completion_request: CompletionRequest,
request_data ):
super().__init__()
self.request_data = request_data
self.completion_request = completion_request
def Start( self ):
self._response_future = self.PostDataToHandlerAsync( self.request_data,
'resolve_completion' )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def OnCompleteDone( self ):
# This is required to be compatible with the "CompletionRequest" API. We're
# not really a CompletionRequest, but we are mutually exclusive with
# completion requests, so we implement this API by delegating to the
# original completion request, which contains all of the code for actually
# handling things like automatic imports etc.
self.completion_request.OnCompleteDone()
def Response( self ):
response = self.HandleFuture( self._response_future,
truncate_message = True,
display_message = True )
if not response or not response[ 'completion' ]:
return { 'completion': [] }
# Vim may not be able to convert the 'errors' entry to its internal format
# so we remove it from the response.
errors = response.pop( 'errors', [] )
for e in errors:
exception = MakeServerException( e )
_logger.error( exception )
DisplayServerException( exception, truncate_message = True )
response[ 'completion' ] = ConvertCompletionDataToVimData(
response[ 'completion' ] )
return response
def ResolveCompletionItem( completion_request, item ):
if not completion_request.Done():
return None
try:
completion_extra_data = json.loads( item[ 'user_data' ] )
except KeyError:
return None
except ( TypeError, json.JSONDecodeError ):
# Can happen with the omni completer
return None
request_data = completion_request.request_data
try:
# Note: We mutate the request_data inside the original completion request
# and pass it into the new request object. this is just a big efficiency
# saving. The request_data for a Done() request is almost certainly no
# longer needed.
request_data[ 'resolve' ] = completion_extra_data[ 'resolve' ]
except KeyError:
return None
resolve_request = ResolveCompletionRequest( completion_request, request_data )
resolve_request.Start()
return resolve_request
| 3,675
|
Python
|
.py
| 81
| 38.493827
| 80
| 0.693598
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,961
|
semantic_tokens_request.py
|
ycm-core_YouCompleteMe/python/ycm/client/semantic_tokens_request.py
|
# Copyright (C) 2020, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import logging
from ycm.client.base_request import ( BaseRequest, DisplayServerException,
MakeServerException )
_logger = logging.getLogger( __name__ )
# FIXME: This is copy/pasta from SignatureHelpRequest - abstract a
# SimpleAsyncRequest base that does all of this generically
class SemanticTokensRequest( BaseRequest ):
def __init__( self, request_data ):
super().__init__()
self.request_data = request_data
self._response_future = None
def Start( self ):
self._response_future = self.PostDataToHandlerAsync( self.request_data,
'semantic_tokens' )
def Done( self ):
return bool( self._response_future ) and self._response_future.done()
def Reset( self ):
self._response_future = None
def Response( self ):
if not self._response_future:
return {}
response = self.HandleFuture( self._response_future,
truncate_message = True )
if not response:
return {}
# Vim may not be able to convert the 'errors' entry to its internal format
# so we remove it from the response.
errors = response.pop( 'errors', [] )
for e in errors:
exception = MakeServerException( e )
_logger.error( exception )
DisplayServerException( exception, truncate_message = True )
return response.get( 'semantic_tokens' ) or {}
| 2,162
|
Python
|
.py
| 49
| 38.22449
| 78
| 0.694948
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,962
|
mock_utils.py
|
ycm-core_YouCompleteMe/python/ycm/tests/mock_utils.py
|
# Copyright (C) 2017 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import json
from unittest import mock
HTTP_OK = 200
class FakeResponse:
"""A fake version of a requests response object, just about suitable for
mocking a server response. Not usually used directly. See
MockServerResponse* methods"""
def __init__( self, response, exception ):
self._json = response
self._exception = exception
self.code = HTTP_OK
def read( self ):
if self._exception:
raise self._exception
return json.dumps( self._json ).encode( 'utf-8' )
def close( self ):
pass
class FakeFuture:
"""A fake version of a future response object, just about suitable for
mocking a server response as generated by PostDataToHandlerAsync.
Not usually used directly. See MockAsyncServerResponse* methods"""
def __init__( self, done, response = None, exception = None ):
self._done = done
if not done:
self._result = None
else:
self._result = FakeResponse( response, exception )
def done( self ):
return self._done
def result( self ):
return self._result
def MockAsyncServerResponseDone( response ):
"""Return a MessagePoll containing a fake future object that is complete with
the supplied response message. Suitable for mocking a response future within
a client request. For example:
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ) as v:
mock_response = MockAsyncServerResponseDone( response )
with patch.dict( ycm._message_poll_requests, {} ):
ycm._message_poll_requests[ filetype ] = MessagesPoll( v.current.buffer )
ycm._message_poll_requests[ filetype ]._response_future = mock_response
# Needed to keep a reference to the mocked dictionary
mock_future = ycm._message_poll_requests[ filetype ]._response_future
ycm.OnPeriodicTick() # Uses ycm._message_poll_requests[ filetype ] ...
"""
return mock.MagicMock( wraps = FakeFuture( True, response ) )
def MockAsyncServerResponseInProgress():
"""Return a fake future object that is incomplete. Suitable for mocking a
response future within a client request. For example:
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ) as v:
mock_response = MockAsyncServerResponseInProgress()
with patch.dict( ycm._message_poll_requests, {} ):
ycm._message_poll_requests[ filetype ] = MessagesPoll( v.current.buffer )
ycm._message_poll_requests[ filetype ]._response_future = mock_response
# Needed to keep a reference to the mocked dictionary
mock_future = ycm._message_poll_requests[ filetype ]._response_future
ycm.OnPeriodicTick() # Uses ycm._message_poll_requests[ filetype ] ...
"""
return mock.MagicMock( wraps = FakeFuture( False ) )
def MockAsyncServerResponseException( exception ):
"""Return a fake future object that is complete, but raises an exception.
Suitable for mocking a response future within a client request. For example:
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ) as v:
mock_response = MockAsyncServerResponseException( exception )
with patch.dict( ycm._message_poll_requests, {} ):
ycm._message_poll_requests[ filetype ] = MessagesPoll( v.current.buffer )
ycm._message_poll_requests[ filetype ]._response_future = mock_response
# Needed to keep a reference to the mocked dictionary
mock_future = ycm._message_poll_requests[ filetype ]._response_future
ycm.OnPeriodicTick() # Uses ycm._message_poll_requests[ filetype ] ...
"""
return mock.MagicMock( wraps = FakeFuture( True, None, exception ) )
# TODO: In future, implement MockServerResponse and MockServerResponseException
# for synchronous cases when such test cases are needed.
| 4,448
|
Python
|
.py
| 89
| 46.101124
| 79
| 0.736563
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,963
|
paths_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/paths_test.py
|
# Copyright (C) 2016-2017 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import MockVimModule
MockVimModule()
from hamcrest import assert_that
from unittest import TestCase
from ycm.paths import _EndsWithPython
def EndsWithPython_Good( path ):
assert_that( _EndsWithPython( path ),
f'Path { path } does not end with a Python name.' )
def EndsWithPython_Bad( path ):
assert_that( not _EndsWithPython( path ),
f'Path { path } does end with a Python name.' )
class PathTest( TestCase ):
def test_EndsWithPython_Python3Paths( self ):
for path in [
'python3',
'/usr/bin/python3.6',
'/home/user/.pyenv/shims/python3.6',
r'C:\Python36\python.exe'
]:
with self.subTest( path = path ):
EndsWithPython_Good( path )
def test_EndsWithPython_BadPaths( self ):
for path in [
None,
'',
'/opt/local/bin/vim',
r'C:\Program Files\Vim\vim74\gvim.exe',
'/usr/bin/python2.7',
'/home/user/.pyenv/shims/python3.2',
]:
with self.subTest( path = path ):
EndsWithPython_Bad( path )
| 1,791
|
Python
|
.py
| 48
| 33.1875
| 72
| 0.708021
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,964
|
vimsupport_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/vimsupport_test.py
|
# Copyright (C) 2015-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests import PathToTestFile
from ycm.tests.test_utils import ( CurrentWorkingDirectory, ExtendedMock,
MockVimBuffers, MockVimModule, Version,
VimBuffer, VimError, WindowsAndMacOnly )
MockVimModule()
from ycm import vimsupport
from hamcrest import ( assert_that, calling, contains_exactly, empty, equal_to,
has_entry, raises )
from unittest import TestCase
from unittest.mock import MagicMock, call, patch
from ycmd.utils import ToBytes
import os
import json
def AssertBuffersAreEqualAsBytes( result_buffer, expected_buffer ):
assert_that( len( result_buffer ), equal_to( len( expected_buffer ) ) )
for result_line, expected_line in zip( result_buffer, expected_buffer ):
assert_that( ToBytes( result_line ), equal_to( ToBytes( expected_line ) ) )
def _BuildChunk( start_line,
start_column,
end_line,
end_column,
replacement_text, filepath='test_file_name' ):
return {
'range': {
'start': {
'filepath': filepath,
'line_num': start_line,
'column_num': start_column,
},
'end': {
'filepath': filepath,
'line_num': end_line,
'column_num': end_column,
},
},
'replacement_text': replacement_text
}
def _BuildLocations( start_line, start_column, end_line, end_column ):
return {
'line_num' : start_line,
'column_num': start_column,
}, {
'line_num' : end_line,
'column_num': end_column,
}
class VimsupportTest( TestCase ):
@patch( 'ycm.vimsupport.WinIDForWindow', side_effect = range( 1001, 1010 ) )
@patch( 'vim.eval', new_callable = ExtendedMock )
def test_SetLocationListsForBuffer_Current( self, vim_eval, *args ):
diagnostics = [ {
'bufnr': 3,
'filename': 'some_filename',
'lnum': 5,
'col': 22,
'type': 'E',
'valid': 1
} ]
current_buffer = VimBuffer( '/test', number = 3 )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
vimsupport.SetLocationListsForBuffer( 3, diagnostics )
vim_eval.assert_has_exact_calls( [
call( 'setloclist( 1001, [], " ", { "title": "ycm_loc", '
'"items": [{"bufnr": 3, "filename": "some_filename", "lnum": 5, '
'"col": 22, "type": "E", "valid": 1}] } )' ),
call( 'getloclist( 1001, { "nr": "$", "id": 0 } ).id' ),
] )
@patch( 'vim.eval', new_callable = ExtendedMock )
def test_SetLocationListsForBuffer_NotCurrent( self, vim_eval ):
diagnostics = [ {
'bufnr': 3,
'filename': 'some_filename',
'lnum': 5,
'col': 22,
'type': 'E',
'valid': 1
} ]
current_buffer = VimBuffer( '/test', number = 3 )
other_buffer = VimBuffer( '/notcurrent', number = 1 )
with MockVimBuffers( [ current_buffer, other_buffer ], [ current_buffer ] ):
vimsupport.SetLocationListsForBuffer( 1, diagnostics )
vim_eval.assert_not_called()
@patch( 'vim.eval', new_callable = ExtendedMock, side_effect = [ -1, 1 ] )
def test_SetLocationListsForBuffer_NotVisible( self, vim_eval ):
diagnostics = [ {
'bufnr': 3,
'filename': 'some_filename',
'lnum': 5,
'col': 22,
'type': 'E',
'valid': 1
} ]
current_buffer = VimBuffer( '/test', number = 3 )
other_buffer = VimBuffer( '/notcurrent', number = 1 )
with MockVimBuffers( [ current_buffer, other_buffer ], [ current_buffer ] ):
vimsupport.SetLocationListsForBuffer( 1, diagnostics )
vim_eval.assert_not_called()
@patch( 'ycm.vimsupport.WinIDForWindow', side_effect = range( 1001, 1010 ) )
@patch( 'vim.eval', new_callable = ExtendedMock, side_effect = [ -1, 1 ] )
def test_SetLocationListsForBuffer_MultipleWindows( self, vim_eval, *args ):
diagnostics = [ {
'bufnr': 3,
'filename': 'some_filename',
'lnum': 5,
'col': 22,
'type': 'E',
'valid': 1
} ]
current_buffer = VimBuffer( '/test', number = 3 )
other_buffer = VimBuffer( '/notcurrent', number = 1 )
with MockVimBuffers( [ current_buffer, other_buffer ],
[ current_buffer, other_buffer ] ):
vimsupport.SetLocationListsForBuffer( 1, diagnostics )
vim_eval.assert_has_exact_calls( [
call( 'setloclist( 1001, [], " ", { "title": "ycm_loc", "items": '
f'{ json.dumps( diagnostics ) } }} )' ),
call( 'getloclist( 1001, { "nr": "$", "id": 0 } ).id' ),
] )
@patch( 'ycm.vimsupport.WinIDForWindow', side_effect = range( 1001, 1010 ) )
@patch( 'vim.eval', new_callable = ExtendedMock )
def test_SetLocationList( self, vim_eval, *args ):
diagnostics = [ {
'bufnr': 3,
'filename': 'some_filename',
'lnum': 5,
'col': 22,
'type': 'E',
'valid': 1
} ]
current_buffer = VimBuffer( '/test', number = 3 )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ):
vimsupport.SetLocationList( diagnostics )
vim_eval.assert_has_exact_calls( [
call( 'setloclist( 1001, [], " ", { "title": "ycm_loc", "items": '
'[{"bufnr": 3, "filename": "some_filename", "lnum": '
'5, "col": 22, "type": "E", "valid": 1}] } )' ),
call( 'getloclist( 1001, { "nr": "$", "id": 0 } ).id' ),
] )
@patch( 'ycm.vimsupport.WinIDForWindow', side_effect = range( 1001, 1010 ) )
@patch( 'vim.eval', new_callable = ExtendedMock )
def test_SetLocationList_NotCurrent( self, vim_eval, *args ):
diagnostics = [ {
'bufnr': 3,
'filename': 'some_filename',
'lnum': 5,
'col': 22,
'type': 'E',
'valid': 1
} ]
current_buffer = VimBuffer( '/test', number = 3 )
other_buffer = VimBuffer( '/notcurrent', number = 1 )
with MockVimBuffers( [ current_buffer, other_buffer ],
[ current_buffer, other_buffer ],
( 1, 1 ) ):
vimsupport.SetLocationList( diagnostics )
# This version does not check the current
# buffer and just sets the current win
vim_eval.assert_has_exact_calls( [
call( 'setloclist( 1001, [], " ", { "title": "ycm_loc", "items": '
'[{"bufnr": 3, "filename": "some_filename", "lnum": 5, "col": 22, '
'"type": "E", "valid": 1}] } )' ),
call( 'getloclist( 1001, { "nr": "$", "id": 0 } ).id' ),
] )
@patch( 'ycm.vimsupport.VariableExists', return_value = True )
@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_OpenLocationList(
self, vim_command, fitting_height, variable_exists ):
vimsupport.OpenLocationList( focus = False, autoclose = True )
vim_command.assert_has_exact_calls( [
call( 'lopen' ),
call( 'augroup ycmlocation' ),
call( 'autocmd! * <buffer>' ),
call( 'autocmd WinLeave <buffer> '
'if bufnr( "%" ) == expand( "<abuf>" ) | q | endif '
'| autocmd! ycmlocation' ),
call( 'augroup END' ),
call( 'doautocmd User YcmLocationOpened' ),
call( 'silent! wincmd p' )
] )
fitting_height.assert_called_once_with()
variable_exists.assert_called_once_with( '#User#YcmLocationOpened' )
@patch( 'vim.command' )
def test_SetFittingHeightForCurrentWindow_LineWrapOn(
self, vim_command, *args ):
# Create a two lines buffer whose first
# line is longer than the window width.
current_buffer = VimBuffer( 'buffer',
contents = [ 'a' * 140, 'b' * 80 ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.width = 120
vim.current.window.options[ 'wrap' ] = True
vimsupport.SetFittingHeightForCurrentWindow()
vim_command.assert_called_once_with( '3wincmd _' )
@patch( 'vim.command' )
def test_SetFittingHeightForCurrentWindow_NoResize(
self, vim_command, *args ):
# Create a two lines buffer whose first
# line is longer than the window width.
current_buffer = VimBuffer( 'buffer',
contents = [ 'a' * 140, 'b' * 80 ],
vars = { 'ycm_no_resize': 1 } )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.width = 120
vim.current.window.options[ 'wrap' ] = True
vimsupport.SetFittingHeightForCurrentWindow()
vim_command.assert_not_called()
@patch( 'vim.command' )
def test_SetFittingHeightForCurrentWindow_LineWrapOff(
self, vim_command, *args ):
# Create a two lines buffer whose first
# line is longer than the window width.
current_buffer = VimBuffer( 'buffer',
contents = [ 'a' * 140, 'b' * 80 ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.width = 120
vim.current.window.options[ 'wrap' ] = False
vimsupport.SetFittingHeightForCurrentWindow()
vim_command.assert_called_once_with( '2wincmd _' )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Repl_1( self ):
# Replace with longer range
result_buffer = VimBuffer( 'buffer', contents = [ 'This is a string' ] )
start, end = _BuildLocations( 1, 11, 1, 17 )
vimsupport.ReplaceChunk( start, end, 'pie', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is a pie' ], result_buffer )
# and replace again
start, end = _BuildLocations( 1, 10, 1, 11 )
vimsupport.ReplaceChunk( start, end, ' piece of ', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is a piece of pie' ], result_buffer )
# and once more, for luck
start, end = _BuildLocations( 1, 1, 1, 5 )
vimsupport.ReplaceChunk( start, end, 'How long', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'How long is a piece of pie' ],
result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Repl_2( self ):
# Replace with shorter range
result_buffer = VimBuffer( 'buffer', contents = [ 'This is a string' ] )
start, end = _BuildLocations( 1, 11, 1, 17 )
vimsupport.ReplaceChunk( start, end, 'test', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is a test' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Repl_3( self ):
# Replace with equal range
result_buffer = VimBuffer( 'buffer', contents = [ 'This is a string' ] )
start, end = _BuildLocations( 1, 6, 1, 8 )
vimsupport.ReplaceChunk( start, end, 'be', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This be a string' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Add_1( self ):
# Insert at start
result_buffer = VimBuffer( 'buffer', contents = [ 'is a string' ] )
start, end = _BuildLocations( 1, 1, 1, 1 )
vimsupport.ReplaceChunk( start, end, 'This ', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is a string' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Add_2( self ):
# Insert at end
result_buffer = VimBuffer( 'buffer', contents = [ 'This is a ' ] )
start, end = _BuildLocations( 1, 11, 1, 11 )
vimsupport.ReplaceChunk( start, end, 'string', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is a string' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Add_3( self ):
# Insert in the middle
result_buffer = VimBuffer( 'buffer', contents = [ 'This is a string' ] )
start, end = _BuildLocations( 1, 8, 1, 8 )
vimsupport.ReplaceChunk( start, end, ' not', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is not a string' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Del_1( self ):
# Delete from start
result_buffer = VimBuffer( 'buffer', contents = [ 'This is a string' ] )
start, end = _BuildLocations( 1, 1, 1, 6 )
vimsupport.ReplaceChunk( start, end, '', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'is a string' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Del_2( self ):
# Delete from end
result_buffer = VimBuffer( 'buffer', contents = [ 'This is a string' ] )
start, end = _BuildLocations( 1, 10, 1, 18 )
vimsupport.ReplaceChunk( start, end, '', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is a' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Del_3( self ):
# Delete from middle
result_buffer = VimBuffer( 'buffer', contents = [ 'This is not a string' ] )
start, end = _BuildLocations( 1, 9, 1, 13 )
vimsupport.ReplaceChunk( start, end, '', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This is a string' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Unicode_ReplaceUnicodeChars( self ):
# Replace Unicode characters.
result_buffer = VimBuffer(
'buffer', contents = [ 'This Uniçø∂‰ string is in the middle' ] )
start, end = _BuildLocations( 1, 6, 1, 20 )
vimsupport.ReplaceChunk( start, end, 'Unicode ', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This Unicode string is in the middle' ],
result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Unicode_ReplaceAfterUnicode( self ):
# Replace ASCII characters after Unicode characters in the line.
result_buffer = VimBuffer(
'buffer', contents = [ 'This Uniçø∂‰ string is in the middle' ] )
start, end = _BuildLocations( 1, 30, 1, 43 )
vimsupport.ReplaceChunk( start, end, 'fåke', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'This Uniçø∂‰ string is fåke' ],
result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleLine_Unicode_Grown( self ):
# Replace ASCII characters after Unicode characters in the line.
result_buffer = VimBuffer( 'buffer', contents = [ 'a' ] )
start, end = _BuildLocations( 1, 1, 1, 2 )
vimsupport.ReplaceChunk( start, end, 'å', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'å' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_RemoveSingleLine( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 2, 1, 3, 1 )
vimsupport.ReplaceChunk( start, end, '', result_buffer )
# First line is not affected.
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleToMultipleLines( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 2, 3, 2, 4 )
vimsupport.ReplaceChunk( start, end, 'cccc', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aBcccc',
'aCa' ], result_buffer )
# now make another change to the second line
start, end = _BuildLocations( 2, 2, 2, 2 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbF', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aEb',
'bFBcccc',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleToMultipleLines2( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 2, 2, 2, 2 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nG', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aEb',
'bFb',
'GBa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleToMultipleLines3( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 2, 2, 2, 2 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbGb', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aEb',
'bFb',
'bGbBa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleToMultipleLinesReplace( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 1, 2, 1, 4 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbGb', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aEb',
'bFb',
'bGb',
'aBa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SingleToMultipleLinesReplace_2( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 1, 4, 1, 4 )
vimsupport.ReplaceChunk( start, end, 'cccc', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAacccc',
'aBa',
'aCa', ], result_buffer )
# now do a subsequent change (insert in the middle of the first line)
start, end = _BuildLocations( 1, 2, 1, 4 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbGb', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aEb',
'bFb',
'bGbcccc',
'aBa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_MultipleLinesToSingleLine( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCaaaa' ] )
start, end = _BuildLocations( 3, 4, 3, 5 )
vimsupport.ReplaceChunk( start, end, 'dd\ndd', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aBa',
'aCadd',
'ddaa' ], result_buffer )
# make another modification applying offsets
start, end = _BuildLocations( 3, 3, 3, 4 )
vimsupport.ReplaceChunk( start, end, 'cccc', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aBa',
'aCccccdd',
'ddaa' ], result_buffer )
# and another, for luck
start, end = _BuildLocations( 2, 2, 3, 2 )
vimsupport.ReplaceChunk( start, end, 'E', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aECccccdd',
'ddaa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_MultipleLinesToSameMultipleLines( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa',
'aDe' ] )
start, end = _BuildLocations( 2, 2, 3, 2 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbF', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aEb',
'bFCa',
'aDe' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_MultipleLinesToMoreMultipleLines( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa',
'aDe' ] )
start, end = _BuildLocations( 2, 2, 3, 2 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbG', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aEb',
'bFb',
'bGCa',
'aDe' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_MultipleLinesToLessMultipleLines( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa',
'aDe' ] )
start, end = _BuildLocations( 1, 2, 3, 2 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbF', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aEb',
'bFCa',
'aDe' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_MultipleLinesToEvenLessMultipleLines( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa',
'aDe' ] )
start, end = _BuildLocations( 1, 2, 4, 2 )
vimsupport.ReplaceChunk( start, end, 'Eb\nbF', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aEb',
'bFDe' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_SpanBufferEdge( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 1, 1, 1, 3 )
vimsupport.ReplaceChunk( start, end, 'bDb', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'bDba',
'aBa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_DeleteTextInLine( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 2, 2, 2, 3 )
vimsupport.ReplaceChunk( start, end, '', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'aa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_AddTextInLine( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 2, 2, 2, 2 )
vimsupport.ReplaceChunk( start, end, 'bDb', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'abDbBa',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_ReplaceTextInLine( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'aAa',
'aBa',
'aCa' ] )
start, end = _BuildLocations( 2, 2, 2, 3 )
vimsupport.ReplaceChunk( start, end, 'bDb', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'aAa',
'abDba',
'aCa' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_NewlineChunk( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'first line',
'second line' ] )
start, end = _BuildLocations( 1, 11, 2, 1 )
vimsupport.ReplaceChunk( start, end, '\n', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'first line',
'second line' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunk_BeyondEndOfFile( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'first line',
'second line' ] )
start, end = _BuildLocations( 1, 11, 3, 1 )
vimsupport.ReplaceChunk( start, end, '\n', result_buffer )
AssertBuffersAreEqualAsBytes( [ 'first line' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 3 ) )
def test_ReplaceChunk_CursorPosition( self ):
result_buffer = VimBuffer( 'buffer', contents = [ 'bar' ] )
start, end = _BuildLocations( 1, 1, 1, 1 )
vimsupport.ReplaceChunk( start,
end,
'xyz\nfoo',
result_buffer )
AssertBuffersAreEqualAsBytes( [ 'xyz', 'foobar' ], result_buffer )
# Cursor line is 0-based.
assert_that( vimsupport.CurrentLineAndColumn(), contains_exactly( 1, 6 ) )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunksInBuffer_SortedChunks( self ):
chunks = [
_BuildChunk( 1, 4, 1, 4, '(' ),
_BuildChunk( 1, 11, 1, 11, ')' )
]
result_buffer = VimBuffer( 'buffer', contents = [ 'CT<10 >> 2> ct' ] )
vimsupport.ReplaceChunksInBuffer( chunks, result_buffer )
AssertBuffersAreEqualAsBytes( [ 'CT<(10 >> 2)> ct' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunksInBuffer_UnsortedChunks( self ):
chunks = [
_BuildChunk( 1, 11, 1, 11, ')' ),
_BuildChunk( 1, 4, 1, 4, '(' )
]
result_buffer = VimBuffer( 'buffer', contents = [ 'CT<10 >> 2> ct' ] )
vimsupport.ReplaceChunksInBuffer( chunks, result_buffer )
AssertBuffersAreEqualAsBytes( [ 'CT<(10 >> 2)> ct' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunksInBuffer_LineOverlappingChunks( self ):
chunks = [
_BuildChunk( 1, 11, 2, 1, '\n ' ),
_BuildChunk( 2, 12, 3, 1, '\n ' ),
_BuildChunk( 3, 11, 4, 1, '\n ' )
]
result_buffer = VimBuffer( 'buffer', contents = [ 'first line',
'second line',
'third line',
'fourth line' ] )
vimsupport.ReplaceChunksInBuffer( chunks, result_buffer )
AssertBuffersAreEqualAsBytes( [ 'first line',
' second line',
' third line',
' fourth line' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunksInBuffer_OutdentChunks( self ):
chunks = [
_BuildChunk( 1, 1, 1, 5, ' ' ),
_BuildChunk( 1, 15, 2, 9, '\n ' ),
_BuildChunk( 2, 20, 3, 3, '\n' )
]
result_buffer = VimBuffer( 'buffer', contents = [ ' first line',
' second line',
' third line' ] )
vimsupport.ReplaceChunksInBuffer( chunks, result_buffer )
AssertBuffersAreEqualAsBytes( [ ' first line',
' second line',
' third line' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunksInBuffer_OneLineIndentingChunks( self ):
chunks = [
_BuildChunk( 1, 8, 2, 1, '\n ' ),
_BuildChunk( 2, 9, 2, 10, '\n ' ),
_BuildChunk( 2, 19, 2, 20, '\n ' )
]
result_buffer = VimBuffer( 'buffer', contents = [ 'class {',
'method { statement }',
'}' ] )
vimsupport.ReplaceChunksInBuffer( chunks, result_buffer )
AssertBuffersAreEqualAsBytes( [ 'class {',
' method {',
' statement',
' }',
'}' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
def test_ReplaceChunksInBuffer_SameLocation( self ):
chunks = [
_BuildChunk( 1, 1, 1, 1, 'this ' ),
_BuildChunk( 1, 1, 1, 1, 'is ' ),
_BuildChunk( 1, 1, 1, 1, 'pure ' )
]
result_buffer = VimBuffer( 'buffer', contents = [ 'folly' ] )
vimsupport.ReplaceChunksInBuffer( chunks, result_buffer )
AssertBuffersAreEqualAsBytes( [ 'this is pure folly' ], result_buffer )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
@patch( 'ycm.vimsupport.VariableExists', return_value = False )
@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' )
@patch( 'vim.command', new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.GetBufferNumberForFilename',
return_value = 1,
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.BufferIsVisible',
return_value = True,
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename' )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
@patch( 'vim.eval', new_callable = ExtendedMock )
def test_ReplaceChunks_SingleFile_Open( self,
vim_eval,
post_vim_message,
open_filename,
buffer_is_visible,
get_buffer_number_for_filename,
*args ):
single_buffer_name = os.path.realpath( 'single_file' )
chunks = [
_BuildChunk( 1, 1, 2, 1, 'replacement', single_buffer_name )
]
result_buffer = VimBuffer(
single_buffer_name,
contents = [
'line1',
'line2',
'line3'
]
)
with patch( 'vim.buffers', [ None, result_buffer, None ] ):
vimsupport.ReplaceChunks( chunks )
# Ensure that we applied the replacement correctly
assert_that( result_buffer.GetLines(), contains_exactly(
'replacementline2',
'line3',
) )
# GetBufferNumberForFilename is called twice:
# - once to the check if we would require opening the file (so that we can
# raise a warning)
# - once whilst applying the changes
get_buffer_number_for_filename.assert_has_exact_calls( [
call( single_buffer_name ),
call( single_buffer_name ),
] )
# BufferIsVisible is called twice for the same reasons as above
buffer_is_visible.assert_has_exact_calls( [
call( 1 ),
call( 1 ),
] )
# we don't attempt to open any files
open_filename.assert_not_called()
qflist = json.dumps( [ {
'bufnr': 1,
'filename': single_buffer_name,
'lnum': 1,
'col': 1,
'text': 'replacement',
'type': 'F'
} ] )
# But we do set the quickfix list
vim_eval.assert_has_exact_calls( [
call( f'setqflist( { qflist } )' )
] )
# And it is ReplaceChunks that prints the message showing the number of
# changes
post_vim_message.assert_has_exact_calls( [
call( 'Applied 1 changes', warning = False ),
] )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
@patch( 'ycm.vimsupport.VariableExists', return_value = False )
@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' )
@patch( 'ycm.vimsupport.GetBufferNumberForFilename',
side_effect = [ -1, -1, 1 ],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.BufferIsVisible',
side_effect = [ False, False, True ],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.Confirm',
return_value = True,
new_callable = ExtendedMock )
@patch( 'vim.eval', return_value = 10, new_callable = ExtendedMock )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_ReplaceChunks_SingleFile_NotOpen( self,
vim_command,
vim_eval,
confirm,
post_vim_message,
open_filename,
buffer_is_visible,
get_buffer_number_for_filename,
set_fitting_height,
variable_exists ):
single_buffer_name = os.path.realpath( 'single_file' )
chunks = [
_BuildChunk( 1, 1, 2, 1, 'replacement', single_buffer_name )
]
result_buffer = VimBuffer(
single_buffer_name,
contents = [
'line1',
'line2',
'line3'
]
)
with patch( 'vim.buffers', [ None, result_buffer, None ] ):
vimsupport.ReplaceChunks( chunks )
# We checked if it was OK to open the file
confirm.assert_has_exact_calls( [
call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) )
] )
# Ensure that we applied the replacement correctly
assert_that( result_buffer.GetLines(), contains_exactly(
'replacementline2',
'line3',
) )
# GetBufferNumberForFilename is called 3 times. The return values are set in
# the @patch call above:
# - once to the check if we would require opening the file (so that we can
# raise a warning) (-1 return)
# - once whilst applying the changes (-1 return)
# - finally after calling OpenFilename (1 return)
get_buffer_number_for_filename.assert_has_exact_calls( [
call( single_buffer_name ),
call( single_buffer_name ),
call( single_buffer_name ),
] )
# BufferIsVisible is called 3 times for the same reasons as above, with the
# return of each one
buffer_is_visible.assert_has_exact_calls( [
call( -1 ),
call( -1 ),
call( 1 ),
] )
# We open 'single_file' as expected.
open_filename.assert_called_with( single_buffer_name, {
'focus': True,
'fix': True,
'size': 10
} )
# And close it again, then show the quickfix window.
vim_command.assert_has_exact_calls( [
call( 'lclose' ),
call( 'hide' ),
] )
qflist = json.dumps( [ {
'bufnr': 1,
'filename': single_buffer_name,
'lnum': 1,
'col': 1,
'text': 'replacement',
'type': 'F'
} ] )
# And update the quickfix list
vim_eval.assert_has_exact_calls( [
call( '&previewheight' ),
call( f'setqflist( { qflist } )' )
] )
# And it is ReplaceChunks that prints the message showing the number of
# changes
post_vim_message.assert_has_exact_calls( [
call( 'Applied 1 changes', warning = False ),
] )
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
@patch( 'ycm.vimsupport.VariableExists', return_value = False )
@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' )
@patch( 'ycm.vimsupport.GetBufferNumberForFilename',
side_effect = [ -1, 1 ],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.BufferIsVisible',
side_effect = [ False, True ],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.Confirm',
return_value = True,
new_callable = ExtendedMock )
@patch( 'vim.eval', return_value = 10, new_callable = ExtendedMock )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_ReplaceChunks_SingleFile_NotOpen_Silent(
self,
vim_command,
vim_eval,
confirm,
post_vim_message,
open_filename,
buffer_is_visible,
get_buffer_number_for_filename,
set_fitting_height,
variable_exists ):
# This test is the same as ReplaceChunks_SingleFile_NotOpen_test, but we
# pass the silent flag, as used by post-complete actions, and shows the
# stuff we _don't_ call in that case.
single_buffer_name = os.path.realpath( 'single_file' )
chunks = [
_BuildChunk( 1, 1, 2, 1, 'replacement', single_buffer_name )
]
result_buffer = VimBuffer(
single_buffer_name,
contents = [
'line1',
'line2',
'line3'
]
)
with patch( 'vim.buffers', [ None, result_buffer, None ] ):
vimsupport.ReplaceChunks( chunks, silent=True )
# We didn't check if it was OK to open the file (silent)
confirm.assert_not_called()
# Ensure that we applied the replacement correctly
assert_that( result_buffer.GetLines(), contains_exactly(
'replacementline2',
'line3',
) )
# GetBufferNumberForFilename is called 2 times. The return values are set in
# the @patch call above:
# - once whilst applying the changes (-1 return)
# - finally after calling OpenFilename (1 return)
get_buffer_number_for_filename.assert_has_exact_calls( [
call( single_buffer_name ),
call( single_buffer_name ),
] )
# BufferIsVisible is called 2 times for the same reasons as above, with the
# return of each one
buffer_is_visible.assert_has_exact_calls( [
call( -1 ),
call( 1 ),
] )
# We open 'single_file' as expected.
open_filename.assert_called_with( single_buffer_name, {
'focus': True,
'fix': True,
'size': 10
} )
# And close it again, but don't show the quickfix window
vim_command.assert_has_exact_calls( [
call( 'lclose' ),
call( 'hide' ),
] )
set_fitting_height.assert_not_called()
# But we _don't_ update the QuickFix list
vim_eval.assert_has_exact_calls( [
call( '&previewheight' ),
] )
# And we don't print a message either
post_vim_message.assert_not_called()
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
@patch( 'ycm.vimsupport.GetBufferNumberForFilename',
side_effect = [ -1, -1, 1 ],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.BufferIsVisible',
side_effect = [ False, False, True ],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.PostVimMessage',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.Confirm',
return_value = False,
new_callable = ExtendedMock )
@patch( 'vim.eval',
return_value = 10,
new_callable = ExtendedMock )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_ReplaceChunks_User_Declines_To_Open_File(
self,
vim_command,
vim_eval,
confirm,
post_vim_message,
open_filename,
buffer_is_visible,
get_buffer_number_for_filename ):
# Same as above, except the user selects Cancel when asked if they should
# allow us to open lots of (ahem, 1) file.
single_buffer_name = os.path.realpath( 'single_file' )
chunks = [
_BuildChunk( 1, 1, 2, 1, 'replacement', single_buffer_name )
]
result_buffer = VimBuffer(
single_buffer_name,
contents = [
'line1',
'line2',
'line3'
]
)
with patch( 'vim.buffers', [ None, result_buffer, None ] ):
vimsupport.ReplaceChunks( chunks )
# We checked if it was OK to open the file
confirm.assert_has_exact_calls( [
call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) )
] )
# Ensure that buffer is not changed
assert_that( result_buffer.GetLines(), contains_exactly(
'line1',
'line2',
'line3',
) )
# GetBufferNumberForFilename is called once. The return values are set in
# the @patch call above:
# - once to the check if we would require opening the file (so that we can
# raise a warning) (-1 return)
get_buffer_number_for_filename.assert_has_exact_calls( [
call( single_buffer_name ),
] )
# BufferIsVisible is called once for the above file, which wasn't visible.
buffer_is_visible.assert_has_exact_calls( [
call( -1 ),
] )
# We don't attempt to open any files or update any quickfix list or anything
# like that
open_filename.assert_not_called()
vim_eval.assert_not_called()
vim_command.assert_not_called()
post_vim_message.assert_not_called()
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
@patch( 'ycm.vimsupport.GetBufferNumberForFilename',
side_effect = [ -1, -1, 1 ],
new_callable = ExtendedMock )
# Key difference is here: In the final check, BufferIsVisible returns False
@patch( 'ycm.vimsupport.BufferIsVisible',
side_effect = [ False, False, False ],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.PostVimMessage',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.Confirm',
return_value = True,
new_callable = ExtendedMock )
@patch( 'vim.eval',
return_value = 10,
new_callable = ExtendedMock )
@patch( 'vim.command',
new_callable = ExtendedMock )
def test_ReplaceChunks_User_Aborts_Opening_File(
self,
vim_command,
vim_eval,
confirm,
post_vim_message,
open_filename,
buffer_is_visible,
get_buffer_number_for_filename ):
# Same as above, except the user selects Abort or Quick during the
# "swap-file-found" dialog
single_buffer_name = os.path.realpath( 'single_file' )
chunks = [
_BuildChunk( 1, 1, 2, 1, 'replacement', single_buffer_name )
]
result_buffer = VimBuffer(
single_buffer_name,
contents = [
'line1',
'line2',
'line3'
]
)
with patch( 'vim.buffers', [ None, result_buffer, None ] ):
assert_that(
calling( vimsupport.ReplaceChunks ).with_args( chunks ),
raises( RuntimeError,
'Unable to open file: .+single_file\n'
'FixIt/Refactor operation aborted prior to completion. '
'Your files have not been fully updated. '
'Please use undo commands to revert the applied changes.' ) )
# We checked if it was OK to open the file
confirm.assert_has_exact_calls( [
call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) )
] )
# Ensure that buffer is not changed
assert_that( result_buffer.GetLines(), contains_exactly(
'line1',
'line2',
'line3',
) )
# We tried to open this file
open_filename.assert_called_with( single_buffer_name, {
'focus': True,
'fix': True,
'size': 10
} )
vim_eval.assert_called_with( "&previewheight" )
# But raised an exception before issuing the message at the end
post_vim_message.assert_not_called()
@patch( 'vim.current.window.cursor', ( 1, 1 ) )
@patch( 'ycm.vimsupport.VariableExists', return_value = False )
@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' )
@patch( 'ycm.vimsupport.GetBufferNumberForFilename', side_effect = [
22, # first_file (check)
-1, # second_file (check)
22, # first_file (apply)
-1, # second_file (apply)
19, # second_file (check after open)
],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.BufferIsVisible', side_effect = [
True, # first_file (check)
False, # second_file (check)
True, # first_file (apply)
False, # second_file (apply)
True, # side_effect (check after open)
],
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.PostVimMessage',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.Confirm', return_value = True,
new_callable = ExtendedMock )
@patch( 'vim.eval', return_value = 10,
new_callable = ExtendedMock )
@patch( 'vim.command',
new_callable = ExtendedMock )
def test_ReplaceChunks_MultiFile_Open( self,
vim_command,
vim_eval,
confirm,
post_vim_message,
open_filename,
buffer_is_visible,
get_buffer_number_for_filename,
set_fitting_height,
variable_exists ):
# Chunks are split across 2 files, one is already open, one isn't
first_buffer_name = os.path.realpath( '1_first_file' )
second_buffer_name = os.path.realpath( '2_second_file' )
chunks = [
_BuildChunk( 1, 1, 2, 1, 'first_file_replacement ', first_buffer_name ),
_BuildChunk( 2, 1, 2, 1, 'second_file_replacement ', second_buffer_name ),
]
first_file = VimBuffer(
first_buffer_name,
number = 22,
contents = [
'line1',
'line2',
'line3',
]
)
second_file = VimBuffer(
second_buffer_name,
number = 19,
contents = [
'another line1',
'ACME line2',
]
)
vim_buffers = [ None ] * 23
vim_buffers[ 22 ] = first_file
vim_buffers[ 19 ] = second_file
with patch( 'vim.buffers', vim_buffers ):
vimsupport.ReplaceChunks( chunks )
# We checked for the right file names
get_buffer_number_for_filename.assert_has_exact_calls( [
call( first_buffer_name ),
call( second_buffer_name ),
call( first_buffer_name ),
call( second_buffer_name ),
call( second_buffer_name ),
] )
# We checked if it was OK to open the file
confirm.assert_has_exact_calls( [
call( vimsupport.FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( 1 ) )
] )
# Ensure that buffers are updated
assert_that( second_file.GetLines(), contains_exactly(
'another line1',
'second_file_replacement ACME line2',
) )
assert_that( first_file.GetLines(), contains_exactly(
'first_file_replacement line2',
'line3',
) )
# We open '2_second_file' as expected.
open_filename.assert_called_with( second_buffer_name, {
'focus': True,
'fix': True,
'size': 10
} )
# And close it again, then show the quickfix window.
vim_command.assert_has_exact_calls( [
call( 'lclose' ),
call( 'hide' ),
] )
qflist = json.dumps( [ {
'bufnr': 22,
'filename': first_buffer_name,
'lnum': 1,
'col': 1,
'text': 'first_file_replacement ',
'type': 'F'
}, {
'bufnr': 19,
'filename': second_buffer_name,
'lnum': 2,
'col': 1,
'text': 'second_file_replacement ',
'type': 'F'
} ] )
# And update the quickfix list with each entry
vim_eval.assert_has_exact_calls( [
call( '&previewheight' ),
call( f'setqflist( { qflist } )' )
] )
# And it is ReplaceChunks that prints the message showing the number of
# changes
post_vim_message.assert_has_exact_calls( [
call( 'Applied 2 changes', warning = False ),
] )
@patch( 'vim.command', new_callable=ExtendedMock )
@patch( 'vim.current', new_callable=ExtendedMock )
def test_WriteToPreviewWindow( self, vim_current, vim_command ):
vim_current.window.options.__getitem__ = MagicMock( return_value = True )
vimsupport.WriteToPreviewWindow( "test", '' )
vim_command.assert_has_exact_calls( [
call( 'silent! pclose!' ),
call( 'silent! pedit! _TEMP_FILE_' ),
call( 'silent! wincmd P' ),
call( 'silent! wincmd p' ) ] )
vim_current.buffer.__setitem__.assert_called_with(
slice( None, None, None ), [ 'test' ] )
vim_current.buffer.options.__setitem__.assert_has_exact_calls( [
call( 'modifiable', True ),
call( 'readonly', False ),
call( 'buftype', 'nofile' ),
call( 'bufhidden', 'wipe' ),
call( 'buflisted', False ),
call( 'swapfile', False ),
call( 'modifiable', False ),
call( 'modified', False ),
call( 'readonly', True ),
], any_order = True )
@patch( 'vim.command', new_callable=ExtendedMock )
@patch( 'vim.current', new_callable=ExtendedMock )
def test_WriteToPreviewWindow_Mods( self, vim_current, vim_command ):
vim_current.window.options.__getitem__ = MagicMock( return_value = True )
vimsupport.WriteToPreviewWindow( "test", 'tab leftabove' )
vim_command.assert_has_exact_calls( [
call( 'silent! pclose!' ),
call( 'silent! tab leftabove pedit! _TEMP_FILE_' ),
call( 'silent! wincmd P' ),
call( 'silent! wincmd p' ) ] )
vim_current.buffer.__setitem__.assert_called_with(
slice( None, None, None ), [ 'test' ] )
vim_current.buffer.options.__setitem__.assert_has_exact_calls( [
call( 'modifiable', True ),
call( 'readonly', False ),
call( 'buftype', 'nofile' ),
call( 'bufhidden', 'wipe' ),
call( 'buflisted', False ),
call( 'swapfile', False ),
call( 'modifiable', False ),
call( 'modified', False ),
call( 'readonly', True ),
], any_order = True )
@patch( 'vim.current' )
def test_WriteToPreviewWindow_MultiLine( self, vim_current ):
vim_current.window.options.__getitem__ = MagicMock( return_value = True )
vimsupport.WriteToPreviewWindow( "test\ntest2", '' )
vim_current.buffer.__setitem__.assert_called_with(
slice( None, None, None ), [ 'test', 'test2' ] )
@patch( 'vim.command', new_callable=ExtendedMock )
@patch( 'vim.current', new_callable=ExtendedMock )
def test_WriteToPreviewWindow_JumpFail( self, vim_current, vim_command ):
vim_current.window.options.__getitem__ = MagicMock( return_value = False )
vimsupport.WriteToPreviewWindow( "test", '' )
vim_command.assert_has_exact_calls( [
call( 'silent! pclose!' ),
call( 'silent! pedit! _TEMP_FILE_' ),
call( 'silent! wincmd P' ),
call( 'redraw' ),
call( "echo 'test'" ),
] )
vim_current.buffer.__setitem__.assert_not_called()
vim_current.buffer.options.__setitem__.assert_not_called()
@patch( 'vim.command', new_callable=ExtendedMock )
@patch( 'vim.current', new_callable=ExtendedMock )
def test_WriteToPreviewWindow_JumpFail_MultiLine(
self, vim_current, vim_command ):
vim_current.window.options.__getitem__ = MagicMock( return_value = False )
vimsupport.WriteToPreviewWindow( "test\ntest2", '' )
vim_command.assert_has_exact_calls( [
call( 'silent! pclose!' ),
call( 'silent! pedit! _TEMP_FILE_' ),
call( 'silent! wincmd P' ),
call( 'redraw' ),
call( "echo 'test'" ),
call( "echo 'test2'" ),
] )
vim_current.buffer.__setitem__.assert_not_called()
vim_current.buffer.options.__setitem__.assert_not_called()
def test_BufferIsVisibleForFilename( self ):
visible_buffer = VimBuffer( 'visible_filename', number = 1 )
hidden_buffer = VimBuffer( 'hidden_filename', number = 2 )
with MockVimBuffers( [ visible_buffer, hidden_buffer ],
[ visible_buffer ] ):
assert_that( vimsupport.BufferIsVisibleForFilename( 'visible_filename' ) )
assert_that(
not vimsupport.BufferIsVisibleForFilename( 'hidden_filename' ) )
assert_that(
not vimsupport.BufferIsVisibleForFilename( 'another_filename' ) )
def test_CloseBuffersForFilename( self ):
current_buffer = VimBuffer( 'some_filename', number = 2 )
other_buffer = VimBuffer( 'some_filename', number = 5 )
with MockVimBuffers( [ current_buffer, other_buffer ],
[ current_buffer ] ) as vim:
vimsupport.CloseBuffersForFilename( 'some_filename' )
assert_that( vim.buffers, empty() )
@patch( 'vim.command', new_callable = ExtendedMock )
@patch( 'vim.current', new_callable = ExtendedMock )
def test_OpenFilename( self, vim_current, vim_command ):
# Options used to open a logfile.
options = {
'size': vimsupport.GetIntValue( '&previewheight' ),
'fix': True,
'focus': False,
'watch': True,
'position': 'end'
}
vimsupport.OpenFilename( __file__, options )
vim_command.assert_has_exact_calls( [
call( f'12split { __file__ }' ),
call( f"exec 'au BufEnter <buffer> :silent! checktime { __file__ }'" ),
call( 'silent! normal! Gzz' ),
call( 'silent! wincmd p' )
] )
vim_current.buffer.options.__setitem__.assert_has_exact_calls( [
call( 'autoread', True ),
] )
vim_current.window.options.__setitem__.assert_has_exact_calls( [
call( 'winfixheight', True )
] )
def test_GetUnsavedAndSpecifiedBufferData_EncodedUnicodeCharsInBuffers(
self ):
filepath = os.path.realpath( 'filename' )
contents = [ ToBytes( 'abc' ), ToBytes( 'f–îa' ) ]
vim_buffer = VimBuffer( filepath, contents = contents )
with patch( 'vim.buffers', [ vim_buffer ] ):
assert_that( vimsupport.GetUnsavedAndSpecifiedBufferData( vim_buffer,
filepath ),
has_entry( filepath,
has_entry( 'contents', 'abc\nf–îa\n' ) ) )
def test_GetBufferFilepath_NoBufferName_UnicodeWorkingDirectory( self ):
vim_buffer = VimBuffer( '', number = 42 )
unicode_dir = PathToTestFile( 'uni¢od€' )
with CurrentWorkingDirectory( unicode_dir ):
assert_that( vimsupport.GetBufferFilepath( vim_buffer ),
equal_to( os.path.join( unicode_dir, '42' ) ) )
# NOTE: Vim returns byte offsets for columns, not actual character columns.
# This makes '–î–î' have 4 columns: column 0, column 2 and column 4.
@patch( 'vim.current.line', ToBytes( '–î–îaa' ) )
@patch( 'ycm.vimsupport.CurrentColumn', side_effect = [ 4 ] )
def test_TextBeforeCursor_EncodedUnicode( *args ):
assert_that( vimsupport.TextBeforeCursor(), equal_to( '–î–î' ) )
# NOTE: Vim returns byte offsets for columns, not actual character columns.
# This makes '–î–î' have 4 columns: column 0, column 2 and column 4.
@patch( 'vim.current.line', ToBytes( 'aa–î–î' ) )
@patch( 'ycm.vimsupport.CurrentColumn', side_effect = [ 2 ] )
def test_TextAfterCursor_EncodedUnicode( *args ):
assert_that( vimsupport.TextAfterCursor(), equal_to( '–î–î' ) )
@patch( 'vim.current.line', ToBytes( 'f–îa' ) )
def test_CurrentLineContents_EncodedUnicode( *args ):
assert_that( vimsupport.CurrentLineContents(), equal_to( 'f–îa' ) )
@patch( 'vim.eval', side_effect = lambda x: x )
def test_VimExpressionToPythonType_IntAsUnicode( *args ):
assert_that( vimsupport.VimExpressionToPythonType( '123' ),
equal_to( 123 ) )
@patch( 'vim.eval', side_effect = lambda x: x )
def test_VimExpressionToPythonType_IntAsBytes( *args ):
assert_that( vimsupport.VimExpressionToPythonType( ToBytes( '123' ) ),
equal_to( 123 ) )
@patch( 'vim.eval', side_effect = lambda x: x )
def test_VimExpressionToPythonType_StringAsUnicode( *args ):
assert_that( vimsupport.VimExpressionToPythonType( 'foo' ),
equal_to( 'foo' ) )
@patch( 'vim.eval', side_effect = lambda x: x )
def test_VimExpressionToPythonType_StringAsBytes( *args ):
assert_that( vimsupport.VimExpressionToPythonType( ToBytes( 'foo' ) ),
equal_to( 'foo' ) )
@patch( 'vim.eval', side_effect = lambda x: x )
def test_VimExpressionToPythonType_ListPassthrough( *args ):
assert_that( vimsupport.VimExpressionToPythonType( [ 1, 2 ] ),
equal_to( [ 1, 2 ] ) )
@patch( 'vim.eval', side_effect = lambda x: x )
def test_VimExpressionToPythonType_ObjectPassthrough( *args ):
assert_that( vimsupport.VimExpressionToPythonType( { 1: 2 } ),
equal_to( { 1: 2 } ) )
@patch( 'vim.eval', side_effect = lambda x: x )
def test_VimExpressionToPythonType_GeneratorPassthrough( *args ):
gen = ( x**2 for x in [ 1, 2, 3 ] )
assert_that( vimsupport.VimExpressionToPythonType( gen ), equal_to( gen ) )
@patch( 'vim.eval',
new_callable = ExtendedMock,
side_effect = [ None, 2, None ] )
def test_SelectFromList_LastItem( self, vim_eval ):
assert_that( vimsupport.SelectFromList( 'test', [ 'a', 'b' ] ),
equal_to( 1 ) )
vim_eval.assert_has_exact_calls( [
call( 'inputsave()' ),
call( 'inputlist( ["test", "1: a", "2: b"] )' ),
call( 'inputrestore()' )
] )
@patch( 'vim.eval',
new_callable = ExtendedMock,
side_effect = [ None, 1, None ] )
def test_SelectFromList_FirstItem( self, vim_eval ):
assert_that( vimsupport.SelectFromList( 'test', [ 'a', 'b' ] ),
equal_to( 0 ) )
vim_eval.assert_has_exact_calls( [
call( 'inputsave()' ),
call( 'inputlist( ["test", "1: a", "2: b"] )' ),
call( 'inputrestore()' )
] )
@patch( 'vim.eval', side_effect = [ None, 3, None ] )
def test_SelectFromList_OutOfRange( self, vim_eval ):
assert_that( calling( vimsupport.SelectFromList ).with_args( 'test',
[ 'a', 'b' ] ),
raises( RuntimeError, vimsupport.NO_SELECTION_MADE_MSG ) )
@patch( 'vim.eval', side_effect = [ None, 0, None ] )
def test_SelectFromList_SelectPrompt( self, vim_eval ):
assert_that( calling( vimsupport.SelectFromList ).with_args( 'test',
[ 'a', 'b' ] ),
raises( RuntimeError, vimsupport.NO_SELECTION_MADE_MSG ) )
@patch( 'vim.eval', side_effect = [ None, -199, None ] )
def test_SelectFromList_Negative( self, vim_eval ):
assert_that( calling( vimsupport.SelectFromList ).with_args( 'test',
[ 'a', 'b' ] ),
raises( RuntimeError, vimsupport.NO_SELECTION_MADE_MSG ) )
def test_Filetypes_IntegerFiletype( self ):
current_buffer = VimBuffer( 'buffer', number = 1, filetype = '42' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( vimsupport.CurrentFiletypes(), contains_exactly( '42' ) )
assert_that( vimsupport.GetBufferFiletypes( 1 ),
contains_exactly( '42' ) )
assert_that( vimsupport.FiletypesForBuffer( current_buffer ),
contains_exactly( '42' ) )
@patch( 'ycm.vimsupport.VariableExists', return_value = False )
@patch( 'ycm.vimsupport.SearchInCurrentBuffer', return_value = 0 )
@patch( 'vim.current' )
def test_InsertNamespace_insert( self, vim_current, *args ):
contents = [ '',
'namespace Taqueria {',
'',
' int taco = Math' ]
vim_current.buffer = VimBuffer( '', contents = contents )
vim_current.window.cursor = ( 1, 1 )
vimsupport.InsertNamespace( 'System' )
expected_buffer = [ 'using System;',
'',
'namespace Taqueria {',
'',
' int taco = Math' ]
AssertBuffersAreEqualAsBytes( expected_buffer, vim_current.buffer )
@patch( 'ycm.vimsupport.VariableExists', return_value = False )
@patch( 'ycm.vimsupport.SearchInCurrentBuffer', return_value = 2 )
@patch( 'vim.current' )
def test_InsertNamespace_append( self, vim_current, *args ):
contents = [ 'namespace Taqueria {',
' using System;',
'',
' class Tasty {',
' int taco;',
' List salad = new List' ]
vim_current.buffer = VimBuffer( '', contents = contents )
vim_current.window.cursor = ( 1, 1 )
vimsupport.InsertNamespace( 'System.Collections' )
expected_buffer = [ 'namespace Taqueria {',
' using System;',
' using System.Collections;',
'',
' class Tasty {',
' int taco;',
' List salad = new List' ]
AssertBuffersAreEqualAsBytes( expected_buffer, vim_current.buffer )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_SameFile_SameBuffer_NoSwapFile( self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vimsupport.JumpToLocation( os.path.realpath( 'uni¬¢êçàd‚Ǩ' ),
2,
5,
'aboveleft',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 2, 4 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_SameBuffer_Unmodified(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
2,
5,
'belowright',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 2, 4 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps belowright edit { target_name }' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_SameFile_NoLineCol( self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.cursor = ( 99, 99 )
target_name = os.path.realpath( 'uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
None,
None,
'belowright',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 99, 99 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_SameFile_NoLine( self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.cursor = ( 99, 99 )
target_name = os.path.realpath( 'uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
None,
1,
'belowright',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 99, 99 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_SameFile_NoCol( self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.cursor = ( 99, 99 )
target_name = os.path.realpath( 'uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
1,
None,
'belowright',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 99, 99 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_NoLineCol( self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.cursor = ( 99, 99 )
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
None,
None,
'belowright',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 99, 99 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps belowright edit { target_name }' ),
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_NoLine( self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.cursor = ( 99, 99 )
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
None,
1,
'belowright',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 99, 99 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps belowright edit { target_name }' ),
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_NoCol( self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.window.cursor = ( 99, 99 )
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
1,
None,
'belowright',
'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 99, 99 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps belowright edit { target_name }' ),
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_SameBuffer_Modified_CannotHide(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ', modified = True )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name, 2, 5, 'botright', 'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 2, 4 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps botright split { target_name }' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_SameBuffer_Modified_CanHide(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ', modified = True, bufhidden = "hide" )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name, 2, 5, 'leftabove', 'same-buffer' )
assert_that( vim.current.window.cursor, equal_to( ( 2, 4 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps leftabove edit { target_name }' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command',
side_effect = [ None, VimError( 'Unknown code' ), None ] )
def test_JumpToLocation_DifferentFile_SameBuffer_SwapFile_Unexpected(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that(
calling( vimsupport.JumpToLocation ).with_args(
os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' ),
2,
5,
'rightbelow',
'same-buffer' ),
raises( VimError, 'Unknown code' )
)
@patch( 'vim.command',
new_callable = ExtendedMock,
side_effect = [ None, VimError( 'E325' ), None ] )
def test_JumpToLocation_DifferentFile_SameBuffer_SwapFile_Quit(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name, 2, 5, 'topleft', 'same-buffer' )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps topleft edit { target_name }' )
] )
@patch( 'vim.command',
new_callable = ExtendedMock,
side_effect = [ None, KeyboardInterrupt, None ] )
def test_JumpToLocation_DifferentFile_SameBuffer_SwapFile_Abort(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name, 2, 5, 'vertical', 'same-buffer' )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps vertical edit { target_name }' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_Split_CurrentTab_NotAlreadyOpened(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
current_window = MagicMock( buffer = current_buffer )
current_tab = MagicMock( windows = [ current_window ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ) as vim:
vim.current.tabpage = current_tab
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
2,
5,
'aboveleft',
'split-or-existing-window' )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps aboveleft split { target_name }' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_Split_CurrentTab_AlreadyOpened(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
different_buffer = VimBuffer( 'different_uni¬¢êçàd‚Ǩ' )
current_window = MagicMock( buffer = current_buffer )
different_window = MagicMock( buffer = different_buffer )
current_tab = MagicMock( windows = [ current_window, different_window ] )
with MockVimBuffers( [ current_buffer, different_buffer ],
[ current_buffer ] ) as vim:
vim.current.tabpage = current_tab
vimsupport.JumpToLocation( os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' ),
2,
5,
'belowright',
'split-or-existing-window' )
assert_that( vim.current.tabpage, equal_to( current_tab ) )
assert_that( vim.current.window, equal_to( different_window ) )
assert_that( vim.current.window.cursor, equal_to( ( 2, 4 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@WindowsAndMacOnly
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_Split_CurrentTab_AlreadyOpened_Case(
self, vim_command ):
current_buffer = VimBuffer( 'current_buffer' )
different_buffer = VimBuffer( 'AnotHer_buFfeR' )
current_window = MagicMock( buffer = current_buffer )
different_window = MagicMock( buffer = different_buffer )
current_tab = MagicMock( windows = [ current_window, different_window ] )
with MockVimBuffers( [ current_buffer, different_buffer ],
[ current_buffer ] ) as vim:
vim.current.tabpage = current_tab
vimsupport.JumpToLocation( os.path.realpath( 'anOther_BuffEr' ),
4,
1,
'belowright',
'split-or-existing-window' )
assert_that( vim.current.tabpage, equal_to( current_tab ) )
assert_that( vim.current.window, equal_to( different_window ) )
assert_that( vim.current.window.cursor, equal_to( ( 4, 0 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_Split_AllTabs_NotAlreadyOpened(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
2,
5,
'tab',
'split-or-existing-window' )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps tab split { target_name }' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_Split_AllTabs_AlreadyOpened(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
different_buffer = VimBuffer( 'different_uni¬¢êçàd‚Ǩ' )
current_window = MagicMock( buffer = current_buffer )
different_window = MagicMock( buffer = different_buffer )
current_tab = MagicMock( windows = [ current_window, different_window ] )
with MockVimBuffers( [ current_buffer, different_buffer ],
[ current_buffer ] ) as vim:
with patch( 'vim.tabpages', [ current_tab ] ):
vimsupport.JumpToLocation( os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' ),
2,
5,
'tab',
'split-or-existing-window' )
assert_that( vim.current.tabpage, equal_to( current_tab ) )
assert_that( vim.current.window, equal_to( different_window ) )
assert_that( vim.current.window.cursor, equal_to( ( 2, 4 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_NewOrExistingTab_NotAlreadyOpened(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
target_name = os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' )
vimsupport.JumpToLocation( target_name,
2,
5,
'aboveleft vertical',
'new-or-existing-tab' )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( f'keepjumps aboveleft vertical tabedit { target_name }' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'vim.command', new_callable = ExtendedMock )
def test_JumpToLocation_DifferentFile_NewOrExistingTab_AlreadyOpened(
self, vim_command ):
current_buffer = VimBuffer( 'uni¬¢êçàd‚Ǩ' )
different_buffer = VimBuffer( 'different_uni¬¢êçàd‚Ǩ' )
current_window = MagicMock( buffer = current_buffer )
different_window = MagicMock( buffer = different_buffer )
current_tab = MagicMock( windows = [ current_window, different_window ] )
with MockVimBuffers( [ current_buffer, different_buffer ],
[ current_buffer ] ) as vim:
with patch( 'vim.tabpages', [ current_tab ] ):
vimsupport.JumpToLocation( os.path.realpath( 'different_uni¬¢êçàd‚Ǩ' ),
2,
5,
'belowright tab',
'new-or-existing-tab' )
assert_that( vim.current.tabpage, equal_to( current_tab ) )
assert_that( vim.current.window, equal_to( different_window ) )
assert_that( vim.current.window.cursor, equal_to( ( 2, 4 ) ) )
vim_command.assert_has_exact_calls( [
call( 'normal! m\'' ),
call( 'normal! zv' ),
call( 'normal! zz' )
] )
@patch( 'ycm.tests.test_utils.VIM_VERSION', Version( 7, 4, 1578 ) )
def test_VimVersionAtLeast( self ):
assert_that( vimsupport.VimVersionAtLeast( '7.3.414' ) )
assert_that( vimsupport.VimVersionAtLeast( '7.4.1578' ) )
assert_that( not vimsupport.VimVersionAtLeast( '7.4.1579' ) )
assert_that( not vimsupport.VimVersionAtLeast( '7.4.1898' ) )
assert_that( not vimsupport.VimVersionAtLeast( '8.1.278' ) )
| 80,900
|
Python
|
.py
| 1,757
| 35.177575
| 86
| 0.566258
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,965
|
test_utils.py
|
ycm-core_YouCompleteMe/python/ycm/tests/test_utils.py
|
# Copyright (C) 2011-2019 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from collections import defaultdict, namedtuple
from unittest.mock import DEFAULT, MagicMock, patch
from unittest import skip
from hamcrest import ( assert_that,
contains_exactly,
contains_inanyorder,
equal_to )
import contextlib
import functools
import json
import os
import re
import sys
from unittest import skipIf
from ycmd.utils import GetCurrentDirectory, OnMac, OnWindows, ToUnicode
BUFNR_REGEX = re.compile(
'^bufnr\\( \'(?P<buffer_filename>.+)\'(, ([01]))? \\)$' )
BUFWINNR_REGEX = re.compile( '^bufwinnr\\( (?P<buffer_number>[0-9]+) \\)$' )
BWIPEOUT_REGEX = re.compile(
'^(?:silent! )bwipeout!? (?P<buffer_number>[0-9]+)$' )
GETBUFVAR_REGEX = re.compile(
'^getbufvar\\((?P<buffer_number>[0-9]+), "(?P<option>.+)"\\)( \\?\\? 0)?$' )
PROP_LIST_REGEX = re.compile(
'^prop_list\\( ' # A literal at the start
'(?P<lnum>\\d+), ' # Start line
'{ "bufnr": (?P<bufnr>\\d+), ' # Corresponding buffer number
'"end_lnum": (?P<end_lnum>[0-9-]+), ' # End line, can be negative.
'"types": (?P<prop_types>\\[.+\\]) } ' # Property types
'\\)$' )
PROP_ADD_REGEX = re.compile(
'^prop_add\\( ' # A literal at the start
'(?P<start_line>\\d+), ' # First argument - number
'(?P<start_column>\\d+), ' # Second argument - number
'{(?P<opts>.+)} ' # Third argument is a complex dict, which
# we parse separately
'\\)$' )
PROP_REMOVE_REGEX = re.compile( '^prop_remove\\( (?P<prop>.+) \\)$' )
OMNIFUNC_REGEX_FORMAT = (
'^{omnifunc_name}\\((?P<findstart>[01]),[\'"](?P<base>.*)[\'"]\\)$' )
FNAMEESCAPE_REGEX = re.compile( '^fnameescape\\(\'(?P<filepath>.+)\'\\)$' )
STRDISPLAYWIDTH_REGEX = re.compile(
'^strdisplaywidth\\( ?\'(?P<text>.+)\' ?\\)$' )
REDIR_START_REGEX = re.compile( '^redir => (?P<variable>[\\w:]+)$' )
REDIR_END_REGEX = re.compile( '^redir END$' )
EXISTS_REGEX = re.compile( '^exists\\( \'(?P<option>[\\w:]+)\' \\)$' )
LET_REGEX = re.compile( '^let (?P<option>[\\w:]+) = (?P<value>.*)$' )
HAS_PATCH_REGEX = re.compile( '^has\\( \'patch(?P<patch>\\d+)\' \\)$' )
# One-and only instance of mocked Vim object. The first 'import vim' that is
# executed binds the vim module to the instance of MagicMock that is created,
# and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively
# update them. The result is that while running the tests, we must assign only
# one instance of MagicMock to sys.modules[ 'vim' ] and always return it.
#
# More explanation is available:
# https://github.com/Valloric/YouCompleteMe/pull/1694
VIM_MOCK = MagicMock()
VIM_PROPS_FOR_BUFFER = defaultdict( list )
VIM_SIGNS = []
VIM_OPTIONS = {
'&completeopt': b'',
'&previewheight': 12,
'&columns': 80,
'&ruler': 0,
'&showcmd': 1,
'&hidden': 0,
'&expandtab': 1
}
Version = namedtuple( 'Version', [ 'major', 'minor', 'patch' ] )
# This variable must be patched with a Version object for tests depending on a
# recent Vim version. Example:
#
# @patch( 'ycm.tests.test_utils.VIM_VERSION', Version( 8, 1, 614 ) )
# def ThisTestDependsOnTheVimVersion_test():
# ...
#
# Default is the oldest supported version.
VIM_VERSION = Version( 7, 4, 1578 )
REDIR = {
'status': False,
'variable': '',
'output': ''
}
WindowsAndMacOnly = skipIf( not OnWindows() or not OnMac(),
'Windows and macOS only' )
@contextlib.contextmanager
def CurrentWorkingDirectory( path ):
old_cwd = GetCurrentDirectory()
os.chdir( path )
try:
yield
finally:
os.chdir( old_cwd )
def _MockGetBufferNumber( buffer_filename ):
for vim_buffer in VIM_MOCK.buffers:
if vim_buffer.name == buffer_filename:
return vim_buffer.number
return -1
def _MockGetBufferWindowNumber( buffer_number ):
for window in VIM_MOCK.windows:
if window.buffer.number == buffer_number:
return window.number
return -1
def _MockGetBufferVariable( buffer_number, option ):
for vim_buffer in VIM_MOCK.buffers:
if vim_buffer.number == buffer_number:
if option == '&mod':
return vim_buffer.modified
if option == '&ft':
return vim_buffer.filetype
if option == 'changedtick':
return vim_buffer.changedtick
if option == '&bh':
return vim_buffer.bufhidden
return ''
return ''
def _MockVimBufferEval( value ):
if value == '&omnifunc':
return VIM_MOCK.current.buffer.omnifunc_name
if value == '&filetype':
return VIM_MOCK.current.buffer.filetype
match = BUFNR_REGEX.search( value )
if match:
buffer_filename = match.group( 'buffer_filename' )
return _MockGetBufferNumber( buffer_filename )
match = BUFWINNR_REGEX.search( value )
if match:
buffer_number = int( match.group( 'buffer_number' ) )
return _MockGetBufferWindowNumber( buffer_number )
match = GETBUFVAR_REGEX.search( value )
if match:
buffer_number = int( match.group( 'buffer_number' ) )
option = match.group( 'option' )
return _MockGetBufferVariable( buffer_number, option )
current_buffer = VIM_MOCK.current.buffer
match = re.search( OMNIFUNC_REGEX_FORMAT.format(
omnifunc_name = current_buffer.omnifunc_name ),
value )
if match:
findstart = int( match.group( 'findstart' ) )
base = match.group( 'base' )
return current_buffer.omnifunc( findstart, base )
return None
def _MockVimWindowEval( value ):
if value == 'winnr("#")':
# For simplicity, we always assume there is no previous window.
return 0
return None
def _MockVimOptionsEval( value ):
result = VIM_OPTIONS.get( value )
if result is not None:
return result
if value == 'keys( g: )':
global_options = {}
for key, value in VIM_OPTIONS.items():
if key.startswith( 'g:' ):
global_options[ key[ 2: ] ] = value
return global_options
match = EXISTS_REGEX.search( value )
if match:
option = match.group( 'option' )
return option in VIM_OPTIONS
return None
def _MockVimFunctionsEval( value ):
if value == 'tempname()':
return '_TEMP_FILE_'
if value == 'tagfiles()':
return [ 'tags' ]
if value == 'shiftwidth()':
return 2
if value.startswith( 'has( "' ):
return False
match = re.match( 'sign_getplaced\\( (?P<bufnr>\\d+), '
'{ "group": "ycm_signs" } \\)', value )
if match:
filtered = list( filter( lambda sign: sign.bufnr ==
int( match.group( 'bufnr' ) ),
VIM_SIGNS ) )
r = [ { 'signs': filtered } ]
return r
match = re.match( 'sign_unplacelist\\( (?P<sign_list>\\[.*\\]) \\)', value )
if match:
sign_list = eval( match.group( 'sign_list' ) )
for sign in sign_list:
VIM_SIGNS.remove( sign )
return True # Why True?
match = re.match( 'sign_placelist\\( (?P<sign_list>\\[.*\\]) \\)', value )
if match:
sign_list = json.loads( match.group( 'sign_list' ).replace( "'", '"' ) )
for sign in sign_list:
VIM_SIGNS.append( VimSign( sign[ 'lnum' ],
sign[ 'name' ],
sign[ 'buffer' ] ) )
return True # Why True?
return None
def _MockVimPropEval( value ):
if match := PROP_LIST_REGEX.search( value ):
if int( match.group( 'end_lnum' ) ) == -1:
return [ p for p in VIM_PROPS_FOR_BUFFER[ int( match.group( 'bufnr' ) ) ]
if p.start_line >= int( match.group( 'lnum' ) ) ]
else:
return [ p for p in VIM_PROPS_FOR_BUFFER[ int( match.group( 'bufnr' ) ) ]
if int( match.group( 'end_lnum' ) ) >= p.start_line and
p.start_line >= int( match.group( 'lnum' ) ) ]
if match := PROP_ADD_REGEX.search( value ):
prop_start_line = int( match.group( 'start_line' ) )
prop_start_column = int( match.group( 'start_column' ) )
import ast
opts = ast.literal_eval( '{' + match.group( 'opts' ) + '}' )
vim_prop = VimProp(
opts[ 'type' ],
prop_start_line,
prop_start_column,
int( opts[ 'end_lnum' ] ),
int( opts[ 'end_col' ] )
)
VIM_PROPS_FOR_BUFFER[ int( opts[ 'bufnr' ] ) ].append( vim_prop )
return vim_prop.id
if match := PROP_REMOVE_REGEX.search( value ):
prop, lin_num = eval( match.group( 'prop' ) )
vim_props = VIM_PROPS_FOR_BUFFER[ prop[ 'bufnr' ] ]
for index, vim_prop in enumerate( vim_props ):
if vim_prop.id == prop[ 'id' ]:
vim_props.pop( index )
return -1
return 0
return None
def _MockVimVersionEval( value ):
match = HAS_PATCH_REGEX.search( value )
if match:
if not isinstance( VIM_VERSION, Version ):
raise RuntimeError( 'Vim version is not set.' )
return VIM_VERSION.patch >= int( match.group( 'patch' ) )
if value == 'v:version':
if not isinstance( VIM_VERSION, Version ):
raise RuntimeError( 'Vim version is not set.' )
return VIM_VERSION.major * 100 + VIM_VERSION.minor
return None
def _MockVimEval( value ): # noqa
if value == 'g:ycm_neovim_ns_id':
return 1
result = _MockVimOptionsEval( value )
if result is not None:
return result
result = _MockVimFunctionsEval( value )
if result is not None:
return result
result = _MockVimBufferEval( value )
if result is not None:
return result
result = _MockVimWindowEval( value )
if result is not None:
return result
result = _MockVimPropEval( value )
if result is not None:
return result
result = _MockVimVersionEval( value )
if result is not None:
return result
match = FNAMEESCAPE_REGEX.search( value )
if match:
return match.group( 'filepath' )
if value == REDIR[ 'variable' ]:
return REDIR[ 'output' ]
match = STRDISPLAYWIDTH_REGEX.search( value )
if match:
return len( match.group( 'text' ) )
raise VimError( f'Unexpected evaluation: { value }' )
def _MockWipeoutBuffer( buffer_number ):
buffers = VIM_MOCK.buffers
for index, buffer in enumerate( buffers ):
if buffer.number == buffer_number:
return buffers.pop( index )
def _MockVimCommand( command ):
match = BWIPEOUT_REGEX.search( command )
if match:
return _MockWipeoutBuffer( int( match.group( 1 ) ) )
match = REDIR_START_REGEX.search( command )
if match:
REDIR[ 'status' ] = True
REDIR[ 'variable' ] = match.group( 'variable' )
return
match = REDIR_END_REGEX.search( command )
if match:
REDIR[ 'status' ] = False
return
if command == 'unlet ' + REDIR[ 'variable' ]:
REDIR[ 'variable' ] = ''
return
match = LET_REGEX.search( command )
if match:
option = match.group( 'option' )
value = json.loads( match.group( 'value' ) )
VIM_OPTIONS[ option ] = value
return
return DEFAULT
def _MockVimOptions( option ):
result = VIM_OPTIONS.get( '&' + option )
if result is not None:
return result
return None
class VimBuffer:
"""An object that looks like a vim.buffer object:
- |name| : full path of the buffer with symbolic links resolved;
- |number| : buffer number;
- |contents| : list of lines representing the buffer contents;
- |filetype| : buffer filetype. Empty string if no filetype is set;
- |modified| : True if the buffer has unsaved changes, False otherwise;
- |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
- |vars|: dict for buffer-local variables
- |omnifunc| : omni completion function used by the buffer. Must be a Python
function that takes the same arguments and returns the same
values as a Vim completion function (:h complete-functions).
Example:
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'c' ]"""
def __init__( self, name,
number = 1,
contents = [ '' ],
filetype = '',
modified = False,
bufhidden = '',
omnifunc = None,
visual_start = None,
visual_end = None,
vars = {} ):
self.name = os.path.realpath( name ) if name else ''
self.number = number
self.contents = contents
self.filetype = filetype
self.modified = modified
self.bufhidden = bufhidden
self.omnifunc = omnifunc
self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
self.changedtick = 1
self.options = {
'mod': modified,
'bh': bufhidden
}
self.visual_start = visual_start
self.visual_end = visual_end
self.vars = vars # should really be a vim-specific dict-like obj
def __getitem__( self, index ):
"""Returns the bytes for a given line at index |index|."""
return self.contents[ index ]
def __len__( self ):
return len( self.contents )
def __setitem__( self, key, value ):
return self.contents.__setitem__( key, value )
def GetLines( self ):
"""Returns the contents of the buffer as a list of unicode strings."""
return [ ToUnicode( x ) for x in self.contents ]
def mark( self, name ):
if name == '<':
return self.visual_start
if name == '>':
return self.visual_end
raise ValueError( f'Unexpected mark: { name }' )
def __repr__( self ):
return f"VimBuffer( name = '{ self.name }', number = { self.number } )"
class VimBuffers:
"""An object that looks like a vim.buffers object."""
def __init__( self, buffers ):
"""|buffers| is a list of VimBuffer objects."""
self._buffers = buffers
def __getitem__( self, number ):
"""Emulates vim.buffers[ number ]"""
for buffer_object in self._buffers:
if number == buffer_object.number:
return buffer_object
raise KeyError( number )
def __iter__( self ):
"""Emulates for loop on vim.buffers"""
return iter( self._buffers )
def pop( self, index ):
return self._buffers.pop( index )
class VimTabpages:
def __init__( self, *args ):
"""|buffers| is a list of VimBuffer objects."""
self._tabpages = []
self._tabpages.extend( args )
def __getitem__( self, number ):
"""Emulates vim.buffers[ number ]"""
for tabpage in self._tabpages:
if number == tabpage.number:
return tabpage
raise KeyError( number )
def __iter__( self ):
"""Emulates for loop on vim.buffers"""
return iter( self._tabpages )
class VimWindow:
"""An object that looks like a vim.window object:
- |number|: number of the window;
- |buffer_object|: a VimBuffer object representing the buffer inside the
window;
- |cursor|: a tuple corresponding to the cursor position."""
def __init__( self, tabpage, number, buffer_object, cursor = None ):
self.tabpage = tabpage
self.number = number
self.buffer = buffer_object
self.cursor = cursor
self.options = {}
self.vars = {}
def __repr__( self ):
return ( f'VimWindow( number = { self.number }, '
f'buffer = { self.buffer }, '
f'cursor = { self.cursor } )' )
class VimTabpage:
"""An object that looks like a vim.windows object."""
def __init__( self, number, buffers, cursor ):
"""|buffers| is a list of VimBuffer objects corresponding to the window
layout. The first element of that list is assumed to be the current window.
|cursor| is the cursor position of that window."""
self.number = number
self.windows = []
self.windows.append( VimWindow( self, 1, buffers[ 0 ], cursor ) )
for window_number in range( 1, len( buffers ) ):
self.windows.append( VimWindow( self,
window_number + 1,
buffers[ window_number ] ) )
def __getitem__( self, number ):
"""Emulates vim.windows[ number ]"""
try:
return self.windows[ number ]
except IndexError:
raise IndexError( 'no such window' )
def __iter__( self ):
"""Emulates for loop on vim.windows"""
return iter( self.windows )
class VimCurrent:
"""An object that looks like a vim.current object. |current_window| must be a
VimWindow object."""
def __init__( self, current_window ):
self.buffer = current_window.buffer
self.window = current_window
self.tabpage = current_window.tabpage
self.line = self.buffer.contents[ current_window.cursor[ 0 ] - 1 ]
class VimProp:
def __init__( self,
prop_type,
start_line,
start_column,
end_line,
end_column ):
current_buffer = VIM_MOCK.current.buffer.number
self.id = len( VIM_PROPS_FOR_BUFFER[ current_buffer ] ) + 1
self.prop_type = prop_type
self.start_line = start_line
self.start_column = start_column
self.end_line = end_line if end_line else start_line
self.end_column = end_column if end_column else start_column
def __eq__( self, other ):
return ( self.prop_type == other.prop_type and
self.start_line == other.start_line and
self.start_column == other.start_column and
self.end_line == other.end_line and
self.end_column == other.end_column )
def __repr__( self ):
return ( f"VimProp( prop_type = '{ self.prop_type }',"
f" start_line = { self.start_line }, "
f" start_column = { self.start_column },"
f" end_line = { self.end_line },"
f" end_column = { self.end_column } )" )
def __getitem__( self, key ):
if key == 'type':
return self.prop_type
elif key == 'id':
return self.id
elif key == 'col':
return self.start_column
elif key == 'length':
return self.end_column - self.start_column
elif key == 'lnum':
return self.start_line
def get( self, key, default = None ):
if key == 'type':
return self.prop_type
class VimSign:
def __init__( self, line, name, bufnr ):
self.line = line
self.name = name
self.bufnr = bufnr
def __eq__( self, other ):
if isinstance( other, dict ):
other = VimSign( other[ 'lnum' ], other[ 'name' ], other[ 'buffer' ] )
return ( self.line == other.line and
self.name == other.name and
self.bufnr == other.bufnr )
def __repr__( self ):
return ( f"VimSign( line = { self.line }, "
f"name = '{ self.name }', bufnr = { self.bufnr } )" )
def __getitem__( self, key ):
if key == 'group':
return self.group
@contextlib.contextmanager
def MockVimBuffers( buffers, window_buffers, cursor_position = ( 1, 1 ) ):
"""Simulates the Vim buffers list |buffers| where |current_buffer| is the
buffer displayed in the current window and |cursor_position| is the current
cursor position. All buffers are represented by a VimBuffer object."""
if ( not isinstance( buffers, list ) or
not all( isinstance( buf, VimBuffer ) for buf in buffers ) ):
raise RuntimeError( 'First parameter must be a list of VimBuffer objects.' )
if ( not isinstance( window_buffers, list ) or
not all( isinstance( buf, VimBuffer ) for buf in window_buffers ) ):
raise RuntimeError( 'Second parameter must be a list of VimBuffer objects '
'representing the window layout.' )
if len( window_buffers ) < 1:
raise RuntimeError( 'Second parameter must contain at least one element '
'which corresponds to the current window.' )
with patch( 'vim.buffers', VimBuffers( buffers ) ):
with patch( 'vim.tabpages', VimTabpages(
VimTabpage( 1, window_buffers, cursor_position ) ) ) as tabpages:
with patch( 'vim.windows', tabpages[ 1 ] ) as windows:
with patch( 'vim.current', VimCurrent( windows[ 0 ] ) ):
yield VIM_MOCK
def MockVimModule():
"""The 'vim' module is something that is only present when running inside the
Vim Python interpreter, so we replace it with a MagicMock for tests. If you
need to add additional mocks to vim module functions, then use 'patch' from
mock module, to ensure that the state of the vim mock is returned before the
next test. That is:
from ycm.tests.test_utils import MockVimModule
from unittest.mock import patch
# Do this once
MockVimModule()
@patch( 'vim.eval', return_value='test' )
@patch( 'vim.command', side_effect=ValueError )
def test( vim_command, vim_eval ):
# use vim.command via vim_command, e.g.:
vim_command.assert_has_calls( ... )
Failure to use this approach may lead to unexpected failures in other
tests."""
VIM_MOCK.command = MagicMock( side_effect = _MockVimCommand )
VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
VIM_MOCK.error = VimError
VIM_MOCK.options = MagicMock()
VIM_MOCK.options.__getitem__.side_effect = _MockVimOptions
sys.modules[ 'vim' ] = VIM_MOCK
return VIM_MOCK
class VimError( Exception ):
def __init__( self, code ):
self.code = code
def __str__( self ):
return repr( self.code )
class ExtendedMock( MagicMock ):
"""An extension to the MagicMock class which adds the ability to check that a
callable is called with a precise set of calls in a precise order.
Example Usage:
from ycm.tests.test_utils import ExtendedMock
@patch( 'test.testing', new_callable = ExtendedMock, ... )
def my_test( test_testing ):
...
"""
def assert_has_exact_calls( self, calls, any_order = False ):
contains = contains_inanyorder if any_order else contains_exactly
assert_that( self.call_args_list, contains( *calls ) )
assert_that( self.call_count, equal_to( len( calls ) ) )
def ExpectedFailure( reason, *exception_matchers ):
"""Defines a decorator to be attached to tests. This decorator
marks the test as being known to fail, e.g. where documenting or exercising
known incorrect behaviour.
The parameters are:
- |reason| a textual description of the reason for the known issue. This
is used for the skip reason
- |exception_matchers| additional arguments are hamcrest matchers to apply
to the exception thrown. If the matchers don't match, then the
test is marked as error, with the original exception.
If the test fails (for the correct reason), then it is marked as skipped.
If it fails for any other reason, it is marked as failed.
If the test passes, then it is also marked as failed."""
def decorator( test ):
@functools.wraps( test )
def Wrapper( *args, **kwargs ):
try:
test( *args, **kwargs )
except Exception as test_exception:
# Ensure that we failed for the right reason
test_exception_message = ToUnicode( test_exception )
try:
for matcher in exception_matchers:
assert_that( test_exception_message, matcher )
except AssertionError:
# Failed for the wrong reason!
import traceback
print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
# Real failure reason is the *original* exception, we're only trapping
# and ignoring the exception that is expected.
raise test_exception
# Failed for the right reason
skip( reason )
else:
raise AssertionError( f'Test was expected to fail: { reason }' )
return Wrapper
return decorator
| 24,374
|
Python
|
.py
| 611
| 33.806874
| 80
| 0.631443
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,966
|
youcompleteme_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/youcompleteme_test.py
|
# Copyright (C) 2016-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.client.messages_request import MessagesPoll
from ycm.tests.test_utils import ( ExtendedMock,
MockVimBuffers,
MockVimModule,
Version,
VimBuffer,
VimProp,
VimSign )
MockVimModule()
import vim
import os
import sys
from hamcrest import ( assert_that, contains_exactly, empty, equal_to,
has_entries, is_in, is_not, matches_regexp )
from unittest.mock import call, MagicMock, patch
from unittest import TestCase
from ycm.paths import _PathToPythonUsedDuringBuild
from ycm.vimsupport import SetVariableValue
from ycm.tests import ( StopServer,
test_utils,
UserOptions,
WaitUntilReady,
YouCompleteMeInstance )
from ycm.client.base_request import _LoadExtraConfFile
from ycm.youcompleteme import YouCompleteMe
from ycmd.responses import ServerError
from ycm.tests.mock_utils import ( MockAsyncServerResponseDone,
MockAsyncServerResponseInProgress,
MockAsyncServerResponseException )
def RunNotifyUserIfServerCrashed( ycm, post_vim_message, test ):
StopServer( ycm )
ycm._logger = MagicMock( autospec = True )
ycm._server_popen = MagicMock( autospec = True )
ycm._server_popen.poll.return_value = test[ 'return_code' ]
ycm.OnFileReadyToParse()
assert_that( ycm._logger.error.call_args[ 0 ][ 0 ],
test[ 'expected_message' ] )
assert_that( post_vim_message.call_args[ 0 ][ 0 ],
test[ 'expected_message' ] )
def YouCompleteMe_UpdateDiagnosticInterface( ycm, post_vim_message, *args ):
contents = "\nint main() { int x, y; x == y }"
# List of diagnostics returned by ycmd for the above code.
diagnostics = [ {
'kind': 'ERROR',
'text': "expected ';' after expression (fix available) "
"[expected_semi_after_expr]",
'location': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 31
},
'location_extent': {
'start': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 31,
},
'end': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 32,
}
},
'ranges': [ {
'start': {
'line_num': 2,
'column_num': 31,
'filepath': 'buffer'
},
'end': {
'line_num': 2,
'column_num': 31,
'filepath': 'buffer'
}
} ],
'fixit_available': False
}, {
'kind': 'WARNING',
'text': 'equality comparison result unused',
'location': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 31,
},
'location_extent': {
'start': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 31,
},
'end': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 32,
}
},
'ranges': [ {
'start': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 24,
},
'end': {
'filepath': 'buffer',
'line_num': 2,
'column_num': 30,
}
} ],
'fixit_available': False
} ]
current_buffer = VimBuffer( 'buffer',
filetype = 'c',
contents = contents.splitlines(),
number = 5 )
test_utils.VIM_SIGNS = []
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 2, 1 ) ):
with patch( 'ycm.client.event_notification.EventNotification.Response',
return_value = diagnostics ):
ycm.OnFileReadyToParse()
ycm.HandleFileParseRequest( block = True )
# The error on the current line is echoed, not the warning.
post_vim_message.assert_called_once_with(
"expected ';' after expression (fix available) "
"[expected_semi_after_expr]",
truncate = True, warning = False )
# Error match is added after warning matches.
assert_that(
test_utils.VIM_PROPS_FOR_BUFFER,
has_entries( {
current_buffer.number: contains_exactly(
VimProp( 'YcmWarningProperty', 2, 31, 2, 32 ),
VimProp( 'YcmWarningProperty', 2, 24, 2, 30 ),
VimProp( 'YcmErrorProperty', 2, 31, 2, 32 ),
VimProp( 'YcmErrorProperty', 2, 31, 2, 31 ),
)
} )
)
# Only the error sign is placed.
assert_that(
test_utils.VIM_SIGNS,
contains_exactly(
VimSign( 2, 'YcmError', 5 )
)
)
# The error is not echoed again when moving the cursor along the line.
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 2, 2 ) ):
post_vim_message.reset_mock()
ycm.OnCursorMoved()
post_vim_message.assert_not_called()
# The error is cleared when moving the cursor to another line.
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 2 ) ):
post_vim_message.reset_mock()
ycm.OnCursorMoved()
post_vim_message.assert_called_once_with( "", warning = False )
# The error is echoed when moving the cursor back.
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 2, 2 ) ):
post_vim_message.reset_mock()
ycm.OnCursorMoved()
post_vim_message.assert_called_once_with(
"expected ';' after expression (fix available) "
"[expected_semi_after_expr]",
truncate = True, warning = False )
with patch( 'ycm.client.event_notification.EventNotification.Response',
return_value = diagnostics[ 1 : ] ):
ycm.OnFileReadyToParse()
ycm.HandleFileParseRequest( block = True )
assert_that(
test_utils.VIM_PROPS_FOR_BUFFER,
has_entries( {
current_buffer.number: contains_exactly(
VimProp( 'YcmWarningProperty', 2, 31, 2, 32 ),
VimProp( 'YcmWarningProperty', 2, 24, 2, 30 )
)
} )
)
assert_that(
test_utils.VIM_SIGNS,
contains_exactly(
VimSign( 2, 'YcmWarning', 5 )
)
)
class YouCompleteMeTest( TestCase ):
@YouCompleteMeInstance()
def test_YouCompleteMe_YcmCoreNotImported( self, ycm ):
assert_that( 'ycm_core', is_not( is_in( sys.modules ) ) )
@patch( 'ycm.vimsupport.PostVimMessage' )
def test_YouCompleteMe_InvalidPythonInterpreterPath( self, post_vim_message ):
with UserOptions( {
'g:ycm_server_python_interpreter': '/invalid/python/path' } ):
try:
ycm = YouCompleteMe()
assert_that( ycm.IsServerAlive(), equal_to( False ) )
post_vim_message.assert_called_once_with(
"Unable to start the ycmd server. "
"Path in 'g:ycm_server_python_interpreter' option does not point "
"to a valid Python 3.6+. "
"Correct the error then restart the server with "
"':YcmRestartServer'." )
post_vim_message.reset_mock()
SetVariableValue( 'g:ycm_server_python_interpreter',
_PathToPythonUsedDuringBuild() )
ycm.RestartServer()
assert_that( ycm.IsServerAlive(), equal_to( True ) )
post_vim_message.assert_called_once_with( 'Restarting ycmd server...' )
finally:
WaitUntilReady()
StopServer( ycm )
@patch( 'ycmd.utils.PathToFirstExistingExecutable', return_value = None )
@patch( 'ycm.paths._EndsWithPython', return_value = False )
@patch( 'ycm.vimsupport.PostVimMessage' )
def test_YouCompleteMe_NoPythonInterpreterFound(
self, post_vim_message, *args ):
with UserOptions( {} ):
try:
with patch( 'ycmd.utils.ReadFile', side_effect = IOError ):
ycm = YouCompleteMe()
assert_that( ycm.IsServerAlive(), equal_to( False ) )
post_vim_message.assert_called_once_with(
"Unable to start the ycmd server. Cannot find Python 3.6+. "
"Set the 'g:ycm_server_python_interpreter' option to a Python "
"interpreter path. "
"Correct the error then restart the server with "
"':YcmRestartServer'." )
post_vim_message.reset_mock()
SetVariableValue( 'g:ycm_server_python_interpreter',
_PathToPythonUsedDuringBuild() )
ycm.RestartServer()
assert_that( ycm.IsServerAlive(), equal_to( True ) )
post_vim_message.assert_called_once_with( 'Restarting ycmd server...' )
finally:
WaitUntilReady()
StopServer( ycm )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_NotifyUserIfServerCrashed_UnexpectedCore(
self, ycm, post_vim_message ):
message = (
"The ycmd server SHUT DOWN \\(restart with ':YcmRestartServer'\\). "
"Unexpected error while loading the YCM core library. Type "
"':YcmToggleLogs ycmd_\\d+_stderr_.+.log' to check the logs." )
RunNotifyUserIfServerCrashed( ycm, post_vim_message, {
'return_code': 3,
'expected_message': matches_regexp( message )
} )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_NotifyUserIfServerCrashed_MissingCore(
self, ycm, post_vim_message ):
message = ( "The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). "
"YCM core library not detected; you need to compile YCM before "
"using it. Follow the instructions in the documentation." )
RunNotifyUserIfServerCrashed( ycm, post_vim_message, {
'return_code': 4,
'expected_message': equal_to( message )
} )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_NotifyUserIfServerCrashed_OutdatedCore(
self, ycm, post_vim_message ):
message = ( "The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). "
"YCM core library too old; PLEASE RECOMPILE by running the "
"install.py script. See the documentation for more details." )
RunNotifyUserIfServerCrashed( ycm, post_vim_message, {
'return_code': 7,
'expected_message': equal_to( message )
} )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_NotifyUserIfServerCrashed_UnexpectedExitCode(
self, ycm, post_vim_message ):
message = (
"The ycmd server SHUT DOWN \\(restart with ':YcmRestartServer'\\). "
"Unexpected exit code 1. Type "
"':YcmToggleLogs ycmd_\\d+_stderr_.+.log' to check the logs." )
RunNotifyUserIfServerCrashed( ycm, post_vim_message, {
'return_code': 1,
'expected_message': matches_regexp( message )
} )
@YouCompleteMeInstance( { 'g:ycm_extra_conf_vim_data': [ 'tempname()' ] } )
@patch( 'ycm.vimsupport.VimSupportsPopupWindows', return_value=True )
def test_YouCompleteMe_DebugInfo_ServerRunning( self, ycm, *args ):
dir_of_script = os.path.dirname( os.path.abspath( __file__ ) )
buf_name = os.path.join( dir_of_script, 'testdata', 'test.cpp' )
extra_conf = os.path.join( dir_of_script, 'testdata', '.ycm_extra_conf.py' )
_LoadExtraConfFile( extra_conf )
current_buffer = VimBuffer( buf_name, filetype = 'cpp' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that(
ycm.DebugInfo(),
matches_regexp(
'Client logfile: .+\n'
'Server Python interpreter: .+\n'
'Server Python version: .+\n'
'Server has Clang support compiled in: (False|True)\n'
'Clang version: .+\n'
'Extra configuration file found and loaded\n'
'Extra configuration path: .*testdata[/\\\\]\\.ycm_extra_conf\\.py\n'
'[\\w\\W]*'
'Server running at: .+\n'
'Server process ID: \\d+\n'
'Server logfiles:\n'
' .+\n'
' .+' )
)
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.VimSupportsPopupWindows', return_value=True )
def test_YouCompleteMe_DebugInfo_ServerNotRunning( self, ycm, *args ):
StopServer( ycm )
current_buffer = VimBuffer( 'current_buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that(
ycm.DebugInfo(),
matches_regexp(
'Client logfile: .+\n'
'Server errored, no debug info from server\n'
'Server running at: .+\n'
'Server process ID: \\d+\n'
'Server logfiles:\n'
' .+\n'
' .+' )
)
@YouCompleteMeInstance()
def test_YouCompleteMe_OnVimLeave_RemoveClientLogfileByDefault( self, ycm ):
client_logfile = ycm._client_logfile
assert_that( os.path.isfile( client_logfile ),
f'Logfile { client_logfile } does not exist.' )
ycm.OnVimLeave()
assert_that( not os.path.isfile( client_logfile ),
f'Logfile { client_logfile } was not removed.' )
@YouCompleteMeInstance( { 'g:ycm_keep_logfiles': 1 } )
def test_YouCompleteMe_OnVimLeave_KeepClientLogfile( self, ycm ):
client_logfile = ycm._client_logfile
assert_that( os.path.isfile( client_logfile ),
f'Logfile { client_logfile } does not exist.' )
ycm.OnVimLeave()
assert_that( os.path.isfile( client_logfile ),
f'Logfile { client_logfile } was removed.' )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.CloseBuffersForFilename',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename', new_callable = ExtendedMock )
def test_YouCompleteMe_ToggleLogs_WithParameters(
self, ycm, open_filename, close_buffers_for_filename ):
logfile_buffer = VimBuffer( ycm._client_logfile )
with MockVimBuffers( [ logfile_buffer ], [ logfile_buffer ] ):
ycm.ToggleLogs( 90,
'botright vertical',
os.path.basename( ycm._client_logfile ),
'nonexisting_logfile',
os.path.basename( ycm._server_stdout ) )
open_filename.assert_has_exact_calls( [
call( ycm._server_stdout, { 'size': 90,
'watch': True,
'fix': True,
'focus': False,
'position': 'end',
'mods': 'botright vertical' } )
] )
close_buffers_for_filename.assert_has_exact_calls( [
call( ycm._client_logfile )
] )
@YouCompleteMeInstance()
# Select the second item of the list which is the ycmd stderr logfile.
@patch( 'ycm.vimsupport.SelectFromList', return_value = 1 )
@patch( 'ycm.vimsupport.OpenFilename', new_callable = ExtendedMock )
def test_YouCompleteMe_ToggleLogs_WithoutParameters_SelectLogfileNotAlreadyOpen( # noqa
self, ycm, open_filename, *args ):
current_buffer = VimBuffer( 'current_buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
ycm.ToggleLogs( 0, '' )
open_filename.assert_has_exact_calls( [
call( ycm._server_stderr, { 'size': 12,
'watch': True,
'fix': True,
'focus': False,
'position': 'end',
'mods': '' } )
] )
@YouCompleteMeInstance()
# Select the third item of the list which is the ycmd stdout logfile.
@patch( 'ycm.vimsupport.SelectFromList', return_value = 2 )
@patch( 'ycm.vimsupport.CloseBuffersForFilename',
new_callable = ExtendedMock )
def test_YouCompleteMe_ToggleLogs_WithoutParameters_SelectLogfileAlreadyOpen(
self, ycm, close_buffers_for_filename, *args ):
logfile_buffer = VimBuffer( ycm._server_stdout )
with MockVimBuffers( [ logfile_buffer ], [ logfile_buffer ] ):
ycm.ToggleLogs( 0, '' )
close_buffers_for_filename.assert_has_exact_calls( [
call( ycm._server_stdout )
] )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.SelectFromList',
side_effect = RuntimeError( 'Error message' ) )
@patch( 'ycm.vimsupport.PostVimMessage' )
def test_YouCompleteMe_ToggleLogs_WithoutParameters_NoSelection(
self, ycm, post_vim_message, *args ):
current_buffer = VimBuffer( 'current_buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
ycm.ToggleLogs( 0, '' )
assert_that(
# Argument passed to PostVimMessage.
post_vim_message.call_args[ 0 ][ 0 ],
equal_to( 'Error message' )
)
@YouCompleteMeInstance()
def test_YouCompleteMe_GetDefinedSubcommands_ListFromServer( self, ycm ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.client.base_request._JsonFromFuture',
return_value = [ 'SomeCommand', 'AnotherCommand' ] ):
assert_that(
ycm.GetDefinedSubcommands(),
contains_exactly(
'SomeCommand',
'AnotherCommand'
)
)
@YouCompleteMeInstance()
@patch( 'ycm.client.base_request._logger', autospec = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_GetDefinedSubcommands_ErrorFromServer(
self, ycm, post_vim_message, logger ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.client.base_request._JsonFromFuture',
side_effect = ServerError( 'Server error' ) ):
result = ycm.GetDefinedSubcommands()
logger.exception.assert_called_with(
'Error while handling server response' )
post_vim_message.assert_has_exact_calls( [
call( 'Server error', truncate = False )
] )
assert_that( result, empty() )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_ShowDetailedDiagnostic_MessageFromServer(
self, ycm, post_vim_message ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.client.base_request._JsonFromFuture',
return_value = { 'message': 'some_detailed_diagnostic' } ):
ycm.ShowDetailedDiagnostic( False ),
post_vim_message.assert_has_exact_calls( [
call( 'some_detailed_diagnostic', warning = False )
] )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_ShowDetailedDiagnostic_Exception(
self, ycm, post_vim_message ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.client.base_request._JsonFromFuture',
side_effect = RuntimeError( 'Some exception' ) ):
ycm.ShowDetailedDiagnostic( False ),
post_vim_message.assert_has_exact_calls( [
call( 'Some exception', truncate = False )
] )
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_ShowDiagnostics_FiletypeNotSupported(
self, ycm, post_vim_message ):
current_buffer = VimBuffer( 'buffer', filetype = 'not_supported' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
ycm.ShowDiagnostics()
post_vim_message.assert_called_once_with(
'Native filetype completion not supported for current file, '
'cannot force recompilation.', warning = False )
@YouCompleteMeInstance()
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.SetLocationListForWindow',
new_callable = ExtendedMock )
def test_YouCompleteMe_ShowDiagnostics_NoDiagnosticsDetected(
self,
ycm,
set_location_list_for_window,
post_vim_message,
*args ):
current_buffer = VimBuffer( 'buffer', filetype = 'cpp' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.client.event_notification.EventNotification.Response',
return_value = {} ):
ycm.ShowDiagnostics()
set_location_list_for_window.assert_called_once_with(
vim.current.window,
[],
1 )
post_vim_message.assert_has_exact_calls( [
call( 'Forcing compilation, this will block Vim until done.',
warning = False ),
call( 'Diagnostics refreshed', warning = False ),
call( 'No warnings or errors detected.', warning = False )
] )
@YouCompleteMeInstance( { 'g:ycm_log_level': 'debug',
'g:ycm_keep_logfiles': 1,
'g:ycm_open_loclist_on_ycm_diags': 0 } )
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.SetLocationListForWindow',
new_callable = ExtendedMock )
def test_YouCompleteMe_ShowDiagnostics_DiagnosticsFound_DoNotOpenLocationList(
self,
ycm,
set_location_list_for_window,
post_vim_message,
*args ):
diagnostic = {
'kind': 'ERROR',
'text': 'error text',
'location': {
'filepath': 'buffer',
'line_num': 19,
'column_num': 2
},
'location_extent': {
'start': {
'filepath': 'buffer',
'line_num': 19,
'column_num': 2
},
'end': {
'filepath': 'buffer',
'line_num': 19,
'column_num': 3
}
}
}
current_buffer = VimBuffer( 'buffer',
filetype = 'cpp',
number = 3 )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.client.event_notification.EventNotification.Response',
return_value = [ diagnostic ] ):
ycm.ShowDiagnostics()
set_location_list_for_window.assert_called_once_with(
vim.current.window, [ {
'bufnr': 3,
'lnum': 19,
'col': 2,
'text': 'error text',
'type': 'E',
'valid': 1
} ], 0 )
post_vim_message.assert_has_exact_calls( [
call( 'Forcing compilation, this will block Vim until done.',
warning = False ),
call( 'Diagnostics refreshed', warning = False )
] )
@YouCompleteMeInstance( { 'g:ycm_open_loclist_on_ycm_diags': 1 } )
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.SetLocationListForWindow',
new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenLocationList', new_callable = ExtendedMock )
def test_YouCompleteMe_ShowDiagnostics_DiagnosticsFound_OpenLocationList(
self,
ycm,
open_location_list,
set_location_list_for_window,
post_vim_message,
*args ):
diagnostic = {
'kind': 'ERROR',
'text': 'error text',
'location': {
'filepath': 'buffer',
'line_num': 19,
'column_num': 2
},
'location_extent': {
'start': {
'filepath': 'buffer',
'line_num': 19,
'column_num': 2
},
'end': {
'filepath': 'buffer',
'line_num': 19,
'column_num': 2
}
}
}
current_buffer = VimBuffer( 'buffer',
filetype = 'cpp',
number = 3 )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.client.event_notification.EventNotification.Response',
return_value = [ diagnostic ] ):
ycm.ShowDiagnostics()
set_location_list_for_window.assert_called_once_with(
vim.current.window, [ {
'bufnr': 3,
'lnum': 19,
'col': 2,
'text': 'error text',
'type': 'E',
'valid': 1
} ], 1 )
post_vim_message.assert_has_exact_calls( [
call( 'Forcing compilation, this will block Vim until done.',
warning = False ),
call( 'Diagnostics refreshed', warning = False )
] )
open_location_list.assert_called_once_with( focus = True )
@YouCompleteMeInstance( { 'g:ycm_echo_current_diagnostic': 1,
'g:ycm_enable_diagnostic_signs': 1,
'g:ycm_enable_diagnostic_highlighting': 1 } )
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.client.event_notification.EventNotification.Done',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_UpdateDiagnosticInterface_OldVim(
self, ycm, post_vim_message, *args ):
YouCompleteMe_UpdateDiagnosticInterface( ycm, post_vim_message )
@YouCompleteMeInstance( { 'g:ycm_echo_current_diagnostic': 1,
'g:ycm_enable_diagnostic_signs': 1,
'g:ycm_enable_diagnostic_highlighting': 1 } )
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.tests.test_utils.VIM_VERSION', Version( 8, 1, 614 ) )
@patch( 'ycm.client.event_notification.EventNotification.Done',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_UpdateDiagnosticInterface_NewVim(
self, ycm, post_vim_message, *args ):
YouCompleteMe_UpdateDiagnosticInterface( ycm, post_vim_message )
@YouCompleteMeInstance( { 'g:ycm_enable_diagnostic_highlighting': 1 } )
def test_YouCompleteMe_UpdateMatches_ClearDiagnosticMatchesInNewBuffer(
self, ycm ):
current_buffer = VimBuffer( 'buffer',
filetype = 'c',
contents = '\n\n\n\n',
number = 5 )
test_utils.VIM_PROPS_FOR_BUFFER[ current_buffer.number ] = [
VimProp( 'YcmWarningProperty', 3, 5, 3, 7 ),
VimProp( 'YcmWarningProperty', 3, 3, 3, 9 ),
VimProp( 'YcmErrorProperty', 3, 8, 3, 9 )
]
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
ycm.UpdateMatches()
assert_that( test_utils.VIM_PROPS_FOR_BUFFER[ current_buffer.number ],
empty() )
@YouCompleteMeInstance( { 'g:ycm_echo_current_diagnostic': 1,
'g:ycm_always_populate_location_list': 1,
'g:ycm_show_diagnostics_ui': 0,
'g:ycm_enable_diagnostic_highlighting': 1 } )
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_AsyncDiagnosticUpdate_UserDisabled(
self,
ycm,
post_vim_message,
*args ):
diagnostics = [
{
'kind': 'ERROR',
'text': 'error text in current buffer',
'location': {
'filepath': '/current',
'line_num': 1,
'column_num': 1
},
'location_extent': {
'start': {
'filepath': '/current',
'line_num': 1,
'column_num': 1,
},
'end': {
'filepath': '/current',
'line_num': 1,
'column_num': 1,
}
},
'ranges': []
},
]
current_buffer = VimBuffer( '/current',
filetype = 'ycmtest',
contents = [ 'current' ] * 10,
number = 1 )
buffers = [ current_buffer ]
windows = [ current_buffer ]
# Register each buffer internally with YCM
for current in buffers:
with MockVimBuffers( buffers, [ current ] ):
ycm.OnFileReadyToParse()
with patch( 'ycm.vimsupport.SetLocationListForWindow',
new_callable = ExtendedMock ) as set_location_list_for_window:
with MockVimBuffers( buffers, windows ):
ycm.UpdateWithNewDiagnosticsForFile( '/current', diagnostics )
post_vim_message.assert_has_exact_calls( [] )
set_location_list_for_window.assert_has_exact_calls( [] )
assert_that(
test_utils.VIM_PROPS_FOR_BUFFER,
empty()
)
@YouCompleteMeInstance( { 'g:ycm_echo_current_diagnostic': 1,
'g:ycm_always_populate_location_list': 1,
'g:ycm_enable_diagnostic_highlighting': 1 } )
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_AsyncDiagnosticUpdate_SingleFile(
self,
ycm,
post_vim_message,
*args ):
# This test simulates asynchronous diagnostic updates associated with a
# single file (e.g. Translation Unit), but where the actual errors refer to
# other open files and other non-open files. This is not strictly invalid,
# nor is it completely normal, but it is supported and does work.
# Contrast with the next test which sends the diagnostics filewise, which
# is what the language server protocol will do.
diagnostics = [
{
'kind': 'ERROR',
'text': 'error text in current buffer',
'location': {
'filepath': '/current',
'line_num': 1,
'column_num': 1
},
'location_extent': {
'start': {
'filepath': '/current',
'line_num': 1,
'column_num': 1,
},
'end': {
'filepath': '/current',
'line_num': 1,
'column_num': 1,
}
},
'ranges': []
},
{
'kind': 'ERROR',
'text': 'error text in hidden buffer',
'location': {
'filepath': '/has_diags',
'line_num': 4,
'column_num': 2
},
'location_extent': {
'start': {
'filepath': '/has_diags',
'line_num': 4,
'column_num': 2,
},
'end': {
'filepath': '/has_diags',
'line_num': 4,
'column_num': 2,
}
},
'ranges': []
},
{
'kind': 'ERROR',
'text': 'error text in buffer not open in Vim',
'location': {
'filepath': '/not_open',
'line_num': 8,
'column_num': 4
},
'location_extent': {
'start': {
'filepath': '/not_open',
'line_num': 8,
'column_num': 4,
},
'end': {
'filepath': '/not_open',
'line_num': 8,
'column_num': 4,
}
},
'ranges': []
}
]
current_buffer = VimBuffer( '/current',
filetype = 'ycmtest',
contents = [ 'current' ] * 10,
number = 1 )
no_diags_buffer = VimBuffer( '/no_diags',
filetype = 'ycmtest',
contents = [ 'nodiags' ] * 10,
number = 2 )
hidden_buffer = VimBuffer( '/has_diags',
filetype = 'ycmtest',
contents = [ 'hasdiags' ] * 10,
number = 3 )
buffers = [ current_buffer, no_diags_buffer, hidden_buffer ]
windows = [ current_buffer, no_diags_buffer ]
# Register each buffer internally with YCM
for current in buffers:
with MockVimBuffers( buffers, [ current ] ):
ycm.OnFileReadyToParse()
with patch( 'ycm.vimsupport.SetLocationListForWindow',
new_callable = ExtendedMock ) as set_location_list_for_window:
with MockVimBuffers( buffers, windows ):
ycm.UpdateWithNewDiagnosticsForFile( '/current', diagnostics )
# Ensure we included all the diags though
set_location_list_for_window.assert_has_exact_calls( [
call( vim.current.window, [
{
'lnum': 1,
'col': 1,
'bufnr': 1,
'valid': 1,
'type': 'E',
'text': 'error text in current buffer',
},
{
'lnum': 4,
'col': 2,
'bufnr': 3,
'valid': 1,
'type': 'E',
'text': 'error text in hidden buffer',
},
{
'lnum': 8,
'col': 4,
'bufnr': -1, # sic: Our mocked bufnr function actually returns -1,
# even though YCM is passing "create if needed".
# FIXME? we shouldn't do that, and we should pass
# filename instead
'valid': 1,
'type': 'E',
'text': 'error text in buffer not open in Vim'
}
], False )
] )
# We update the diagnostic on the current cursor position
post_vim_message.assert_has_exact_calls( [
call( "error text in current buffer", truncate = True, warning = False ),
] )
assert_that(
test_utils.VIM_PROPS_FOR_BUFFER,
has_entries( {
1: contains_exactly(
VimProp( 'YcmErrorProperty', 1, 1, 1, 1 )
)
} )
)
@YouCompleteMeInstance( { 'g:ycm_echo_current_diagnostic': 1,
'g:ycm_always_populate_location_list': 1,
'g:ycm_enable_diagnostic_highlighting': 1 } )
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_YouCompleteMe_AsyncDiagnosticUpdate_PerFile(
self,
ycm,
post_vim_message,
*args ):
# This test simulates asynchronous diagnostic updates which are delivered
# per file, including files which are open and files which are not.
# Ordered to ensure that the calls to update are deterministic
diagnostics_per_file = [
( '/current', [ {
'kind': 'ERROR',
'text': 'error text in current buffer',
'location': {
'filepath': '/current',
'line_num': 1,
'column_num': 1
},
'location_extent': {
'start': {
'filepath': '/current',
'line_num': 1,
'column_num': 1,
},
'end': {
'filepath': '/current',
'line_num': 1,
'column_num': 1,
}
},
'ranges': [],
} ] ),
( '/separate_window', [ {
'kind': 'ERROR',
'text': 'error text in a buffer open in a separate window',
'location': {
'filepath': '/separate_window',
'line_num': 3,
'column_num': 3
},
'location_extent': {
'start': {
'filepath': '/separate_window',
'line_num': 3,
'column_num': 3,
},
'end': {
'filepath': '/separate_window',
'line_num': 3,
'column_num': 3,
}
},
'ranges': []
} ] ),
( '/hidden', [ {
'kind': 'ERROR',
'text': 'error text in hidden buffer',
'location': {
'filepath': '/hidden',
'line_num': 4,
'column_num': 2
},
'location_extent': {
'start': {
'filepath': '/hidden',
'line_num': 4,
'column_num': 2,
},
'end': {
'filepath': '/hidden',
'line_num': 4,
'column_num': 2,
}
},
'ranges': []
} ] ),
( '/not_open', [ {
'kind': 'ERROR',
'text': 'error text in buffer not open in Vim',
'location': {
'filepath': '/not_open',
'line_num': 8,
'column_num': 4
},
'location_extent': {
'start': {
'filepath': '/not_open',
'line_num': 8,
'column_num': 4,
},
'end': {
'filepath': '/not_open',
'line_num': 8,
'column_num': 4,
}
},
'ranges': []
} ] )
]
current_buffer = VimBuffer( '/current',
filetype = 'ycmtest',
contents = [ 'current' ] * 10,
number = 1 )
no_diags_buffer = VimBuffer( '/no_diags',
filetype = 'ycmtest',
contents = [ 'no_diags' ] * 10,
number = 2 )
separate_window = VimBuffer( '/separate_window',
filetype = 'ycmtest',
contents = [ 'separate_window' ] * 10,
number = 3 )
hidden_buffer = VimBuffer( '/hidden',
filetype = 'ycmtest',
contents = [ 'hidden' ] * 10,
number = 4 )
buffers = [
current_buffer,
no_diags_buffer,
separate_window,
hidden_buffer
]
windows = [
current_buffer,
no_diags_buffer,
separate_window
]
# Register each buffer internally with YCM
for current in buffers:
with MockVimBuffers( buffers, [ current ] ):
ycm.OnFileReadyToParse()
with patch( 'ycm.vimsupport.SetLocationListForWindow',
new_callable = ExtendedMock ) as set_location_list_for_window:
with MockVimBuffers( buffers, windows ):
for filename, diagnostics in diagnostics_per_file:
ycm.UpdateWithNewDiagnosticsForFile( filename, diagnostics )
# Ensure we included all the diags though
set_location_list_for_window.assert_has_exact_calls( [
call( vim.windows[ 0 ], [
{
'lnum': 1,
'col': 1,
'bufnr': 1,
'valid': 1,
'type': 'E',
'text': 'error text in current buffer',
},
], False ),
call( vim.windows[ 2 ], [
{
'lnum': 3,
'col': 3,
'bufnr': 3,
'valid': 1,
'type': 'E',
'text': 'error text in a buffer open in a separate window',
},
], False )
] )
# We update the diagnostic on the current cursor position
post_vim_message.assert_has_exact_calls( [
call( "error text in current buffer", truncate = True, warning = False ),
] )
assert_that(
test_utils.VIM_PROPS_FOR_BUFFER,
has_entries( {
1: contains_exactly(
VimProp( 'YcmErrorProperty', 1, 1, 1, 1 )
),
3: contains_exactly(
VimProp( 'YcmErrorProperty', 3, 3, 3, 3 )
)
} )
)
@YouCompleteMeInstance()
def test_YouCompleteMe_OnPeriodicTick_ServerNotRunning( self, ycm ):
with patch.object( ycm, 'IsServerAlive', return_value = False ):
assert_that( ycm.OnPeriodicTick(), equal_to( False ) )
@YouCompleteMeInstance()
def test_YouCompleteMe_OnPeriodicTick_ServerNotReady( self, ycm ):
with patch.object( ycm, 'IsServerAlive', return_value = True ):
with patch.object( ycm, 'IsServerReady', return_value = False ):
assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
@YouCompleteMeInstance()
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.client.base_request._ValidateResponseObject',
return_value = True )
@patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
def test_YouCompleteMe_OnPeriodicTick_DontRetry(
self,
ycm,
post_data_to_handler_async,
*args ):
current_buffer = VimBuffer( '/current',
filetype = 'ycmtest',
number = 1 )
# Create the request and make the first poll; we expect no response
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ):
assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
post_data_to_handler_async.assert_called()
assert ycm._message_poll_requests[ 'ycmtest' ] is not None
post_data_to_handler_async.reset_mock()
# OK that sent the request, now poll to check if it is complete (say it is
# not)
with MockVimBuffers( [ current_buffer ],
[ current_buffer ],
( 1, 1 ) ) as v:
mock_response = MockAsyncServerResponseInProgress()
with patch.dict( ycm._message_poll_requests, {} ):
ycm._message_poll_requests[ 'ycmtest' ] = MessagesPoll(
v.current.buffer )
ycm._message_poll_requests[ 'ycmtest' ]._response_future = mock_response
mock_future = ycm._message_poll_requests[ 'ycmtest' ]._response_future
poll_again = ycm.OnPeriodicTick()
mock_future.done.assert_called()
mock_future.result.assert_not_called()
assert_that( poll_again, equal_to( True ) )
# Poll again, but return a response (telling us to stop polling)
with MockVimBuffers( [ current_buffer ],
[ current_buffer ],
( 1, 1 ) ) as v:
mock_response = MockAsyncServerResponseDone( False )
with patch.dict( ycm._message_poll_requests, {} ):
ycm._message_poll_requests[ 'ycmtest' ] = MessagesPoll(
v.current.buffer )
ycm._message_poll_requests[ 'ycmtest' ]._response_future = mock_response
mock_future = ycm._message_poll_requests[ 'ycmtest' ]._response_future
poll_again = ycm.OnPeriodicTick()
mock_future.done.assert_called()
mock_future.result.assert_called()
post_data_to_handler_async.assert_not_called()
# We reset and don't poll anymore
assert_that( ycm._message_poll_requests[ 'ycmtest' ] is None )
assert_that( poll_again, equal_to( False ) )
@YouCompleteMeInstance()
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.client.base_request._ValidateResponseObject',
return_value = True )
@patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
def test_YouCompleteMe_OnPeriodicTick_Exception(
self,
ycm,
post_data_to_handler_async,
*args ):
current_buffer = VimBuffer( '/current',
filetype = 'ycmtest',
number = 1 )
# Create the request and make the first poll; we expect no response
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ):
assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
post_data_to_handler_async.assert_called()
post_data_to_handler_async.reset_mock()
# Poll again, but return an exception response
with MockVimBuffers( [ current_buffer ],
[ current_buffer ],
( 1, 1 ) ) as v:
mock_response = MockAsyncServerResponseException(
RuntimeError( 'test' ) )
with patch.dict( ycm._message_poll_requests, {} ):
ycm._message_poll_requests[ 'ycmtest' ] = MessagesPoll(
v.current.buffer )
ycm._message_poll_requests[ 'ycmtest' ]._response_future = mock_response
mock_future = ycm._message_poll_requests[ 'ycmtest' ]._response_future
assert_that( ycm.OnPeriodicTick(), equal_to( False ) )
mock_future.done.assert_called()
mock_future.result.assert_called()
post_data_to_handler_async.assert_not_called()
# We reset and don't poll anymore
assert_that( ycm._message_poll_requests[ 'ycmtest' ] is None )
@YouCompleteMeInstance()
@patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = True )
@patch( 'ycm.client.base_request._ValidateResponseObject',
return_value = True )
@patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
@patch( 'ycm.client.messages_request._HandlePollResponse' )
def test_YouCompleteMe_OnPeriodicTick_ValidResponse(
self, ycm, handle_poll_response, post_data_to_handler_async, *args ):
current_buffer = VimBuffer( '/current',
filetype = 'ycmtest',
number = 1 )
# Create the request and make the first poll; we expect no response
with MockVimBuffers( [ current_buffer ],
[ current_buffer ],
( 1, 1 ) ):
assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
post_data_to_handler_async.assert_called()
post_data_to_handler_async.reset_mock()
# Poll again, and return a _proper_ response (finally!).
# Note, _HandlePollResponse is tested independently (for simplicity)
with MockVimBuffers( [ current_buffer ],
[ current_buffer ],
( 1, 1 ) ) as v:
mock_response = MockAsyncServerResponseDone( [] )
with patch.dict( ycm._message_poll_requests, {} ):
ycm._message_poll_requests[ 'ycmtest' ] = MessagesPoll(
v.current.buffer )
ycm._message_poll_requests[ 'ycmtest' ]._response_future = mock_response
mock_future = ycm._message_poll_requests[ 'ycmtest' ]._response_future
assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
handle_poll_response.assert_called()
mock_future.done.assert_called()
mock_future.result.assert_called()
post_data_to_handler_async.assert_called() # Poll again!
assert_that( ycm._message_poll_requests[ 'ycmtest' ] is not None )
@YouCompleteMeInstance()
@patch( 'ycm.client.completion_request.CompletionRequest.OnCompleteDone' )
def test_YouCompleteMe_OnCompleteDone_CompletionRequest(
self, ycm, on_complete_done ):
current_buffer = VimBuffer( 'current_buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ):
ycm.SendCompletionRequest()
ycm.OnCompleteDone()
on_complete_done.assert_called()
@YouCompleteMeInstance()
@patch( 'ycm.client.completion_request.CompletionRequest.OnCompleteDone' )
def test_YouCompleteMe_OnCompleteDone_NoCompletionRequest(
self, ycm, on_complete_done ):
ycm.OnCompleteDone()
on_complete_done.assert_not_called()
@YouCompleteMeInstance()
def test_YouCompleteMe_ShouldResendFileParseRequest_NoParseRequest(
self, ycm ):
current_buffer = VimBuffer( 'current_buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( ycm.ShouldResendFileParseRequest(), equal_to( False ) )
| 48,739
|
Python
|
.py
| 1,202
| 30.693012
| 89
| 0.582132
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,967
|
signature_help_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/signature_help_test.py
|
# Copyright (C) 2019 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from hamcrest import ( assert_that,
empty )
from unittest import TestCase
from ycm import signature_help as sh
class SignatureHelpTest( TestCase ):
def test_MakeSignatureHelpBuffer_Empty( self ):
assert_that( sh._MakeSignatureHelpBuffer( {} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'activeSignature': 0,
'activeParameter': 0,
'signatures': []
} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'activeSignature': 0,
'activeParameter': 0,
} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'signatures': []
} ), empty() )
| 1,372
|
Python
|
.py
| 35
| 35.571429
| 72
| 0.721139
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,968
|
base_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/base_test.py
|
# Copyright (C) 2013 Google Inc.
# 2020 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import contextlib
from hamcrest import assert_that, equal_to
from unittest import TestCase
from unittest.mock import patch
from ycm.tests.test_utils import MockVimModule
vim_mock = MockVimModule()
from ycm import base
@contextlib.contextmanager
def MockCurrentFiletypes( filetypes = [ '' ] ):
with patch( 'ycm.vimsupport.CurrentFiletypes', return_value = filetypes ):
yield
@contextlib.contextmanager
def MockCurrentColumnAndLineContents( column, line_contents ):
with patch( 'ycm.vimsupport.CurrentColumn', return_value = column ):
with patch( 'ycm.vimsupport.CurrentLineContents',
return_value = line_contents ):
yield
@contextlib.contextmanager
def MockTextAfterCursor( text ):
with patch( 'ycm.vimsupport.TextAfterCursor', return_value = text ):
yield
class BaseTest( TestCase ):
def test_AdjustCandidateInsertionText_Basic( self ):
with MockTextAfterCursor( 'bar' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_ParenInTextAfterCursor( self ):
with MockTextAfterCursor( 'bar(zoo' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_PlusInTextAfterCursor( self ):
with MockTextAfterCursor( 'bar+zoo' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_WhitespaceInTextAfterCursor( self ):
with MockTextAfterCursor( 'bar zoo' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_MoreThanWordMatchingAfterCursor( self ):
with MockTextAfterCursor( 'bar.h' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar.h' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar.h', 'abbr': '' } ] ) ) )
with MockTextAfterCursor( 'bar(zoo' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar(zoo' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar(zoo', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_NotSuffix( self ):
with MockTextAfterCursor( 'bar' ):
assert_that( [ { 'word': 'foofoo', 'abbr': 'foofoo' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foofoo', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_NothingAfterCursor( self ):
with MockTextAfterCursor( '' ):
assert_that( [ { 'word': 'foofoo', 'abbr': '' },
{ 'word': 'zobar', 'abbr': '' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foofoo', 'abbr': '' },
{ 'word': 'zobar', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_MultipleStrings( self ):
with MockTextAfterCursor( 'bar' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar' },
{ 'word': 'zo', 'abbr': 'zobar' },
{ 'word': 'q', 'abbr': 'qbar' },
{ 'word': '', 'abbr': 'bar' }, ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar', 'abbr': '' },
{ 'word': 'zobar', 'abbr': '' },
{ 'word': 'qbar', 'abbr': '' },
{ 'word': 'bar', 'abbr': '' } ] ) ) )
def test_AdjustCandidateInsertionText_DontTouchAbbr( self ):
with MockTextAfterCursor( 'bar' ):
assert_that( [ { 'word': 'foo', 'abbr': '1234' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar', 'abbr': '1234' } ] ) ) )
def test_AdjustCandidateInsertionText_NoAbbr( self ):
with MockTextAfterCursor( 'bar' ):
assert_that( [ { 'word': 'foo', 'abbr': 'foobar' } ],
equal_to( base.AdjustCandidateInsertionText( [
{ 'word': 'foobar' } ] ) ) )
def test_OverlapLength_Basic( self ):
assert_that( 3, equal_to( base.OverlapLength( 'foo bar', 'bar zoo' ) ) )
assert_that( 3, equal_to( base.OverlapLength( 'foobar', 'barzoo' ) ) )
def test_OverlapLength_BasicWithUnicode( self ):
assert_that( 3, equal_to( base.OverlapLength( 'bar fäö', 'fäö bar' ) ) )
assert_that( 3, equal_to( base.OverlapLength( 'zoofäö', 'fäözoo' ) ) )
def test_OverlapLength_OneCharOverlap( self ):
assert_that( 1, equal_to( base.OverlapLength( 'foo b', 'b zoo' ) ) )
def test_OverlapLength_SameStrings( self ):
assert_that( 6, equal_to( base.OverlapLength( 'foobar', 'foobar' ) ) )
def test_OverlapLength_Substring( self ):
assert_that( 6, equal_to( base.OverlapLength( 'foobar', 'foobarzoo' ) ) )
assert_that( 6, equal_to( base.OverlapLength( 'zoofoobar', 'foobar' ) ) )
def test_OverlapLength_LongestOverlap( self ):
assert_that( 7, equal_to( base.OverlapLength( 'bar foo foo',
'foo foo bar' ) ) )
def test_OverlapLength_EmptyInput( self ):
assert_that( 0, equal_to( base.OverlapLength( '', 'goobar' ) ) )
assert_that( 0, equal_to( base.OverlapLength( 'foobar', '' ) ) )
assert_that( 0, equal_to( base.OverlapLength( '', '' ) ) )
def test_OverlapLength_NoOverlap( self ):
assert_that( 0, equal_to( base.OverlapLength( 'foobar', 'goobar' ) ) )
assert_that( 0, equal_to( base.OverlapLength( 'foobar', '(^($@#$#@' ) ) )
assert_that( 0, equal_to( base.OverlapLength( 'foo bar zoo',
'foo zoo bar' ) ) )
def test_LastEnteredCharIsIdentifierChar_Basic( self ):
with MockCurrentFiletypes():
with MockCurrentColumnAndLineContents( 3, 'abc' ):
assert_that( base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 2, 'abc' ):
assert_that( base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 1, 'abc' ):
assert_that( base.LastEnteredCharIsIdentifierChar() )
def test_LastEnteredCharIsIdentifierChar_FiletypeHtml( self ):
with MockCurrentFiletypes( [ 'html' ] ):
with MockCurrentColumnAndLineContents( 3, 'ab-' ):
assert_that( base.LastEnteredCharIsIdentifierChar() )
def test_LastEnteredCharIsIdentifierChar_ColumnIsZero( self ):
with MockCurrentColumnAndLineContents( 0, 'abc' ):
assert_that( not base.LastEnteredCharIsIdentifierChar() )
def test_LastEnteredCharIsIdentifierChar_LineEmpty( self ):
with MockCurrentFiletypes():
with MockCurrentColumnAndLineContents( 3, '' ):
assert_that( not base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 0, '' ):
assert_that( not base.LastEnteredCharIsIdentifierChar() )
def test_LastEnteredCharIsIdentifierChar_NotIdentChar( self ):
with MockCurrentFiletypes():
with MockCurrentColumnAndLineContents( 3, 'ab;' ):
assert_that( not base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 1, ';' ):
assert_that( not base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 3, 'ab-' ):
assert_that( not base.LastEnteredCharIsIdentifierChar() )
def test_LastEnteredCharIsIdentifierChar_Unicode( self ):
with MockCurrentFiletypes():
# CurrentColumn returns a byte offset and character ø is 2 bytes length.
with MockCurrentColumnAndLineContents( 5, 'føo(' ):
assert_that( not base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 4, 'føo(' ):
assert_that( base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 3, 'føo(' ):
assert_that( base.LastEnteredCharIsIdentifierChar() )
with MockCurrentColumnAndLineContents( 1, 'føo(' ):
assert_that( base.LastEnteredCharIsIdentifierChar() )
def test_CurrentIdentifierFinished_Basic( self ):
with MockCurrentFiletypes():
with MockCurrentColumnAndLineContents( 3, 'ab;' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 2, 'ab;' ):
assert_that( not base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 1, 'ab;' ):
assert_that( not base.CurrentIdentifierFinished() )
def test_CurrentIdentifierFinished_NothingBeforeColumn( self ):
with MockCurrentColumnAndLineContents( 0, 'ab;' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 0, '' ):
assert_that( base.CurrentIdentifierFinished() )
def test_CurrentIdentifierFinished_InvalidColumn( self ):
with MockCurrentFiletypes():
with MockCurrentColumnAndLineContents( 5, '' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 5, 'abc' ):
assert_that( not base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 4, 'ab;' ):
assert_that( base.CurrentIdentifierFinished() )
def test_CurrentIdentifierFinished_InMiddleOfLine( self ):
with MockCurrentFiletypes():
with MockCurrentColumnAndLineContents( 4, 'bar.zoo' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 4, 'bar(zoo' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ):
assert_that( base.CurrentIdentifierFinished() )
def test_CurrentIdentifierFinished_Html( self ):
with MockCurrentFiletypes( [ 'html' ] ):
with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ):
assert_that( not base.CurrentIdentifierFinished() )
def test_CurrentIdentifierFinished_WhitespaceOnly( self ):
with MockCurrentFiletypes():
with MockCurrentColumnAndLineContents( 1, '\n' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 3, '\n ' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 3, '\t\t\t\t' ):
assert_that( base.CurrentIdentifierFinished() )
def test_CurrentIdentifierFinished_Unicode( self ):
with MockCurrentFiletypes():
# CurrentColumn returns a byte offset and character ø is 2 bytes length.
with MockCurrentColumnAndLineContents( 6, 'føo ' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 5, 'føo ' ):
assert_that( base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 4, 'føo ' ):
assert_that( not base.CurrentIdentifierFinished() )
with MockCurrentColumnAndLineContents( 3, 'føo ' ):
assert_that( not base.CurrentIdentifierFinished() )
| 12,200
|
Python
|
.py
| 218
| 47.37156
| 80
| 0.652657
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,969
|
syntax_parse_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/syntax_parse_test.py
|
# Copyright (C) 2013 Google Inc.
# 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import MockVimModule
MockVimModule()
import os
from hamcrest import assert_that, contains_inanyorder, has_item, has_items
from unittest import TestCase
from ycm import syntax_parse
from ycmd.utils import ReadFile
def ContentsOfTestFile( test_file ):
dir_of_script = os.path.dirname( os.path.abspath( __file__ ) )
full_path_to_test_file = os.path.join( dir_of_script, 'testdata', test_file )
return ReadFile( full_path_to_test_file )
class SyntaxTest( TestCase ):
def test_KeywordsFromSyntaxListOutput_PythonSyntax( self ):
expected_keywords = ( 'bytearray', 'IndexError', 'all', 'help', 'vars',
'SyntaxError', 'global', 'elif', 'unicode', 'sorted', 'memoryview',
'isinstance', 'except', 'nonlocal', 'NameError', 'finally',
'BytesWarning', 'dict', 'IOError', 'pass', 'oct', 'bin', 'SystemExit',
'return', 'StandardError', 'format', 'TabError', 'break', 'next',
'not', 'UnicodeDecodeError', 'False', 'RuntimeWarning', 'list', 'iter',
'try', 'reload', 'Warning', 'round', 'dir', 'cmp', 'set', 'bytes',
'UnicodeTranslateError', 'intern', 'issubclass', 'yield', 'Ellipsis',
'hash', 'locals', 'BufferError', 'slice', 'for', 'FloatingPointError',
'sum', 'VMSError', 'getattr', 'abs', 'print', 'import', 'True',
'FutureWarning', 'ImportWarning', 'None', 'EOFError', 'len',
'frozenset', 'ord', 'super', 'raise', 'TypeError', 'KeyboardInterrupt',
'UserWarning', 'filter', 'range', 'staticmethod', 'SystemError', 'or',
'BaseException', 'pow', 'RuntimeError', 'float', 'MemoryError',
'StopIteration', 'globals', 'divmod', 'enumerate', 'apply',
'LookupError', 'open', 'basestring', 'from', 'UnicodeError', 'zip',
'hex', 'long', 'IndentationError', 'int', 'chr', '__import__', 'type',
'Exception', 'continue', 'tuple', 'reduce', 'reversed', 'else',
'assert', 'UnicodeEncodeError', 'input', 'with', 'hasattr', 'delattr',
'setattr', 'raw_input', 'PendingDeprecationWarning', 'compile',
'ArithmeticError', 'while', 'del', 'str', 'property', 'def', 'and',
'GeneratorExit', 'ImportError', 'xrange', 'is', 'EnvironmentError',
'KeyError', 'coerce', 'SyntaxWarning', 'file', 'in', 'unichr', 'ascii',
'any', 'as', 'if', 'OSError', 'DeprecationWarning', 'min',
'UnicodeWarning', 'execfile', 'id', 'complex', 'bool', 'ValueError',
'NotImplemented', 'map', 'exec', 'buffer', 'max', 'class', 'object',
'repr', 'callable', 'ZeroDivisionError', 'eval', '__debug__',
'ReferenceError', 'AssertionError', 'classmethod', 'UnboundLocalError',
'NotImplementedError', 'lambda', 'AttributeError', 'OverflowError',
'WindowsError' )
assert_that( syntax_parse._KeywordsFromSyntaxListOutput(
ContentsOfTestFile( 'python_syntax' ) ),
contains_inanyorder( *expected_keywords ) )
def test_KeywordsFromSyntaxListOutput_CppSyntax( self ):
expected_keywords = (
'int_fast32_t', 'FILE', 'size_t', 'bitor', 'typedef', 'const', 'struct',
'uint8_t', 'fpos_t', 'thread_local', 'unsigned', 'uint_least16_t', 'do',
'intptr_t', 'uint_least64_t', 'return', 'auto', 'void', '_Complex',
'break', '_Alignof', 'not', 'using', '_Static_assert', '_Thread_local',
'public', 'uint_fast16_t', 'this', 'continue', 'char32_t', 'int16_t',
'intmax_t', 'static', 'clock_t', 'sizeof', 'int_fast64_t', 'mbstate_t',
'try', 'xor', 'uint_fast32_t', 'int_least8_t', 'div_t', 'volatile',
'template', 'char16_t', 'new', 'ldiv_t', 'int_least16_t', 'va_list',
'uint_least8_t', 'goto', 'noreturn', 'enum', 'static_assert', 'bitand',
'compl', 'imaginary', 'jmp_buf', 'throw', 'asm', 'ptrdiff_t', 'uint16_t',
'or', 'uint_fast8_t', '_Bool', 'int32_t', 'float', 'private', 'restrict',
'wint_t', 'operator', 'not_eq', '_Imaginary', 'alignas', 'union', 'long',
'uint_least32_t', 'int_least64_t', 'friend', 'uintptr_t', 'int8_t',
'else', 'export', 'int_fast8_t', 'catch', 'true', 'case', 'default',
'double', '_Noreturn', 'signed', 'typename', 'while', 'protected',
'wchar_t', 'wctrans_t', 'uint64_t', 'delete', 'and', 'register', 'false',
'int', 'uintmax_t', 'off_t', 'char', 'int64_t', 'int_fast16_t', 'DIR',
'_Atomic', 'time_t', 'xor_eq', 'namespace', 'virtual', 'complex', 'bool',
'mutable', 'if', 'int_least32_t', 'sig_atomic_t', 'and_eq', 'ssize_t',
'alignof', '_Alignas', '_Generic', 'extern', 'class', 'typeid', 'short',
'for', 'uint_fast64_t', 'wctype_t', 'explicit', 'or_eq', 'switch',
'uint32_t', 'inline' )
assert_that( syntax_parse._KeywordsFromSyntaxListOutput(
ContentsOfTestFile( 'cpp_syntax' ) ),
contains_inanyorder( *expected_keywords ) )
def test_KeywordsFromSyntaxListOutput_JavaSyntax( self ):
expected_keywords = (
'code', 'text', 'cols', 'datetime', 'disabled', 'shape', 'codetype',
'alt', 'compact', 'style', 'valuetype', 'short', 'finally', 'continue',
'extends', 'valign', 'bordercolor', 'do', 'return', 'rel', 'rules',
'void', 'nohref', 'abbr', 'background', 'scrolling', 'instanceof',
'name', 'summary', 'try', 'default', 'noshade', 'coords', 'dir', 'frame',
'usemap', 'ismap', 'static', 'hspace', 'vlink', 'for', 'selected', 'rev',
'vspace', 'content', 'method', 'version', 'volatile', 'above', 'new',
'charoff', 'public', 'alink', 'enum', 'codebase', 'if', 'noresize',
'interface', 'checked', 'byte', 'super', 'throw', 'src', 'language',
'package', 'standby', 'script', 'longdesc', 'maxlength', 'cellpadding',
'throws', 'tabindex', 'color', 'colspan', 'accesskey', 'float', 'while',
'private', 'height', 'boolean', 'wrap', 'prompt', 'nowrap', 'size',
'rows', 'span', 'clip', 'bgcolor', 'top', 'long', 'start', 'scope',
'scheme', 'type', 'final', 'lang', 'visibility', 'else', 'assert',
'transient', 'link', 'catch', 'true', 'serializable', 'target', 'lowsrc',
'this', 'double', 'align', 'value', 'cite', 'headers', 'below',
'protected', 'declare', 'classid', 'defer', 'false', 'synchronized',
'int', 'abstract', 'accept', 'hreflang', 'char', 'border', 'id',
'native', 'rowspan', 'charset', 'archive', 'strictfp', 'readonly',
'axis', 'cellspacing', 'profile', 'multiple', 'object', 'action',
'pagex', 'pagey', 'marginheight', 'data', 'class', 'frameborder',
'enctype', 'implements', 'break', 'gutter', 'url', 'clear', 'face',
'switch', 'marginwidth', 'width', 'left' )
assert_that( syntax_parse._KeywordsFromSyntaxListOutput(
ContentsOfTestFile( 'java_syntax' ) ),
contains_inanyorder( *expected_keywords ) )
def test_KeywordsFromSyntaxListOutput_PhpSyntax_ContainsFunctions( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput(
ContentsOfTestFile( 'php_syntax' ) ),
has_items( 'array_change_key_case' ) )
def test_KeywordsFromSyntaxListOutput_PhpSyntax_ContainsPreProc( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput(
ContentsOfTestFile( 'php_syntax' ) ),
has_items( 'skip', 'function' ) )
def test_KeywordsFromSyntaxListOutput_Basic( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
foogroup xxx foo bar
zoo goo
links to Statement""" ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_KeywordsFromSyntaxListOutput_Function( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
foogroup xxx foo bar
zoo goo
links to Function""" ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_KeywordsFromSyntaxListOutput_ContainedArgAllowed( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
phpFunctions xxx contained gzclose yaz_syntax html_entity_decode fbsql_read_blob png2wbmp mssql_init cpdf_set_title gztell fbsql_insert_id empty cpdf_restore mysql_field_type closelog swftext ldap_search curl_errno gmp_div_r mssql_data_seek getmyinode printer_draw_pie mcve_initconn ncurses_getmaxyx defined
contained replace_child has_attributes specified insertdocument assign node_name hwstat addshape get_attribute_node html_dump_mem userlist
links to Function""" ), # noqa
has_items( 'gzclose', 'userlist', 'ldap_search' ) )
def test_KeywordsFromSyntaxListOutput_JunkIgnored( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
--- Syntax items ---
foogroup xxx foo bar
zoo goo
links to Statement
Spell cluster=NONE
NoSpell cluster=NONE""" ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_KeywordsFromSyntaxListOutput_MultipleStatementGroups( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
foogroup xxx foo bar
links to Statement
bargroup xxx zoo goo
links to Statement""" ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_KeywordsFromSyntaxListOutput_StatementAndTypeGroups( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
foogroup xxx foo bar
links to Statement
bargroup xxx zoo goo
links to Type""" ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_KeywordsFromSyntaxListOutput_StatementHierarchy( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
baa xxx foo bar
links to Foo
Foo xxx zoo goo
links to Bar
Bar xxx qux moo
links to Statement""" ),
contains_inanyorder( 'foo', 'bar', 'zoo',
'goo', 'qux', 'moo' ) )
def test_KeywordsFromSyntaxListOutput_TypeHierarchy( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
baa xxx foo bar
links to Foo
Foo xxx zoo goo
links to Bar
Bar xxx qux moo
links to Type""" ),
contains_inanyorder( 'foo', 'bar', 'zoo',
'goo', 'qux', 'moo' ) )
def test_KeywordsFromSyntaxListOutput_StatementAndTypeHierarchy( self ):
assert_that( syntax_parse._KeywordsFromSyntaxListOutput( """
tBaa xxx foo bar
links to tFoo
tFoo xxx zoo goo
links to tBar
tBar xxx qux moo
links to Type
sBaa xxx na bar
links to sFoo
sFoo xxx zoo nb
links to sBar
sBar xxx qux nc
links to Statement""" ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo', 'qux', 'moo',
'na', 'nb', 'nc' ) )
def test_SyntaxGroupsFromOutput_Basic( self ):
assert_that( syntax_parse._SyntaxGroupsFromOutput( """
foogroup xxx foo bar
zoo goo
links to Statement""" ),
has_item( 'foogroup' ) )
def test_ExtractKeywordsFromGroup_Basic( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'foo bar',
'zoo goo',
] ) ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_Commas( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'foo, bar,',
'zoo goo',
] ) ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_WithLinksTo( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'foo bar',
'zoo goo',
'links to Statement'
] ) ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_KeywordStarts( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'foo bar',
'contained boo baa',
'zoo goo',
] ) ),
contains_inanyorder( 'foo', 'bar', 'boo',
'baa', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_KeywordMiddle( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'foo contained bar',
'zoo goo'
] ) ),
contains_inanyorder( 'foo', 'contained',
'bar', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_KeywordAssign( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'nextgroup=zoo skipwhite foo bar',
'zoo goo',
] ) ),
contains_inanyorder( 'foo', 'bar', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_KeywordAssignAndMiddle( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'nextgroup=zoo foo skipnl bar',
'zoo goo',
] ) ),
contains_inanyorder( 'foo', 'skipnl', 'bar', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_KeywordWithoutNextgroup( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'skipempty foo bar',
'zoo goo',
] ) ),
contains_inanyorder( 'skipempty', 'foo',
'bar', 'zoo', 'goo' ) )
def test_ExtractKeywordsFromGroup_ContainedSyntaxArgAllowed( self ):
assert_that( syntax_parse._ExtractKeywordsFromGroup(
syntax_parse.SyntaxGroup( '', [
'contained foo zoq',
'contained bar goo',
'far'
] ) ),
contains_inanyorder( 'foo', 'zoq', 'bar', 'goo', 'far' ) )
| 15,195
|
Python
|
.py
| 278
| 44.546763
| 309
| 0.592652
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,970
|
diagnostic_interface_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/diagnostic_interface_test.py
|
# Copyright (C) 2015-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm import diagnostic_interface
from ycm.tests.test_utils import VimBuffer, MockVimModule, MockVimBuffers
from hamcrest import ( assert_that,
contains_exactly,
equal_to,
has_entries,
has_item )
from unittest import TestCase
MockVimModule()
def SimpleDiagnosticToJson( start_line, start_col, end_line, end_col ):
return {
'kind': 'ERROR',
'location': { 'line_num': start_line, 'column_num': start_col },
'location_extent': {
'start': {
'line_num': start_line,
'column_num': start_col
},
'end': {
'line_num': end_line,
'column_num': end_col
}
},
'ranges': [
{
'start': {
'line_num': start_line,
'column_num': start_col
},
'end': {
'line_num': end_line,
'column_num': end_col
}
}
]
}
def SimpleDiagnosticToJsonWithInvalidLineNum( start_line, start_col,
end_line, end_col ):
return {
'kind': 'ERROR',
'location': { 'line_num': start_line, 'column_num': start_col },
'location_extent': {
'start': {
'line_num': start_line,
'column_num': start_col
},
'end': {
'line_num': end_line,
'column_num': end_col
}
},
'ranges': [
{
'start': {
'line_num': 0,
'column_num': 0
},
'end': {
'line_num': 0,
'column_num': 0
}
},
{
'start': {
'line_num': start_line,
'column_num': start_col
},
'end': {
'line_num': end_line,
'column_num': end_col
}
}
]
}
def YcmTextPropertyTupleMatcher( start_line, start_col, end_line, end_col ):
return has_item( contains_exactly(
start_line,
start_col,
'YcmErrorProperty',
has_entries( { 'end_col': end_col, 'end_lnum': end_line } ) ) )
class DiagnosticInterfaceTest( TestCase ):
def test_ConvertDiagnosticToTextProperties( self ):
for diag, contents, result in [
# Error in middle of the line
[
SimpleDiagnosticToJson( 1, 16, 1, 23 ),
[ 'Highlight this error please' ],
YcmTextPropertyTupleMatcher( 1, 16, 1, 23 )
],
# Error at the end of the line
[
SimpleDiagnosticToJson( 1, 16, 1, 21 ),
[ 'Highlight this warning' ],
YcmTextPropertyTupleMatcher( 1, 16, 1, 21 )
],
[
SimpleDiagnosticToJson( 1, 16, 1, 19 ),
[ 'Highlight unicøde' ],
YcmTextPropertyTupleMatcher( 1, 16, 1, 19 )
],
# Non-positive position
[
SimpleDiagnosticToJson( 0, 0, 0, 0 ),
[ 'Some contents' ],
{}
],
[
SimpleDiagnosticToJson( -1, -2, -3, -4 ),
[ 'Some contents' ],
YcmTextPropertyTupleMatcher( 1, 1, 1, 1 )
],
]:
with self.subTest( diag = diag, contents = contents, result = result ):
current_buffer = VimBuffer( 'foo', number = 1, contents = [ '' ] )
target_buffer = VimBuffer( 'bar', number = 2, contents = contents )
with MockVimBuffers( [ current_buffer, target_buffer ],
[ current_buffer, target_buffer ] ):
actual = diagnostic_interface._ConvertDiagnosticToTextProperties(
target_buffer.number,
diag )
print( actual )
assert_that( actual, result )
def test_ConvertDiagnosticWithInvalidLineNum( self ):
for diag, contents, result in [
# Error in middle of the line
[
SimpleDiagnosticToJsonWithInvalidLineNum( 1, 16, 1, 23 ),
[ 'Highlight this error please' ],
YcmTextPropertyTupleMatcher( 1, 16, 1, 23 )
],
# Error at the end of the line
[
SimpleDiagnosticToJsonWithInvalidLineNum( 1, 16, 1, 21 ),
[ 'Highlight this warning' ],
YcmTextPropertyTupleMatcher( 1, 16, 1, 21 )
],
[
SimpleDiagnosticToJsonWithInvalidLineNum( 1, 16, 1, 19 ),
[ 'Highlight unicøde' ],
YcmTextPropertyTupleMatcher( 1, 16, 1, 19 )
],
]:
with self.subTest( diag = diag, contents = contents, result = result ):
current_buffer = VimBuffer( 'foo', number = 1, contents = [ '' ] )
target_buffer = VimBuffer( 'bar', number = 2, contents = contents )
with MockVimBuffers( [ current_buffer, target_buffer ],
[ current_buffer, target_buffer ] ):
actual = diagnostic_interface._ConvertDiagnosticToTextProperties(
target_buffer.number,
diag )
print( actual )
assert_that( actual, result )
def test_IsValidRange( self ):
for start_line, start_col, end_line, end_col, expect in (
( 1, 1, 1, 1, True ),
( 1, 1, 0, 0, False ),
( 1, 1, 2, 1, True ),
( 1, 2, 2, 1, True ),
( 2, 1, 1, 1, False ),
( 2, 2, 2, 1, False ),
):
with self.subTest( start=( start_line, start_col ),
end=( end_line, end_col ),
expect = expect ):
assert_that( diagnostic_interface._IsValidRange( start_line,
start_col,
end_line,
end_col ),
equal_to( expect ) )
| 6,284
|
Python
|
.py
| 185
| 25.048649
| 77
| 0.551282
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,971
|
__init__.py
|
ycm-core_YouCompleteMe/python/ycm/tests/__init__.py
|
# Copyright (C) 2016-2020 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import os
from ycm.tests.test_utils import MockVimModule
MockVimModule()
import contextlib
import functools
import time
from urllib.error import HTTPError, URLError
from ycm.client.base_request import BaseRequest
from ycm.tests import test_utils
from ycm.youcompleteme import YouCompleteMe
from ycmd.utils import CloseStandardStreams, WaitUntilProcessIsTerminated
def PathToTestFile( *args ):
dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) )
return os.path.join( dir_of_current_script, 'testdata', *args )
# The default options which are required for a working YouCompleteMe object.
DEFAULT_CLIENT_OPTIONS = {
# YCM options
'g:ycm_log_level': 'info',
'g:ycm_keep_logfiles': 0,
'g:ycm_extra_conf_vim_data': [],
'g:ycm_server_python_interpreter': '',
'g:ycm_show_diagnostics_ui': 1,
'g:ycm_enable_diagnostic_signs': 1,
'g:ycm_enable_diagnostic_highlighting': 0,
'g:ycm_echo_current_diagnostic': 1,
'g:ycm_filter_diagnostics': {},
'g:ycm_always_populate_location_list': 0,
'g:ycm_open_loclist_on_ycm_diags': 1,
'g:ycm_collect_identifiers_from_tags_files': 0,
'g:ycm_seed_identifiers_with_syntax': 0,
'g:ycm_goto_buffer_command': 'same-buffer',
'g:ycm_update_diagnostics_in_insert_mode': 1,
# ycmd options
'g:ycm_auto_trigger': 1,
'g:ycm_min_num_of_chars_for_completion': 2,
'g:ycm_semantic_triggers': {},
'g:ycm_filetype_specific_completion_to_disable': { 'gitcommit': 1 },
'g:ycm_max_num_candidates': 50,
'g:ycm_max_diagnostics_to_display': 30,
'g:ycm_disable_signature_help': 0,
}
@contextlib.contextmanager
def UserOptions( options ):
old_vim_options = test_utils.VIM_OPTIONS.copy()
test_utils.VIM_OPTIONS.update( DEFAULT_CLIENT_OPTIONS )
test_utils.VIM_OPTIONS.update( options )
try:
yield
finally:
test_utils.VIM_OPTIONS = old_vim_options
def _IsReady():
return BaseRequest().GetDataFromHandler( 'ready' )
def WaitUntilReady( timeout = 5 ):
expiration = time.time() + timeout
while True:
try:
if time.time() > expiration:
raise RuntimeError( 'Waited for the server to be ready '
f'for { timeout } seconds, aborting.' )
if _IsReady():
return
except ( URLError, HTTPError ):
pass
finally:
time.sleep( 0.1 )
def StopServer( ycm ):
try:
ycm.OnVimLeave()
WaitUntilProcessIsTerminated( ycm._server_popen )
CloseStandardStreams( ycm._server_popen )
except Exception:
pass
def YouCompleteMeInstance( custom_options = {} ):
"""Defines a decorator function for tests that passes a unique YouCompleteMe
instance as a parameter. This instance is initialized with the default options
`DEFAULT_CLIENT_OPTIONS`. Use the optional parameter |custom_options| to give
additional options and/or override the already existing ones.
Example usage:
from ycm.tests import YouCompleteMeInstance
@YouCompleteMeInstance( { 'log_level': 'debug',
'keep_logfiles': 1 } )
def Debug_test( ycm ):
...
"""
def Decorator( test ):
@functools.wraps( test )
def Wrapper( test_case_instance, *args, **kwargs ):
with UserOptions( custom_options ):
ycm = YouCompleteMe()
WaitUntilReady()
ycm.CheckIfServerIsReady()
try:
test_utils.VIM_PROPS_FOR_BUFFER.clear()
return test( test_case_instance, ycm, *args, **kwargs )
finally:
StopServer( ycm )
return Wrapper
return Decorator
@contextlib.contextmanager
def youcompleteme_instance( custom_options = {} ):
"""Defines a context manager to be used in case a shared YCM state
between subtests is to be avoided, as could be the case with completion
caching."""
with UserOptions( custom_options ):
ycm = YouCompleteMe()
WaitUntilReady()
try:
test_utils.VIM_PROPS_FOR_BUFFER.clear()
yield ycm
finally:
StopServer( ycm )
| 4,670
|
Python
|
.py
| 127
| 32.669291
| 80
| 0.716877
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,972
|
event_notification_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/event_notification_test.py
|
# Copyright (C) 2015-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import ( CurrentWorkingDirectory, ExtendedMock,
MockVimBuffers, MockVimModule, VimBuffer,
VimSign )
MockVimModule()
import contextlib
import os
from ycm.tests import ( PathToTestFile, test_utils, YouCompleteMeInstance,
WaitUntilReady )
from ycmd.responses import ( BuildDiagnosticData, Diagnostic, Location, Range,
UnknownExtraConf, ServerError )
from hamcrest import ( assert_that, contains_exactly, empty, equal_to,
has_entries, has_entry, has_item, has_items, has_key,
is_not )
from unittest import TestCase
from unittest.mock import call, MagicMock, patch
def PresentDialog_Confirm_Call( message ):
"""Return a mock.call object for a call to vimsupport.PresentDialog, as called
why vimsupport.Confirm with the supplied confirmation message"""
return call( message, [ 'Ok', 'Cancel' ] )
@contextlib.contextmanager
def MockArbitraryBuffer( filetype ):
"""Used via the with statement, set up a single buffer with an arbitrary name
and no contents. Its filetype is set to the supplied filetype."""
# Arbitrary, but valid, single buffer open.
current_buffer = VimBuffer( os.path.realpath( 'TEST_BUFFER' ),
filetype = filetype )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
yield
@contextlib.contextmanager
def MockEventNotification( response_method, native_filetype_completer = True ):
"""Mock out the EventNotification client request object, replacing the
Response handler's JsonFromFuture with the supplied |response_method|.
Additionally mock out YouCompleteMe's FiletypeCompleterExistsForFiletype
method to return the supplied |native_filetype_completer| parameter, rather
than querying the server"""
# We don't want the event to actually be sent to the server, just have it
# return success
with patch( 'ycm.client.event_notification.EventNotification.'
'PostDataToHandlerAsync',
return_value = MagicMock( return_value=True ) ):
# We set up a fake a Response (as called by EventNotification.Response)
# which calls the supplied callback method. Generally this callback just
# raises an apropriate exception, otherwise it would have to return a mock
# future object.
with patch( 'ycm.client.base_request._JsonFromFuture',
side_effect = response_method ):
# Filetype available information comes from the server, so rather than
# relying on that request, we mock out the check. The caller decides if
# filetype completion is available
with patch(
'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
return_value = native_filetype_completer ):
yield
def _Check_FileReadyToParse_Diagnostic_Error( ycm ):
# Tests Vim sign placement and error/warning count python API
# when one error is returned.
def DiagnosticResponse( *args ):
start = Location( 1, 2, 'TEST_BUFFER' )
end = Location( 1, 4, 'TEST_BUFFER' )
extent = Range( start, end )
diagnostic = Diagnostic( [], start, extent, 'expected ;', 'ERROR' )
return [ BuildDiagnosticData( diagnostic ) ]
with MockArbitraryBuffer( 'cpp' ):
with MockEventNotification( DiagnosticResponse ):
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
assert_that(
test_utils.VIM_SIGNS,
contains_exactly(
VimSign( 1, 'YcmError', 1 )
)
)
assert_that( ycm.GetErrorCount(), equal_to( 1 ) )
assert_that( ycm.GetWarningCount(), equal_to( 0 ) )
# Consequent calls to HandleFileParseRequest shouldn't mess with
# existing diagnostics, when there is no new parse request.
ycm.HandleFileParseRequest()
assert_that(
test_utils.VIM_SIGNS,
contains_exactly(
VimSign( 1, 'YcmError', 1 )
)
)
assert_that( ycm.GetErrorCount(), equal_to( 1 ) )
assert_that( ycm.GetWarningCount(), equal_to( 0 ) )
assert_that( not ycm.ShouldResendFileParseRequest() )
# New identical requests should result in the same diagnostics.
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
assert_that(
test_utils.VIM_SIGNS,
contains_exactly(
VimSign( 1, 'YcmError', 1 )
)
)
assert_that( ycm.GetErrorCount(), equal_to( 1 ) )
assert_that( ycm.GetWarningCount(), equal_to( 0 ) )
assert_that( not ycm.ShouldResendFileParseRequest() )
def _Check_FileReadyToParse_Diagnostic_Warning( ycm ):
# Tests Vim sign placement/unplacement and error/warning count python API
# when one warning is returned.
# Should be called after _Check_FileReadyToParse_Diagnostic_Error
def DiagnosticResponse( *args ):
start = Location( 2, 2, 'TEST_BUFFER' )
end = Location( 2, 4, 'TEST_BUFFER' )
extent = Range( start, end )
diagnostic = Diagnostic( [], start, extent, 'cast', 'WARNING' )
return [ BuildDiagnosticData( diagnostic ) ]
with MockArbitraryBuffer( 'cpp' ):
with MockEventNotification( DiagnosticResponse ):
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
assert_that(
test_utils.VIM_SIGNS,
contains_exactly(
VimSign( 2, 'YcmWarning', 1 )
)
)
assert_that( ycm.GetErrorCount(), equal_to( 0 ) )
assert_that( ycm.GetWarningCount(), equal_to( 1 ) )
# Consequent calls to HandleFileParseRequest shouldn't mess with
# existing diagnostics, when there is no new parse request.
ycm.HandleFileParseRequest()
assert_that(
test_utils.VIM_SIGNS,
contains_exactly(
VimSign( 2, 'YcmWarning', 1 )
)
)
assert_that( ycm.GetErrorCount(), equal_to( 0 ) )
assert_that( ycm.GetWarningCount(), equal_to( 1 ) )
assert_that( not ycm.ShouldResendFileParseRequest() )
def _Check_FileReadyToParse_Diagnostic_Clean( ycm ):
# Tests Vim sign unplacement and error/warning count python API
# when there are no errors/warnings left.
# Should be called after _Check_FileReadyToParse_Diagnostic_Warning
with MockArbitraryBuffer( 'cpp' ):
with MockEventNotification( MagicMock( return_value = [] ) ):
ycm.OnFileReadyToParse()
ycm.HandleFileParseRequest()
assert_that(
test_utils.VIM_SIGNS,
empty()
)
assert_that( ycm.GetErrorCount(), equal_to( 0 ) )
assert_that( ycm.GetWarningCount(), equal_to( 0 ) )
assert_that( not ycm.ShouldResendFileParseRequest() )
class EventNotificationTest( TestCase ):
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
@YouCompleteMeInstance()
def test_EventNotification_FileReadyToParse_NonDiagnostic_Error(
self, ycm, post_vim_message ):
# This test validates the behaviour of YouCompleteMe.HandleFileParseRequest
# in combination with YouCompleteMe.OnFileReadyToParse when the completer
# raises an exception handling FileReadyToParse event notification
ERROR_TEXT = 'Some completer response text'
def ErrorResponse( *args ):
raise ServerError( ERROR_TEXT )
with MockArbitraryBuffer( 'some_filetype' ):
with MockEventNotification( ErrorResponse ):
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
# The first call raises a warning
post_vim_message.assert_has_exact_calls( [
call( ERROR_TEXT, truncate = True )
] )
# Subsequent calls don't re-raise the warning
ycm.HandleFileParseRequest()
post_vim_message.assert_has_exact_calls( [
call( ERROR_TEXT, truncate = True )
] )
assert_that( not ycm.ShouldResendFileParseRequest() )
# But it does if a subsequent event raises again
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
post_vim_message.assert_has_exact_calls( [
call( ERROR_TEXT, truncate = True ),
call( ERROR_TEXT, truncate = True )
] )
assert_that( not ycm.ShouldResendFileParseRequest() )
@YouCompleteMeInstance()
def test_EventNotification_FileReadyToParse_NonDiagnostic_Error_NonNative(
self, ycm ):
test_utils.VIM_MATCHES = []
test_utils.VIM_SIGNS = []
with MockArbitraryBuffer( 'some_filetype' ):
with MockEventNotification( None, False ):
ycm.OnFileReadyToParse()
ycm.HandleFileParseRequest()
assert_that( test_utils.VIM_MATCHES, empty() )
assert_that( test_utils.VIM_SIGNS, empty() )
assert_that( not ycm.ShouldResendFileParseRequest() )
@YouCompleteMeInstance()
def test_EventNotification_FileReadyToParse_NonDiagnostic_ConfirmExtraConf(
self, ycm ):
# This test validates the behaviour of YouCompleteMe.HandleFileParseRequest
# in combination with YouCompleteMe.OnFileReadyToParse when the completer
# raises the (special) UnknownExtraConf exception
FILE_NAME = 'a_file'
MESSAGE = ( 'Found ' + FILE_NAME + '. Load? \n\n(Question can be '
'turned off with options, see YCM docs)' )
def UnknownExtraConfResponse( *args ):
raise UnknownExtraConf( FILE_NAME )
with patch( 'ycm.client.base_request.BaseRequest.PostDataToHandler',
new_callable = ExtendedMock ) as post_data_to_handler:
with MockArbitraryBuffer( 'some_filetype' ):
with MockEventNotification( UnknownExtraConfResponse ):
# When the user accepts the extra conf, we load it
with patch( 'ycm.vimsupport.PresentDialog',
return_value = 0,
new_callable = ExtendedMock ) as present_dialog:
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
present_dialog.assert_has_exact_calls( [
PresentDialog_Confirm_Call( MESSAGE ),
] )
post_data_to_handler.assert_has_exact_calls( [
call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' )
] )
# Subsequent calls don't re-raise the warning
ycm.HandleFileParseRequest()
present_dialog.assert_has_exact_calls( [
PresentDialog_Confirm_Call( MESSAGE )
] )
post_data_to_handler.assert_has_exact_calls( [
call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' )
] )
assert_that( ycm.ShouldResendFileParseRequest() )
# But it does if a subsequent event raises again
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
present_dialog.assert_has_exact_calls( [
PresentDialog_Confirm_Call( MESSAGE ),
PresentDialog_Confirm_Call( MESSAGE ),
] )
post_data_to_handler.assert_has_exact_calls( [
call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' ),
call( { 'filepath': FILE_NAME }, 'load_extra_conf_file' )
] )
assert_that( ycm.ShouldResendFileParseRequest() )
post_data_to_handler.reset_mock()
# When the user rejects the extra conf, we reject it
with patch( 'ycm.vimsupport.PresentDialog',
return_value = 1,
new_callable = ExtendedMock ) as present_dialog:
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
present_dialog.assert_has_exact_calls( [
PresentDialog_Confirm_Call( MESSAGE ),
] )
post_data_to_handler.assert_has_exact_calls( [
call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' )
] )
# Subsequent calls don't re-raise the warning
ycm.HandleFileParseRequest()
present_dialog.assert_has_exact_calls( [
PresentDialog_Confirm_Call( MESSAGE )
] )
post_data_to_handler.assert_has_exact_calls( [
call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' )
] )
assert_that( ycm.ShouldResendFileParseRequest() )
# But it does if a subsequent event raises again
ycm.OnFileReadyToParse()
assert_that( ycm.FileParseRequestReady() )
ycm.HandleFileParseRequest()
present_dialog.assert_has_exact_calls( [
PresentDialog_Confirm_Call( MESSAGE ),
PresentDialog_Confirm_Call( MESSAGE ),
] )
post_data_to_handler.assert_has_exact_calls( [
call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' ),
call( { 'filepath': FILE_NAME }, 'ignore_extra_conf_file' )
] )
assert_that( ycm.ShouldResendFileParseRequest() )
@YouCompleteMeInstance()
def test_EventNotification_FileReadyToParse_Diagnostic_Error_Native(
self, ycm ):
test_utils.VIM_SIGNS = []
_Check_FileReadyToParse_Diagnostic_Error( ycm )
_Check_FileReadyToParse_Diagnostic_Warning( ycm )
_Check_FileReadyToParse_Diagnostic_Clean( ycm )
@patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' )
@YouCompleteMeInstance( { 'g:ycm_collect_identifiers_from_tags_files': 1 } )
def test_EventNotification_FileReadyToParse_TagFiles_UnicodeWorkingDirectory(
self, ycm, *args ):
unicode_dir = PathToTestFile( 'uni¢od€' )
current_buffer_file = PathToTestFile( 'uni¬¢êçàd‚Ǩ', 'current_buffer' )
current_buffer = VimBuffer( name = current_buffer_file,
contents = [ 'current_buffer_contents' ],
filetype = 'some_filetype' )
with patch( 'ycm.client.event_notification.EventNotification.'
'PostDataToHandlerAsync' ) as post_data_to_handler_async:
with CurrentWorkingDirectory( unicode_dir ):
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 5 ) ):
ycm.OnFileReadyToParse()
assert_that(
# Positional arguments passed to PostDataToHandlerAsync.
post_data_to_handler_async.call_args[ 0 ],
contains_exactly(
has_entries( {
'filepath': current_buffer_file,
'line_num': 1,
'column_num': 6,
'file_data': has_entries( {
current_buffer_file: has_entries( {
'contents': 'current_buffer_contents\n',
'filetypes': [ 'some_filetype' ]
} )
} ),
'event_name': 'FileReadyToParse',
'tag_files': has_item( PathToTestFile( 'uni¢od€', 'tags' ) )
} ),
'event_notification'
)
)
@patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' )
@YouCompleteMeInstance()
def test_EventNotification_BufferVisit_BuildRequestForCurrentAndUnsavedBuffers( # noqa
self, ycm, *args ):
current_buffer_file = os.path.realpath( 'current_buffer' )
current_buffer = VimBuffer( name = current_buffer_file,
number = 1,
contents = [ 'current_buffer_contents' ],
filetype = 'some_filetype',
modified = False )
modified_buffer_file = os.path.realpath( 'modified_buffer' )
modified_buffer = VimBuffer( name = modified_buffer_file,
number = 2,
contents = [ 'modified_buffer_contents' ],
filetype = 'some_filetype',
modified = True )
unmodified_buffer_file = os.path.realpath( 'unmodified_buffer' )
unmodified_buffer = VimBuffer( name = unmodified_buffer_file,
number = 3,
contents = [ 'unmodified_buffer_contents' ],
filetype = 'some_filetype',
modified = False )
with patch( 'ycm.client.event_notification.EventNotification.'
'PostDataToHandlerAsync' ) as post_data_to_handler_async:
with MockVimBuffers( [ current_buffer,
modified_buffer,
unmodified_buffer ],
[ current_buffer ],
( 1, 5 ) ):
ycm.OnBufferVisit()
assert_that(
# Positional arguments passed to PostDataToHandlerAsync.
post_data_to_handler_async.call_args[ 0 ],
contains_exactly(
has_entries( {
'filepath': current_buffer_file,
'line_num': 1,
'column_num': 6,
'file_data': has_entries( {
current_buffer_file: has_entries( {
'contents': 'current_buffer_contents\n',
'filetypes': [ 'some_filetype' ]
} ),
modified_buffer_file: has_entries( {
'contents': 'modified_buffer_contents\n',
'filetypes': [ 'some_filetype' ]
} )
} ),
'event_name': 'BufferVisit'
} ),
'event_notification'
)
)
@YouCompleteMeInstance()
def test_EventNotification_BufferUnload_BuildRequestForDeletedAndUnsavedBuffers( # noqa
self, ycm ):
current_buffer_file = os.path.realpath( 'current_βuffer' )
current_buffer = VimBuffer( name = current_buffer_file,
number = 1,
contents = [ 'current_buffer_contents' ],
filetype = 'some_filetype',
modified = True )
deleted_buffer_file = os.path.realpath( 'deleted_βuffer' )
deleted_buffer = VimBuffer( name = deleted_buffer_file,
number = 2,
contents = [ 'deleted_buffer_contents' ],
filetype = 'some_filetype',
modified = False )
with patch( 'ycm.client.event_notification.EventNotification.'
'PostDataToHandlerAsync' ) as post_data_to_handler_async:
with MockVimBuffers( [ current_buffer, deleted_buffer ],
[ current_buffer ] ):
ycm.OnBufferUnload( deleted_buffer.number )
assert_that(
# Positional arguments passed to PostDataToHandlerAsync.
post_data_to_handler_async.call_args[ 0 ],
contains_exactly(
has_entries( {
'filepath': deleted_buffer_file,
'line_num': 1,
'column_num': 1,
'file_data': has_entries( {
current_buffer_file: has_entries( {
'contents': 'current_buffer_contents\n',
'filetypes': [ 'some_filetype' ]
} ),
deleted_buffer_file: has_entries( {
'contents': 'deleted_buffer_contents\n',
'filetypes': [ 'some_filetype' ]
} )
} ),
'event_name': 'BufferUnload'
} ),
'event_notification'
)
)
@patch( 'ycm.vimsupport.CaptureVimCommand', return_value = """
fooGroup xxx foo bar
links to Statement""" )
@YouCompleteMeInstance( { 'g:ycm_seed_identifiers_with_syntax': 1 } )
def test_EventNotification_FileReadyToParse_SyntaxKeywords_SeedWithCache(
self, ycm, *args ):
current_buffer = VimBuffer( name = 'current_buffer',
filetype = 'some_filetype' )
with patch( 'ycm.client.event_notification.EventNotification.'
'PostDataToHandlerAsync' ) as post_data_to_handler_async:
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
ycm.OnFileReadyToParse()
assert_that(
# Positional arguments passed to PostDataToHandlerAsync.
post_data_to_handler_async.call_args[ 0 ],
contains_exactly(
has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ),
'event_notification'
)
)
# Do not send again syntax keywords in subsequent requests.
ycm.OnFileReadyToParse()
assert_that(
# Positional arguments passed to PostDataToHandlerAsync.
post_data_to_handler_async.call_args[ 0 ],
contains_exactly(
is_not( has_key( 'syntax_keywords' ) ),
'event_notification'
)
)
@patch( 'ycm.vimsupport.CaptureVimCommand', return_value = """
fooGroup xxx foo bar
links to Statement""" )
@YouCompleteMeInstance( { 'g:ycm_seed_identifiers_with_syntax': 1 } )
def test_EventNotification_FileReadyToParse_SyntaxKeywords_ClearCacheIfRestart( # noqa
self, ycm, *args ):
current_buffer = VimBuffer( name = 'current_buffer',
filetype = 'some_filetype' )
with patch( 'ycm.client.event_notification.EventNotification.'
'PostDataToHandlerAsync' ) as post_data_to_handler_async:
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
ycm.OnFileReadyToParse()
assert_that(
# Positional arguments passed to PostDataToHandlerAsync.
post_data_to_handler_async.call_args[ 0 ],
contains_exactly(
has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ),
'event_notification'
)
)
# Send again the syntax keywords after restarting the server.
ycm.RestartServer()
WaitUntilReady()
ycm.OnFileReadyToParse()
assert_that(
# Positional arguments passed to PostDataToHandlerAsync.
post_data_to_handler_async.call_args[ 0 ],
contains_exactly(
has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ),
'event_notification'
)
)
| 23,101
|
Python
|
.py
| 498
| 36.094378
| 89
| 0.624994
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,973
|
omni_completer_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/omni_completer_test.py
|
# encoding: utf-8
#
# Copyright (C) 2016-2019 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from hamcrest import assert_that, contains_exactly, empty, has_entries
from unittest import TestCase
from ycm.tests.test_utils import MockVimBuffers, MockVimModule, VimBuffer
MockVimModule()
from ycm import vimsupport
from ycm.tests import YouCompleteMeInstance, youcompleteme_instance
FILETYPE = 'ycmtest'
TRIGGERS = {
'ycmtest': [ '.' ]
}
def StartColumnCompliance( ycm,
omnifunc_start_column,
ycm_completions,
ycm_start_column ):
def Omnifunc( findstart, base ):
if findstart:
return omnifunc_start_column
return [ 'foo' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'fo' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 2 ) ):
ycm.SendCompletionRequest( force_semantic = True )
r = ycm.GetCompletionResponse()
assert_that(
r,
has_entries( {
'completions': ycm_completions,
'completion_start_column': ycm_start_column
} )
)
class OmniCompleterTest( TestCase ):
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_List( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 5 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'a', 'equal': 1 },
{ 'word': 'b', 'equal': 1 },
{ 'word': 'cdef', 'equal': 1 }
],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_ListFilter( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.t' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': empty(),
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_List( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 5 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'a', 'equal': 1 },
{ 'word': 'b', 'equal': 1 },
{ 'word': 'cdef', 'equal': 1 }
],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_ListFilter( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.t' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest()
# Actual result is that the results are not filtered, as we expect the
# omnifunc or vim itself to do this filtering.
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'a', 'equal': 1 },
{ 'word': 'b', 'equal': 1 },
{ 'word': 'cdef', 'equal': 1 }
],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_UseFindStart( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 0
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.t' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest()
# Actual result is that the results are not filtered, as we expect the
# omnifunc or vim itself to do this filtering.
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'a', 'equal': 1 },
{ 'word': 'b', 'equal': 1 },
{ 'word': 'cdef', 'equal': 1 }
],
'completion_start_column': 1
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_UseFindStart( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 0
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.t' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest()
# There are no results because the query 'test.t' doesn't match any
# candidate (and cache_omnifunc=1, so we FilterAndSortCandidates).
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': empty(),
'completion_start_column': 1
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_Object( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return { 'words': [ 'a', 'b', 'CDtEF' ] }
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.t' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ { 'word': 'CDtEF', 'equal': 1 } ],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_ObjectList( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [
{
'word': 'a',
'abbr': 'ABBR',
'menu': 'MENU',
'info': 'INFO',
'kind': 'K'
},
{
'word': 'test',
'abbr': 'ABBRTEST',
'menu': 'MENUTEST',
'info': 'INFOTEST',
'kind': 'T'
}
]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.tt' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': contains_exactly( {
'word' : 'test',
'abbr' : 'ABBRTEST',
'menu' : 'MENUTEST',
'info' : 'INFOTEST',
'kind' : 'T',
'equal': 1
} ),
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_ObjectList( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [
{
'word': 'a',
'abbr': 'ABBR',
'menu': 'MENU',
'info': 'INFO',
'kind': 'K'
},
{
'word': 'test',
'abbr': 'ABBRTEST',
'menu': 'MENUTEST',
'info': 'INFOTEST',
'kind': 'T'
}
]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.tt' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ):
ycm.SendCompletionRequest()
# We don't filter the result - we expect the omnifunc to do that
# based on the query we supplied (Note: that means no fuzzy matching!).
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ {
'word' : 'a',
'abbr' : 'ABBR',
'menu' : 'MENU',
'info' : 'INFO',
'kind' : 'K',
'equal': 1
}, {
'word' : 'test',
'abbr' : 'ABBRTEST',
'menu' : 'MENUTEST',
'info' : 'INFOTEST',
'kind' : 'T',
'equal': 1
} ],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_ObjectListObject( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return { 'words': [
{
'word': 'a',
'abbr': 'ABBR',
'menu': 'MENU',
'info': 'INFO',
'kind': 'K'
},
{
'word': 'test',
'abbr': 'ABBRTEST',
'menu': 'MENUTEST',
'info': 'INFOTEST',
'kind': 'T'
}
] }
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.tt' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ {
'word' : 'test',
'abbr' : 'ABBRTEST',
'menu' : 'MENUTEST',
'info' : 'INFOTEST',
'kind' : 'T',
'equal': 1
} ],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_ObjectListObject( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return { 'words': [
{
'word': 'a',
'abbr': 'ABBR',
'menu': 'MENU',
'info': 'INFO',
'kind': 'K'
},
{
'word': 'test',
'abbr': 'ABBRTEST',
'menu': 'MENUTEST',
'info': 'INFOTEST',
'kind': 'T'
}
] }
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.tt' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ):
ycm.SendCompletionRequest()
# No FilterAndSortCandidates for cache_omnifunc=0 (we expect the omnifunc
# to do the filtering?)
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ {
'word' : 'a',
'abbr' : 'ABBR',
'menu' : 'MENU',
'info' : 'INFO',
'kind' : 'K',
'equal': 1
}, {
'word' : 'test',
'abbr' : 'ABBRTEST',
'menu' : 'MENUTEST',
'info' : 'INFOTEST',
'kind' : 'T',
'equal': 1
} ],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_List_Unicode( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 12
return [ '†est', 'å_unicode_identifier', 'πππππππ yummy πie' ]
current_buffer = VimBuffer( 'buffer',
contents = [ '†åsty_π.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 12 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'å_unicode_identifier', 'equal': 1 },
{ 'word': 'πππππππ yummy πie', 'equal': 1 },
{ 'word': '†est', 'equal': 1 }
],
'completion_start_column': 13
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_List_Unicode( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 12
return [ '†est', 'å_unicode_identifier', 'πππππππ yummy πie' ]
current_buffer = VimBuffer( 'buffer',
contents = [ '†åsty_π.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 12 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': '†est', 'equal': 1 },
{ 'word': 'å_unicode_identifier', 'equal': 1 },
{ 'word': 'πππππππ yummy πie', 'equal': 1 }
],
'completion_start_column': 13
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_List_Filter_Unicode( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 12
return [ '†est', 'å_unicode_identifier', 'πππππππ yummy πie' ]
current_buffer = VimBuffer( 'buffer',
contents = [ '†åsty_π.ππ' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 17 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ { 'word': 'πππππππ yummy πie', 'equal': 1 } ],
'completion_start_column': 13
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_List_Filter_Unicode(
self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 12
return [ 'πππππππ yummy πie' ]
current_buffer = VimBuffer( 'buffer',
contents = [ '†åsty_π.ππ' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 17 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ { 'word': 'πππππππ yummy πie', 'equal': 1 } ],
'completion_start_column': 13
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_ObjectList_Unicode( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 12
return [
{
'word': 'ålpha∫et',
'abbr': 'å∫∫®',
'menu': 'µ´~¨á',
'info': '^~fo',
'kind': '˚'
},
{
'word': 'π†´ß†π',
'abbr': 'ÅııÂʉÍÊ',
'menu': '˜‰ˆËʉÍÊ',
'info': 'ÈˆÏØÊ‰ÍÊ',
'kind': 'Ê'
}
]
current_buffer = VimBuffer( 'buffer',
contents = [ '†åsty_π.ππ' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 17 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ {
'word' : 'π†´ß†π',
'abbr' : 'ÅııÂʉÍÊ',
'menu' : '˜‰ˆËʉÍÊ',
'info' : 'ÈˆÏØÊ‰ÍÊ',
'kind' : 'Ê',
'equal': 1
} ],
'completion_start_column': 13
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_Cache_ObjectListObject_Unicode(
self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 12
return {
'words': [
{
'word': 'ålpha∫et',
'abbr': 'å∫∫®',
'menu': 'µ´~¨á',
'info': '^~fo',
'kind': '˚'
},
{
'word': 'π†´ß†π',
'abbr': 'ÅııÂʉÍÊ',
'menu': '˜‰ˆËʉÍÊ',
'info': 'ÈˆÏØÊ‰ÍÊ',
'kind': 'Ê'
},
{
'word': 'test',
'abbr': 'ÅııÂʉÍÊ',
'menu': '˜‰ˆËʉÍÊ',
'info': 'ÈˆÏØÊ‰ÍÊ',
'kind': 'Ê'
}
]
}
current_buffer = VimBuffer( 'buffer',
contents = [ '†åsty_π.t' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 13 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': contains_exactly( {
'word' : 'test',
'abbr' : 'ÅııÂʉÍÊ',
'menu' : '˜‰ˆËʉÍÊ',
'info' : 'ÈˆÏØÊ‰ÍÊ',
'kind' : 'Ê',
'equal': 1
}, {
'word' : 'ålpha∫et',
'abbr' : 'å∫∫®',
'menu' : 'µ´~¨á',
'info' : '^~fo',
'kind' : '˚',
'equal': 1
} ),
'completion_start_column': 13
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_RestoreCursorPositionAfterOmnifuncCall(
self, ycm ):
# This omnifunc moves the cursor to the test definition like
# ccomplete#Complete would.
def Omnifunc( findstart, base ):
vimsupport.SetCurrentLineAndColumn( 0, 0 )
if findstart:
return 5
return [ 'length' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'String test',
'',
'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 3, 5 ) ):
ycm.SendCompletionRequest()
assert_that(
vimsupport.CurrentLineAndColumn(),
contains_exactly( 2, 5 )
)
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ { 'word': 'length', 'equal': 1 } ],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_MoveCursorPositionAtStartColumn(
self, ycm ):
# This omnifunc relies on the cursor being moved at the start column when
# called the second time like LanguageClient#complete from the
# LanguageClient-neovim plugin.
def Omnifunc( findstart, base ):
if findstart:
return 5
if vimsupport.CurrentColumn() == 5:
return [ 'length' ]
return []
current_buffer = VimBuffer( 'buffer',
contents = [ 'String test',
'',
'test.le' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 3, 7 ) ):
ycm.SendCompletionRequest()
assert_that(
vimsupport.CurrentLineAndColumn(),
contains_exactly( 2, 7 )
)
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ { 'word': 'length', 'equal': 1 } ],
'completion_start_column': 6
} )
)
def test_OmniCompleter_GetCompletions_StartColumnCompliance( self ):
for omnifunc_start_column, ycm_completions, ycm_start_column in [
[ -4, [ { 'word': 'foo', 'equal': 1 } ], 3 ],
[ -3, [], 1 ],
[ -2, [], 1 ],
[ -1, [ { 'word': 'foo', 'equal': 1 } ], 3 ],
[ 0, [ { 'word': 'foo', 'equal': 1 } ], 1 ],
[ 1, [ { 'word': 'foo', 'equal': 1 } ], 2 ],
[ 2, [ { 'word': 'foo', 'equal': 1 } ], 3 ],
[ 3, [ { 'word': 'foo', 'equal': 1 } ], 3 ]
]:
with youcompleteme_instance( { 'g:ycm_cache_omnifunc': 1 } ) as ycm:
with self.subTest( omnifunc_start_column = omnifunc_start_column,
ycm_completions = ycm_completions,
ycm_start_column = ycm_start_column ):
StartColumnCompliance( ycm,
omnifunc_start_column,
ycm_completions,
ycm_start_column )
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_NoSemanticTrigger( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 0
return [ 'test' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'te' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 3 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': empty(),
'completion_start_column': 1
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 0,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_NoCache_ForceSemantic( self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 0
return [ 'test' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'te' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 3 ) ):
ycm.SendCompletionRequest( force_semantic = True )
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [ { 'word': 'test', 'equal': 1 } ],
'completion_start_column': 1
} )
)
@YouCompleteMeInstance( { 'g:ycm_cache_omnifunc': 1,
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_ConvertStringsToDictionaries(
self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [
{ 'word': 'a' },
'b'
]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 7 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'a', 'equal': 1 },
{ 'word': 'b', 'equal': 1 }
],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( {
'g:ycm_cache_omnifunc': 0,
'g:ycm_filetype_specific_completion_to_disable': { FILETYPE: 1 },
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_FiletypeDisabled_SemanticTrigger(
self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': empty(),
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( {
'g:ycm_cache_omnifunc': 0,
'g:ycm_filetype_specific_completion_to_disable': { '*': 1 },
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_AllFiletypesDisabled_SemanticTrigger(
self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest()
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': empty(),
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( {
'g:ycm_cache_omnifunc': 0,
'g:ycm_filetype_specific_completion_to_disable': { FILETYPE: 1 },
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_FiletypeDisabled_ForceSemantic(
self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest( force_semantic = True )
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'a', 'equal': 1 },
{ 'word': 'b', 'equal': 1 },
{ 'word': 'cdef', 'equal': 1 }
],
'completion_start_column': 6
} )
)
@YouCompleteMeInstance( {
'g:ycm_cache_omnifunc': 0,
'g:ycm_filetype_specific_completion_to_disable': { '*': 1 },
'g:ycm_semantic_triggers': TRIGGERS } )
def test_OmniCompleter_GetCompletions_AllFiletypesDisabled_ForceSemantic(
self, ycm ):
def Omnifunc( findstart, base ):
if findstart:
return 5
return [ 'a', 'b', 'cdef' ]
current_buffer = VimBuffer( 'buffer',
contents = [ 'test.' ],
filetype = FILETYPE,
omnifunc = Omnifunc )
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 6 ) ):
ycm.SendCompletionRequest( force_semantic = True )
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': [
{ 'word': 'a', 'equal': 1 },
{ 'word': 'b', 'equal': 1 },
{ 'word': 'cdef', 'equal': 1 }
],
'completion_start_column': 6
} )
)
| 31,259
|
Python
|
.py
| 837
| 25.455197
| 79
| 0.497532
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,974
|
diagnostic_filter_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/diagnostic_filter_test.py
|
# Copyright (C) 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import MockVimModule
MockVimModule()
from hamcrest import assert_that, equal_to
from unittest import TestCase
from ycm.diagnostic_filter import DiagnosticFilter
def _assert_accept_equals( filter, text_or_obj, expected ):
if not isinstance( text_or_obj, dict ):
text_or_obj = { 'text': text_or_obj }
assert_that( filter.IsAllowed( text_or_obj ), equal_to( expected ) )
def _assert_accepts( filter, text ):
_assert_accept_equals( filter, text, True )
def _assert_rejects( filter, text ):
_assert_accept_equals( filter, text, False )
def _JavaFilter( config ):
return { 'filter_diagnostics' : { 'java': config } }
def _CreateFilterForTypes( opts, types ):
return DiagnosticFilter.CreateFromOptions( opts ).SubsetForTypes( types )
class DiagnosticFilterTest( TestCase ):
def test_RegexFilter( self ):
opts = _JavaFilter( { 'regex' : 'taco' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
def test_RegexSingleList( self ):
opts = _JavaFilter( { 'regex' : [ 'taco' ] } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
def test_RegexMultiList( self ):
opts = _JavaFilter( { 'regex' : [ 'taco', 'burrito' ] } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
_assert_rejects( f, 'This is a Taco' )
_assert_rejects( f, 'This is a Burrito' )
def test_RegexNotFiltered( self ):
opts = _JavaFilter( { 'regex' : 'taco' } )
f = _CreateFilterForTypes( opts, [ 'cs' ] )
_assert_accepts( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
def test_LevelWarnings( self ):
opts = _JavaFilter( { 'level' : 'warning' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
_assert_rejects( f, { 'text' : 'This is an unimportant taco',
'kind' : 'WARNING' } )
_assert_accepts( f, { 'text' : 'This taco will be shown',
'kind' : 'ERROR' } )
def test_LevelErrors( self ):
opts = _JavaFilter( { 'level' : 'error' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
_assert_accepts( f, { 'text' : 'This is an IMPORTANT taco',
'kind' : 'WARNING' } )
_assert_rejects( f, { 'text' : 'This taco will NOT be shown',
'kind' : 'ERROR' } )
def test_MultipleFilterTypesTypeTest( self ):
opts = _JavaFilter( { 'regex' : '.*taco.*',
'level' : 'warning' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
_assert_rejects( f, { 'text' : 'This is an unimportant taco',
'kind' : 'WARNING' } )
_assert_rejects( f, { 'text' : 'This taco will NOT be shown',
'kind' : 'ERROR' } )
_assert_accepts( f, { 'text' : 'This burrito WILL be shown',
'kind' : 'ERROR' } )
def test_MergeMultipleFiletypes( self ):
opts = { 'filter_diagnostics' : {
'java' : { 'regex' : '.*taco.*' },
'xml' : { 'regex' : '.*burrito.*' } } }
f = _CreateFilterForTypes( opts, [ 'java', 'xml' ] )
_assert_rejects( f, 'This is a Taco' )
_assert_rejects( f, 'This is a Burrito' )
_assert_accepts( f, 'This is some Nachos' )
def test_CommaSeparatedFiletypes( self ):
opts = { 'filter_diagnostics' : {
'java,c,cs' : { 'regex' : '.*taco.*' } } }
f = _CreateFilterForTypes( opts, [ 'cs' ] )
_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
| 4,364
|
Python
|
.py
| 92
| 41.467391
| 75
| 0.623137
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,975
|
completion_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/completion_test.py
|
# Copyright (C) 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import ( CurrentWorkingDirectory, ExtendedMock,
MockVimModule, MockVimBuffers, VimBuffer )
MockVimModule()
import contextlib
from hamcrest import ( assert_that,
contains_exactly,
empty,
equal_to,
has_entries )
from unittest import TestCase
from unittest.mock import call, MagicMock, patch
from ycm.tests import PathToTestFile, YouCompleteMeInstance
from ycmd.responses import ServerError
import json
@contextlib.contextmanager
def MockCompletionRequest( response_method ):
"""Mock out the CompletionRequest, replacing the response handler
JsonFromFuture with the |response_method| parameter."""
# We don't want the requests to actually be sent to the server, just have it
# return success.
with patch( 'ycm.client.completer_available_request.'
'CompleterAvailableRequest.PostDataToHandler',
return_value = True ):
with patch( 'ycm.client.completion_request.CompletionRequest.'
'PostDataToHandlerAsync',
return_value = MagicMock( return_value=True ) ):
# We set up a fake response.
with patch( 'ycm.client.base_request._JsonFromFuture',
side_effect = response_method ):
yield
@contextlib.contextmanager
def MockResolveRequest( response_method ):
"""Mock out the CompletionRequest, replacing the response handler
JsonFromFuture with the |response_method| parameter."""
with patch( 'ycm.client.resolve_completion_request.ResolveCompletionRequest.'
'PostDataToHandlerAsync',
return_value = MagicMock( return_value=True ) ):
# We set up a fake response.
with patch( 'ycm.client.base_request._JsonFromFuture',
side_effect = response_method ):
yield
class CompletionTest( TestCase ):
@YouCompleteMeInstance()
def test_SendCompletionRequest_UnicodeWorkingDirectory( self, ycm ):
unicode_dir = PathToTestFile( 'uni¢od€' )
current_buffer = VimBuffer( PathToTestFile( 'uni¬¢êçàd‚Ǩ', 'current_buffer' ) )
def ServerResponse( *args ):
return { 'completions': [], 'completion_start_column': 1 }
with CurrentWorkingDirectory( unicode_dir ):
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with MockCompletionRequest( ServerResponse ):
ycm.SendCompletionRequest()
assert_that( ycm.CompletionRequestReady() )
assert_that(
ycm.GetCompletionResponse(),
has_entries( {
'completions': empty(),
'completion_start_column': 1
} )
)
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_SendCompletionRequest_ResponseContainingError(
self, ycm, post_vim_message ):
current_buffer = VimBuffer( 'buffer' )
def ServerResponse( *args ):
return {
'completions': [ {
'insertion_text': 'insertion_text',
'menu_text': 'menu_text',
'extra_menu_info': 'extra_menu_info',
'detailed_info': 'detailed_info',
'kind': 'kind',
'extra_data': {
'doc_string': 'doc_string'
}
} ],
'completion_start_column': 3,
'errors': [ {
'exception': {
'TYPE': 'Exception'
},
'message': 'message',
'traceback': 'traceback'
} ]
}
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with MockCompletionRequest( ServerResponse ):
ycm.SendCompletionRequest()
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
post_vim_message.assert_has_exact_calls( [
call( 'Exception: message', truncate = True )
] )
assert_that(
response,
has_entries( {
'completions': contains_exactly( has_entries( {
'word': 'insertion_text',
'abbr': 'menu_text',
'menu': 'extra_menu_info',
'info': 'detailed_info\ndoc_string',
'kind': 'k',
'dup': 1,
'empty': 1
} ) ),
'completion_start_column': 3
} )
)
@YouCompleteMeInstance()
@patch( 'ycm.client.base_request._logger', autospec = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_SendCompletionRequest_ErrorFromServer( self,
ycm,
post_vim_message,
logger ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with MockCompletionRequest( ServerError( 'Server error' ) ):
ycm.SendCompletionRequest()
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
logger.exception.assert_called_with( 'Error while handling server '
'response' )
post_vim_message.assert_has_exact_calls( [
call( 'Server error', truncate = True )
] )
assert_that(
response,
has_entries( {
'completions': empty(),
'completion_start_column': -1
} )
)
@YouCompleteMeInstance()
@patch( 'ycm.client.base_request._logger', autospec = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_ResolveCompletionRequest_Resolves( self,
ycm,
post_vim_message,
logger ):
def CompletionResponse( *args ):
return {
'completions': [ {
'insertion_text': 'insertion_text',
'menu_text': 'menu_text',
'extra_menu_info': 'extra_menu_info',
'detailed_info': 'detailed_info',
'kind': 'kind',
'extra_data': {
'doc_string': 'doc_string',
'resolve': 10
}
} ],
'completion_start_column': 3,
'errors': []
}
def ResolveResponse( *args ):
return {
'completion': {
'insertion_text': 'insertion_text',
'menu_text': 'menu_text',
'extra_menu_info': 'extra_menu_info',
'detailed_info': 'detailed_info',
'kind': 'kind',
'extra_data': {
'doc_string': 'doc_string with more info'
}
},
'errors': []
}
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with MockCompletionRequest( CompletionResponse ):
ycm.SendCompletionRequest()
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
post_vim_message.assert_not_called()
assert_that(
response,
has_entries( {
'completions': contains_exactly( has_entries( {
'word': 'insertion_text',
'abbr': 'menu_text',
'menu': 'extra_menu_info',
'info': 'detailed_info\ndoc_string',
'kind': 'k',
'dup': 1,
'empty': 1
} ) ),
'completion_start_column': 3
} )
)
item = response[ 'completions' ][ 0 ]
assert_that( json.loads( item[ 'user_data' ] ),
has_entries( { 'resolve': 10 } ) )
with MockResolveRequest( ResolveResponse ):
assert_that( ycm.ResolveCompletionItem( item ), equal_to( True ) )
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
post_vim_message.assert_not_called()
assert_that(
response,
has_entries( {
'completion': has_entries( {
'word': 'insertion_text',
'abbr': 'menu_text',
'menu': 'extra_menu_info',
'info': 'detailed_info\ndoc_string with more info',
'kind': 'k',
'dup': 1,
'empty': 1
} )
} )
)
item = response[ 'completion' ]
with MockResolveRequest( ServerError( 'must not be called' ) ):
assert_that( ycm.ResolveCompletionItem( item ), equal_to( False ) )
post_vim_message.assert_not_called()
@YouCompleteMeInstance()
@patch( 'ycm.client.base_request._logger', autospec = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_ResolveCompletionRequest_ResponseContainsErrors( self,
ycm,
post_vim_message,
logger ):
def CompletionResponse( *args ):
return {
'completions': [ {
'insertion_text': 'insertion_text',
'menu_text': 'menu_text',
'extra_menu_info': 'extra_menu_info',
'detailed_info': 'detailed_info',
'kind': 'kind',
'extra_data': {
'doc_string': 'doc_string',
'resolve': 10
}
} ],
'completion_start_column': 3,
'errors': []
}
def ResolveResponse( *args ):
return {
'completion': {
'insertion_text': 'insertion_text',
'menu_text': 'menu_text',
'extra_menu_info': 'extra_menu_info',
'detailed_info': 'detailed_info',
'kind': 'kind',
'extra_data': {
'doc_string': 'doc_string with more info'
}
},
'errors': [ {
'exception': {
'TYPE': 'Exception'
},
'message': 'message',
'traceback': 'traceback'
} ]
}
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with MockCompletionRequest( CompletionResponse ):
ycm.SendCompletionRequest()
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
post_vim_message.assert_not_called()
assert_that(
response,
has_entries( {
'completions': contains_exactly( has_entries( {
'word': 'insertion_text',
'abbr': 'menu_text',
'menu': 'extra_menu_info',
'info': 'detailed_info\ndoc_string',
'kind': 'k',
'dup': 1,
'empty': 1
} ) ),
'completion_start_column': 3
} )
)
item = response[ 'completions' ][ 0 ]
assert_that( json.loads( item[ 'user_data' ] ),
has_entries( { 'resolve': 10 } ) )
with MockResolveRequest( ResolveResponse ):
assert_that( ycm.ResolveCompletionItem( item ), equal_to( True ) )
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
post_vim_message.assert_has_exact_calls( [
call( 'Exception: message', truncate = True )
] )
assert_that(
response,
has_entries( {
'completion': has_entries( {
'word': 'insertion_text',
'abbr': 'menu_text',
'menu': 'extra_menu_info',
'info': 'detailed_info\ndoc_string with more info',
'kind': 'k',
'dup': 1,
'empty': 1
} )
} )
)
@YouCompleteMeInstance()
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_ResolveCompletionItem_NoUserData( self, ycm, post_vim_message ):
def CompletionResponse( *args ):
return {
'completions': [ {
'insertion_text': 'insertion_text',
'menu_text': 'menu_text',
'extra_menu_info': 'extra_menu_info',
'detailed_info': 'detailed_info',
'kind': 'kind'
} ],
'completion_start_column': 3,
'errors': []
}
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with MockCompletionRequest( CompletionResponse ):
ycm.SendCompletionRequest()
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
post_vim_message.assert_not_called()
assert_that(
response,
has_entries( {
'completions': contains_exactly( has_entries( {
'word': 'insertion_text',
'abbr': 'menu_text',
'menu': 'extra_menu_info',
'info': 'detailed_info',
'kind': 'k',
'dup': 1,
'empty': 1
} ) ),
'completion_start_column': 3
} )
)
item = response[ 'completions' ][ 0 ]
item.pop( 'user_data' )
with MockResolveRequest( ServerError( 'must not be called' ) ):
assert_that( ycm.ResolveCompletionItem( item ), equal_to( False ) )
post_vim_message.assert_not_called()
@YouCompleteMeInstance()
def test_ResolveCompletionItem_NoRequest( self, ycm ):
assert_that( ycm.GetCurrentCompletionRequest(), equal_to( None ) )
assert_that( ycm.ResolveCompletionItem( {} ), equal_to( False ) )
@YouCompleteMeInstance()
@patch( 'ycm.client.base_request._logger', autospec = True )
@patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
def test_ResolveCompletionRequest_ServerError(
self, ycm, post_vim_message, logger ):
def ServerResponse( *args ):
return {
'completions': [ {
'insertion_text': 'insertion_text',
'menu_text': 'menu_text',
'extra_menu_info': 'extra_menu_info',
'detailed_info': 'detailed_info',
'kind': 'kind',
'extra_data': {
'doc_string': 'doc_string',
'resolve': 10
}
} ],
'completion_start_column': 3,
'errors': []
}
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with MockCompletionRequest( ServerResponse ):
ycm.SendCompletionRequest()
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
post_vim_message.assert_not_called()
assert_that(
response,
has_entries( {
'completions': contains_exactly( has_entries( {
'word': 'insertion_text',
'abbr': 'menu_text',
'menu': 'extra_menu_info',
'info': 'detailed_info\ndoc_string',
'kind': 'k',
'dup': 1,
'empty': 1
} ) ),
'completion_start_column': 3
} )
)
item = response[ 'completions' ][ 0 ]
assert_that( json.loads( item[ 'user_data' ] ),
has_entries( { 'resolve': 10 } ) )
with MockResolveRequest( ServerError( 'Server error' ) ):
ycm.ResolveCompletionItem( item )
assert_that( ycm.CompletionRequestReady() )
response = ycm.GetCompletionResponse()
logger.exception.assert_called_with( 'Error while handling server '
'response' )
post_vim_message.assert_has_exact_calls( [
call( 'Server error', truncate = True )
] )
| 16,482
|
Python
|
.py
| 425
| 28.096471
| 85
| 0.55882
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,976
|
command_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/command_test.py
|
# Copyright (C) 2016-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import MockVimModule, MockVimBuffers, VimBuffer
MockVimModule()
from hamcrest import assert_that, contains_exactly, has_entries
from unittest.mock import patch
from unittest import TestCase
from ycm.tests import YouCompleteMeInstance
class CommandTest( TestCase ):
@YouCompleteMeInstance( { 'g:ycm_extra_conf_vim_data': [ 'tempname()' ] } )
def test_SendCommandRequest_ExtraConfVimData_Works( self, ycm ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'aboveleft', False, 1, 1 )
assert_that(
# Positional arguments passed to SendCommandRequest.
send_request.call_args[ 0 ],
contains_exactly(
contains_exactly( 'GoTo' ),
'aboveleft',
'same-buffer',
has_entries( {
'options': has_entries( {
'tab_size': 2,
'insert_spaces': True,
} ),
'extra_conf_data': has_entries( {
'tempname()': '_TEMP_FILE_'
} ),
} ),
)
)
@YouCompleteMeInstance( {
'g:ycm_extra_conf_vim_data': [ 'undefined_value' ] } )
def test_SendCommandRequest_ExtraConfData_UndefinedValue( self, ycm ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'belowright', False, 1, 1 )
assert_that(
# Positional arguments passed to SendCommandRequest.
send_request.call_args[ 0 ],
contains_exactly(
contains_exactly( 'GoTo' ),
'belowright',
'same-buffer',
has_entries( {
'options': has_entries( {
'tab_size': 2,
'insert_spaces': True,
} )
} ),
)
)
@YouCompleteMeInstance()
def test_SendCommandRequest_BuildRange_NoVisualMarks( self, ycm, *args ):
current_buffer = VimBuffer( 'buffer', contents = [ 'first line',
'second line' ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], '', True, 1, 2 )
send_request.assert_called_once_with(
[ 'GoTo' ],
'',
'same-buffer',
{
'options': {
'tab_size': 2,
'insert_spaces': True
},
'range': {
'start': {
'line_num': 1,
'column_num': 1
},
'end': {
'line_num': 2,
'column_num': 12
}
}
},
)
@YouCompleteMeInstance()
def test_SendCommandRequest_BuildRange_VisualMarks( self, ycm, *args ):
current_buffer = VimBuffer( 'buffer',
contents = [ 'first line',
'second line' ],
visual_start = [ 1, 4 ],
visual_end = [ 2, 8 ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'tab', True, 1, 2 )
send_request.assert_called_once_with(
[ 'GoTo' ],
'tab',
'same-buffer',
{
'options': {
'tab_size': 2,
'insert_spaces': True
},
'range': {
'start': {
'line_num': 1,
'column_num': 5
},
'end': {
'line_num': 2,
'column_num': 9
}
}
},
)
@YouCompleteMeInstance()
def test_SendCommandRequest_IgnoreFileTypeOption( self, ycm, *args ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
expected_args = (
[ 'GoTo' ],
'',
'same-buffer',
{
'completer_target': 'python',
'options': {
'tab_size': 2,
'insert_spaces': True
},
},
)
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'ft=python', 'GoTo' ], '', False, 1, 1 )
send_request.assert_called_once_with( *expected_args )
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo', 'ft=python' ], '', False, 1, 1 )
send_request.assert_called_once_with( *expected_args )
| 5,746
|
Python
|
.py
| 150
| 27.966667
| 77
| 0.551514
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,977
|
postcomplete_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/postcomplete_test.py
|
# encoding: utf-8
#
# Copyright (C) 2015-2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import MockVimModule
MockVimModule()
import contextlib
import json
from hamcrest import assert_that, contains_exactly, empty, equal_to, none
from unittest import TestCase
from unittest.mock import MagicMock, DEFAULT, patch
from ycm import vimsupport
from ycmd.utils import ToBytes
from ycm.client.completion_request import ( CompletionRequest,
_FilterToMatchingCompletions,
_GetRequiredNamespaceImport )
from ycm.client.omni_completion_request import OmniCompletionRequest
def CompleteItemIs( word, abbr = None, menu = None,
info = None, kind = None, **kwargs ):
item = {
'word': ToBytes( word ),
'abbr': ToBytes( abbr ),
'menu': ToBytes( menu ),
'info': ToBytes( info ),
'kind': ToBytes( kind ),
}
item.update( **kwargs )
return item
def GetVariableValue_CompleteItemIs( word, abbr = None, menu = None,
info = None, kind = None, **kwargs ):
def Result( variable ):
if variable == 'v:completed_item':
return CompleteItemIs( word, abbr, menu, info, kind, **kwargs )
return DEFAULT
return MagicMock( side_effect = Result )
def BuildCompletion( insertion_text = 'Test',
menu_text = None,
extra_menu_info = None,
detailed_info = None,
kind = None,
extra_data = None ):
completion = {
'insertion_text': insertion_text
}
if extra_menu_info:
completion[ 'extra_menu_info' ] = extra_menu_info
if menu_text:
completion[ 'menu_text' ] = menu_text
if detailed_info:
completion[ 'detailed_info' ] = detailed_info
if kind:
completion[ 'kind' ] = kind
if extra_data:
completion[ 'extra_data' ] = extra_data
return completion
def BuildCompletionNamespace( namespace = None,
insertion_text = 'Test',
menu_text = None,
extra_menu_info = None,
detailed_info = None,
kind = None ):
return BuildCompletion( insertion_text = insertion_text,
menu_text = menu_text,
extra_menu_info = extra_menu_info,
detailed_info = detailed_info,
kind = kind,
extra_data = {
'required_namespace_import': namespace
} )
def BuildCompletionFixIt( fixits,
insertion_text = 'Test',
menu_text = None,
extra_menu_info = None,
detailed_info = None,
kind = None ):
return BuildCompletion( insertion_text = insertion_text,
menu_text = menu_text,
extra_menu_info = extra_menu_info,
detailed_info = detailed_info,
kind = kind,
extra_data = {
'fixits': fixits,
} )
@contextlib.contextmanager
def _SetupForCsharpCompletionDone( completions ):
with patch( 'ycm.vimsupport.InsertNamespace' ):
with _SetUpCompleteDone( completions ) as request:
yield request
@contextlib.contextmanager
def _SetUpCompleteDone( completions ):
with patch( 'ycm.vimsupport.TextBeforeCursor', return_value = ' Test' ):
request = CompletionRequest( None )
request.Done = MagicMock( return_value = True )
request._RawResponse = MagicMock( return_value = {
'completions': completions
} )
yield request
class PostcompleteTest( TestCase ):
@patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'ycmtest' ] )
def test_OnCompleteDone_DefaultFixIt( self, *args ):
request = CompletionRequest( None )
request.Done = MagicMock( return_value = True )
request._OnCompleteDone_Csharp = MagicMock()
request._OnCompleteDone_FixIt = MagicMock()
request.OnCompleteDone()
request._OnCompleteDone_Csharp.assert_not_called()
request._OnCompleteDone_FixIt.assert_called_once_with()
@patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'cs' ] )
def test_OnCompleteDone_CsharpFixIt( self, *args ):
request = CompletionRequest( None )
request.Done = MagicMock( return_value = True )
request._OnCompleteDone_Csharp = MagicMock()
request._OnCompleteDone_FixIt = MagicMock()
request.OnCompleteDone()
request._OnCompleteDone_Csharp.assert_called_once_with()
request._OnCompleteDone_FixIt.assert_not_called()
@patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'ycmtest' ] )
def test_OnCompleteDone_NoFixItIfNotDone( self, *args ):
request = CompletionRequest( None )
request.Done = MagicMock( return_value = False )
request._OnCompleteDone_Csharp = MagicMock()
request._OnCompleteDone_FixIt = MagicMock()
request.OnCompleteDone()
request._OnCompleteDone_Csharp.assert_not_called()
request._OnCompleteDone_FixIt.assert_not_called()
@patch( 'ycm.vimsupport.CurrentFiletypes', return_value = [ 'ycmtest' ] )
def test_OnCompleteDone_NoFixItForOmnifunc( self, *args ):
request = OmniCompletionRequest( 'omnifunc', None )
request.Done = MagicMock( return_value = True )
request._OnCompleteDone_Csharp = MagicMock()
request._OnCompleteDone_FixIt = MagicMock()
request.OnCompleteDone()
request._OnCompleteDone_Csharp.assert_not_called()
request._OnCompleteDone_FixIt.assert_not_called()
def test_FilterToCompletedCompletions_MatchIsReturned( self ):
completions = [ BuildCompletion( insertion_text = 'Test' ) ]
result = _FilterToMatchingCompletions( CompleteItemIs( 'Test' ),
completions )
assert_that( list( result ), contains_exactly( {} ) )
def test_FilterToCompletedCompletions_ShortTextDoesntRaise( self ):
completions = [ BuildCompletion( insertion_text = 'AAA' ) ]
result = _FilterToMatchingCompletions( CompleteItemIs( 'A' ), completions )
assert_that( list( result ), empty() )
def test_FilterToCompletedCompletions_ExactMatchIsReturned( self ):
completions = [ BuildCompletion( insertion_text = 'Test' ) ]
result = _FilterToMatchingCompletions( CompleteItemIs( 'Test' ),
completions )
assert_that( list( result ), contains_exactly( {} ) )
def test_FilterToCompletedCompletions_NonMatchIsntReturned( self ):
completions = [ BuildCompletion( insertion_text = 'A' ) ]
result = _FilterToMatchingCompletions( CompleteItemIs( ' Quote' ),
completions )
assert_that( list( result ), empty() )
def test_FilterToCompletedCompletions_Unicode( self ):
completions = [ BuildCompletion( insertion_text = '†es†' ) ]
result = _FilterToMatchingCompletions( CompleteItemIs( '†es†' ),
completions )
assert_that( list( result ), contains_exactly( {} ) )
def test_GetRequiredNamespaceImport_ReturnNoneForNoExtraData( self ):
assert_that( _GetRequiredNamespaceImport( {} ), none() )
def test_GetRequiredNamespaceImport_ReturnNamespaceFromExtraData( self ):
namespace = 'A_NAMESPACE'
assert_that( _GetRequiredNamespaceImport(
BuildCompletionNamespace( namespace )[ 'extra_data' ] ),
equal_to( namespace ) )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Te' ) )
def test_GetExtraDataUserMayHaveCompleted_ReturnEmptyIfPendingMatches(
*args ):
completions = [ BuildCompletionNamespace( None ) ]
with _SetupForCsharpCompletionDone( completions ) as request:
assert_that( request._GetExtraDataUserMayHaveCompleted(), empty() )
def test_GetExtraDataUserMayHaveCompleted_ReturnMatchIfExactMatches(
self, *args ):
info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ]
completions = [ BuildCompletionNamespace( *info ) ]
with _SetupForCsharpCompletionDone( completions ) as request:
with patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( *info[ 1: ] ) ):
assert_that( request._GetExtraDataUserMayHaveCompleted(),
contains_exactly( completions[ 0 ][ 'extra_data' ] ) )
def test_GetExtraDataUserMayHaveCompleted_ReturnMatchIfExactMatchesEvenIfPartial( self ): # noqa
info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ]
completions = [ BuildCompletionNamespace( *info ),
BuildCompletion( insertion_text = 'TestTest' ) ]
with _SetupForCsharpCompletionDone( completions ) as request:
with patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( *info[ 1: ] ) ):
assert_that( request._GetExtraDataUserMayHaveCompleted(),
contains_exactly( completions[ 0 ][ 'extra_data' ] ) )
def test_GetExtraDataUserMayHaveCompleted_DontReturnMatchIfNoExactMatchesAndPartial( self ): # noqa
info = [ 'NS', 'Test', 'Abbr', 'Menu', 'Info', 'Kind' ]
completions = [ BuildCompletion( insertion_text = info[ 0 ] ),
BuildCompletion( insertion_text = 'TestTest' ) ]
with _SetupForCsharpCompletionDone( completions ) as request:
with patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( *info[ 1: ] ) ):
assert_that( request._GetExtraDataUserMayHaveCompleted(), empty() )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
def test_GetExtraDataUserMayHaveCompleted_ReturnMatchIfMatches( self, *args ):
completions = [ BuildCompletionNamespace( None ) ]
with _SetupForCsharpCompletionDone( completions ) as request:
assert_that( request._GetExtraDataUserMayHaveCompleted(),
contains_exactly( completions[ 0 ][ 'extra_data' ] ) )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs(
'Test',
user_data=json.dumps( {
'required_namespace_import': 'namespace1' } ) ) )
def test_GetExtraDataUserMayHaveCompleted_UseUserData0( self, *args ):
# Identical completions but we specify the first one via user_data.
completions = [
BuildCompletionNamespace( 'namespace1' ),
BuildCompletionNamespace( 'namespace2' )
]
with _SetupForCsharpCompletionDone( completions ) as request:
assert_that(
request._GetExtraDataUserMayHaveCompleted(),
contains_exactly(
BuildCompletionNamespace( 'namespace1' )[ 'extra_data' ] ) )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs(
'Test',
user_data=json.dumps( {
'required_namespace_import': 'namespace2' } ) ) )
def test_GetExtraDataUserMayHaveCompleted_UseUserData1( self, *args ):
# Identical completions but we specify the second one via user_data.
completions = [
BuildCompletionNamespace( 'namespace1' ),
BuildCompletionNamespace( 'namespace2' )
]
with _SetupForCsharpCompletionDone( completions ) as request:
assert_that(
request._GetExtraDataUserMayHaveCompleted(),
contains_exactly(
BuildCompletionNamespace( 'namespace2' )[ 'extra_data' ] ) )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test', user_data='' ) )
def test_GetExtraDataUserMayHaveCompleted_EmptyUserData( self, *args ):
# Identical completions but none is selected.
completions = [
BuildCompletionNamespace( 'namespace1' ),
BuildCompletionNamespace( 'namespace2' )
]
with _SetupForCsharpCompletionDone( completions ) as request:
assert_that( request._GetExtraDataUserMayHaveCompleted(), empty() )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
def test_PostCompleteCsharp_EmptyDoesntInsertNamespace( self, *args ):
with _SetupForCsharpCompletionDone( [] ) as request:
request._OnCompleteDone_Csharp()
assert_that( not vimsupport.InsertNamespace.called )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
def test_PostCompleteCsharp_ExistingWithoutNamespaceDoesntInsertNamespace(
self, *args ):
completions = [ BuildCompletionNamespace( None ) ]
with _SetupForCsharpCompletionDone( completions ) as request:
request._OnCompleteDone_Csharp()
assert_that( not vimsupport.InsertNamespace.called )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
def test_PostCompleteCsharp_ValueDoesInsertNamespace( self, *args ):
namespace = 'A_NAMESPACE'
completions = [ BuildCompletionNamespace( namespace ) ]
with _SetupForCsharpCompletionDone( completions ) as request:
request._OnCompleteDone_Csharp()
vimsupport.InsertNamespace.assert_called_once_with( namespace )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
@patch( 'ycm.vimsupport.PresentDialog', return_value = 1 )
def test_PostCompleteCsharp_InsertSecondNamespaceIfSelected( self, *args ):
namespace = 'A_NAMESPACE'
namespace2 = 'ANOTHER_NAMESPACE'
completions = [
BuildCompletionNamespace( namespace ),
BuildCompletionNamespace( namespace2 ),
]
with _SetupForCsharpCompletionDone( completions ) as request:
request._OnCompleteDone_Csharp()
vimsupport.InsertNamespace.assert_called_once_with( namespace2 )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
@patch( 'ycm.vimsupport.ReplaceChunks' )
def test_PostCompleteFixIt_ApplyFixIt_NoFixIts( self, replace_chunks, *args ):
completions = [
BuildCompletionFixIt( [] )
]
with _SetUpCompleteDone( completions ) as request:
request._OnCompleteDone_FixIt()
replace_chunks.assert_not_called()
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
@patch( 'ycm.vimsupport.ReplaceChunks' )
def test_PostCompleteFixIt_ApplyFixIt_EmptyFixIt(
self, replace_chunks, *args ):
completions = [
BuildCompletionFixIt( [ { 'chunks': [] } ] )
]
with _SetUpCompleteDone( completions ) as request:
request._OnCompleteDone_FixIt()
replace_chunks.assert_called_once_with( [], silent = True )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
@patch( 'ycm.vimsupport.ReplaceChunks' )
def test_PostCompleteFixIt_ApplyFixIt_NoFixIt( self, replace_chunks, *args ):
completions = [
BuildCompletion()
]
with _SetUpCompleteDone( completions ) as request:
request._OnCompleteDone_FixIt()
replace_chunks.assert_not_called()
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs( 'Test' ) )
@patch( 'ycm.vimsupport.ReplaceChunks' )
def test_PostCompleteFixIt_ApplyFixIt_PickFirst(
self, replace_chunks, *args ):
completions = [
BuildCompletionFixIt( [ { 'chunks': 'one' } ] ),
BuildCompletionFixIt( [ { 'chunks': 'two' } ] ),
]
with _SetUpCompleteDone( completions ) as request:
request._OnCompleteDone_FixIt()
replace_chunks.assert_called_once_with( 'one', silent = True )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs(
'Test',
user_data=json.dumps( { 'fixits': [ { 'chunks': 'one' } ] } ) ) )
@patch( 'ycm.vimsupport.ReplaceChunks' )
def test_PostCompleteFixIt_ApplyFixIt_PickFirstUserData( self,
replace_chunks,
*args ):
completions = [
BuildCompletionFixIt( [ { 'chunks': 'one' } ] ),
BuildCompletionFixIt( [ { 'chunks': 'two' } ] ),
]
with _SetUpCompleteDone( completions ) as request:
request._OnCompleteDone_FixIt()
replace_chunks.assert_called_once_with( 'one', silent = True )
@patch( 'ycm.vimsupport.GetVariableValue',
GetVariableValue_CompleteItemIs(
'Test',
user_data=json.dumps( { 'fixits': [ { 'chunks': 'two' } ] } ) ) )
@patch( 'ycm.vimsupport.ReplaceChunks' )
def test_PostCompleteFixIt_ApplyFixIt_PickSecond(
self, replace_chunks, *args ):
completions = [
BuildCompletionFixIt( [ { 'chunks': 'one' } ] ),
BuildCompletionFixIt( [ { 'chunks': 'two' } ] ),
]
with _SetUpCompleteDone( completions ) as request:
request._OnCompleteDone_FixIt()
replace_chunks.assert_called_once_with( 'two', silent = True )
| 17,826
|
Python
|
.py
| 368
| 39.896739
| 101
| 0.663865
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,978
|
command_request_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/client/command_request_test.py
|
# Copyright (C) 2016 YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import ExtendedMock, MockVimModule
MockVimModule()
import json
from hamcrest import assert_that
from unittest import TestCase
from unittest.mock import patch, call
from ycm.client.command_request import CommandRequest
def GoToTest( command, response ):
with patch( 'ycm.vimsupport.JumpToLocation' ) as jump_to_location:
request = CommandRequest( [ command ] )
request._response = response
request.RunPostCommandActionsIfNeeded( 'rightbelow' )
jump_to_location.assert_called_with(
response[ 'filepath' ],
response[ 'line_num' ],
response[ 'column_num' ],
'rightbelow',
'same-buffer' )
def GoToListTest( command, response ):
# Note: the detail of these called are tested by
# GoToResponse_QuickFix_test, so here we just check that the right call is
# made
with patch( 'ycm.vimsupport.SetQuickFixList' ) as set_qf_list:
with patch( 'ycm.vimsupport.OpenQuickFixList' ) as open_qf_list:
request = CommandRequest( [ command ] )
request._response = response
request.RunPostCommandActionsIfNeeded( 'tab' )
assert_that( set_qf_list.called )
assert_that( open_qf_list.called )
BASIC_GOTO = {
'filepath': 'test',
'line_num': 10,
'column_num': 100,
}
BASIC_FIXIT = {
'fixits': [ {
'resolve': False,
'chunks': [ {
'dummy chunk contents': True
} ]
} ]
}
BASIC_FIXIT_CHUNKS = BASIC_FIXIT[ 'fixits' ][ 0 ][ 'chunks' ]
MULTI_FIXIT = {
'fixits': [ {
'text': 'first',
'resolve': False,
'chunks': [ {
'dummy chunk contents': True
} ]
}, {
'text': 'second',
'resolve': False,
'chunks': [ {
'dummy chunk contents': False
} ]
} ]
}
MULTI_FIXIT_FIRST_CHUNKS = MULTI_FIXIT[ 'fixits' ][ 0 ][ 'chunks' ]
MULTI_FIXIT_SECOND_CHUNKS = MULTI_FIXIT[ 'fixits' ][ 1 ][ 'chunks' ]
class GoToResponse_QuickFixTest( TestCase ):
"""This class tests the generation of QuickFix lists for GoTo responses which
return multiple locations, such as the Python completer and JavaScript
completer. It mostly proves that we use 1-based indexing for the column
number."""
def setUp( self ):
self._request = CommandRequest( [ 'GoToTest' ] )
def tearDown( self ):
self._request = None
def test_GoTo_EmptyList( self ):
self._CheckGoToList( [], [] )
def test_GoTo_SingleItem_List( self ):
self._CheckGoToList( [ {
'filepath': 'dummy_file',
'line_num': 10,
'column_num': 1,
'description': 'this is some text',
} ], [ {
'filename': 'dummy_file',
'text': 'this is some text',
'lnum': 10,
'col': 1
} ] )
def test_GoTo_MultiItem_List( self ):
self._CheckGoToList( [ {
'filepath': 'dummy_file',
'line_num': 10,
'column_num': 1,
'description': 'this is some other text',
}, {
'filepath': 'dummy_file2',
'line_num': 1,
'column_num': 21,
'description': 'this is some text',
} ], [ {
'filename': 'dummy_file',
'text': 'this is some other text',
'lnum': 10,
'col': 1
}, {
'filename': 'dummy_file2',
'text': 'this is some text',
'lnum': 1,
'col': 21
} ] )
@patch( 'ycm.vimsupport.VariableExists', return_value = True )
@patch( 'ycm.vimsupport.SetFittingHeightForCurrentWindow' )
@patch( 'vim.command', new_callable = ExtendedMock )
@patch( 'vim.eval', new_callable = ExtendedMock )
def _CheckGoToList( self,
completer_response,
expected_qf_list,
vim_eval,
vim_command,
set_fitting_height,
variable_exists ):
self._request._response = completer_response
self._request.RunPostCommandActionsIfNeeded( 'aboveleft' )
vim_eval.assert_has_exact_calls( [
call( f'setqflist( { json.dumps( expected_qf_list ) } )' )
] )
vim_command.assert_has_exact_calls( [
call( 'botright copen' ),
call( 'augroup ycmquickfix' ),
call( 'autocmd! * <buffer>' ),
call( 'autocmd WinLeave <buffer> '
'if bufnr( "%" ) == expand( "<abuf>" ) | q | endif '
'| autocmd! ycmquickfix' ),
call( 'augroup END' ),
call( 'doautocmd User YcmQuickFixOpened' )
] )
set_fitting_height.assert_called_once_with()
class Response_Detection_Test( TestCase ):
def test_BasicResponse( self ):
def _BasicResponseTest( command, response ):
with patch( 'vim.command' ) as vim_command:
request = CommandRequest( [ command ] )
request._response = response
request.RunPostCommandActionsIfNeeded( 'belowright' )
vim_command.assert_called_with( f"echo '{ response }'" )
for command, response in [
[ 'AnythingYouLike', True ],
[ 'GoToEvenWorks', 10 ],
[ 'FixItWorks', 'String!' ],
[ 'and8434fd andy garbag!', 10.3 ],
]:
with self.subTest( command = command, response = response ):
_BasicResponseTest( command, response )
def test_FixIt_Response_Empty( self ):
# Ensures we recognise and handle fixit responses which indicate that there
# are no fixits available
def EmptyFixItTest( command ):
with patch( 'ycm.vimsupport.ReplaceChunks' ) as replace_chunks:
with patch( 'ycm.vimsupport.PostVimMessage' ) as post_vim_message:
request = CommandRequest( [ command ] )
request._response = {
'fixits': []
}
request.RunPostCommandActionsIfNeeded( 'botright' )
post_vim_message.assert_called_with(
'No fixits found for current line', warning = False )
replace_chunks.assert_not_called()
for command in [ 'FixIt', 'Refactor', 'GoToHell', 'any_old_garbade!!!21' ]:
with self.subTest( command = command ):
EmptyFixItTest( command )
def test_FixIt_Response( self ):
# Ensures we recognise and handle fixit responses with some dummy chunk data
def FixItTest( command, response, chunks, selection, silent ):
with patch( 'ycm.vimsupport.ReplaceChunks' ) as replace_chunks:
with patch( 'ycm.vimsupport.PostVimMessage' ) as post_vim_message:
with patch( 'ycm.vimsupport.SelectFromList',
return_value = selection ):
request = CommandRequest( [ command ] )
request._response = response
request.RunPostCommandActionsIfNeeded( 'leftabove' )
replace_chunks.assert_called_with( chunks, silent = silent )
post_vim_message.assert_not_called()
for command, response, chunks, selection, silent in [
[ 'AnythingYouLike',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'GoToEvenWorks',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'FixItWorks',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'and8434fd andy garbag!',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'Format',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, True ],
[ 'select from multiple 1',
MULTI_FIXIT, MULTI_FIXIT_FIRST_CHUNKS, 0, False ],
[ 'select from multiple 2',
MULTI_FIXIT, MULTI_FIXIT_SECOND_CHUNKS, 1, False ],
]:
with self.subTest( command = command,
response = response,
chunks = chunks,
selection = selection,
silent = silent ):
FixItTest( command, response, chunks, selection, silent )
def test_Message_Response( self ):
# Ensures we correctly recognise and handle responses with a message to show
# to the user
def MessageTest( command, message ):
with patch( 'ycm.vimsupport.PostVimMessage' ) as post_vim_message:
request = CommandRequest( [ command ] )
request._response = { 'message': message }
request.RunPostCommandActionsIfNeeded( 'rightbelow' )
post_vim_message.assert_called_with( message, warning = False )
for command, message in [
[ '___________', 'This is a message' ],
[ '', 'this is also a message' ],
[ 'GetType', 'std::string' ],
]:
with self.subTest( command = command, message = message ):
MessageTest( command, message )
def test_Detailed_Info( self ):
# Ensures we correctly detect and handle detailed_info responses which are
# used to display information in the preview window
def DetailedInfoTest( command, info ):
with patch( 'ycm.vimsupport.WriteToPreviewWindow' ) as write_to_preview:
request = CommandRequest( [ command ] )
request._response = { 'detailed_info': info }
request.RunPostCommandActionsIfNeeded( 'topleft' )
write_to_preview.assert_called_with( info, 'topleft' )
for command, info in [
[ '___________', 'This is a message' ],
[ '', 'this is also a message' ],
[ 'GetDoc', 'std::string\netc\netc' ],
]:
with self.subTest( command = command, info = info ):
DetailedInfoTest( command, info )
def test_GoTo_Single( self ):
for test, command, response in [
[ GoToTest, 'AnythingYouLike', BASIC_GOTO ],
[ GoToTest, 'GoTo', BASIC_GOTO ],
[ GoToTest, 'FindAThing', BASIC_GOTO ],
[ GoToTest, 'FixItGoto', BASIC_GOTO ],
[ GoToListTest, 'AnythingYouLike', [ BASIC_GOTO ] ],
[ GoToListTest, 'GoTo', [] ],
[ GoToListTest, 'FixItGoto', [ BASIC_GOTO, BASIC_GOTO ] ],
]:
with self.subTest( test = test, command = command, response = response ):
test( command, response )
| 10,655
|
Python
|
.py
| 259
| 34.250965
| 80
| 0.614961
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,979
|
completion_request_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/client/completion_request_test.py
|
# Copyright (C) 2015-2019 YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import json
from hamcrest import assert_that, equal_to
from unittest import TestCase
from ycm.tests import UserOptions
from ycm.tests.test_utils import MockVimModule
vim_mock = MockVimModule()
from ycm.client import completion_request
class ConvertCompletionResponseToVimDatasTest( TestCase ):
""" This class tests the
completion_request.ConvertCompletionResponseToVimDatas method """
def _Check( self, completion_data, expected_vim_data ):
vim_data = completion_request.ConvertCompletionDataToVimData(
completion_data )
try:
assert_that( vim_data, equal_to( expected_vim_data ) )
except Exception:
print( "Expected:\n"
f"'{ expected_vim_data }'\n"
"when parsing:\n'"
f"{ completion_data }'\n"
"But found:\n"
f"'{ vim_data }'" )
raise
def test_AllFields( self ):
extra_data = {
'doc_string': 'DOC STRING',
}
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'detailed_info': 'DETAILED INFO',
'extra_data': extra_data,
}, {
'word' : 'INSERTION TEXT',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : 'DETAILED INFO\nDOC STRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
def test_OnlyInsertionTextField( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT'
}, {
'word' : 'INSERTION TEXT',
'abbr' : '',
'menu' : '',
'kind' : '',
'info' : '',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': '{}',
} )
def test_JustDetailedInfo( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'detailed_info': 'DETAILED INFO',
}, {
'word' : 'INSERTION TEXT',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : 'DETAILED INFO',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': '{}',
} )
def test_JustDocString( self ):
extra_data = {
'doc_string': 'DOC STRING',
}
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'extra_data': extra_data,
}, {
'word' : 'INSERTION TEXT',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : 'DOC STRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
def test_ExtraInfoNoDocString( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'extra_data': {
},
}, {
'word' : 'INSERTION TEXT',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : '',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': '{}',
} )
def test_NullCharactersInExtraInfoAndDocString( self ):
extra_data = {
'doc_string': 'DOC\x00STRING'
}
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'detailed_info': 'DETAILED\x00INFO',
'extra_data': extra_data,
}, {
'word' : 'INSERTION TEXT',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : 'DETAILEDINFO\nDOCSTRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
def test_ExtraInfoNoDocStringWithDetailedInfo( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'detailed_info': 'DETAILED INFO',
'extra_data': {
},
}, {
'word' : 'INSERTION TEXT',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : 'DETAILED INFO',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': '{}',
} )
def test_EmptyInsertionText( self ):
extra_data = {
'doc_string': 'DOC STRING',
}
self._Check( {
'insertion_text': '',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'detailed_info': 'DETAILED INFO',
'extra_data': extra_data,
}, {
'word' : '',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : 'DETAILED INFO\nDOC STRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
def test_TruncateForPopup( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
}
self._Check( {
'insertion_text': '',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR',
'kind': 'K',
'detailed_info': 'DETAILED INFO',
'extra_data': extra_data,
}, {
'word' : '',
'abbr' : 'MENU TEXT',
'menu' : 'ESPECIALLY LONG E...',
'kind' : 'k',
'info' : 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR\n\n' +
'DETAILED INFO\nDOC STRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
def test_OnlyTruncateForPopupIfNecessary( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
}
self._Check( {
'insertion_text': '',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'EXTRA MENU INFO',
'kind': 'K',
'detailed_info': 'DETAILED INFO',
'extra_data': extra_data,
}, {
'word' : '',
'abbr' : 'MENU TEXT',
'menu' : 'EXTRA MENU INFO',
'kind' : 'k',
'info' : 'DETAILED INFO\nDOC STRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
def test_DontTruncateIfNotPopup( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'preview,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
}
self._Check( {
'insertion_text': '',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR',
'kind': 'K',
'detailed_info': 'DETAILED INFO',
'extra_data': extra_data,
}, {
'word' : '',
'abbr' : 'MENU TEXT',
'menu' : 'ESPECIALLY LONG EXTRA MENU INFO LOREM IPSUM DOLOR',
'kind' : 'k',
'info' : 'DETAILED INFO\nDOC STRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
def test_TruncateForPopupWithoutDuplication( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
}
self._Check( {
'insertion_text': '',
'menu_text': 'MENU TEXT',
'extra_menu_info': 'ESPECIALLY LONG METHOD SIGNATURE LOREM IPSUM',
'kind': 'K',
'detailed_info': 'ESPECIALLY LONG METHOD SIGNATURE LOREM IPSUM',
'extra_data': extra_data,
}, {
'word' : '',
'abbr' : 'MENU TEXT',
'menu' : 'ESPECIALLY LONG M...',
'kind' : 'k',
'info' : 'ESPECIALLY LONG METHOD SIGNATURE LOREM IPSUM\n' +
'DOC STRING',
'equal' : 1,
'dup' : 1,
'empty' : 1,
'user_data': json.dumps( extra_data ),
} )
| 9,479
|
Python
|
.py
| 291
| 25.728522
| 79
| 0.50546
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,980
|
base_request_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/client/base_request_test.py
|
# Copyright (C) 2017-2018 YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import MockVimBuffers, MockVimModule, VimBuffer
MockVimModule()
from hamcrest import assert_that, has_entry
from unittest import TestCase
from unittest.mock import patch
from ycm.client.base_request import BuildRequestData
class BaseRequestTest( TestCase ):
@patch( 'ycm.client.base_request.GetCurrentDirectory',
return_value = '/some/dir' )
def test_BuildRequestData_AddWorkingDir( self, *args ):
current_buffer = VimBuffer( 'foo' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( BuildRequestData(), has_entry( 'working_dir', '/some/dir' ) )
@patch( 'ycm.client.base_request.GetCurrentDirectory',
return_value = '/some/dir' )
def test_BuildRequestData_AddWorkingDirWithFileName( self, *args ):
current_buffer = VimBuffer( 'foo' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( BuildRequestData( current_buffer.number ),
has_entry( 'working_dir', '/some/dir' ) )
| 1,760
|
Python
|
.py
| 36
| 45.638889
| 80
| 0.748545
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,981
|
messages_request_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/client/messages_request_test.py
|
# Copyright (C) 2017 YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from ycm.tests.test_utils import MockVimModule
MockVimModule()
from hamcrest import assert_that, equal_to
from unittest import TestCase
from unittest.mock import patch, call
from ycm.client.messages_request import _HandlePollResponse
from ycm.tests.test_utils import ExtendedMock
class MessagesRequestTest( TestCase ):
def test_HandlePollResponse_NoMessages( self ):
assert_that( _HandlePollResponse( True, None ), equal_to( True ) )
# Other non-False responses mean the same thing
assert_that( _HandlePollResponse( '', None ), equal_to( True ) )
assert_that( _HandlePollResponse( 1, None ), equal_to( True ) )
assert_that( _HandlePollResponse( {}, None ), equal_to( True ) )
def test_HandlePollResponse_PollingNotSupported( self ):
assert_that( _HandlePollResponse( False, None ), equal_to( False ) )
# 0 is not False
assert_that( _HandlePollResponse( 0, None ), equal_to( True ) )
@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def test_HandlePollResponse_SingleMessage( self, post_vim_message ):
assert_that( _HandlePollResponse( [ { 'message': 'this is a message' } ] ,
None ),
equal_to( True ) )
post_vim_message.assert_has_exact_calls( [
call( 'this is a message', warning=False, truncate=True )
] )
@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def test_HandlePollResponse_MultipleMessages( self, post_vim_message ):
assert_that( _HandlePollResponse( [ { 'message': 'this is a message' },
{ 'message': 'this is another one' } ] ,
None ),
equal_to( True ) )
post_vim_message.assert_has_exact_calls( [
call( 'this is a message', warning=False, truncate=True ),
call( 'this is another one', warning=False, truncate=True )
] )
def test_HandlePollResponse_SingleDiagnostic( self ):
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER' ] },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls(
[
call( 'foo', [ 'PLACEHOLDER' ] )
] )
def test_HandlePollResponse_MultipleDiagnostics( self ):
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] },
{ 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] },
{ 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] },
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls(
[
call( 'foo', [ 'PLACEHOLDER1' ] ),
call( 'bar', [ 'PLACEHOLDER2' ] ),
call( 'baz', [ 'PLACEHOLDER3' ] ),
call( 'foo', [ 'PLACEHOLDER4' ] )
] )
@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def test_HandlePollResponse_MultipleMessagesAndDiagnostics(
self, post_vim_message ):
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] },
{ 'message': 'On the first day of Christmas, my VimScript gave to me' },
{ 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] },
{ 'message': 'A test file in a Command-T' },
{ 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] },
{ 'message': 'On the second day of Christmas, my VimScript gave to me' },
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] },
{ 'message': 'Two popup menus, and a test file in a Command-T' },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls(
[
call( 'foo', [ 'PLACEHOLDER1' ] ),
call( 'bar', [ 'PLACEHOLDER2' ] ),
call( 'baz', [ 'PLACEHOLDER3' ] ),
call( 'foo', [ 'PLACEHOLDER4' ] )
] )
post_vim_message.assert_has_exact_calls( [
call( 'On the first day of Christmas, my VimScript gave to me',
warning=False,
truncate=True ),
call( 'A test file in a Command-T', warning=False, truncate=True ),
call( 'On the second day of Christmas, my VimScript gave to me',
warning=False,
truncate=True ),
call( 'Two popup menus, and a test file in a Command-T',
warning=False,
truncate=True ),
] )
| 5,563
|
Python
|
.py
| 118
| 40.186441
| 80
| 0.646321
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,982
|
omni_completion_request_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/client/omni_completion_request_test.py
|
# Copyright (C) 2020 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from unittest import TestCase
from unittest.mock import MagicMock
from hamcrest import assert_that, has_entries
from ycm.client.omni_completion_request import OmniCompletionRequest
def BuildOmnicompletionRequest( results, start_column = 1 ):
omni_completer = MagicMock()
omni_completer.ComputeCandidates = MagicMock( return_value = results )
request_data = {
'line_num': 1,
'column_num': 1,
'start_column': start_column
}
request = OmniCompletionRequest( omni_completer, request_data )
request.Start()
return request
class OmniCompletionRequestTest( TestCase ):
def test_Done_AlwaysTrue( self ):
request = BuildOmnicompletionRequest( [] )
assert_that( request.Done() )
def test_Response_FromOmniCompleter( self ):
results = [ { "word": "test" } ]
request = BuildOmnicompletionRequest( results )
assert_that( request.Response(), has_entries( {
'line': 1,
'column': 1,
'completion_start_column': 1,
'completions': results
} ) )
| 1,743
|
Python
|
.py
| 44
| 36.568182
| 72
| 0.750445
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,983
|
debug_info_request_test.py
|
ycm-core_YouCompleteMe/python/ycm/tests/client/debug_info_request_test.py
|
# Copyright (C) 2017 YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
from copy import deepcopy
from hamcrest import assert_that, contains_string, equal_to
from unittest import TestCase
from ycm.client.debug_info_request import FormatDebugInfoResponse
GENERIC_RESPONSE = {
'clang': {
'has_support': True,
'version': 'Clang version'
},
'completer': {
'items': [
{
'key': 'key',
'value': 'value'
}
],
'name': 'Completer name',
'servers': [
{
'address': '127.0.0.1',
'executable': '/path/to/executable',
'extras': [
{
'key': 'key',
'value': 'value'
}
],
'is_running': True,
'logfiles': [
'/path/to/stdout/logfile',
'/path/to/stderr/logfile'
],
'name': 'Server name',
'pid': 12345,
'port': 1234
}
]
},
'extra_conf': {
'is_loaded': False,
'path': '/path/to/extra/conf'
},
'python': {
'executable': '/path/to/python/interpreter',
'version': 'Python version'
}
}
class DebugInfoRequestTest( TestCase ):
def test_FormatDebugInfoResponse_NoResponse( self ):
assert_that(
FormatDebugInfoResponse( None ),
equal_to( 'Server errored, no debug info from server\n' )
)
def test_FormatDebugInfoResponse_NoExtraConf( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': False,
'path': None
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'No extra configuration file found\n'
)
)
def test_FormatDebugInfoResponse_ExtraConfFoundButNotLoaded( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': False,
'path': '/path/to/extra/conf'
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Extra configuration file found but not loaded\n'
'Extra configuration path: /path/to/extra/conf\n'
)
)
def test_FormatDebugInfoResponse_ExtraConfFoundAndLoaded( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': True,
'path': '/path/to/extra/conf'
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Extra configuration file found and loaded\n'
'Extra configuration path: /path/to/extra/conf\n'
)
)
def test_FormatDebugInfoResponse_Completer_ServerRunningWithHost( self ):
response = deepcopy( GENERIC_RESPONSE )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name running at: http://127.0.0.1:1234\n'
' Server name process ID: 12345\n'
' Server name executable: /path/to/executable\n'
' Server name logfiles:\n'
' /path/to/stdout/logfile\n'
' /path/to/stderr/logfile\n'
' Server name key: value\n'
' Key: value\n'
)
)
def test_FormatDebugInfoResponse_Completer_ServerRunningWithoutHost( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'completer' ][ 'servers' ][ 0 ].update( {
'address': None,
'port': None
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name running\n'
' Server name process ID: 12345\n'
' Server name executable: /path/to/executable\n'
' Server name logfiles:\n'
' /path/to/stdout/logfile\n'
' /path/to/stderr/logfile\n'
' Server name key: value\n'
' Key: value\n'
)
)
def test_FormatDebugInfoResponse_Completer_ServerNotRunningWithNoLogfiles(
self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'completer' ][ 'servers' ][ 0 ].update( {
'is_running': False,
'logfiles': []
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name not running\n'
' Server name executable: /path/to/executable\n'
' No logfiles available\n'
' Server name key: value\n'
' Key: value\n'
)
)
| 5,100
|
Python
|
.py
| 161
| 25.621118
| 78
| 0.634424
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,984
|
.ycm_extra_conf.py
|
ycm-core_YouCompleteMe/python/ycm/tests/testdata/.ycm_extra_conf.py
|
def FlagsForFile( filename, **kwargs ):
temp_dir = kwargs[ 'client_data' ][ 'tempname()' ]
return {
'flags': [ temp_dir ],
'do_cache': False
}
| 158
|
Python
|
.py
| 6
| 22.833333
| 52
| 0.596026
|
ycm-core/YouCompleteMe
| 25,406
| 2,800
| 29
|
GPL-3.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,985
|
setup.py
|
OpenRCE_sulley/setup.py
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='sulley',
version=0.1,
description='A pure-python fully automated'
'and unattended fuzzing framework.',
author='OpenRCE',
packages=['sulley', 'sulley.legos', 'sulley.pgraph', 'sulley.utils'],
install_requires=[
'pydot'
]
)
| 340
|
Python
|
.py
| 13
| 21
| 73
| 0.646154
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,986
|
process_monitor.py
|
OpenRCE_sulley/process_monitor.py
|
#!c:\\python\\python.exe
import subprocess
import threading
import getopt
import time
import sys
import os
import pydbg
import pydbg.defines
import utils
from sulley import pedrpc
PORT = 26002
ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1)
USAGE = """USAGE: process_monitor.py
<-c|--crash_bin FILENAME> filename to serialize crash bin class to
[-p|--proc_name NAME] process name to search for and attach to
[-i|--ignore_pid PID] ignore this PID when searching for the target process
[-l|--log_level LEVEL] log level (default 1), increase for more verbosity
[--port PORT] TCP port to bind this agent to
"""
########################################################################################################################
class DebuggerThread (threading.Thread):
def __init__ (self, process_monitor, process, pid_to_ignore=None):
"""
Instantiate a new PyDbg instance and register user and access violation callbacks.
"""
threading.Thread.__init__(self)
self.process_monitor = process_monitor
self.proc_name = process
self.ignore_pid = pid_to_ignore
self.access_violation = False
self.active = True
self.dbg = pydbg.pydbg()
self.pid = None
# give this thread a unique name.
self.setName("%d" % time.time())
self.process_monitor.log("debugger thread initialized with UID: %s" % self.getName(), 5)
# set the user callback which is response for checking if this thread has been killed.
self.dbg.set_callback(pydbg.defines.USER_CALLBACK_DEBUG_EVENT, self.dbg_callback_user)
self.dbg.set_callback(pydbg.defines.EXCEPTION_ACCESS_VIOLATION, self.dbg_callback_access_violation)
def dbg_callback_access_violation (self, dbg):
"""
Ignore first chance exceptions. Record all unhandled exceptions to the process monitor crash bin and kill
the target process.
"""
# ignore first chance exceptions.
if dbg.dbg.u.Exception.dwFirstChance:
return pydbg.defines.DBG_EXCEPTION_NOT_HANDLED
# raise the access violation flag.
self.access_violation = True
# record the crash to the process monitor crash bin.
# include the test case number in the "extra" information block.
self.process_monitor.crash_bin.record_crash(dbg, self.process_monitor.test_number)
# save the the crash synopsis.
self.process_monitor.last_synopsis = self.process_monitor.crash_bin.crash_synopsis()
first_line = self.process_monitor.last_synopsis.split("\n")[0]
self.process_monitor.log("debugger thread-%s caught access violation: '%s'" % (self.getName(), first_line))
# this instance of pydbg should no longer be accessed, i want to know if it is.
self.process_monitor.crash_bin.pydbg = None
# kill the process.
dbg.terminate_process()
return pydbg.defines.DBG_CONTINUE
def dbg_callback_user (self, dbg):
"""
The user callback is run roughly every 100 milliseconds (WaitForDebugEvent() timeout from pydbg_core.py). Simply
check if the active flag was lowered and if so detach from the target process. The thread should then exit.
"""
if not self.active:
self.process_monitor.log("debugger thread-%s detaching" % self.getName(), 5)
dbg.detach()
return pydbg.defines.DBG_CONTINUE
def run (self):
"""
Main thread routine, called on thread.start(). Thread exits when this routine returns.
"""
self.process_monitor.log("debugger thread-%s looking for process name: %s" % (self.getName(), self.proc_name))
# watch for and try attaching to the process.
try:
self.watch()
self.dbg.attach(self.pid)
self.dbg.run()
self.process_monitor.log("debugger thread-%s exiting" % self.getName())
except:
pass
# TODO: removing the following line appears to cause some concurrency issues.
del self.dbg
def watch (self):
"""
Continuously loop, watching for the target process. This routine "blocks" until the target process is found.
Update self.pid when found and return.
"""
while not self.pid:
for (pid, name) in self.dbg.enumerate_processes():
# ignore the optionally specified PID.
if pid == self.ignore_pid:
continue
if name.lower() == self.proc_name.lower():
self.pid = pid
break
self.process_monitor.log("debugger thread-%s found match on pid %d" % (self.getName(), self.pid))
########################################################################################################################
class ProcessMonitorPedrpcServer (pedrpc.server):
def __init__ (self, host, port, crash_filename, proc=None, pid_to_ignore=None, level=1):
"""
@type host: str
@param host: Hostname or IP address
@type port: int
@param port: Port to bind server to
@type crash_filename: str
@param crash_filename: Name of file to (un)serialize crash bin to/from
@type proc: str
@param proc: (Optional, def=None) Process name to search for and attach to
@type pid_to_ignore: int
@param pid_to_ignore: (Optional, def=None) Ignore this PID when searching for the target process
@type level: int
@param level: (Optional, def=1) Log output level, increase for more verbosity
"""
# initialize the PED-RPC server.
pedrpc.server.__init__(self, host, port)
self.crash_filename = os.path.abspath(crash_filename)
self.proc_name = proc
self.ignore_pid = pid_to_ignore
self.log_level = level
self.stop_commands = []
self.start_commands = []
self.test_number = None
self.debugger_thread = None
self.crash_bin = utils.crash_binning.crash_binning()
self.last_synopsis = ""
if not os.access(os.path.dirname(self.crash_filename), os.X_OK):
self.log("invalid path specified for crash bin: %s" % self.crash_filename)
raise Exception
# restore any previously recorded crashes.
try:
self.crash_bin.import_file(self.crash_filename)
except:
pass
self.log("Process Monitor PED-RPC server initialized:")
self.log("\t crash file: %s" % self.crash_filename)
self.log("\t # records: %d" % len(self.crash_bin.bins))
self.log("\t proc name: %s" % self.proc_name)
self.log("\t log level: %d" % self.log_level)
self.log("awaiting requests...")
def alive (self):
"""
Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive.
"""
return True
def get_crash_synopsis (self):
"""
Return the last recorded crash synopsis.
@rtype: String
@return: Synopsis of last recorded crash.
"""
return self.last_synopsis
def get_bin_keys (self):
"""
Return the crash bin keys, ie: the unique list of exception addresses.
@rtype: List
@return: List of crash bin exception addresses (keys).
"""
return self.crash_bin.bins.keys()
def get_bin (self, binary):
"""
Return the crash entries from the specified bin or False if the bin key is invalid.
@type binary: Integer (DWORD)
@param binary: Crash bin key (ie: exception address)
@rtype: list
@return: List of crashes in specified bin.
"""
if binary not in self.crash_bin.bins:
return False
return self.crash_bin.bins[binary]
def log (self, msg="", level=1):
"""
If the supplied message falls under the current log level, print the specified message to screen.
@type msg: str
@param msg: Message to log
"""
if self.log_level >= level:
print "[%s] %s" % (time.strftime("%I:%M.%S"), msg)
def post_send (self):
"""
This routine is called after the fuzzer transmits a test case and returns the status of the target.
@rtype: bool
@return: Return True if the target is still active, False otherwise.
"""
crashes = 0
av = self.debugger_thread.access_violation
# if there was an access violation, wait for the debugger thread to finish then kill thread handle.
# it is important to wait for the debugger thread to finish because it could be taking its sweet ass time
# uncovering the details of the access violation.
if av:
while self.debugger_thread.isAlive():
time.sleep(1)
self.debugger_thread = None
# serialize the crash bin to disk.
self.crash_bin.export_file(self.crash_filename)
# for binary in self.crash_bin.bins.keys():
# crashes += len(self.crash_bin.bins[binary])
for binary, crash_list in self.crash_bin.bins.iteritems():
crashes += len(crash_list)
return not av
def pre_send (self, test_number):
"""
This routine is called before the fuzzer transmits a test case and ensure the debugger thread is operational.
@type test_number: Integer
@param test_number: Test number to retrieve PCAP for.
"""
self.log("pre_send(%d)" % test_number, 10)
self.test_number = test_number
# un-serialize the crash bin from disk. this ensures we have the latest copy (ie: vmware image is cycling).
try:
self.crash_bin.import_file(self.crash_filename)
except:
pass
# if we don't already have a debugger thread, instantiate and start one now.
if not self.debugger_thread or not self.debugger_thread.isAlive():
self.log("creating debugger thread", 5)
self.debugger_thread = DebuggerThread(self, self.proc_name, self.ignore_pid)
self.debugger_thread.start()
self.log("giving debugger thread 2 seconds to settle in", 5)
time.sleep(2)
def start_target (self):
"""
Start up the target process by issuing the commands in self.start_commands.
"""
self.log("starting target process")
for command in self.start_commands:
subprocess.Popen(command)
self.log("done. target up and running, giving it 5 seconds to settle in.")
time.sleep(5)
return True
def stop_target (self):
"""
Kill the current debugger thread and stop the target process by issuing the commands in self.stop_commands.
"""
# give the debugger thread a chance to exit.
time.sleep(1)
self.log("stopping target process")
for command in self.stop_commands:
if command == "TERMINATE_PID":
dbg = pydbg.pydbg()
for (pid, name) in dbg.enumerate_processes():
if name.lower() == self.proc_name.lower():
os.system("taskkill /pid %d" % pid)
break
else:
os.system(command)
def set_proc_name (self, new_proc_name):
self.log("updating target process name to '%s'" % new_proc_name)
self.proc_name = new_proc_name
def set_start_commands (self, new_start_commands):
self.log("updating start commands to: %s" % new_start_commands)
self.start_commands = new_start_commands
def set_stop_commands (self, new_stop_commands):
self.log("updating stop commands to: %s" % new_stop_commands)
self.stop_commands = new_stop_commands
########################################################################################################################
if __name__ == "__main__":
opts = None
# parse command line options.
try:
# TODO: Refactor to use something less dumb
opts, args = getopt.getopt(
sys.argv[1:],
"c:i:l:p:",
[
"crash_bin=",
"ignore_pid=",
"log_level=",
"proc_name=",
"port="
]
)
except getopt.GetoptError:
ERR(USAGE)
crash_bin = ignore_pid = proc_name = None
log_level = 1
for opt, arg in opts:
if opt in ("-c", "--crash_bin"):
crash_bin = arg
if opt in ("-i", "--ignore_pid"):
ignore_pid = int(arg)
if opt in ("-l", "--log_level"):
log_level = int(arg)
if opt in ("-p", "--proc_Name"):
proc_name = arg
if opt in ("-P", "--port"):
PORT = int(arg)
if not crash_bin:
ERR(USAGE)
# spawn the PED-RPC servlet.
try:
servlet = ProcessMonitorPedrpcServer("0.0.0.0", PORT, crash_bin, proc_name, ignore_pid, log_level)
servlet.serve_forever()
except Exception, e:
# TODO: Add servlet.shutdown
# TODO: Add KeyboardInterrupt
ERR("Error starting RPC server!\n\t%s" % e)
| 14,009
|
Python
|
.py
| 300
| 36.056667
| 121
| 0.574847
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,987
|
vmcontrol.py
|
OpenRCE_sulley/vmcontrol.py
|
#!/usr/bin/python
#!c:\\python\\python.exe
import os
import sys
import time
import getopt
try:
from win32api import GetShortPathName
from win32com.shell import shell
except:
if os.name == "nt":
print "[!] Failed to import win32api/win32com modules, please install these! Bailing..."
sys.exit(1)
from sulley import pedrpc
PORT = 26003
ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1)
USAGE = "USAGE: vmcontrol.py" \
"\n <-x|--vmx FILENAME|NAME> path to VMX to control or name of VirtualBox image" \
"\n <-r|--vmrun FILENAME> path to vmrun.exe or VBoxManage" \
"\n <-s|--snapshot NAME> set the snapshot name" \
"\n [-l|--log_level LEVEL] log level (default 1), increase for more verbosity" \
"\n [-i|--interactive] Interactive mode, prompts for input values" \
"\n [--port PORT] TCP port to bind this agent to" \
"\n [--vbox] control an Oracle VirtualBox VM"
########################################################################################################################
class vmcontrol_pedrpc_server (pedrpc.server):
def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False):
'''
@type host: String
@param host: Hostname or IP address to bind server to
@type port: Integer
@param port: Port to bind server to
@type vmrun: String
@param vmrun: Path to VMWare vmrun.exe
@type vmx: String
@param vmx: Path to VMX file
@type snap_name: String
@param snap_name: (Optional, def=None) Snapshot name to revert to on restart
@type log_level: Integer
@param log_level: (Optional, def=1) Log output level, increase for more verbosity
@type interactive: Boolean
@param interactive: (Option, def=False) Interactive mode, prompts for input values
'''
# initialize the PED-RPC server.
pedrpc.server.__init__(self, host, port)
self.host = host
self.port = port
self.interactive = interactive
if interactive:
print "[*] Entering interactive mode..."
# get vmrun path
try:
while 1:
print "[*] Please browse to the folder containing vmrun.exe..."
pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing vmrun.exe:")
fullpath = shell.SHGetPathFromIDList(pidl)
file_list = os.listdir(fullpath)
if "vmrun.exe" not in file_list:
print "[!] vmrun.exe not found in selected folder, please try again"
else:
vmrun = fullpath + "\\vmrun.exe"
print "[*] Using %s" % vmrun
break
except:
print "[!] Error while trying to find vmrun.exe. Try again without -i."
sys.exit(1)
# get vmx path
try:
while 1:
print "[*] Please browse to the folder containing the .vmx file..."
pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing the .vmx file:")
fullpath = shell.SHGetPathFromIDList(pidl)
file_list = os.listdir(fullpath)
exists = False
for file in file_list:
idx = file.find(".vmx")
if idx == len(file) - 4:
exists = True
vmx = fullpath + "\\" + file
print "[*] Using %s" % vmx
if exists:
break
else:
print "[!] No .vmx file found in the selected folder, please try again"
except:
raise
print "[!] Error while trying to find the .vmx file. Try again without -i."
sys.exit(1)
# Grab snapshot name and log level if we're in interactive mode
if interactive:
snap_name = raw_input("[*] Please enter the snapshot name: ")
log_level = raw_input("[*] Please enter the log level (default 1): ")
if log_level:
log_level = int(log_level)
else:
log_level = 1
# if we're on windows, get the DOS path names
if os.name == "nt":
self.vmrun = GetShortPathName(r"%s" % vmrun)
self.vmx = GetShortPathName(r"%s" % vmx)
else:
self.vmrun = vmrun
self.vmx = vmx
self.snap_name = snap_name
self.log_level = log_level
self.interactive = interactive
self.log("VMControl PED-RPC server initialized:")
self.log("\t vmrun: %s" % self.vmrun)
self.log("\t vmx: %s" % self.vmx)
self.log("\t snap name: %s" % self.snap_name)
self.log("\t log level: %d" % self.log_level)
self.log("Awaiting requests...")
def alive (self):
'''
Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive.
'''
return True
def log (self, msg="", level=1):
'''
If the supplied message falls under the current log level, print the specified message to screen.
@type msg: String
@param msg: Message to log
'''
if self.log_level >= level:
print "[%s] %s" % (time.strftime("%I:%M.%S"), msg)
def set_vmrun (self, vmrun):
self.log("setting vmrun to %s" % vmrun, 2)
self.vmrun = vmrun
def set_vmx (self, vmx):
self.log("setting vmx to %s" % vmx, 2)
self.vmx = vmx
def set_snap_name (self, snap_name):
self.log("setting snap_name to %s" % snap_name, 2)
self.snap_name = snap_name
def vmcommand (self, command):
'''
Execute the specified command, keep trying in the event of a failure.
@type command: String
@param command: VMRun command to execute
'''
while 1:
self.log("executing: %s" % command, 5)
pipe = os.popen(command)
out = pipe.readlines()
try:
pipe.close()
except IOError:
self.log("IOError trying to close pipe")
if not out:
break
elif not out[0].lower().startswith("close failed"):
break
self.log("failed executing command '%s' (%s). will try again." % (command, out))
time.sleep(1)
return "".join(out)
###
### VMRUN COMMAND WRAPPERS
###
def delete_snapshot (self, snap_name=None):
if not snap_name:
snap_name = self.snap_name
self.log("deleting snapshot: %s" % snap_name, 2)
command = self.vmrun + " deleteSnapshot " + self.vmx + " " + '"' + snap_name + '"'
return self.vmcommand(command)
def list (self):
self.log("listing running images", 2)
command = self.vmrun + " list"
return self.vmcommand(command)
def list_snapshots (self):
self.log("listing snapshots", 2)
command = self.vmrun + " listSnapshots " + self.vmx
return self.vmcommand(command)
def reset (self):
self.log("resetting image", 2)
command = self.vmrun + " reset " + self.vmx
return self.vmcommand(command)
def revert_to_snapshot (self, snap_name=None):
if not snap_name:
snap_name = self.snap_name
self.log("reverting to snapshot: %s" % snap_name, 2)
command = self.vmrun + " revertToSnapshot " + self.vmx + " " + '"' + snap_name + '"'
return self.vmcommand(command)
def snapshot (self, snap_name=None):
if not snap_name:
snap_name = self.snap_name
self.log("taking snapshot: %s" % snap_name, 2)
command = self.vmrun + " snapshot " + self.vmx + " " + '"' + snap_name + '"'
return self.vmcommand(command)
def start (self):
self.log("starting image", 2)
command = self.vmrun + " start " + self.vmx
return self.vmcommand(command)
def stop (self):
self.log("stopping image", 2)
command = self.vmrun + " stop " + self.vmx
return self.vmcommand(command)
def suspend (self):
self.log("suspending image", 2)
command = self.vmrun + " suspend " + self.vmx
return self.vmcommand(command)
###
### EXTENDED COMMANDS
###
def restart_target (self):
self.log("restarting virtual machine...")
# revert to the specified snapshot and start the image.
self.revert_to_snapshot()
self.start()
# wait for the snapshot to come alive.
self.wait()
def is_target_running (self):
# sometimes vmrun reports that the VM is up while it's still reverting.
time.sleep(10)
for line in self.list().lower().split('\n'):
if os.name == "nt":
try:
line = GetShortPathName(line)
# skip invalid paths.
except:
continue
if self.vmx.lower() == line.lower():
return True
return False
def wait (self):
self.log("waiting for vmx to come up: %s" % self.vmx)
while 1:
if self.is_target_running():
break
########################################################################################################################
########################################################################################################################
class vboxcontrol_pedrpc_server (vmcontrol_pedrpc_server):
def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False):
'''
Controls an Oracle VirtualBox Virtual Machine
@type host: String
@param host: Hostname or IP address to bind server to
@type port: Integer
@param port: Port to bind server to
@type vmrun: String
@param vmrun: Path to VBoxManage
@type vmx: String
@param vmx: Name of the virtualbox VM to control (no quotes)
@type snap_name: String
@param snap_name: (Optional, def=None) Snapshot name to revert to on restart
@type log_level: Integer
@param log_level: (Optional, def=1) Log output level, increase for more verbosity
@type interactive: Boolean
@param interactive: (Option, def=False) Interactive mode, prompts for input values
'''
# initialize the PED-RPC server.
pedrpc.server.__init__(self, host, port)
self.host = host
self.port = port
self.interactive = interactive
if interactive:
print "[*] Entering interactive mode..."
# get vmrun path
try:
while 1:
print "[*] Please browse to the folder containing VBoxManage.exe..."
pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing VBoxManage.exe")
fullpath = shell.SHGetPathFromIDList(pidl)
file_list = os.listdir(fullpath)
if "VBoxManage.exe" not in file_list:
print "[!] VBoxManage.exe not found in selected folder, please try again"
else:
vmrun = fullpath + "\\VBoxManage.exe"
print "[*] Using %s" % vmrun
break
except:
print "[!] Error while trying to find VBoxManage.exe. Try again without -I."
sys.exit(1)
# Grab vmx, snapshot name and log level if we're in interactive mode
if interactive:
vmx = raw_input("[*] Please enter the VirtualBox virtual machine name: ")
snap_name = raw_input("[*] Please enter the snapshot name: ")
log_level = raw_input("[*] Please enter the log level (default 1): ")
if log_level:
log_level = int(log_level)
else:
log_level = 1
# if we're on windows, get the DOS path names
if os.name == "nt":
self.vmrun = GetShortPathName(r"%s" % vmrun)
self.vmx = GetShortPathName(r"%s" % vmx)
else:
self.vmrun = vmrun
self.vmx = vmx
self.snap_name = snap_name
self.log_level = log_level
self.interactive = interactive
self.log("VirtualBox PED-RPC server initialized:")
self.log("\t vboxmanage: %s" % self.vmrun)
self.log("\t machine name: %s" % self.vmx)
self.log("\t snap name: %s" % self.snap_name)
self.log("\t log level: %d" % self.log_level)
self.log("Awaiting requests...")
###
### VBOXMANAGE COMMAND WRAPPERS
###
def delete_snapshot (self, snap_name=None):
if not snap_name:
snap_name = self.snap_name
self.log("deleting snapshot: %s" % snap_name, 2)
command = self.vmrun + " snapshot " + self.vmx + " delete " + snap_name + '"'
return self.vmcommand(command)
def list (self):
self.log("listing running images", 2)
command = self.vmrun + " list runningvms"
return self.vmcommand(command)
def list_snapshots (self):
self.log("listing snapshots", 2)
command = self.vmrun + " snapshot " + self.vmx + " list"
return self.vmcommand(command)
def reset (self):
self.log("resetting image", 2)
command = self.vmrun + " controlvm " + self.vmx + " reset"
return self.vmcommand(command)
def pause (self):
self.log("pausing image", 2)
command = self.vmrun + " controlvm " + self.vmx + " pause"
return self.vmcommand(command)
def resume (self):
self.log("resuming image", 2)
command = self.vmrun + " controlvm " + self.vmx + " resume"
return self.vmcommand(command)
def revert_to_snapshot (self, snap_name=None):
if not snap_name:
snap_name = self.snap_name
#VirtualBox flips out if you try to do this with a running VM
if self.is_target_running():
self.stop()
self.log("reverting to snapshot: %s" % snap_name, 2)
command = self.vmrun + " snapshot " + self.vmx + " restore " + snap_name
return self.vmcommand(command)
def snapshot (self, snap_name=None):
if not snap_name:
snap_name = self.snap_name
#VirtualBox flips out if you try to do this with a running VM
if self.is_target_running():
self.pause()
self.log("taking snapshot: %s" % snap_name, 2)
command = self.vmrun + " snapshot " + self.vmx + " take " + snap_name
return self.vmcommand(command)
def start (self):
self.log("starting image", 2)
command = self.vmrun + " startvm " + self.vmx
# TODO: we may want to do more here with headless, gui, etc...
return self.vmcommand(command)
def stop (self):
self.log("stopping image", 2)
command = self.vmrun + " controlvm " + self.vmx + " poweroff"
return self.vmcommand(command)
def suspend (self):
self.log("suspending image", 2)
command = self.vmrun + " controlvm " + self.vmx + " pause"
return self.vmcommand(command)
###
### EXTENDED COMMANDS
###
#added a function here to get vminfo... useful for parsing stuff out later
def get_vminfo(self):
self.log("getting vminfo", 2)
command = self.vmrun + " showvminfo " + self.vmx + " --machinereadable"
return self.vmcommand(command)
def restart_target (self):
self.log("restarting virtual machine...")
#VirtualBox flips out if you try to do this with a running VM
if self.is_target_running():
self.stop()
# revert to the specified snapshot and start the image.
self.revert_to_snapshot()
self.start()
# wait for the snapshot to come alive.
self.wait()
def is_target_running (self):
# sometimes vmrun reports that the VM is up while it's still reverting.
time.sleep(10)
for line in self.get_vminfo().split('\n'):
if line == 'VMState="running"':
return True
return False
def is_target_paused (self):
time.sleep(10)
for line in self.get_vminfo().split('\n'):
if line == 'VMState="paused"':
return True
return False
########################################################################################################################
if __name__ == "__main__":
# parse command line options.
try:
opts, args = getopt.getopt(sys.argv[1:], "x:r:s:l:i", ["vmx=", "vmrun=", "snapshot=", "log_level=", "interactive", "port=", "vbox"])
except getopt.GetoptError:
ERR(USAGE)
vmrun = None
vmx = None
snap_name = None
log_level = 1
interactive = False
virtualbox = False
for opt, arg in opts:
if opt in ("-x", "--vmx"): vmx = arg
if opt in ("-r", "--vmrun"): vmrun = arg
if opt in ("-s", "--snapshot"): snap_name = arg
if opt in ("-l", "--log_level"): log_level = int(arg)
if opt in ("-i", "--interactive"): interactive = True
if opt in ("--port"): PORT = int(arg)
if opt in ("--vbox"): virtualbox = True
# OS check
if interactive and not os.name == "nt":
print "[!] Interactive mode currently only works on Windows operating systems."
ERR(USAGE)
if (not vmx or not vmrun or not snap_name) and not interactive:
ERR(USAGE)
if not virtualbox:
servlet = vmcontrol_pedrpc_server("0.0.0.0", PORT, vmrun, vmx, snap_name, log_level, interactive)
elif virtualbox:
servlet = vboxcontrol_pedrpc_server("0.0.0.0", PORT, vmrun, vmx, snap_name, log_level, interactive)
servlet.serve_forever()
| 18,965
|
Python
|
.py
| 420
| 34.404762
| 140
| 0.536104
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,988
|
network_monitor.py
|
OpenRCE_sulley/network_monitor.py
|
#!c:\\python\\python.exe
import threading
import getopt
import time
import sys
import os
import pcapy
import impacket
import impacket.ImpactDecoder
import signal
from sulley import pedrpc
def log_error(message=None):
try:
sys.stderr.write("ERR> %s\n" % message) or sys.exit(1)
except Exception, e:
print e
sys.exit(1)
def create_usage():
message = """USAGE: network_monitor.py
<-d|--device DEVICE #> device to sniff on (see list below)
[-f|--filter PCAP FILTER] BPF filter string
[-P|--log_path PATH] log directory to store pcaps to
[-l|--log_level LEVEL] log level (default 1), increase for more verbosity
[--port PORT] TCP port to bind this agent to
Network Device List:
"""
for index, pcapy_device in enumerate(pcapy.findalldevs()):
IFS.append(pcapy_device)
# if we are on windows, try and resolve the device UUID into an IP address.
if sys.platform.startswith("win"):
import _winreg
try:
# extract the device UUID and open the TCP/IP parameters key for it.
pcapy_device = pcapy_device[pcapy_device.index("{"):pcapy_device.index("}") + 1]
subkey = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % pcapy_device
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey)
# if there is a DHCP address snag that, otherwise fall back to the IP address.
try:
ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0]
except:
ip = _winreg.QueryValueEx(key, "IPAddress")[0][0]
pcapy_device = pcapy_device + "\t" + ip
except:
pass
message += " [%d] %s\n" % (index, pcapy_device)
return message
########################################################################################################################
class PcapThread (threading.Thread):
def __init__ (self, network_monitor, pcap, pcap_save_path):
self.network_monitor = network_monitor
self.pcap = pcap
self.decoder = None
self.dumper = self.pcap.dump_open(pcap_save_path)
self.active = True
self.data_bytes = 0
# register the appropriate decoder.
if pcap.datalink() == pcapy.DLT_EN10MB or pcap.datalink() == pcapy.DLT_NULL:
self.decoder = impacket.ImpactDecoder.EthDecoder()
elif pcap.datalink() == pcapy.DLT_LINUX_SLL:
self.decoder = impacket.ImpactDecoder.LinuxSLLDecoder()
else:
raise Exception
threading.Thread.__init__(self)
def packet_handler (self, header, data):
# add the captured data to the PCAP.
self.dumper.dump(header, data)
# increment the captured byte count.
self.data_bytes += len(data)
# log the decoded data at the appropriate log level.
self.network_monitor.log(self.decoder.decode(data), 15)
def run (self):
# process packets while the active flag is raised.
while self.active:
self.pcap.dispatch(0, self.packet_handler)
########################################################################################################################
class NetworkMonitorPedrpcServer (pedrpc.server):
def __init__ (self, host, port, monitor_device, bpf_filter="", path="./", level=1):
"""
@type host: str
@param host: Hostname or IP address to bind server to
@type port: int
@param port: Port to bind server to
@type monitor_device: str
@param monitor_device: Name of device to capture packets on
@type bpf_filter: str
@param bpf_filter: BPF filter to apply to the capture
@type path: str
@param path: (Optional, def="./") Path to save recorded PCAPs to
@type level: int
@param level: (Optional, def=1) Log output level, increase for more verbosity
"""
# initialize the PED-RPC server.
pedrpc.server.__init__(self, host, port)
self.device = monitor_device
self.filter = bpf_filter
self.log_path = path
self.log_level = level
self.pcap = None
self.pcap_thread = None
# ensure the log path is valid.
if not os.access(self.log_path, os.X_OK):
self.log("invalid log path: %s" % self.log_path)
raise Exception
self.log("Network Monitor PED-RPC server initialized:")
self.log("\t device: %s" % self.device)
self.log("\t filter: %s" % self.filter)
self.log("\t log path: %s" % self.log_path)
self.log("\t log_level: %d" % self.log_level)
self.log("Awaiting requests...")
def __stop (self):
"""
Kill the PCAP thread.
"""
if self.pcap_thread:
self.log("stopping active packet capture thread.", 10)
self.pcap_thread.active = False
self.pcap_thread = None
def alive (self):
"""
Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive.
"""
return True
def post_send (self):
"""
This routine is called after the fuzzer transmits a test case and returns the number of bytes captured by the
PCAP thread.
@rtype: Integer
@return: Number of bytes captured in PCAP thread.
"""
# grab the number of recorded bytes.
data_bytes = self.pcap_thread.data_bytes
# stop the packet capture thread.
self.__stop()
self.log("stopped PCAP thread, snagged %d bytes of data" % data_bytes)
return data_bytes
def pre_send (self, test_number):
"""
This routine is called before the fuzzer transmits a test case and spin off a packet capture thread.
"""
self.log("initializing capture for test case #%d" % test_number)
# open the capture device and set the BPF filter.
self.pcap = pcapy.open_live(self.device, -1, 1, 100)
self.pcap.setfilter(self.filter)
# instantiate the capture thread.
pcap_log_path = "%s/%d.pcap" % (self.log_path, test_number)
self.pcap_thread = PcapThread(self, self.pcap, pcap_log_path)
self.pcap_thread.start()
def log (self, msg="", level=1):
"""
If the supplied message falls under the current log level, print the specified message to screen.
@type msg: str
@param msg: Message to log
"""
if self.log_level >= level:
print "[%s] %s" % (time.strftime("%I:%M.%S"), msg)
def retrieve (self, test_number):
"""
Return the raw binary contents of the PCAP saved for the specified test case number.
@type test_number: int
@param test_number: Test number to retrieve PCAP for.
"""
self.log("retrieving PCAP for test case #%d" % test_number)
pcap_log_path = "%s/%d.pcap" % (self.log_path, test_number)
fh = open(pcap_log_path, "rb")
data = fh.read()
fh.close()
return data
def set_filter (self, new_filter):
self.log("updating PCAP filter to '%s'" % new_filter)
self.filter = new_filter
def set_log_path (self, new_log_path):
self.log("updating log path to '%s'" % new_log_path)
self.log_path = new_log_path
########################################################################################################################
if __name__ == "__main__":
IFS = []
usage_message = create_usage()
rpc_port = 26001
opts = None
# parse command line options.
try:
opts, args = getopt.getopt(sys.argv[1:], "d:f:P:l:", ["device=", "filter=", "log_path=", "log_level=", "port="])
except getopt.GetoptError:
log_error(usage_message)
device = None
pcap_filter = ""
log_path = "./"
log_level = 1
for opt, arg in opts:
if opt in ("-d", "--device"):
device = IFS[int(arg)]
if opt in ("-f", "--filter"):
pcap_filter = arg
if opt in ("-P", "--log_path"):
log_path = arg
if opt in ("-l", "--log_level"):
log_level = int(arg)
if opt in "--port":
rpc_port = int(arg)
if not device:
log_error(usage_message)
try:
servlet = NetworkMonitorPedrpcServer("0.0.0.0", rpc_port, device, pcap_filter, log_path, log_level)
t = threading.Thread(target=servlet.serve_forever)
t.daemon = True
t.start()
# Now wait in a way that will not block signals like SIGINT
try:
while True:
signal.pause()
except AttributeError:
# signal.pause() is missing for Windows; wait 1ms and loop instead
while True:
time.sleep(.001)
except:
pass
| 9,203
|
Python
|
.py
| 216
| 33.907407
| 120
| 0.559897
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,989
|
process_monitor_unix.py
|
OpenRCE_sulley/process_monitor_unix.py
|
import os
import sys
import getopt
import signal
import time
import threading
from sulley import pedrpc
'''
By nnp
http://www.unprotectedhex.com
This intended as a basic replacement for Sulley's process_monitor.py on *nix.
The below options are accepted. Crash details are limited to the signal that
caused the death and whatever operating system supported mechanism is in place (i.e
core dumps)
Replicated methods:
- alive
- log
- post_send
- pre_send
_ start_target
- stop_target
- set_start_commands
- set_stop_commands
Limitations
- Cannot attach to an already running process
- Currently only accepts one start_command
- Limited 'crash binning'. Relies on the availability of core dumps. These
should be created in the same directory the process is ran from on Linux
and in the (hidden) /cores directory on OS X. On OS X you have to add
the option COREDUMPS=-YES- to /etc/hostconfig and then `ulimit -c
unlimited` as far as I know. A restart may be required. The file
specified by crash_bin will any other available details such as the test
that caused the crash and the signal received by the program
'''
USAGE = "USAGE: process_monitor_unix.py"\
"\n -c|--crash_bin File to record crash info too" \
"\n [-P|--port PORT] TCP port to bind this agent too"\
"\n [-l|--log_level LEVEL] log level (default 1), increase for more verbosity"
ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1)
class debugger_thread:
def __init__(self, start_command):
'''
This class isn't actually ran as a thread, only the start_monitoring
method is. It can spawn/stop a process, wait for it to exit and report on
the exit status/code.
'''
self.start_command = start_command
self.tokens = start_command.split(' ')
self.cmd_args = []
self.pid = None
self.exit_status = None
self.alive = False
def spawn_target(self):
print self.tokens
self.pid = os.spawnv(os.P_NOWAIT, self.tokens[0], self.tokens)
self.alive = True
def start_monitoring(self):
'''
self.exit_status = os.waitpid(self.pid, os.WNOHANG | os.WUNTRACED)
while self.exit_status == (0, 0):
self.exit_status = os.waitpid(self.pid, os.WNOHANG | os.WUNTRACED)
'''
self.exit_status = os.waitpid(self.pid, 0)
# [0] is the pid
self.exit_status = self.exit_status[1]
self.alive = False
def get_exit_status(self):
return self.exit_status
def stop_target(self):
os.kill(self.pid, signal.SIGKILL)
self.alive = False
def isAlive(self):
return self.alive
########################################################################################################################
class nix_process_monitor_pedrpc_server(pedrpc.server):
def __init__(self, host, port, crash_bin, log_level=1):
'''
@type host: String
@param host: Hostname or IP address
@type port: Integer
@param port: Port to bind server to
@type crash_bin: String
@param crash_bin: Where to save monitored process crashes for analysis
'''
pedrpc.server.__init__(self, host, port)
self.crash_bin = crash_bin
self.log_level = log_level
self.dbg = None
self.log("Process Monitor PED-RPC server initialized:")
self.log("Listening on %s:%s" % (host, port))
self.log("awaiting requests...")
def alive (self):
'''
Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive.
'''
return True
def log (self, msg="", level=1):
'''
If the supplied message falls under the current log level, print the specified message to screen.
@type msg: String
@param msg: Message to log
'''
if self.log_level >= level:
print "[%s] %s" % (time.strftime("%I:%M.%S"), msg)
def post_send (self):
'''
This routine is called after the fuzzer transmits a test case and returns the status of the target.
@rtype: Boolean
@return: Return True if the target is still active, False otherwise.
'''
if not self.dbg.isAlive():
exit_status = self.dbg.get_exit_status()
rec_file = open(self.crash_bin, 'a')
if os.WCOREDUMP(exit_status):
reason = 'Segmentation fault'
elif os.WIFSTOPPED(exit_status):
reason = 'Stopped with signal ' + str(os.WTERMSIG(exit_status))
elif os.WIFSIGNALED(exit_status):
reason = 'Terminated with signal ' + str(os.WTERMSIG(exit_status))
elif os.WIFEXITED(exit_status):
reason = 'Exit with code - ' + str(os.WEXITSTATUS(exit_status))
else:
reason = 'Process died for unknown reason'
self.last_synopsis = '[%s] Crash : Test - %d Reason - %s\n' % (time.strftime("%I:%M.%S"), self.test_number, reason)
rec_file.write(self.last_synopsis)
rec_file.close()
return self.dbg.isAlive()
def pre_send (self, test_number):
'''
This routine is called before the fuzzer transmits a test case and ensure the debugger thread is operational.
(In this implementation do nothing for now)
@type test_number: Integer
@param test_number: Test number to retrieve PCAP for.
'''
if self.dbg == None:
self.start_target()
self.log("pre_send(%d)" % test_number, 10)
self.test_number = test_number
def start_target (self):
'''
Start up the target process by issuing the commands in self.start_commands.
'''
self.log("starting target process")
self.dbg = debugger_thread(self.start_commands[0])
self.dbg.spawn_target()
# prevent blocking by spawning off another thread to waitpid
threading.Thread(target=self.dbg.start_monitoring).start()
self.log("done. target up and running, giving it 5 seconds to settle in.")
time.sleep(5)
def stop_target (self):
'''
Kill the current debugger thread and stop the target process by issuing the commands in self.stop_commands.
'''
# give the debugger thread a chance to exit.
time.sleep(1)
self.log("stopping target process")
for command in self.stop_commands:
if command == "TERMINATE_PID":
self.dbg.stop_target()
else:
os.system(command)
def set_start_commands (self, start_commands):
'''
We expect start_commands to be a list with one element for example
['/usr/bin/program arg1 arg2 arg3']
'''
if len(start_commands) > 1:
self.log("This process monitor does not accept > 1 start command")
return
self.log("updating start commands to: %s" % start_commands)
self.start_commands = start_commands
def set_stop_commands (self, stop_commands):
self.log("updating stop commands to: %s" % stop_commands)
self.stop_commands = stop_commands
def set_proc_name (self, proc_name):
self.log("updating target process name to '%s'" % proc_name)
self.proc_name = proc_name
def get_crash_synopsis (self):
'''
Return the last recorded crash synopsis.
@rtype: String
@return: Synopsis of last recorded crash.
'''
return self.last_synopsis
########################################################################################################################
if __name__ == "__main__":
# parse command line options.
try:
opts, args = getopt.getopt(sys.argv[1:], "c:P:l:", ["crash_bin=","port=","log_level=",])
except getopt.GetoptError:
ERR(USAGE)
log_level = 1
PORT = None
crash_bin = None
for opt, arg in opts:
if opt in ("-c", "--crash_bin"): crash_bin = arg
if opt in ("-P", "--port"): PORT = int(arg)
if opt in ("-l", "--log_level"): log_level = int(arg)
if not crash_bin: ERR(USAGE)
if PORT == None:
PORT = 26002
# spawn the PED-RPC servlet.
servlet = nix_process_monitor_pedrpc_server("0.0.0.0", PORT, crash_bin, log_level)
servlet.serve_forever()
| 8,707
|
Python
|
.py
| 204
| 33.970588
| 127
| 0.598346
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,990
|
fuzz_trillian_jabber.py
|
OpenRCE_sulley/examples/fuzz_trillian_jabber.py
|
#!c:\\python\\python.exe
#
# pedram amini <pamini@tippingpoint.com>
#
# on vmware:
# cd shared\sulley\branches\pedram
# network_monitor.py -d 1 -f "src or dst port 5298" -p audits\trillian_jabber
# process_monitor.py -c audits\trillian_jabber.crashbin -p trillian.exe
#
# on localhost:
# vmcontrol.py -r "c:\Progra~1\VMware\VMware~1\vmrun.exe" -x "v:\vmfarm\images\windows\xp\win_xp_pro-clones\allsor~1\win_xp_pro.vmx" --snapshot "sulley ready and waiting"
#
# note:
# you MUST register the IP address of the fuzzer as a valid MDNS "presence" host. to do so, simply install and
# launch trillian on the fuzz box with rendezvous enabled. otherwise the target will drop the connection.
#
from sulley import *
from requests import jabber
def init_message (sock):
init = '<?xml version="1.0" encoding="UTF-8" ?>\n'
init += '<stream:stream to="152.67.137.126" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">'
sock.send(init)
sock.recv(1024)
sess = sessions.session(session_filename="audits/trillian.session")
target = sessions.target("152.67.137.126", 5298)
target.netmon = pedrpc.client("152.67.137.126", 26001)
target.procmon = pedrpc.client("152.67.137.126", 26002)
target.vmcontrol = pedrpc.client("127.0.0.1", 26003)
target.procmon_options = { "proc_name" : "trillian.exe" }
# start up the target.
target.vmcontrol.restart_target()
print "virtual machine up and running"
sess.add_target(target)
sess.pre_send = init_message
sess.connect(sess.root, s_get("chat message"))
sess.fuzz()
| 1,618
|
Python
|
.py
| 36
| 43.305556
| 174
| 0.702857
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,991
|
fuzz_trend_server_protect_5168.py
|
OpenRCE_sulley/examples/fuzz_trend_server_protect_5168.py
|
#!c:\\python\\python.exe
#
# pedram amini <pamini@tippingpoint.com>
#
# on vmware:
# cd shared\sulley\branches\pedram
# process_monitor.py -c audits\trend_server_protect_5168.crashbin -p SpntSvc.exe
# network_monitor.py -d 1 -f "src or dst port 5168" -p audits\trend_server_protect_5168
#
# on localhost:
# vmcontrol.py -r "c:\Progra~1\VMware\VMware~1\vmrun.exe" -x "v:\vmfarm\images\windows\2000\win_2000_pro-clones\TrendM~1\win_2000_pro.vmx" --snapshot "sulley ready and waiting"
#
# this key gets written which fucks trend service even on reboot.
# HKEY_LOCAL_MACHINE\SOFTWARE\TrendMicro\ServerProtect\CurrentVersion\Engine
#
# uncomment the req/num to do a single test case.
#
import time
from sulley import *
from requests import trend
req = num = None
#req = "5168: op-3"
#num = "\x04"
def rpc_bind (sock):
bind = utils.dcerpc.bind("25288888-bd5b-11d1-9d53-0080c83a5c2c", "1.0")
sock.send(bind)
utils.dcerpc.bind_ack(sock.recv(1000))
def do_single (req, num):
import socket
# connect to the server.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.181.133", 5168))
# send rpc bind.
rpc_bind(s)
request = s_get(req)
while 1:
if request.names["subs"].value == num:
break
s_mutate()
print "xmitting single test case"
s.send(s_render())
print "done."
def do_fuzz ():
sess = sessions.session(session_filename="audits/trend_server_protect_5168.session")
target = sessions.target("192.168.181.133", 5168)
target.netmon = pedrpc.client("192.168.181.133", 26001)
target.procmon = pedrpc.client("192.168.181.133", 26002)
target.vmcontrol = pedrpc.client("127.0.0.1", 26003)
target.procmon_options = \
{
"proc_name" : "SpntSvc.exe",
"stop_commands" : ['net stop "trend serverprotect"'],
"start_commands" : ['net start "trend serverprotect"'],
}
# start up the target.
target.vmcontrol.restart_target()
print "virtual machine up and running"
sess.add_target(target)
sess.pre_send = rpc_bind
sess.connect(s_get("5168: op-1"))
sess.connect(s_get("5168: op-2"))
sess.connect(s_get("5168: op-3"))
sess.connect(s_get("5168: op-5"))
sess.connect(s_get("5168: op-a"))
sess.connect(s_get("5168: op-1f"))
sess.fuzz()
print "done fuzzing. web interface still running."
if not req or not num:
do_fuzz()
else:
do_single(req, num)
| 2,497
|
Python
|
.py
| 71
| 31.028169
| 180
| 0.671244
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,992
|
mdns.py
|
OpenRCE_sulley/examples/mdns.py
|
#!/usr/bin/python
# A partial MDNS fuzzer. Could be made to be a DNS fuzzer trivially
# Charlie Miller <cmiller@securityevaluators.com>
from sulley import *
from binascii import *
from struct import *
def insert_questions (sess, node, edge, sock):
node.names['Questions'].value = 1+node.names['queries'].current_reps
node.names['Authority'].value = 1+node.names['auth_nameservers'].current_reps
s_initialize("query")
s_word(0, name="TransactionID")
s_word(0, name="Flags")
s_word(1, name="Questions", endian='>')
s_word(0, name="Answer", endian='>')
s_word(1, name="Authority", endian='>')
s_word(0, name="Additional", endian='>')
######### Queries ################
if s_block_start("query"):
if s_block_start("name_chunk"):
s_size("string", length=1)
if s_block_start("string"):
s_string("A"*10)
s_block_end()
s_block_end()
s_repeat("name_chunk", min_reps=2, max_reps=4, step=1, fuzzable=True, name="aName")
s_group("end", values=["\x00", "\xc0\xb0"]) # very limited pointer fuzzing
s_word(0xc, name="Type", endian='>')
s_word(0x8001, name="Class", endian='>')
s_block_end()
s_repeat("query", 0, 1000, 40, name="queries")
######## Authorities ############
if s_block_start("auth_nameserver"):
if s_block_start("name_chunk_auth"):
s_size("string_auth", length=1)
if s_block_start("string_auth"):
s_string("A"*10)
s_block_end()
s_block_end()
s_repeat("name_chunk_auth", min_reps=2, max_reps=4, step=1, fuzzable=True, name="aName_auth")
s_group("end_auth", values=["\x00", "\xc0\xb0"]) # very limited pointer fuzzing
s_word(0xc, name="Type_auth", endian='>')
s_word(0x8001, name="Class_auth", endian='>')
s_dword(0x78, name="TTL_auth", endian='>')
s_size("data_length", length=2, endian='>')
if s_block_start("data_length"):
s_binary("00 00 00 00 00 16 c0 b0") # This should be fuzzed according to the type, but I'm too lazy atm
s_block_end()
s_block_end()
s_repeat("auth_nameserver", 0, 1000, 40, name="auth_nameservers")
s_word(0)
sess = sessions.session(proto="udp")
target = sessions.target("224.0.0.251", 5353)
sess.add_target(target)
sess.connect(s_get("query"), callback=insert_questions )
sess.fuzz()
| 2,247
|
Python
|
.py
| 55
| 38.145455
| 110
| 0.652134
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,993
|
fuzz_trend_control_manager_20901.py
|
OpenRCE_sulley/examples/fuzz_trend_control_manager_20901.py
|
#!c:\\python\\python.exe
#
# pedram amini <pamini@tippingpoint.com>
#
# this was a really half assed fuzz. someone should take it further, see my notes in the requests file for more info.
#
from sulley import *
from requests import trend
########################################################################################################################
sess = sessions.session(session_filename="audits/trend_server_protect_20901.session", sleep_time=.25, log_level=10)
sess.add_target(sessions.target("192.168.181.2", 20901))
sess.connect(s_get("20901"))
sess.fuzz()
| 579
|
Python
|
.py
| 13
| 43.230769
| 120
| 0.603203
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,994
|
crashbin_explorer.py
|
OpenRCE_sulley/utils/crashbin_explorer.py
|
#!c:\\python\\python.exe
import getopt
import sys
sys.path.append(r"../../../paimei")
import utils
import pgraph
USAGE = "\nUSAGE: crashbin_explorer.py <xxx.crashbin>" \
"\n [-t|--test #] dump the crash synopsis for a specific test case number" \
"\n [-g|--graph name] generate a graph of all crash paths, save to 'name'.udg\n"
#
# parse command line options.
#
try:
if len(sys.argv) < 2:
raise Exception
opts, args = getopt.getopt(sys.argv[2:], "t:g:", ["test=", "graph="])
except:
print USAGE
sys.exit(1)
test_number = graph_name = graph = None
for opt, arg in opts:
if opt in ("-t", "--test"): test_number = int(arg)
if opt in ("-g", "--graph"): graph_name = arg
try:
crashbin = utils.crash_binning.crash_binning()
crashbin.import_file(sys.argv[1])
except:
print "unable to open crashbin: '%s'." % sys.argv[1]
sys.exit(1)
#
# display the full crash dump of a specific test case
#
if test_number:
for bin, crashes in crashbin.bins.iteritems():
for crash in crashes:
if test_number == crash.extra:
print crashbin.crash_synopsis(crash)
sys.exit(0)
#
# display an overview of all recorded crashes.
#
if graph_name:
graph = pgraph.graph()
for bin, crashes in crashbin.bins.iteritems():
synopsis = crashbin.crash_synopsis(crashes[0]).split("\n")[0]
if graph:
crash_node = pgraph.node(crashes[0].exception_address)
crash_node.count = len(crashes)
crash_node.label = "[%d] %s.%08x" % (crash_node.count, crashes[0].exception_module, crash_node.id)
graph.add_node(crash_node)
print "[%d] %s" % (len(crashes), synopsis)
print "\t",
for crash in crashes:
if graph:
last = crash_node.id
for entry in crash.stack_unwind:
address = long(entry.split(":")[1], 16)
n = graph.find_node("id", address)
if not n:
n = pgraph.node(address)
n.count = 1
n.label = "[%d] %s" % (n.count, entry)
graph.add_node(n)
else:
n.count += 1
n.label = "[%d] %s" % (n.count, entry)
edge = pgraph.edge(n.id, last)
graph.add_edge(edge)
last = n.id
print "%d," % crash.extra,
print "\n"
if graph:
fh = open("%s.udg" % graph_name, "w+")
fh.write(graph.render_graph_udraw())
fh.close()
| 2,593
|
Python
|
.py
| 75
| 27.12
| 106
| 0.556445
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,995
|
crash_binning.py
|
OpenRCE_sulley/utils/crash_binning.py
|
#
# Crash Binning
# Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com>
#
# $Id: crash_binning.py 193 2007-04-05 13:30:01Z cameron $
#
# This program 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 2 of the License, or (at your option) any later
# version.
#
# This program 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 this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
'''
@author: Pedram Amini
@license: GNU General Public License 2.0 or later
@contact: pedram.amini@gmail.com
@organization: www.openrce.org
'''
import sys
import zlib
import cPickle
class __crash_bin_struct__:
exception_module = None
exception_address = 0
write_violation = 0
violation_address = 0
violation_thread_id = 0
context = None
context_dump = None
disasm = None
disasm_around = []
stack_unwind = []
seh_unwind = []
extra = None
class crash_binning:
'''
@todo: Add MySQL import/export.
'''
bins = {}
last_crash = None
pydbg = None
####################################################################################################################
def __init__ (self):
'''
'''
self.bins = {}
self.last_crash = None
self.pydbg = None
####################################################################################################################
def record_crash (self, pydbg, extra=None):
'''
Given a PyDbg instantiation that at the current time is assumed to have "crashed" (access violation for example)
record various details such as the disassemly around the violating address, the ID of the offending thread, the
call stack and the SEH unwind. Store the recorded data in an internal dictionary, binning them by the exception
address.
@type pydbg: pydbg
@param pydbg: Instance of pydbg
@type extra: Mixed
@param extra: (Optional, Def=None) Whatever extra data you want to store with this bin
'''
self.pydbg = pydbg
crash = __crash_bin_struct__()
# add module name to the exception address.
exception_module = pydbg.addr_to_module(pydbg.dbg.u.Exception.ExceptionRecord.ExceptionAddress)
if exception_module:
exception_module = exception_module.szModule
else:
exception_module = "[INVALID]"
crash.exception_module = exception_module
crash.exception_address = pydbg.dbg.u.Exception.ExceptionRecord.ExceptionAddress
crash.write_violation = pydbg.dbg.u.Exception.ExceptionRecord.ExceptionInformation[0]
crash.violation_address = pydbg.dbg.u.Exception.ExceptionRecord.ExceptionInformation[1]
crash.violation_thread_id = pydbg.dbg.dwThreadId
crash.context = pydbg.context
crash.context_dump = pydbg.dump_context(pydbg.context, print_dots=False)
crash.disasm = pydbg.disasm(crash.exception_address)
crash.disasm_around = pydbg.disasm_around(crash.exception_address, 10)
crash.stack_unwind = pydbg.stack_unwind()
crash.seh_unwind = pydbg.seh_unwind()
crash.extra = extra
# add module names to the stack unwind.
for i in xrange(len(crash.stack_unwind)):
addr = crash.stack_unwind[i]
module = pydbg.addr_to_module(addr)
if module:
module = module.szModule
else:
module = "[INVALID]"
crash.stack_unwind[i] = "%s:%08x" % (module, addr)
# add module names to the SEH unwind.
for i in xrange(len(crash.seh_unwind)):
(addr, handler) = crash.seh_unwind[i]
module = pydbg.addr_to_module(handler)
if module:
module = module.szModule
else:
module = "[INVALID]"
crash.seh_unwind[i] = (addr, handler, "%s:%08x" % (module, handler))
if not self.bins.has_key(crash.exception_address):
self.bins[crash.exception_address] = []
self.bins[crash.exception_address].append(crash)
self.last_crash = crash
####################################################################################################################
def crash_synopsis (self, crash=None):
'''
For the supplied crash, generate and return a report containing the disassemly around the violating address,
the ID of the offending thread, the call stack and the SEH unwind. If not crash is specified, then call through
to last_crash_synopsis() which returns the same information for the last recorded crash.
@see: crash_synopsis()
@type crash: __crash_bin_struct__
@param crash: (Optional, def=None) Crash object to generate report on
@rtype: String
@return: Crash report
'''
if not crash:
return self.last_crash_synopsis()
if crash.write_violation:
direction = "write to"
else:
direction = "read from"
synopsis = "%s:%08x %s from thread %d caused access violation\nwhen attempting to %s 0x%08x\n\n" % \
(
crash.exception_module, \
crash.exception_address, \
crash.disasm, \
crash.violation_thread_id, \
direction, \
crash.violation_address \
)
synopsis += crash.context_dump
synopsis += "\ndisasm around:\n"
for (ea, inst) in crash.disasm_around:
synopsis += "\t0x%08x %s\n" % (ea, inst)
if len(crash.stack_unwind):
synopsis += "\nstack unwind:\n"
for entry in crash.stack_unwind:
synopsis += "\t%s\n" % entry
if len(crash.seh_unwind):
synopsis += "\nSEH unwind:\n"
for (addr, handler, handler_str) in crash.seh_unwind:
synopsis += "\t%08x -> %s\n" % (addr, handler_str)
return synopsis + "\n"
####################################################################################################################
def export_file (self, file_name):
'''
Dump the entire object structure to disk.
@see: import_file()
@type file_name: str
@param file_name: File name to export to
@rtype: crash_binning
@return: self
'''
# null out what we don't serialize but save copies to restore after dumping to disk.
last_crash = self.last_crash
pydbg = self.pydbg
self.last_crash = self.pydbg = None
fh = open(file_name, "wb+")
fh.write(zlib.compress(cPickle.dumps(self, protocol=2)))
fh.close()
self.last_crash = last_crash
self.pydbg = pydbg
return self
####################################################################################################################
def import_file (self, file_name):
'''
Load the entire object structure from disk.
@see: export_file()
@type file_name: str
@param file_name: File name to import from
@rtype: crash_binning
@return: self
'''
fh = open(file_name, "rb")
tmp = cPickle.loads(zlib.decompress(fh.read()))
fh.close()
self.bins = tmp.bins
return self
####################################################################################################################
def last_crash_synopsis (self):
'''
For the last recorded crash, generate and return a report containing the disassemly around the violating
address, the ID of the offending thread, the call stack and the SEH unwind.
@see: crash_synopsis()
@rtype: String
@return: Crash report
'''
if self.last_crash.write_violation:
direction = "write to"
else:
direction = "read from"
synopsis = "%s:%08x %s from thread %d caused access violation\nwhen attempting to %s 0x%08x\n\n" % \
(
self.last_crash.exception_module, \
self.last_crash.exception_address, \
self.last_crash.disasm, \
self.last_crash.violation_thread_id, \
direction, \
self.last_crash.violation_address \
)
synopsis += self.last_crash.context_dump
synopsis += "\ndisasm around:\n"
for (ea, inst) in self.last_crash.disasm_around:
synopsis += "\t0x%08x %s\n" % (ea, inst)
if len(self.last_crash.stack_unwind):
synopsis += "\nstack unwind:\n"
for entry in self.last_crash.stack_unwind:
synopsis += "\t%s\n" % entry
if len(self.last_crash.seh_unwind):
synopsis += "\nSEH unwind:\n"
for (addr, handler, handler_str) in self.last_crash.seh_unwind:
try:
disasm = self.pydbg.disasm(handler)
except:
disasm = "[INVALID]"
synopsis += "\t%08x -> %s %s\n" % (addr, handler_str, disasm)
return synopsis + "\n"
| 10,048
|
Python
|
.py
| 220
| 36.404545
| 120
| 0.541645
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,996
|
ida_fuzz_library_extender.py
|
OpenRCE_sulley/utils/ida_fuzz_library_extender.py
|
#!c:\python\python.exe
#
# Aaron Portnoy
# TippingPoint Security Research Team
# (C) 2007
#
########################################################################################################################
def get_string( ea):
str_type = GetStringType(ea)
if str_type == 0:
string_buf = ""
while Byte(ea) != 0x00:
string_buf += "%c" % Byte(ea)
ea += 1
return string_buf
elif str_type == 3:
string_buf = ""
while Word(ea) != 0x0000:
string_buf += "%c%c" % (Byte(ea), Byte(ea+1))
ea += 2
return string_buf
else:
pass
########################################################################################################################
def get_arguments(ea):
xref_ea = ea
args = 0
found = None
if GetMnem(xref_ea) != "call":
return False
cur_ea = PrevHead(ea, xref_ea - 32)
while (cur_ea < xref_ea - 32) or (args <= 6):
cur_mnem = GetMnem(cur_ea);
if cur_mnem == "push":
args += 1
op_type = GetOpType(cur_ea, 0)
if Comment(cur_ea):
pass
#print(" %s = %s," % (Comment(cur_ea), GetOpnd(cur_ea, 0)))
else:
if op_type == 1:
pass
#print(" %s" % GetOpnd(cur_ea, 0))
elif op_type == 5:
found = get_string(GetOperandValue(cur_ea, 0))
elif cur_mnem == "call" or "j" in cur_mnem:
break;
cur_ea = PrevHead(cur_ea, xref_ea - 32)
if found: return found
########################################################################################################################
def find_ints (start_address):
constants = []
# loop heads
for head in Heads(start_address, SegEnd(start_address)):
# if it's code, check for cmp instruction
if isCode(GetFlags(head)):
mnem = GetMnem(head)
op1 = int(GetOperandValue(head, 1))
# if it's a cmp and it's immediate value is unique, add it to the list
if "cmp" in mnem and op1 not in constants:
constants.append(op1)
print "Found %d constant values used in compares." % len(constants)
print "-----------------------------------------------------"
for i in xrange(0, len(constants), 20):
print constants[i:i+20]
return constants
########################################################################################################################
def find_strings (start_address):
strings = []
string_arg = None
# do import checking
import_ea = start_address
while import_ea < SegEnd(start_address):
import_name = Name(import_ea)
if len(import_name) > 1 and "cmp" in import_name:
xref_start = import_ea
xref_cur = DfirstB(xref_start)
while xref_cur != BADADDR:
#print "Found call to ", import_name
string_arg = get_arguments(xref_cur)
if string_arg and string_arg not in strings:
strings.append(string_arg)
xref_cur = DnextB(xref_start, xref_cur)
import_ea += 4
# now do FLIRT checking
for function_ea in Functions(SegByName(".text"), SegEnd(start_address)):
flags = GetFunctionFlags(function_ea)
if flags & FUNC_LIB:
lib_name = GetFunctionName(function_ea)
if len(lib_name) > 1 and "cmp" in lib_name:
# found one, now find xrefs to it and grab arguments
xref_start = function_ea
xref_cur = RfirstB(xref_start)
while xref_cur != BADADDR:
string_arg = get_arguments(xref_cur)
if string_arg and string_arg not in strings:
strings.append(string_arg)
xref_cur = RnextB(xref_start, xref_cur)
print "Found %d string values used in compares." % len(strings)
print "-----------------------------------------------------"
for i in xrange(0, len(strings), 5):
print strings[i:i+5]
return strings
########################################################################################################################
# get file names to save to
constants_file = AskFile(1, ".fuzz_ints", "Enter filename for saving the discovered integers: ")
strings_file = AskFile(1, ".fuzz_strings", "Enter filename for saving the discovered strings: ")
# get integers
start_address = SegByName(".text")
constants = find_ints(start_address)
constants = map(lambda x: "0x%x" % x, constants)
print
# get strings
start_address = SegByName(".idata")
strings = find_strings(start_address)
# write integers
fh = open(constants_file, 'w+')
for c in constants:
fh.write(c + "\n")
fh.close()
# write strings
fh = open(strings_file, 'w+')
for s in strings:
fh.write(s + "\n")
fh.close()
print "Done."
| 5,064
|
Python
|
.py
| 126
| 31.65873
| 120
| 0.48616
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,997
|
pdml_parser.py
|
OpenRCE_sulley/utils/pdml_parser.py
|
#!c:\python\python.exe
import sys
from xml.sax import make_parser
from xml.sax import ContentHandler
from xml.sax.handler import feature_namespaces
########################################################################################################################
class ParsePDML (ContentHandler):
def __init__ (self):
self.current = None
self.start_parsing = False
self.sulley = ""
def startElement (self, name, attributes):
if name == "proto":
self.current = attributes["name"]
# if parsing flag is set, we're past tcp
if self.start_parsing:
if not name == "field":
print "Found payload with name %s" % attributes["name"]
elif name == "field":
if "value" in attributes.keys():
val_string = self.get_string(attributes["value"])
if val_string:
self.sulley += "s_string(\"%s\")\n" % (val_string)
print self.sulley
#print "\tFound value: %s" % val_string
else:
# not string
pass
else:
raise "WTFException"
def characters (self, data):
pass
def endElement (self, name):
# if we're closing a packet
if name == "packet":
self.start_parsing = False
# if we're closing a proto tag
if name == "proto":
# and that proto is tcp, set parsing flag
if self.current == "tcp":
#print "Setting parsing flag to TRUE"
self.start_parsing = True
else:
self.start_parsing = False
def get_string(self, parsed):
parsed = parsed.replace("\t", "")
parsed = parsed.replace("\r", "")
parsed = parsed.replace("\n", "")
parsed = parsed.replace(",", "")
parsed = parsed.replace("0x", "")
parsed = parsed.replace("\\x", "")
value = ""
while parsed:
pair = parsed[:2]
parsed = parsed[2:]
hex = int(pair, 16)
if hex > 0x7f:
return False
value += chr(hex)
value = value.replace("\t", "")
value = value.replace("\r", "")
value = value.replace("\n", "")
value = value.replace(",", "")
value = value.replace("0x", "")
value = value.replace("\\x", "")
return value
def error (self, exception):
print "Oh shitz: ", exception
sys.exit(1)
########################################################################################################################
if __name__ == '__main__':
# create the parser object
parser = make_parser()
# dont care about xml namespace
parser.setFeature(feature_namespaces, 0)
# make the document handler
handler = ParsePDML()
# point parser to handler
parser.setContentHandler(handler)
# parse
parser.parse(sys.argv[1])
| 3,304
|
Python
|
.py
| 81
| 27.950617
| 120
| 0.477174
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,998
|
print_session.py
|
OpenRCE_sulley/utils/print_session.py
|
#! /usr/bin/python
import os
import sys
import zlib
import cPickle
USAGE = "\nUSAGE: print_session.py <session file>\n"
if len(sys.argv) != 2:
print USAGE
sys.exit(1)
fh = open(sys.argv[1], "rb")
data = cPickle.loads(zlib.decompress(fh.read()))
fh.close()
#print data
for key in data.keys():
print key + " -> " + str(data[key])
| 347
|
Python
|
.py
| 15
| 20.866667
| 52
| 0.683077
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
15,999
|
pcap_cleaner.py
|
OpenRCE_sulley/utils/pcap_cleaner.py
|
#!c:\\python\\python.exe
import os
import sys
sys.path.append(r"..\..\..\paimei")
import utils
USAGE = "\nUSAGE: pcap_cleaner.py <xxx.crashbin> <path to pcaps>\n"
if len(sys.argv) != 3:
print USAGE
sys.exit(1)
#
# generate a list of all test cases that triggered a crash.
#
try:
crashbin = utils.crash_binning.crash_binning()
crashbin.import_file(sys.argv[1])
except:
print "unable to open crashbin: '%s'." % sys.argv[1]
sys.exit(1)
test_cases = []
for bin, crashes in crashbin.bins.iteritems():
for crash in crashes:
test_cases.append("%d.pcap" % crash.extra)
#
# step through the pcap directory and erase all files not pertaining to a crash.
#
for filename in os.listdir(sys.argv[2]):
if filename not in test_cases:
os.unlink("%s/%s" % (sys.argv[2], filename))
| 821
|
Python
|
.py
| 28
| 26.25
| 80
| 0.687101
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|