Commit 5b9da5ac authored by Sylvaine Ferrachat's avatar Sylvaine Ferrachat
Browse files

Initial import

This is WIP!

`mk_script.py` is a small utility to create an empty script with
pre-filled header in a chosen language based on template.

See `mk_script.py --help` for details on usage and options.

So far, only python template is offered.

Dependencies:
  * begins
  * Cheetah3
  * simplequestions

[pip-designed installation will be installed later].
parents
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
# -*- coding: utf-8 -*-
"""
Sylvaine Ferrachat 2019-03
Run `mk_script.py --help` for full description / usage
or inspect the below `run` function docstring
"""
#------------------------------------------
#-- Import preamble:
import datetime
import logging
import os
from pkg_resources import resource_filename
import sys
import begin # nice wrapper around argparse
import Cheetah.Template as ctmpl # templating utility
from simplequestions import question # handles interactive yes/no
#------------------------------------------
#-- Contants
DEFT_enc = 'utf-8'
DEFT_lang = 'python'
DEFT_python_version = '3'
DEFT_with_begin = False
DEFT_with_license = True
DEFT_spdx_license = 'GPL-3.0-or-later'
YYYY_MM = '{:%Y-%m}'.format(datetime.date.today())
tmpl_dir = resource_filename(__name__,'templates')
tmpl_ext = '.tmpl'
#------------------------------------------
#-- Classes
class Script:
def __init__(self, lang, user_ext, namespace):
self.lang = lang
self.user_ext = user_ext
self.namespace = namespace
self.tmpl_file = os.path.join(tmpl_dir,self.lang + tmpl_ext)
def make_tmpl(self):
#-- Interpolate vars in appropriate template
try:
t = ctmpl.Template(file=self.tmpl_file, namespaces = self.namespace)
except FileNotFoundError:
logging.warning('{} is not a supported language!'.format(self.lang))
exit(1)
#-- Handle file extension
try:
if t.default_ext != self.user_ext:
msg = 'WARNING! Chosen extension "{}" is different from the default "{}".\n'\
.format(self.user_ext,t.default_ext)
logging.warning(msg)
except AttributeError:
pass
filename = self.namespace['filename']
#-- Security on filename
if os.path.exists(filename) == True:
msg = '"{}" exists. Do you want to overwrite it? '.format(filename)
ans = question(msg,default = 'n')
if ans == False:
exit(0)
#-- output to file
with open(filename,'w',encoding=self.namespace['enc']) as f:
f.write(str(t))
f.close()
#-- Set 'execute' file mode bits
os.chmod(filename,0o755)
#-- Terminate
logging.info('{} successfully created!'.format(filename))
return
#------------------------------------------
#-- Main
@begin.start(cmd_delim='--',
config_file='.mk_script.cfg',
)
@begin.logging
def run(
filename : 'file name of the script to create',
author : 'author' = None,
lang : 'Script language to apply' = DEFT_lang,
python_version : 'Python version (will be discarded in no-python context)' = DEFT_python_version,
with_begin : 'include python "begins" lib (will be discarded in no-python context)' = DEFT_with_begin,
with_license : 'Include license identifyer' = DEFT_with_license,
spdx_license : 'License identifier (according to SPDX standards)' = DEFT_spdx_license,
):
"""
Tool to create an empty script with pre-filled header in a chosen language
based on template.
"""
fn_decomp = filename.split('.')
if len(fn_decomp) == 1:
basename = filename
user_ext = ''
else:
basename = '.'.join(fn_decomp[:-1])
user_ext = fn_decomp[-1]
#-- Define namespace values to apply to template:
namespace = {
'filename' : filename,
'author' : author,
'yyyy_mm' : YYYY_MM,
'with_license' : with_license,
'enc' : DEFT_enc,
}
if lang == 'python':
namespace['python_version'] = python_version
namespace['with_begin'] = with_begin
if with_begin == True:
namespace['config_file'] = '.' + basename + '.cfg'
if with_license == True:
namespace['spdx_license'] = spdx_license
#-- Create script from template
script = Script(lang, user_ext, namespace)
script.make_tmpl()
return
#!/usr/bin/env python$python_version
#if $with_license == True:
# SPDX-License-Identifier: $spdx_license
#end if
# -*- coding: $enc -*-
#attr $default_ext = 'py'
'''
$author $yyyy_mm
#if $with_begin == True:
Run `$filename --help` for full description / usage
or inspect the below `run` function docstring
#else
Purpose:
[Some purpose description here]
Usage:
[Usage here]
#end if
'''
#------------------------------------------
#-- Import preamble
#if $with_begin == True:
import logging
import begin
#end if
#------------------------------------------
#-- Main
#if $with_begin == True:
@begin.start(cmd_delim='--',
config_file='$config_file',
)
@begin.logging
def run(
):
'''
[Command description here]
'''
return
#else
if(__name__ == '__main__'):
#end if
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment