Created
September 2, 2013 16:27
-
-
Save zielmicha/6414692 to your computer and use it in GitHub Desktop.
Makefile generating "library". Very lightweight alternative to CMake, autotools etc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pipes | |
import shlex | |
def shellquote(s): | |
return pipes.quote(s) if s else "''" | |
def reext(thing, src, dst): | |
if isinstance(thing, list): | |
return map(lambda a: reext(a, src, dst), thing) | |
if thing.endswith(src): | |
return thing[:-len(src)] + dst | |
else: | |
return thing | |
def strip_ext(thing): | |
return thing.rsplit('.', 1)[0] | |
def maybe_shell_join(l, op=' '): | |
if isinstance(l, list): | |
return op.join(map(shellquote, l)) | |
else: | |
return l | |
def maybe_shell_split(l, op=' '): | |
if isinstance(l, list): | |
return l | |
else: | |
return shlex.split(l) | |
class Makefile: | |
def __init__(self): | |
self.targets = {} | |
self.source = '' | |
self.dest = '' | |
def add(self, name, cmd, dep=[]): | |
self.targets[name] = (maybe_shell_join(cmd), | |
maybe_shell_join(dep)) | |
def add_compile(self, name, src, flags=[], dep=[], compiler=None): | |
if not compiler: | |
compiler = 'gcc' if name.endswith('.c') else 'g++' | |
obj = strip_ext(name) + '.o' | |
self.add(obj, [compiler, src, '-c', '-o', obj] + flags, dep=dep + [src]) | |
def add_link(self, name, src, flags=[], dep=[], linker='gcc'): | |
objs = list( strip_ext(name) + '.o' for name in src ) | |
self.add(name, [linker, '-o', name, ] + | |
objs + | |
flags, | |
dep=dep + objs) | |
def write(self, out, default): | |
if isinstance(out, basestring): | |
out = open(out, 'w') | |
try: | |
out.write(self.to_str(default)) | |
finally: | |
out.close() | |
def to_str(self, default): | |
l = [] | |
targets = self.targets.copy() | |
l.append(self._target_to_str(default, targets[default])) | |
del targets[default] | |
for k, v in targets.items(): | |
l.append(self._target_to_str(k, v)) | |
return '\n'.join(l) + '\n' | |
def _target_to_str(self, k, v): | |
cmd, dep = v | |
return '%s: %s\n\t%s' % (k, dep, cmd.replace('\n', '\n\t')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment