[grilo/ebassi/subproject-variables: 2/6] tools: Clean up the core keys generator script




commit 2e532777809dcc27d562f7c17783ad604cd08706
Author: Emmanuele Bassi <ebassi gnome org>
Date:   Tue Sep 27 14:23:35 2022 +0100

    tools: Clean up the core keys generator script
    
    Make it slightly more Pythonic, starting from the PEP8 coding style,
    context managers for files, and a slightly more readable regexp.

 tools/grilo-inspect/generate_core_keys.py | 50 ++++++++++++++++---------------
 1 file changed, 26 insertions(+), 24 deletions(-)
---
diff --git a/tools/grilo-inspect/generate_core_keys.py b/tools/grilo-inspect/generate_core_keys.py
index ddd2f3a..867a55a 100644
--- a/tools/grilo-inspect/generate_core_keys.py
+++ b/tools/grilo-inspect/generate_core_keys.py
@@ -11,42 +11,44 @@
 import re
 import sys
 
+
+COMMENT_RE = re.compile(
+    r'''
+    //.*?$ | /\*.*?\*/ | \'(?:\\. | [^\\\'])*\' | "(?:\\. | [^\\"])*"
+    ''',
+    re.DOTALL | re.MULTILINE)
+
+
 # From https://stackoverflow.com/a/241506
 def comment_remover(text):
     def replacer(match):
         s = match.group(0)
         if s.startswith('/'):
-            return " " # note: a space and not an empty string
+            return " "  # note: a space and not an empty string
         else:
             return s
-    pattern = re.compile(
-        r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
-        re.DOTALL | re.MULTILINE
-    )
-    return re.sub(pattern, replacer, text)
+    return re.sub(COMMENT_RE, replacer, text)
+
 
 if len(sys.argv) != 3:
     print("Usage: " + sys.argv[0] + " <input> <output>")
     exit(1)
 
-finput = open(sys.argv[1], "r")
-input_data = finput.read()
-input_data = comment_remover(input_data).split('\n')
-finput.close()
-foutput = open(sys.argv[2], "w")
-
-foutput.write("gchar *grl_core_keys[] = {\n")
+with open(sys.argv[1], "r") as finput:
+    input_data = finput.read()
+    input_data = comment_remover(input_data).split('\n')
 
-output_keys = False
-for line in input_data:
-    if re.search("GRL_METADATA_KEY_ALBUM", line):
-        output_keys = True
-    if re.search("G_BEGIN_DECLS", line):
-        output_keys = False
-    m = re.search("GRL_METADATA_KEY_[^ ]+", line)
-    if output_keys and m:
-            foutput.write("\"" +  m.group(0) + "\",\n")
+with open(sys.argv[2], "w") as foutput:
+    foutput.write("gchar *grl_core_keys[] = {\n")
 
-foutput.write("};");
+    output_keys = False
+    for line in input_data:
+        if re.search("GRL_METADATA_KEY_ALBUM", line):
+            output_keys = True
+        if re.search("G_BEGIN_DECLS", line):
+            output_keys = False
+        m = re.search("GRL_METADATA_KEY_[^ ]+", line)
+        if output_keys and m:
+            foutput.write('"' + m.group(0) + '",\n')
 
-foutput.close()
+    foutput.write("};")


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]