Source

template_clone / clone

Full commit
#!/usr/bin/env python3

"""
clone - creates files based on templates that live in ~/.clone_templates

Examples:
  $ clone new .hgrc #<-- create a new template called .hgrc. It will open this in $EDITOR
  $ clone edit .hgrc # <-- edits the template .hgrc
  $ clone clone .hgrc .hgrc_here #<-- clones the template .hgrc to the file,
                                    in the current directory, name .hgrc_here
  $ clone clone .hgrc ~/Temp/hgrc_here #<-- clones .hgrc to ~/Temp/hgrc_here

Why?

I need to create the same files over and over again on the command line.
For example, .hgignore files, .gitignore files for Rails, README.markdown
files for new projects I create etc.

There are some solution in the GUI space for this, but nothing that I
found on the command line.

"""

__author__ = "Ryan Wilcox <rwilcox@wilcoxd.com>"
__copyright__ = "2010 Wilcox Development Solutions"
__license__ = "BSD"
__url__ = "http://www.wilcoxd.com"
__version__ = "0.1"



from optparse import OptionParser
import os.path
import subprocess
import glob
import shutil
import sys

PROJECT_DIR="~/.clone_templates/"

def clone_templates_must_exist(fObj):
    templatePath = os.path.expanduser(PROJECT_DIR)
    if not(os.path.exists(templatePath)):
        print("Creating " + PROJECT_DIR)
        os.mkdir(templatePath)
    return fObj


def template_path(name):
    templatePath = os.path.expanduser(PROJECT_DIR)
    path = "%(tPath)s/%(n)s" % dict(tPath = templatePath, n=name)
    return path


def open_file_in_editor(path):
    commandLine = "$EDITOR " + path
    #print(commandLine)
    subprocess.Popen(commandLine, shell=True)


@clone_templates_must_exist
def handle_new(parameters):
    path = template_path( parameters[1] )
    open_file_in_editor(path)


@clone_templates_must_exist
def handle_list(parameters):
    templatePath = os.path.expanduser(PROJECT_DIR)
    files =  os.listdir(templatePath)
    [ print(curr_item) for curr_item in files ]
    if (len(files) == 0):
        print("No templates created yet!")
    


@clone_templates_must_exist
def handle_clone(parameters):
    templateName = parameters[1]
    tPath = template_path(templateName)
    destination = os.path.abspath( parameters[2] )
    print("Cloned to: " + destination)
    shutil.copyfile(tPath, destination)
    


def handle_help(parameters):
    module = sys.modules[__name__] 
    print(module.__doc__)


def main():
    parser = OptionParser()
    options, args = parser.parse_args()
    
    subCommand = args[0]
    parameters = []
    if len(args) > 1:
        parameters = args[0:]
    subCommands = dict(list=handle_list, new=handle_new, edit=handle_new, 
            help=handle_help, clone=handle_clone)
    try:
        subCommands[subCommand](parameters)
    except KeyError as e:
        print( "Could not find command %(what)s" % dict(what=subCommand) )


if __name__ == '__main__':
    main()