ckparser 0.3.1__tar.gz → 0.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ckparser
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: Parse Paradox Jomini data files to Python/JSON and revert them back experimentally.
5
5
  Author: Marc Debureaux (debnet)
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ckparser
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: Parse Paradox Jomini data files to Python/JSON and revert them back experimentally.
5
5
  Author: Marc Debureaux (debnet)
6
6
  License-Expression: MIT
@@ -41,7 +41,7 @@ import re
41
41
  import time
42
42
 
43
43
  # Script version
44
- __version__ = "0.3.1"
44
+ __version__ = "0.3.2"
45
45
 
46
46
  # Logger (because logging is awesome)
47
47
  logger = logging.getLogger(__name__)
@@ -104,9 +104,11 @@ regex_inner_string = re.compile(r"\|(?P<index>\d+)\|")
104
104
  # Regex to remove comments in files
105
105
  regex_comment = re.compile(r"(?P<space>\s*)(?P<comment>#.*)", re.MULTILINE)
106
106
  # Regex to fix blocks with no equal sign
107
- regex_missing = re.compile(r"^\s*([\w\.]+)\s+([{])", re.MULTILINE)
107
+ regex_missing = re.compile(r"^(\s*)([\w\.]+)\s+([{])", re.MULTILINE)
108
108
  # Regex to remove "list" prefix
109
109
  regex_list = re.compile(r"\s*=\s*list\s+([\{\"\|])", re.MULTILINE)
110
+ # Regex to split brackets on new lines
111
+ regex_jump = re.compile(r"(\s*)([{}])")
110
112
  # Regex for color blocks (color = [rgb|hsv] { x y z })
111
113
  regex_color = re.compile(r"=\s*(?P<type>\w+)\s*{", re.MULTILINE)
112
114
  # Regex to parse items with format key=value
@@ -129,6 +131,8 @@ regex_keyword = re.compile(r"(" + "|".join(map(re.escape, sorted(keywords, key=l
129
131
  regex_count = re.compile(r"([?!<=>]+)\s*([§\n]+)\s*\{")
130
132
  # Regex for string indexes
131
133
  regex_index = re.compile(r"\|(\d+)\|")
134
+ # Regex to clean line numbers
135
+ regex_clean = re.compile(r"^§+\n", re.MULTILINE)
132
136
  # Regex for variables
133
137
  regex_variables = re.compile(r"\b([\w]+)\b")
134
138
 
@@ -238,12 +242,12 @@ def parse_text(text, return_text_on_error=False, comments=False, dates=False, fi
238
242
  if missings := regex_missing.findall(text):
239
243
  if filename:
240
244
  logger.warning(f"Filename: {filename}")
241
- for key, val in missings:
245
+ for _, key, val in missings:
242
246
  logger.warning(f"Potential missing `=` operator between `{key}` and `{val}` needs to be fixed.")
243
- text = regex_missing.sub(r"\g<1>=\g<2>", text)
247
+ text = regex_missing.sub(r"\g<1>\g<2>=\g<3>", text)
244
248
  text = regex_color.sub(r"={\n\g<1>", text)
245
249
  text = regex_list.sub(r"|list=\g<1>", text)
246
- text = text.replace("{", "\n{\n").replace("}", "\n}\n")
250
+ text = regex_jump.sub(r"\n\g<1>\g<2>\n", text)
247
251
  text = regex_inline.sub(r"\g<1>\n", text)
248
252
  text = regex_block.sub(r"\g<2>\g<4>{", text)
249
253
  text = regex_empty.sub(r"\n", text)
@@ -418,10 +422,14 @@ def parse_text(text, return_text_on_error=False, comments=False, dates=False, fi
418
422
  nodes.pop()
419
423
  # If line is a list or list item
420
424
  else:
425
+ # Assuming the parsed file is just an array
426
+ if len(nodes) == 1 and not node:
427
+ root = node = []
428
+ nodes = [("", root)]
421
429
  # Ensure previous data are treated as list
422
430
  if not isinstance(node, list):
423
431
  if len(nodes) < 2:
424
- raise SyntaxError("Incorrect file format or syntax!")
432
+ raise SyntaxError("Incorrect file format or unknown syntax error!")
425
433
  _, prev = nodes[-2]
426
434
  if node_name:
427
435
  if node and isinstance(node, dict):
@@ -472,12 +480,12 @@ def parse_text(text, return_text_on_error=False, comments=False, dates=False, fi
472
480
  result = None
473
481
  if isinstance(result, float):
474
482
  result = round(result, 5)
475
- node.append({"@type": "formula", "@value": value, "@result": result})
483
+ node.append({"@type": "formula", "@value": item, "@result": result})
476
484
  elif item.startswith("@"):
477
485
  if (result := variables.get(item)) is None:
478
486
  if filename:
479
487
  logger.warning(f"Filename: {filename}")
480
- logger.warning(f'Value for "{value}" cannot be found (line: {line_number})')
488
+ logger.warning(f'Value for "{item}" cannot be found (line: {line_number})')
481
489
  node.append({"@type": "variable", "@value": item, "@result": result})
482
490
  elif dates and regex_date.fullmatch(item):
483
491
  item = convert_date(item) or item
@@ -494,7 +502,7 @@ def parse_text(text, return_text_on_error=False, comments=False, dates=False, fi
494
502
  logger.error(f"Line {line_number}: {line_text}")
495
503
  logger.error(f"Parse error: {error}")
496
504
  logger.debug("Exception:", exc_info=True)
497
- return text if return_text_on_error else None
505
+ return regex_clean.sub("", text) if return_text_on_error else None
498
506
  return root
499
507
 
500
508
 
@@ -736,11 +744,13 @@ def revert(obj, from_key=None, prev_key=None, depth=-1, sep="\t", sort=False):
736
744
  if from_key and (from_key.lower() == "this" or not any(regex.match(from_key) for regex in list_keys_rules)):
737
745
  for value in sorted(obj) if sort else obj:
738
746
  lines.extend(revert(value, from_key=from_key, prev_key=prev_key, depth=depth, sep=sep, sort=sort))
739
- elif not any(isinstance(o, (dict, list)) for o in obj):
747
+ elif not any(isinstance(o, (dict, list)) for o in obj) and not any(
748
+ o.startswith("#") and o.endswith("#") for o in obj if isinstance(o, str)
749
+ ):
740
750
  prefix = f"{tabs}{from_key} = {{"
741
751
  # Only for color modes
742
752
  if from_key == "color" and len(obj) == 4 and isinstance(obj[0], str):
743
- prefix = f"{tabs}{from_key} {obj[0]} = {{"
753
+ prefix = f"{tabs}{from_key} = {obj[0]} {{"
744
754
  obj = obj[1:]
745
755
  func = functools.partial(revert_value, from_key=from_key, prev_key=prev_key, sep=sep, sort=sort)
746
756
  values = " ".join(map(str, map(func, obj)))
@@ -783,7 +793,7 @@ def revert_value(value, from_key=None, prev_key=None, **kwargs):
783
793
  return "yes" if value else "no"
784
794
  elif isinstance(value, str):
785
795
  if value.startswith("#") and value.endswith("#"):
786
- return f"#{value}"
796
+ return f"#{value.strip("#")}"
787
797
  elif (
788
798
  " " in value
789
799
  or (value.startswith("$") and value.endswith("$"))
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ckparser"
7
- version = "0.3.1"
7
+ version = "0.3.2"
8
8
  description = "Parse Paradox Jomini data files to Python/JSON and revert them back experimentally."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
File without changes
File without changes
File without changes
File without changes