Permalink
Switch branches/tags
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
129 lines (107 sloc) 2.85 KB
# -*- coding: utf-8 -*-
#'''
#ipm
#/com/file.py
#By James Walker.
#Copyright ©James Walker 2018. Licensed under the MIT License.
#
#This file contains the "file" command for ipm to create new files.
#'''
import os, paths, re, strings
from rvars import rvars
from comc import Command
from project import project
#'''
#CLASS file(Command)
#ipm file creation command.
#'''
class file(Command):
#'''
#FUNCTION file.run(self)
#Implement the run method.
#'''
def run(self):
#Get filename to create
if len(self.args) < 1:
sys.exit(strings.FILE_NOPATH)
filename = self.args[0]
path = os.path.join(self.wd, filename)
#Set runtime variable for filename
rvars.set("file", filename)
#Create the path to the file
dirs = filename.split("/")[:-1]
dirs = os.path.sep.join(dirs)
dirpath = os.path.join(self.wd, dirs)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
#Create the file - "a" to avoid overwriting if exists already
file = open(path, "a")
#Check whether to populate the file with a template
if len(self.args) >= 2:
self.populate(file, self.args[1])
#Close the file handle
file.close()
#'''
#FUNCTION file.populate(self, file, template)
#Populates the file handle <file> with the template <template>.
#'''
def populate(self, file, template):
#Configure variables
found = False
#Find the template
for path in paths.TEMPLATES_PLACES:
path = os.path.join(path, template)
if os.path.exists(path):
found = True
break
if not found:
print(strings.FILE_TEMPLATE_NO)
return False
#Print template path
print(strings.FILE_TEMPLATE + template)
#Load the template contents
template_file = open(path, "r")
template = template_file.read()
template_file.close()
#Write the template file
file.write(self.process_tags(template))
#'''
#FUNCTION file.process_tags(self, template)
#Processes tags in a template.
#'''
def process_tags(self, template):
#Find template tags
tags = re.findall("{(.+?)}", template);
#Process template tags
for tag in tags:
#Value to replace with
tag_value = "{ipm_" + tag + "}"
#Build complete tag name
tag_replace = "{" + tag + "}"
#Check if uppercase
upper = False
if tag.isupper():
upper = True
tag = tag.lower()
#Check tag type
if tag[0] == "%":
try:
tag_value = self.process_tags(getattr(rvars, tag.replace("%", "")))
except:
pass
elif tag[0] == ":":
tag_value = input(tag.replace(":", "") + ": ")
else:
try:
tag_value = getattr(project, tag)
except:
pass
#Check if uppercase
if upper:
tag_value = tag_value.upper()
#Replace the tag in the template file
template = template.replace(tag_replace, tag_value)
return template
#'''
#End of file.
#'''