|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2022 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing some utility functions for the Black based code formatting. |
|
8 """ |
|
9 |
|
10 import re |
|
11 |
|
12 from PyQt6.QtCore import QCoreApplication |
|
13 |
|
14 import black |
|
15 |
|
16 |
|
17 def getDefaultConfiguration(): |
|
18 """ |
|
19 Function to generate a default set of configuration parameters. |
|
20 |
|
21 @return dictionary containing the default parameters |
|
22 @rtype dict |
|
23 """ |
|
24 return { |
|
25 "target-version": set(), |
|
26 "line-length": black.DEFAULT_LINE_LENGTH, |
|
27 "skip-string-normalization": False, |
|
28 "skip-magic-trailing-comma": False, |
|
29 "extend-exclude": "", |
|
30 "exclude": black.DEFAULT_EXCLUDES, # not shown in config dialog |
|
31 "force-exclude": "", # not shown in config dialog |
|
32 } |
|
33 |
|
34 |
|
35 def compileRegExp(regexp): |
|
36 """ |
|
37 Function to compile a given regular expression. |
|
38 |
|
39 @param regexp regular expression to be compiled |
|
40 @type str |
|
41 @return compiled regular expression object |
|
42 @rtype re.Pattern |
|
43 """ |
|
44 if "\n" in regexp: |
|
45 # multi line regexp |
|
46 regexp = f"(?x){regexp}" |
|
47 compiled = re.compile(regexp) |
|
48 return compiled |
|
49 |
|
50 |
|
51 def validateRegExp(regexp): |
|
52 """ |
|
53 Function to validate a given regular expression. |
|
54 |
|
55 @param regexp regular expression to be validated |
|
56 @type str |
|
57 @return tuple containing a flag indicating validity and an error message |
|
58 @rtype tuple of (bool, str) |
|
59 """ |
|
60 if regexp: |
|
61 try: |
|
62 compileRegExp(regexp) |
|
63 return True, "" |
|
64 except re.error as e: |
|
65 return ( |
|
66 False, |
|
67 QCoreApplication.translate( |
|
68 "BlackUtilities", |
|
69 "Invalid regular expression: {0}" |
|
70 ).format(str(e)) |
|
71 ) |
|
72 except IndexError: |
|
73 return ( |
|
74 False, |
|
75 QCoreApplication.translate( |
|
76 "BlackUtilities", |
|
77 "Invalid regular expression: missing group name" |
|
78 ) |
|
79 ) |
|
80 else: |
|
81 return ( |
|
82 False, |
|
83 QCoreApplication.translate( |
|
84 "BlackUtilities", |
|
85 "A regular expression must be given." |
|
86 ) |
|
87 ) |