Skip to content

Instantly share code, notes, and snippets.

@luvies
Created December 22, 2016 01:56
Show Gist options
  • Save luvies/26c85a150d7f94c768960fcda9734014 to your computer and use it in GitHub Desktop.
Save luvies/26c85a150d7f94c768960fcda9734014 to your computer and use it in GitHub Desktop.
A script to convert full C# files to ones which can be used by Space Engineers.
"""
A script to edit space engineers source files to a copiable format to paste into
the programmable blocks. Whitespace and comments (both single line and multiline)
are removed (all contents inside double quoted strings are preserved), and anything
between the following comments are removed also:
/*-*/<content>/*-*/
(repeatable). This enables the automatic removal of usings and namespaces.
"""
import os
import re
import itertools
BASEDIR = os.path.abspath(os.path.join("..", "Scripts"))
OUTDIR = os.path.join(BASEDIR, "out")
IGNORE = [
"BaseProgram.cs",
"configuable automatic lcds.cs"
]
print("Buildings files in '{}' to '{}'.".format(BASEDIR, OUTDIR))
if not os.path.isdir(OUTDIR):
os.mkdir(OUTDIR)
CSFILE = re.compile(r"^.*\.cs$", re.IGNORECASE)
RMV_CUSTOM = re.compile(r"(/\*-\*/)(?:.)*?\1", re.IGNORECASE | re.DOTALL)
RMV_SINGLE_COMMENT = re.compile(r"//.*?\n", re.IGNORECASE)
RMV_MULTI_COMMENT = re.compile(r"/\*.*?\*/", re.IGNORECASE | re.DOTALL)
RPL_WHITESPACE = re.compile(r'(?:(?:\s\s+)|(?:\n))(?=((\\[\\"]|[^\\"])*"(\\[\\"]|[^\\"])*")*(\\[\\"]|[^\\"])*$)', re.IGNORECASE)
print()
files = []
for fname in os.listdir(BASEDIR):
fpath = os.path.join(BASEDIR, fname)
if os.path.isfile(fpath) and CSFILE.match(fpath) and fname not in IGNORE:
print("Found '{}'".format(fname))
files.append(fname)
print("{} files found, processing...".format(len(files)))
for fname in files:
towrite = ""
with open(os.path.join(BASEDIR, fname)) as fin:
content = fin.read()
char_ignores = []
for rx in [RMV_CUSTOM, RMV_MULTI_COMMENT, RMV_SINGLE_COMMENT]:
for match in rx.finditer(content):
char_ignores.append(range(match.start(), match.end()))
ignore_ranges = itertools.chain(*char_ignores)
content_builder = list(content)
for i in ignore_ranges:
content_builder[i] = " "
content = "".join(content_builder)
towrite = RPL_WHITESPACE.sub(" ", content).strip()
with open(os.path.join(OUTDIR, fname), "w") as fout:
fout.write(towrite)
print("Processed '{}'".format(fname))
print("Finished all processing.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment