|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2013 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 import json |
|
7 import sys |
|
8 |
|
9 def printerr(string): |
|
10 sys.stderr.write(string) |
|
11 sys.stderr.flush() |
|
12 |
|
13 def rxValidate(regexp, options): |
|
14 """ |
|
15 Function to validate the given regular expression. |
|
16 |
|
17 @param regexp regular expression to validate (string) |
|
18 @param options list of options (list of string) |
|
19 @return tuple of flag indicating validity (boolean), error |
|
20 string (string) and error offset (integer) |
|
21 """ |
|
22 try: |
|
23 from PyQt5.QtCore import QRegularExpression |
|
24 rxOptions = QRegularExpression.NoPatternOption |
|
25 if "CaseInsensitiveOption" in options: |
|
26 rxOptions |= QRegularExpression.CaseInsensitiveOption |
|
27 if "MultilineOption" in options: |
|
28 rxOptions |= QRegularExpression.MultilineOption |
|
29 if "DotMatchesEverythingOption" in options: |
|
30 rxOptions |= QRegularExpression.DotMatchesEverythingOption |
|
31 if "ExtendedPatternSyntaxOption" in options: |
|
32 rxOptions |= QRegularExpression.ExtendedPatternSyntaxOption |
|
33 if "InvertedGreedinessOption" in options: |
|
34 rxOptions |= QRegularExpression.InvertedGreedinessOption |
|
35 if "UseUnicodePropertiesOption" in options: |
|
36 rxOptions |= QRegularExpression.UseUnicodePropertiesOption |
|
37 if "DontCaptureOption" in options: |
|
38 rxOptions |= QRegularExpression.DontCaptureOption |
|
39 |
|
40 error = "" |
|
41 errorOffset = -1 |
|
42 re = QRegularExpression(regexp, rxOptions) |
|
43 valid = re.isValid() |
|
44 if not valid: |
|
45 error = re.errorString() |
|
46 errorOffset = re.patternErrorOffset() |
|
47 except ImportError: |
|
48 valid = False |
|
49 error = "ImportError" |
|
50 errorOffset = 0 |
|
51 |
|
52 return valid, error, errorOffset |
|
53 |
|
54 |
|
55 if __name__ == "__main__": |
|
56 while True: |
|
57 commandStr = sys.stdin.readline() |
|
58 try: |
|
59 commandDict = json.loads(commandStr) |
|
60 responseDict = {"error": ""} |
|
61 printerr(str(commandDict)) |
|
62 if "command" in commandDict: |
|
63 command = commandDict["command"] |
|
64 if command == "exit": |
|
65 break |
|
66 elif command == "available": |
|
67 try: |
|
68 import PyQt5 # __IGNORE_WARNING__ |
|
69 responseDict["available"] = True |
|
70 except ImportError: |
|
71 responseDict["available"] = False |
|
72 elif command == "validate": |
|
73 valid, error, errorOffset = rxValidate(commandDict["regexp"], |
|
74 commandDict["options"]) |
|
75 responseDict["valid"] = valid |
|
76 responseDict["errorMessage"] = error |
|
77 responseDict["errorOffset"] = errorOffset |
|
78 except ValueError as err: |
|
79 responseDict = {"error": str(err)} |
|
80 except Exception as err: |
|
81 responseDict = {"error": str(err)} |
|
82 responseStr = json.dumps(responseDict) |
|
83 sys.stdout.write(responseStr) |
|
84 sys.stdout.flush() |
|
85 |
|
86 sys.exit(0) |