A simple drupal module maker written in python

So if you have ever written a few drupal modules in your day then you probably find it as redundant as I every time you need to create a new module.  So maybe this simple little python script will be helpful if you are regularly creating drupal modules.  I’m just now getting into Python, so im sure there are ways this could be better written and would love any suggestions.  Down the road I would like to add support for more drupal hooks, .install files, themes, templating, and to append hooks to an existing module, but for now this will do.

#!/usr/bin/python

import argparse, os, errno

hookTxt = ''

parser = argparse.ArgumentParser()
parser.add_argument('-n', '--name')
parser.add_argument('-m', '--machine-name')
parser.add_argument('-v', '--version')
parser.add_argument('-hh', '--hooks')
args = parser.parse_args()

def mkFunc(hook, name, args='', code=''):
	return "/*\n" \
			+ " * Implementation of hook_" + hook \
			+ "\n */\n" \
			+ "function " + name + "_" + hook + "(" + args + ") {\n" + code + "\n}\n\n"

def mkHook(hook, name):
	if hook == 'block':
		code = "$op = 'list', $delta = 0, $edit = array()"
	elif hook == 'form_alter':
		code = "&$form, &$form_state, $form_id"
	elif hook == 'nodeapi':
		code = '&$node, $op, $a3 = NULL, $a4 = NULL'
	elif hook == 'filter':
		code = '$op, $delta = 0, $format = -1, $text = '', $cache_id = 0'
	elif hook == 'mail':
		code = '$key, &$message, $params'
	else:
		code = ''

	text = mkFunc(hook, name, code)
	return text

def mkFile(dir, ext, text):
	file = open(dir + "/" + dir + ext, "w", 0)
	file.writelines(text)
	file.close()

if args.version == None:
	args.version = "6.x-1.0"

if args.hooks != None:
	hooks = args.hooks.split(',')

	for i in hooks:
		hookTxt += mkHook(i, args.machine_name)

if args.machine_name != None:
	try:
		os.makedirs(args.machine_name)
	except OSError as exc:
		if exc.errno == errno.EEXIST:
			pass
		else: raise

	infoTxt = "name = " + args.name \
			+ "\npackage = " + args.machine_name \
		  	+ "\ncore = 6.x" \
		  	+ "\nversion = '" + args.version + "'" \
		  	+ "\nproject = '" + args.machine_name + "'" 

	moduleTxt = "

Leave a Reply

See also: