Skip to content

Instantly share code, notes, and snippets.

@nirlanka
Last active April 10, 2022 21:35
Show Gist options
  • Save nirlanka/8d573803b0241bbdec7cccf120f5010c to your computer and use it in GitHub Desktop.
Save nirlanka/8d573803b0241bbdec7cccf120f5010c to your computer and use it in GitHub Desktop.
A simple set of macros for C# codebases
## Run in the command line with C# folder as -p argument.
import sys, os, re
args = sys.argv
path = '.\\'
def handle_args():
try:
path_index = args.index('-p') + 1
path = args[path_index]
except:
print('No solution or project folder path given. Use -p to input the path.')
handle_args()
files = []
def list_files_recursively():
for r, d, f in os.walk(path):
for file in f:
if file[-3:] == '.cs':
files.append(os.path.join(r, file))
list_files_recursively()
def get_classname(f):
class_name = None
with open(f, 'r+') as lines:
txt = None
try:
for l in lines:
if not class_name and 'class' in l:
tokens = l.split()
try:
idx = tokens.index('class') + 1
class_name = tokens[idx]
break
except ValueError:
pass
except IndexError:
pass
except UnicodeDecodeError:
pass
return class_name
for f in files:
ff = f[-3:]
if ff == '.cs' \
and '\\obj\\' not in ff \
and '\\bin\\' not in ff \
and '\\Properties\\' not in ff \
and '.g.cs' not in ff \
and '.g.i.cs' not in ff:
# print(f)
with open(f, 'r+') as file:
txt = file.read()
macros = re.findall(r'// macro: (.*\n.*;)\n', txt)
# print('macros', macros)
if len(macros) > 0:
class_name = get_classname(f)
for m in macros:
_m = m.split('\n')
# print('_m', _m)
mm = _m[0].split()
ll = _m[1]
if 'set' in mm:
var = mm[1]
if var == 'ClassName':
new_ll = re.sub(r'= .*;', '= "' + class_name + '";', ll)
txt = txt.replace(ll, new_ll)
## TODO:
## - Add more variables like MethodName, ...
with open(f, 'w+') as writefile:
writefile.write(txt)
is_saved = True
print('Updating class', class_name)
using Abc;
public class One
{
public void Foo()
{
// macro: set ClassName // Changes the assigned default or any value in the line below
string className = default;
Console.WriteLine(className + " Foo");
}
}
@nirlanka
Copy link
Author

nirlanka commented Dec 9, 2019

This is meant to be used in a large codebase for keeping trivial code-specific values updated, for situations such as logging and error handling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment