Merge pull request #136 from MightyCreak/move-constants-to-config-file

Don't configure any Python file (.in) through Meson
This commit is contained in:
Creak 2021-11-27 22:04:00 -05:00 committed by GitHub
commit fbdbefb1e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 4114 additions and 3482 deletions

View File

@ -21,9 +21,25 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get -y install libgirepository1.0-dev appstream appstream-util desktop-file-utils gettext
sudo apt-get -y install libgirepository1.0-dev
pip install -r requirements.dev.txt
- name: Flake8
run: flake8 src/ po/
- name: MyPy
run: mypy src/ po/
meson-build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- name: Install dependencies
run: |
sudo apt-get -y install appstream appstream-util desktop-file-utils gettext
- name: Meson build
uses: BSFishy/meson-build@v1.0.3
with:
@ -35,21 +51,6 @@ jobs:
with:
action: test
- name: Meson install
uses: BSFishy/meson-build@v1.0.3
with:
action: install
- name: Flake8
run: |
flake8 /tmp/diffuse/
flake8 po/
- name: MyPy
run: |
mypy /tmp/diffuse/
mypy po/
flatpak-build-test:
runs-on: ubuntu-latest
container:

585
.pylintrc
View File

@ -1,585 +0,0 @@
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-allow-list=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
# for backward compatibility.)
extension-pkg-whitelist=
# Return non-zero exit code if any of these messages/categories are detected,
# even if score is above --fail-under value. Syntax same as enable. Messages
# specified are enabled, while categories only check already-enabled messages.
fail-on=
# Specify a score threshold to be exceeded before program exits with error.
fail-under=10.0
# Files or directories to be skipped. They should be base names, not paths.
ignore=CVS
# Add files or directories matching the regex patterns to the ignore-list. The
# regex matches against paths.
ignore-paths=src/diffuse/main.py
# Files or directories matching the regex patterns are skipped. The regex
# matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Min Python version to use for version dependend checks. Will default to the
# version used to run pylint.
py-version=3.9
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
# temporary silenced messages (ordered alphabetically)
duplicate-code,
fixme,
invalid-name,
missing-class-docstring,
missing-function-docstring,
missing-module-docstring,
too-few-public-methods,
too-many-arguments,
too-many-branches,
too-many-instance-attributes,
too-many-lines,
too-many-locals,
too-many-nested-blocks,
too-many-statements,
unnecessary-dict-index-lookup,
unused-argument
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'error', 'warning', 'refactor', and 'convention'
# which contain the number of messages in each category, as well as 'statement'
# which is the total number of statements analyzed. This score is used by the
# global evaluation report (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit,argparse.parse_error
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=
# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE
# Regular expression matching correct class constant names. Overrides class-
# const-naming-style.
#class-const-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module.
max-module-lines=1000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
#notes-rgx=
[SIMILARITIES]
# Comments are removed from the similarity computation
ignore-comments=yes
# Docstrings are removed from the similarity computation
ignore-docstrings=yes
# Imports are removed from the similarity computation
ignore-imports=no
# Signatures are removed from the similarity computation
ignore-signatures=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. Available dictionaries: en_AG (hunspell), en_AU
# (hunspell), en_BS (hunspell), en_BW (hunspell), en_BZ (hunspell), en_CA
# (hunspell), en_DK (hunspell), en_GB (hunspell), en_GH (hunspell), en_HK
# (hunspell), en_IE (hunspell), en_IN (hunspell), en_JM (hunspell), en_MW
# (hunspell), en_NA (hunspell), en_NG (hunspell), en_NZ (hunspell), en_PH
# (hunspell), en_SG (hunspell), en_TT (hunspell), en_US (hunspell), en_ZA
# (hunspell), en_ZM (hunspell), en_ZW (hunspell), fr_BE (hunspell), fr_CA
# (hunspell), fr_CH (hunspell), fr_FR (hunspell), fr_LU (hunspell), fr_MC
# (hunspell).
spelling-dict=
# List of comma separated words that should be considered directives if they
# appear and the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# List of decorators that change the signature of a decorated function.
signature-mutators=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=_
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of names allowed to shadow builtins
allowed-redefined-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
[CLASSES]
# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
__post_init__
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[DESIGN]
# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=
# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=
# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=
# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception

View File

@ -1,5 +1,7 @@
# /etc/diffuserc: System-wide initialisation file for Diffuse
#
# Copyright (C) 2006-2009 Derrick Moser <derrick_moser@yahoo.com>
# System-wide initialization file for Diffuse
option log_print_output @LOG_PRINT_OUTPUT@
option log_print_stack @LOG_PRINT_STACK@
option use_flatpak @USE_FLATPAK@
import @PKGDATADIR@/syntax/*.syntax

View File

@ -33,6 +33,9 @@ endif
# Diffuse config file
conf = configuration_data()
conf.set('LOG_PRINT_OUTPUT', get_option('log_print_output'))
conf.set('LOG_PRINT_STACK', get_option('log_print_stack'))
conf.set('USE_FLATPAK', get_option('use_flatpak'))
conf.set('PKGDATADIR', pkgdatadir)
configure_file(

View File

@ -3,7 +3,7 @@
data/io.github.mightycreak.Diffuse.desktop.in
data/io.github.mightycreak.Diffuse.appdata.xml.in
src/diffuse/constants.py.in
src/diffuse/constants.py
src/diffuse/dialogs.py
src/diffuse/diffuse.in
src/diffuse/main.py

450
po/cs.po

File diff suppressed because it is too large Load Diff

450
po/de.po

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

450
po/es.po

File diff suppressed because it is too large Load Diff

450
po/it.po

File diff suppressed because it is too large Load Diff

450
po/ja.po

File diff suppressed because it is too large Load Diff

450
po/ko.po

File diff suppressed because it is too large Load Diff

450
po/pl.po

File diff suppressed because it is too large Load Diff

450
po/pt.po

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

450
po/ru.po

File diff suppressed because it is too large Load Diff

450
po/sv.po

File diff suppressed because it is too large Load Diff

450
po/th.po

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -17,14 +17,12 @@
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from gettext import gettext as _
APP_NAME = 'Diffuse'
VERSION = '@VERSION@'
COPYRIGHT = '''{copyright} © 2006-2019 Derrick Moser
{copyright} © 2015-2021 Romain Failliot'''.format(copyright=_("Copyright")) # type: ignore
{copyright} © 2015-2021 Romain Failliot'''.format(copyright=_("Copyright"))
WEBSITE = 'https://mightycreak.github.io/diffuse/'
SYSCONFIGDIR = '@SYSCONFIGDIR@'
LOG_PRINT_OUTPUT = @LOG_PRINT_OUTPUT@
LOG_PRINT_STACK = @LOG_PRINT_STACK@
USE_FLATPAK = @USE_FLATPAK@
# Constants are set in main()
VERSION = '0.0.0'

View File

@ -19,6 +19,8 @@
import os
from gettext import gettext as _
from diffuse import constants
from diffuse import utils

View File

@ -22,9 +22,16 @@
import sys
import gettext
sys.path.insert(1, '@PKGDATADIR@')
gettext.install('diffuse', '@LOCALEDIR@')
VERSION = '@VERSION@'
PKGDATADIR = '@PKGDATADIR@'
LOCALEDIR = '@LOCALEDIR@'
SYSCONFIGDIR = '@SYSCONFIGDIR@'
sys.path.insert(1, PKGDATADIR)
gettext.bindtextdomain('diffuse', localedir=LOCALEDIR)
gettext.textdomain('diffuse')
if __name__ == '__main__':
from diffuse import main
sys.exit(main.main())
sys.exit(main.main(VERSION, SYSCONFIGDIR))

View File

@ -25,6 +25,7 @@ import shlex
import stat
import webbrowser
from gettext import gettext as _
from urllib.parse import urlparse
from diffuse import constants
@ -958,7 +959,7 @@ class Diffuse(Gtk.Window):
self.int_state['window_width'] = event.width
self.int_state['window_height'] = event.height
# record the window's maximised state
# record the window's maximized state
def window_state_cb(self, window, event):
self.bool_state['window_maximized'] = (
(event.new_window_state & Gdk.WindowState.MAXIMIZED) != 0
@ -1309,7 +1310,7 @@ class Diffuse(Gtk.Window):
new_items = []
for item in items:
name, data = item
# get full path to an existing ancessor directory
# get full path to an existing ancestor directory
dn = os.path.abspath(name)
while not os.path.isdir(dn):
dn, old_dn = os.path.dirname(dn), dn
@ -1614,7 +1615,7 @@ class Diffuse(Gtk.Window):
help_url = None
if utils.isWindows():
# help documentation is distributed as local HTML files
# search for localised manual first
# search for localized manual first
parts = ['manual']
if utils.lang is not None:
parts = ['manual']
@ -1637,7 +1638,7 @@ class Diffuse(Gtk.Window):
browser = fp
break
if browser is not None:
# find localised help file
# find localized help file
if utils.lang is None:
parts = []
else:
@ -1661,7 +1662,7 @@ class Diffuse(Gtk.Window):
if help_url is None:
# no local help file is available, show on-line help
help_url = constants.WEBSITE + 'manual.html'
# ask for localised manual
# ask for localized manual
if utils.lang is not None:
help_url += '?lang=' + utils.lang
# use a web browser to display the help documentation
@ -1752,13 +1753,15 @@ GObject.signal_new('save', Diffuse.FileDiffViewer.PaneHeader, GObject.SignalFlag
GObject.signal_new('save-as', Diffuse.FileDiffViewer.PaneHeader, GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, ()) # noqa: E501
def main():
def main(version, sysconfigdir):
# app = Application()
# return app.run(sys.argv)
args = sys.argv
argc = len(args)
constants.VERSION = version
if argc == 2 and args[1] in ['-v', '--version']:
print('%s %s\n%s' % (constants.APP_NAME, constants.VERSION, constants.COPYRIGHT))
return 0
@ -1828,25 +1831,23 @@ Display Options:
rc_files.append(args[i])
i += 1
else:
# parse system wide then personal initialisation files
# parse system wide then personal initialization files
if utils.isWindows():
rc_file = os.path.join(utils.bin_dir, 'diffuserc')
else:
rc_file = os.path.join(utils.bin_dir, f'{constants.SYSCONFIGDIR}/diffuserc')
rc_file = os.path.join(utils.bin_dir, f'{sysconfigdir}/diffuserc')
for rc_file in rc_file, os.path.join(rc_dir, 'diffuserc'):
if os.path.isfile(rc_file):
rc_files.append(rc_file)
for rc_file in rc_files:
# convert to absolute path so the location of any processing errors are
# reported with normalised file names
# reported with normalized file names
rc_file = os.path.abspath(rc_file)
try:
# diffuse.theResources.parse(rc_file) # Modularization
theResources.parse(rc_file)
except IOError:
utils.logError(_('Error reading %s.') % (rc_file, ))
# diff = diffuse.Diffuse(rc_dir) # Modularization
diff = Diffuse(rc_dir)
# load state

View File

@ -5,8 +5,10 @@ python = import('python')
conf = configuration_data()
conf.set('PYTHON', python.find_installation('python3').path())
conf.set('VERSION', meson.project_version())
conf.set('PKGDATADIR', pkgdatadir)
conf.set('LOCALEDIR', join_paths(get_option('prefix'), get_option('localedir')))
conf.set('SYSCONFIGDIR', join_paths(get_option('prefix'), get_option('sysconfdir')))
configure_file(
input: 'diffuse.in',
@ -16,23 +18,9 @@ configure_file(
install_dir: get_option('bindir')
)
conf = configuration_data()
conf.set('VERSION', meson.project_version())
conf.set('SYSCONFIGDIR', join_paths(get_option('prefix'), get_option('sysconfdir')))
conf.set('LOG_PRINT_OUTPUT', get_option('log_print_output'))
conf.set('LOG_PRINT_STACK', get_option('log_print_stack'))
conf.set('USE_FLATPAK', get_option('use_flatpak'))
configure_file(
input: 'constants.py.in',
output: 'constants.py',
configuration: conf,
install: true,
install_dir: moduledir
)
diffuse_sources = [
'__init__.py',
'constants.py',
'dialogs.py',
'main.py',
'preferences.py',

View File

@ -23,6 +23,8 @@ import os
import shlex
import sys
from gettext import gettext as _
from diffuse import constants
from diffuse import utils

View File

@ -17,18 +17,21 @@
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# This class to hold all customisable behaviour not exposed in the preferences
# This class to hold all customizable behavior not exposed in the preferences
# dialogue: hotkey assignment, colours, syntax highlighting, etc.
# Syntax highlighting is implemented in supporting '*.syntax' files normally
# read from the system wide initialisation file '/etc/diffuserc'.
# The personal initialisation file '~/diffuse/diffuserc' can be used to change
# default behaviour.
# read from the system wide initialization file '/etc/diffuserc'.
# The personal initialization file '~/diffuse/diffuserc' can be used to change
# default behavior.
import glob
import os
import re
import shlex
from distutils import util
from gettext import gettext as _
from diffuse import utils
import gi # type: ignore
@ -197,6 +200,13 @@ class Resources:
'line_selection_opacity': 0.4
}
# default options
self.options = {
'log_print_output': 'False',
'log_print_stack': 'False',
'use_flatpak': 'False'
}
# default strings
self.strings = {}
@ -225,14 +235,14 @@ class Resources:
elif token == 'Alt':
modifiers |= Gdk.ModifierType.MOD1_MASK
elif len(token) == 0 or token[0] == '_':
raise ValueError()
raise ValueError(_('The key binding "{key}" is invalid').format(key=v))
else:
token = 'KEY_' + token
if not hasattr(Gdk, token):
raise ValueError()
raise ValueError(_('The key binding "{key}" is invalid').format(key=v))
key = getattr(Gdk, token)
if key is None:
raise ValueError()
raise ValueError(_('The key binding "{key}" is invalid').format(key=v))
key_tuple = (ctx, (key, modifiers))
# remove any existing binding
@ -298,14 +308,25 @@ class Resources:
self.floats[symbol] = v = 0.5
return v
def getOption(self, option: str) -> str:
'''Get the option value.'''
try:
return self.options[option]
except KeyError:
utils.logDebug(f'Warning: unknown option "{option}"')
return ''
def getOptionAsBool(self, option: str) -> bool:
'''Get the option value, casted as a boolean.'''
return util.strtobool(self.getOption(option))
# string resources
def getString(self, symbol):
try:
return self.strings[symbol]
except KeyError:
utils.logDebug(f'Warning: unknown string "{symbol}"')
self.strings[symbol] = v = ''
return v
return ''
# syntax highlighting
def getSyntaxNames(self):
@ -346,7 +367,9 @@ class Resources:
try:
# eg. add Python syntax highlighting:
# import /usr/share/diffuse/syntax/python.syntax
if args[0] == 'import' and len(args) == 2:
if args[0] == 'import':
if len(args) != 2:
raise SyntaxError(_('Imports must have one argument'))
path = os.path.expanduser(args[1])
# relative paths are relative to the parsed file
path = os.path.join(utils.globEscape(os.path.dirname(file_name)), path)
@ -356,23 +379,41 @@ class Resources:
for path in paths:
# convert to absolute path so the location of
# any processing errors are reported with
# normalised file names
# normalized file names
self.parse(os.path.abspath(path))
# eg. make Ctrl+o trigger the open_file menu item
# keybinding menu open_file Ctrl+o
elif args[0] == 'keybinding' and len(args) == 4:
elif args[0] == 'keybinding':
if len(args) != 4:
raise SyntaxError(_('Key bindings must have three arguments'))
self.setKeyBinding(args[1], args[2], args[3])
# eg. set the regular background colour to white
# colour text_background 1.0 1.0 1.0
elif args[0] in ['colour', 'color'] and len(args) == 5:
elif args[0] in ['colour', 'color']:
if len(args) != 5:
raise SyntaxError(_('Colors must have four arguments'))
self.colours[args[1]] = _Colour(float(args[2]), float(args[3]), float(args[4]))
# eg. set opacity of the line_selection colour
# float line_selection_opacity 0.4
elif args[0] == 'float' and len(args) == 3:
elif args[0] == 'float':
if len(args) != 3:
raise SyntaxError(_('Floats must have two arguments'))
self.floats[args[1]] = float(args[2])
# eg. enable option log_print_output
# option log_print_output true
elif args[0] == 'option':
if len(args) != 3:
raise SyntaxError(_('Options must have two arguments'))
if args[1] not in self.options:
raise SyntaxError(
_('Options "{option}" is unknown').format(option=args[1])
)
self.options[args[1]] = args[2]
# eg. set the help browser
# string help_browser gnome-help
elif args[0] == 'string' and len(args) == 3:
elif args[0] == 'string':
if len(args) != 3:
raise SyntaxError(_('Strings must have two arguments'))
self.strings[args[1]] = args[2]
if args[1] == 'difference_colours':
self.setDifferenceColours(args[2])
@ -381,7 +422,9 @@ class Resources:
# where 'normal' is the name of the default state and
# 'text' is the classification of all characters not
# explicitly matched by a syntax highlighting rule
elif args[0] == 'syntax' and (len(args) == 2 or len(args) == 4):
elif args[0] == 'syntax':
if len(args) != 3 and len(args) != 4:
raise SyntaxError(_('Syntaxes must have two or three arguments'))
key = args[1]
if len(args) == 2:
# remove file pattern for a syntax specification
@ -407,17 +450,15 @@ class Resources:
# the pattern '#' is matched and classify the matched
# characters as 'python_comment'
# syntax_pattern normal comment python_comment '#'
elif (
args[0] == 'syntax_pattern' and
self.current_syntax is not None and
len(args) >= 5
):
elif args[0] == 'syntax_pattern' and self.current_syntax is not None:
if len(args) < 5:
raise SyntaxError(_('Syntax patterns must have at least four arguments'))
flags = 0
for arg in args[5:]:
if arg == 'ignorecase':
flags |= re.IGNORECASE
else:
raise ValueError()
raise SyntaxError(_('Value "{value}" is unknown').format(value=arg))
self.current_syntax.addPattern(
args[1],
args[2],
@ -426,7 +467,9 @@ class Resources:
# eg. default to the Python syntax rules when viewing
# a file ending with '.py' or '.pyw'
# syntax_files Python '\.pyw?$'
elif args[0] == 'syntax_files' and (len(args) == 2 or len(args) == 3):
elif args[0] == 'syntax_files':
if len(args) != 2 and len(args) != 3:
raise SyntaxError(_('Syntax files must have one or two arguments'))
key = args[1]
if len(args) == 2:
# remove file pattern for a syntax specification
@ -442,7 +485,9 @@ class Resources:
# eg. default to the Python syntax rules when viewing
# a files starting with patterns like #!/usr/bin/python
# syntax_magic Python '^#!/usr/bin/python$'
elif args[0] == 'syntax_magic' and len(args) > 1:
elif args[0] == 'syntax_magic':
if len(args) < 2:
raise SyntaxError(_('Syntax magics must have at least one argument'))
key = args[1]
if len(args) == 2:
# remove magic pattern for a syntax specification
@ -456,16 +501,30 @@ class Resources:
if arg == 'ignorecase':
flags |= re.IGNORECASE
else:
raise ValueError()
raise SyntaxError(
_('Value "{value}" is unknown').format(value=arg)
)
self.syntax_magic_patterns[key] = re.compile(args[2], flags)
else:
raise ValueError()
# except ValueError:
except: # noqa: E722 # Grr... the 're' module throws weird errors
utils.logError(_('Error processing line {line} of {file}.'.format(
raise SyntaxError(_('Keyword "{keyword}" is unknown').format(keyword=args[0]))
except SyntaxError as e:
error_msg = _('Syntax error at line {line} of {file}').format(
line=i + 1,
file=file_name
)))
)
utils.logError(f'{error_msg}: {e.msg}')
except ValueError as e:
error_msg = _('Value error at line {line} of {file}').format(
line=i + 1,
file=file_name
)
utils.logError(f'{error_msg}: {e.msg}')
except re.error:
error_msg = _('Regex error at line {line} of {file}.')
utils.logError(error_msg.format(line=i + 1, file=file_name))
except: # noqa: E722
error_msg = _('Unhandled error at line {line} of {file}.')
utils.logError(error_msg.format(line=i + 1, file=file_name))
# colour resources

View File

@ -23,7 +23,10 @@ import locale
import subprocess
import traceback
from gettext import gettext as _
from diffuse import constants
from diffuse.resources import theResources
import gi # type: ignore
gi.require_version('Gtk', '3.0')
@ -77,9 +80,9 @@ def isWindows():
def _logPrintOutput(msg):
if constants.LOG_PRINT_OUTPUT:
if theResources.getOptionAsBool('log_print_output'):
print(msg, file=sys.stderr)
if constants.LOG_PRINT_STACK:
if theResources.getOptionAsBool('log_print_stack'):
traceback.print_stack()
@ -154,7 +157,7 @@ def _bash_escape(s):
def _use_flatpak():
return constants.USE_FLATPAK
return theResources.getOptionAsBool('use_flatpak')
# use popen to read the output of a command

View File

@ -19,6 +19,8 @@
import os
from gettext import gettext as _
from diffuse import utils
from diffuse.vcs.folder_set import FolderSet
from diffuse.vcs.vcs_interface import VcsInterface

View File

@ -22,8 +22,10 @@ import os
class FolderSet:
'''Utility class to help support Git and Monotone.
Represents a set of files and folders of interest for "git status" or
"mtn automate inventory."'''
"mtn automate inventory."
'''
def __init__(self, names):
self.folders = f = []

View File

@ -19,6 +19,8 @@
import os
from gettext import gettext as _
from diffuse import utils
from diffuse.vcs.vcs_interface import VcsInterface

View File

@ -20,6 +20,8 @@
import os
import glob
from gettext import gettext as _
from diffuse import utils
from diffuse.vcs.folder_set import FolderSet
from diffuse.vcs.vcs_interface import VcsInterface

View File

@ -19,6 +19,8 @@
import os
from gettext import gettext as _
from diffuse import utils
from diffuse.vcs.folder_set import FolderSet
from diffuse.vcs.bzr import Bzr

View File

@ -21,6 +21,7 @@ import difflib
import os
import unicodedata
from gettext import gettext as _
from typing import Dict
from diffuse import utils
@ -641,7 +642,7 @@ class FileDiffViewerBase(Gtk.Grid):
panes = self.panes
else:
panes = [self.panes[f]]
for _, pane in enumerate(panes):
for pane in panes:
del pane.syntax_cache[:]
del pane.diff_cache[:]
# re-compute the high water mark