Skip to content

Instantly share code, notes, and snippets.

@mmontone
Created February 11, 2019 22:15
Show Gist options
  • Save mmontone/baf4d0147c85dd335bdb693cdb75a185 to your computer and use it in GitHub Desktop.
Save mmontone/baf4d0147c85dd335bdb693cdb75a185 to your computer and use it in GitHub Desktop.
Python clg (command line generator) shelll extensions
# clgshell
#
# clgshell is an extension to python-clg (command line generator) for writing shell commands
#
# Usage:
#
# 1. create a commands.py file
# 2. import clgshell from there
# 3. use @cmd decorator for defining shell commands
# 4. reference those commands from YAML python-clg spec:
# execute:
# file: commands.py
# function: <name of the defined command>
#
# Syntax:
#
# Use @cmd decorator wrapping a command function. The command function should return a string to be executed in a shell (via os.system function). Normal console arguments are replaced via python's format function. That means, arguments appear between braces like: {argname}. Also, conditional arguments syntax is supported. Conditional arguments have the following form: ?arg[str]. That means, if arg is passed and not false, then str appears in the shell command.
#
# Example:
#
# @clgshell.cmd
# def docker_run (args):
# return 'docker run --name simplecal -p {port}:9090 -p ?detached[-d] simplecal'
#
# In the above example, `port` is extracted from command line arguments. Also, if `detached` argument is present and True, then `-d` is added to the command.
#
# from the YAML file:
# run:
# help: Run an instance of Docker image
# options:
# detached:
# short: d
# help: Run Docker image detached
# action: store_true
# port:
# short: p
# default: 9090
# swank-port:
# default: 4050
# execute:
# file: commands.py
# function: docker_run
import re
import os
def format_cond(str, **args):
"Format a string conditionally. Conditions syntax is ?condition[output]"
regex = r'\?(\w+)\[(.*)\]'
def replacer(match):
cond = match.group(1)
rep = match.group(2)
if args[cond]:
# The condition holds. Replace condition body formatting args
return match.group(2).format(**args)
else:
'' # The condition doesn't hold. Replace with empty string
return re.sub(regex, replacer, str)
def cmd (func):
def cmd_func(args):
vargs = vars(args)
cmdstr = func(vargs)
cmdstr = format_cond(cmdstr, **vargs)
cmdstr = cmdstr.format(**vargs)
print cmdstr
os.system(cmdstr)
return cmd_func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment