本文整理匯總了Python中rapuma.core.tools.Tools.dieNow方法的典型用法代碼示例。如果您正苦於以下問題:Python Tools.dieNow方法的具體用法?Python Tools.dieNow怎麽用?Python Tools.dieNow使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類rapuma.core.tools.Tools
的用法示例。
在下文中一共展示了Tools.dieNow方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: ProjData
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
#.........這裏部分代碼省略.........
# Get rid of edited backup files
if fileName[-1] == '~' :
excludeFiles.append(os.path.join(root, fileName))
continue
ext = os.path.splitext(fileName)[1][1:]
if ext in excludeTypes :
# A special indicator for file we want to keep
if fileName.find('-ext.') > 0 :
continue
return excludeFiles
# FIXME: Should archiveProject() use self.pid instead of explicitly passing in a pid?
def archiveProject (self, pid, path = None) :
'''Archive a project. Send the compressed archive file to the user-specified
archive folder. If none is specified, put the archive in cwd. If a valid
path is specified, send it to that location. Like backup, this too will
overwrite any existing file of the same name. The difference is that this
will also disable the project so it cannot be accesses by Rapuma. When a
project is archived, all work should cease on the project.'''
# Make a private project object just for archiving
aProject = Project(pid, self.gid)
# Set some paths and file names
archName = aProject.projectIDCode + '.rapuma'
userArchives = self.userConfig['Resources']['archive']
archTarget = ''
if path :
path = self.tools.resolvePath(path)
if os.path.isdir(path) :
archTarget = os.path.join(path, archName)
else :
self.tools.terminal('\nError: The path given is not valid: [' + path + ']\n')
self.tools.dieNow()
elif os.path.isdir(userArchives) :
archTarget = os.path.join(userArchives, archName)
elif os.path.isdir(os.path.dirname(aProject.local.projHome)) :
# Default to the dir just above the project
archTarget = os.path.dirname(aProject.local.projHome)
else :
self.tools.terminal('\nError: Cannot resolve a path to create the archive file!\n')
self.tools.dieNow()
# Get a list of files we don't want
excludeFiles = self.makeExcludeFileList(source)
self.zipUpProject(archTarget, excludeFiles)
# Rename the source dir to indicate it was archived
bakArchProjDir = aProject.local.projHome + '(archived)'
if os.path.isdir(bakArchProjDir) :
self.tools.terminal('\nError: Cannot complete archival process!\n')
self.tools.terminal('\nAnother archived version of this project exsits with the folder name of: ' + self.tools.fName(bakArchProjDir) + '\n')
self.tools.terminal('\nPlease remove or rename it and then repete the process.\n')
self.tools.dieNow()
else :
os.rename(aProject.local.projHome, bakArchProjDir)
# Finish here
self.tools.terminal('Archive for [' + pid + '] created and saved to: ' + archTarget + '\n')
def zipUpProject (self, target, excludeFiles = None) :
'''Zip up a project and deposit it to target location. Be sure to strip
out all all auto-created, user-specific files that could mess up a
transfer to another system. This goes for archives and backups'''
示例2: Template
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
#.........這裏部分代碼省略.........
fl = os.path.join(tempDir, 'Config', f + '.conf')
if os.path.exists(fl) :
os.remove(fl)
# Remove unnecessary project config stuff
needNot = ['Groups', 'Backup']
for s in needNot :
if tc.has_key(s) :
del tc[s]
# Write out the new template project config file
tc.filename = os.path.join(tempDir, 'Config', 'project.conf')
tc.write()
# Kill the log file
os.remove(os.path.join(tempDir, 'rapuma.log'))
# Exclude files
excludeFiles = self.projData.makeExcludeFileList(source)
# Zip it up using the above params
root_len = len(tempDir)
with zipfile.ZipFile(target, 'w', compression=zipfile.ZIP_DEFLATED) as myzip :
sys.stdout.write('Creating template')
sys.stdout.flush()
for root, dirs, files in os.walk(tempDir):
# Chop off the part of the path we do not need to store
zip_root = os.path.abspath(root)[root_len:]
for f in files:
if f[-1] == '~' :
continue
elif f in excludeFiles :
continue
elif f.rfind('.') != -1 :
fullpath = os.path.join(root, f)
zip_name = os.path.join(zip_root, f)
sys.stdout.write('.')
sys.stdout.flush()
myzip.write(fullpath, zip_name, zipfile.ZIP_DEFLATED)
# Add space for next message
sys.stdout.write('\n')
# Remove the temp project dir we made
self.tools.terminal('\nCompleted creating template: ' + target + '\n')
def templateToProject (self, targetDir = None, source = None) :
'''Create a new project based on the provided template ID. If a path to
the template is not provided it will look in the users template lib. A PID
must be provided. That is checked with the system. If the same PID is
found in the system, it must be removed before reruning this function. If
a non-default location is needed, a target path must be provided.'''
# import pdb; pdb.set_trace()
# Set a default target path
projHome = os.path.join(self.local.projParentDefaultFolder, self.pid)
# See if we can build a better target path
if targetDir != '' :
projHome = os.path.join(targetDir, self.pid)
elif self.local.projHome :
projHome = os.path.join(self.local.projHome, self.pid)
# self.tools.dieNow()
# Test to see if the project already exists
if self.pid in self.projList :
self.tools.terminal('\nError: Project ID [' + self.pid + '] is already exists on this system. Use the remove command to remove it.')
self.tools.dieNow()
# Test for source template file
if not source :
source = os.path.join(self.local.userLibTemplate, self.pid + '.zip')
if not os.path.exists(source) :
self.tools.terminal('\nError: No template can be found for [' + self.pid + ']\n')
self.tools.dieNow()
# Unzip the template in place to start the new project
with zipfile.ZipFile(source, 'r') as myzip :
myzip.extractall(projHome)
# Peek into the project
pc = ConfigObj(os.path.join(projHome, 'Config', 'project.conf'), encoding='utf-8')
pc['ProjectInfo']['projectCreateDate'] = self.tools.tStamp()
pc['ProjectInfo']['projectIDCode'] = self.pid
pc.filename = os.path.join(projHome, 'Config', 'project.conf')
pc.write()
# Get the media type from the newly placed project for registration
projectMediaIDCode = pc['ProjectInfo']['projectMediaIDCode']
# Reset the local settings
self.local = ProjLocal(self.pid)
# Create any folders that might be needed
for fld in self.local.projFolders :
folder = os.path.join(self.local.projHome, fld)
if not os.path.exists(folder) :
os.makedirs(folder)
# Report what happened
self.tools.terminal('A new project [' + self.pid + '] has been created based on the [' + self.tools.fName(source) + '] template.')
示例3: ProjCommander
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
class ProjCommander (object) :
def __init__(self, pid) :
'''Intitate the whole class and create the object.'''
self.pid = pid
self.tools = Tools()
self.user = UserConfig()
self.userConfig = self.user.userConfig
self.projHome = os.path.join(os.environ['RAPUMA_PROJECTS'], self.pid)
self.local = ProjLocal(self.pid)
self.proj_config = Config(pid)
self.proj_config.getProjectConfig()
self.projectConfig = self.proj_config.projectConfig
self.projectMediaIDCode = self.projectConfig['ProjectInfo']['projectMediaIDCode']
# Log messages for this module
self.errorCodes = {
'0000' : ['MSG', 'Placeholder message'],
}
###############################################################################
########################## Command Creation Functions #########################
###############################################################################
def removeScripts (self) :
'''Remove any unnecessary group control scripts from the project.'''
self.tools.dieNow('removeScripts() not implemented yet.')
def updateScripts (self) :
'''Update all the helper command scripts in a project.'''
self.makeStaticScripts()
self.makeGrpScripts()
def makeGrpScripts (self) :
'''Create scripts that process specific group components.'''
if not os.path.isdir(self.local.projHelpScriptFolder) :
os.mkdir(self.local.projHelpScriptFolder)
# Output the scripts (If this is a new project we need to pass)
if self.projectConfig.has_key('Groups') :
for gid in self.projectConfig['Groups'].keys() :
allScripts = self.getGrpScripInfo(gid)
for key in allScripts.keys() :
fullFile = os.path.join(self.local.projHelpScriptFolder, key) + gid
with codecs.open(fullFile, "w", encoding='utf_8') as writeObject :
writeObject.write(self.makeScriptHeader(allScripts[key][0], allScripts[key][1]))
# Strip out extra spaces from command
cmd = re.sub(ur'\s+', ur' ', allScripts[key][1])
writeObject.write(cmd + '\n\n')
# Make the script executable
self.tools.makeExecutable(fullFile)
self.tools.terminal('\nCompleted creating/recreating group helper scripts.\n')
else :
pass
def makeStaticScripts (self) :
'''Create helper scripts for a project to help with repetitive tasks.
If any scripts are present with the same name they will be overwritten.
Note: This is only for temporary use due to the lack of an interface at
this time (20130306140636). It assumes the cType is usfm which, at some point
may not be the case.'''
if not os.path.isdir(self.local.projHelpScriptFolder) :
os.mkdir(self.local.projHelpScriptFolder)
# Output the scripts
allScripts = self.getStaticScripInfo()
for key in allScripts.keys() :
fullFile = os.path.join(self.local.projHelpScriptFolder, key)
with codecs.open(fullFile, "w", encoding='utf_8') as writeObject :
writeObject.write(self.makeScriptHeader(allScripts[key][0], allScripts[key][1]))
writeObject.write(allScripts[key][1] + '\n\n')
# Make the script executable
self.tools.makeExecutable(fullFile)
self.tools.terminal('\nCompleted creating/recreating static helper scripts.\n')
def makeScriptHeader (self, desc, cmd) :
'''Make a helper script header.'''
return '#!/bin/sh\n\n# Description: ' + desc + '\n\necho \necho Rapuma helper script: ' + desc + '\n\necho \necho command: ' + self.echoClean(cmd) + '\n\n'
def echoClean (self, cmdStr) :
'''Clean up a string for an echo statement in a shell script.'''
clean = re.sub(ur'\;', ur'\\;', cmdStr)
clean = re.sub(ur'\s+', ur' ', clean)
#.........這裏部分代碼省略.........
示例4: Xetex
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
#.........這裏部分代碼省略.........
if outputTest :
print '\t', setting.get(k)
appendLine(setting['texCode'], realVal)
# Only write out sections that have something in them
if len(linesOut) > 1 :
writeObject.write('\n')
for line in linesOut :
writeObject.write(line + '\n')
# Continue here with injecting the font settings which are guided by
# the config file because the XML source(s) could vary
writeObject.write('\n% INSTALLED FONTS\n')
installedFonts = self.fontConfig['Fonts'].keys()
cTypeFont = self.projectConfig['CompTypes'][self.cType.capitalize()]['fontName']
for font in installedFonts :
if font == cTypeFont :
# Output the primary font
for key in self.fontConfig['Fonts'][font]['TexMapping']['PrimaryFont'].keys() :
writeObject.write(self.proj_config.processNestedPlaceholders(self.fontConfig['Fonts'][font]['TexMapping']['PrimaryFont'][key]) + '\n')
# Output the seconday settings as well for this font
for key in self.fontConfig['Fonts'][font]['TexMapping']['SecondaryFont'].keys() :
writeObject.write(self.proj_config.processNestedPlaceholders(self.fontConfig['Fonts'][font]['TexMapping']['SecondaryFont'][key]) + '\n')
else :
# There can only be one primary font, this is not it
for key in self.fontConfig['Fonts'][font]['TexMapping']['SecondaryFont'].keys() :
writeObject.write(self.proj_config.processNestedPlaceholders(self.fontConfig['Fonts'][font]['TexMapping']['SecondaryFont'][key]) + '\n')
writeObject.write('\n')
# Die here if testing
if outputTest :
self.tools.dieNow()
# Report finished if not
return True
def affirm (self, boolDependInfo) :
'''Affirm by returning True if the actual bool matches its
state setting. Returning 'None' will cause a setting to be skipped.'''
realBool = self.returnConfRefValue(boolDependInfo['#text']).lower()
if boolDependInfo['@state'].lower() == realBool.lower() :
return True
def returnConfRefValue (self, ref) :
'''Return the value of a given config reference. The ref syntax is
as follows: [config:configObj|section|key]. This should be able to
recuse as deep as necessary.'''
# import pdb; pdb.set_trace()
ref = ref.lstrip('[').rstrip(']')
(holderType, holderKey) = ref.split(':', 1)
if holderType.lower() == 'config' :
val = holderKey.split('|')
dct = ['self.' + val[0]]
val.remove(val[0])
for i in val :
i = self.proj_config.processNestedPlaceholders(i, '')
dct.append('["' + i + '"]')
return eval(''.join(dct))
示例5: Text
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
#.........這裏部分代碼省略.........
self.tools.writeConfFile(self.project.projectConfig)
self.compSettings = self.project.projectConfig['Managers'][self.manager]
for k, v in self.compSettings.iteritems() :
setattr(self, k, v)
# Log messages for this module
self.errorCodes = {
'TEXT-000' : ['MSG', 'Text module messages'],
'TEXT-005' : ['ERR', 'Component type [<<1>>] is not supported by the text manager.'],
'TEXT-015' : ['MSG', 'TEXT-015 - Unassigned error message ID.'],
'TEXT-030' : ['LOG', 'Copied [<<1>>] to [<<2>>] in project.'],
'TEXT-040' : ['WRN', 'The [<<1>>] component is locked. It must be unlocked before any modifications can be made.'],
'TEXT-050' : ['LOG', 'Working text file for [<<1>>] has been completed.'],
'TEXT-055' : ['ERR', 'TEXT-055 - Unassigned error message ID.'],
'TEXT-080' : ['LOG', 'Validating text using the [<<1>>] style file.'],
'TEXT-150' : ['MSG', 'USFM file: [<<1>>] is valid.'],
'TEXT-160' : ['ERR', 'Unable to complete working text installation for [<<1>>]. May require \"force\" (-f).'],
'0000' : ['MSG', 'Placeholder message'],
}
###############################################################################
############################ Project Level Functions ##########################
###############################################################################
# def setSourceEditor (self, editor) :
# '''Set the source editor for the cType. It assumes the editor is valid.
# This cannot fail.'''
# se = ''
# if self.project.projectConfig['CompTypes'][self.Ctype].has_key('sourceEditor') :
# se = self.project.projectConfig['CompTypes'][self.Ctype]['sourceEditor']
# if se != editor :
# self.project.projectConfig['CompTypes'][self.Ctype]['sourceEditor'] = editor
# self.tools.writeConfFile(self.project.projectConfig)
# FIXME: Get rid of the PT dependencies
#def updateManagerSettings (self, gid) :
#'''Update the settings for this manager if needed.'''
## import pdb; pdb.set_trace()
#sourceEditor = self.pt_tools.getSourceEditor()
## If the source editor is PT, then a lot of information can be
## gleaned from the .ssf file. Otherwise we will go pretty much with
## the defaults and hope for the best.
#if sourceEditor.lower() == 'paratext' :
## Do a compare on the settings
#ptSet = self.pt_tools.getPTSettings()
#oldCompSet = self.compSettings.dict()
## Don't overwrite manager settings (default sets reset to False) if
## there already is a setting present on the nameFormID.
#if self.project.projectConfig['Managers'][self.cType + '_Text']['nameFormID'] :
#newCompSet = self.pt_tools.mapPTTextSettings(self.compSettings.dict(), ptSet)
#else :
#newCompSet = self.pt_tools.mapPTTextSettings(self.compSettings.dict(), ptSet, True)
#if not newCompSet == oldCompSet :
#self.compSettings.merge(newCompSet)
#self.tools.writeConfFile(self.project.projectConfig)
## Be sure to update the current session settings
#for k, v in self.compSettings.iteritems() :
#setattr(self, k, v)
## A generic editor means we really do not know where the text came
## from. In that case, we just do the best we can.
#elif sourceEditor.lower() == 'generic' :
#if not self.project.projectConfig['Managers'][self.cType + '_Text']['nameFormID'] or \
#not self.project.projectConfig['Managers'][self.cType + '_Text']['postPart'] :
#self.project.projectConfig['Managers'][self.cType + '_Text']['nameFormID'] = 'USFM'
#self.project.projectConfig['Managers'][self.cType + '_Text']['postPart'] = 'usfm'
#self.tools.writeConfFile(self.project.projectConfig)
#else :
#self.project.log.writeToLog('TEXT-010', [sourceEditor])
#self.tools.dieNow()
#return True
def testCompTextFile (self, cName, source, projSty = None) :
'''This will direct a request to the proper validator for
testing the source of a component text file.'''
if self.cType == 'usfm' :
# If this fails it will die at the validation process
if self.project.components[cName].usfmTextFileIsValid(source, projSty) :
self.project.log.writeToLog('TEXT-150', [source])
return True
else :
self.project.log.writeToLog('TEXT-005', [self.cType])
self.tools.dieNow()
示例6: ProjLog
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
class ProjLog (object) :
def __init__(self, pid) :
'''Do the primary initialization for this manager.'''
self.tools = Tools()
self.pid = pid
self.rapumaHome = os.environ.get('RAPUMA_BASE')
self.userHome = os.environ.get('RAPUMA_USER')
self.user = UserConfig()
self.userConfig = self.user.userConfig
self.local = ProjLocal(pid)
###############################################################################
############################### Logging Functions #############################
###############################################################################
# These have to do with keeping a running project log file. Everything done is
# recorded in the log file and that file is trimmed to a length that is
# specified in the system settings. Everything is channeled to the log file but
# depending on what has happened, they are classed in three levels:
# 1) [MSG] - Common event going to log and terminal
# 2) [WRN] - Warning event going to log and terminal if debugging is turned on
# 3) [ERR] - Error event going to the log and terminal and kills the process
# 4) [LOG] - Messages that go only to the log file to help with debugging
# FIXME: Following not implemented yet
# 5) [TOD] - To do list. Output to a file that helps guide the user.
def writeToLog (self, errCode, args=None, location=None) :
'''Send an event to one of the log files or the terminal if specified.
Everything gets written to a log. Where a message gets written to
depends on what type code it is. The type code is in with the error
code data. There are five type codes:
MSG = General messages go to both the terminal and log file
LOG = Messages that go only to the log file
WRN = Warnings that go to the terminal and log file
ERR = Errors that go to both the terminal and log file
TOD = Messages that will go to a special todo file to guide the user
The errCode points to a specific message that will be sent to a log
file. The args parameter can contain extra information like file names
to help the user better figure out what happened.'''
# Get the message from the errorCode list the module sent
if type(errCode) == list :
if location :
msg = errCode[1] + ' : (' + location + ')'
else :
msg = errCode[1]
code = errCode[0]
else :
self.tools.terminal('\nThe code: [' + errCode + '] is not recognized by the Rapuma system.')
return
# If args were given, do s/r on them and add
# args info that needs to be added to msg.
# Look for a <<#>> pattern replace it with
# the corresponding position in the args list.
if args :
for count, arg in enumerate(args) :
msg = msg.replace('<<' + str(count+1) + '>>', arg)
# Write out everything but LOG messages to the terminal
if code != 'LOG' and code != 'TOD' :
self.tools.terminal('\n' + code + ' - ' + msg)
# Test to see if this is a live project by seeing if the project conf is
# there. If it is, we can write out log files. Otherwise, why bother?
if self.local.projectConfFile and os.path.exists(self.local.projectConfFile) :
# Build the event line
eventLine = '\"' + self.tools.tStamp() + '\", \"' + code + '\", \"' + msg + '\"'
# Do we need a log file made?
try :
if not os.path.isfile(self.local.projLogFile) or os.path.getsize(self.local.projLogFile) == 0 :
writeObject = codecs.open(self.local.projLogFile, "w", encoding='utf_8')
writeObject.write('Rapuma event log file created: ' + self.tools.tStamp() + '\n')
writeObject.close()
# Now log the event to the top of the log file using preAppend().
self.preAppend(eventLine, self.local.projLogFile)
# FIXME: Add the TOD list output here, also, output any TODs
# to the error log as well as these are bad errors.
# Write errors and warnings to the error log file
if code == 'WRN' and self.userConfig['System']['debugging'] == 'True':
self.writeToErrorLog(self.local.projErrorLogFile, eventLine)
if code == 'ERR' :
self.writeToErrorLog(self.local.projErrorLogFile, eventLine)
except Exception as e :
# If we don't succeed, we should probably quite here
self.tools.terminal("Failed to write message to log file: " + msg)
self.tools.terminal('Internal error: [' + str(e) + ']')
self.tools.dieNow()
#.........這裏部分代碼省略.........
示例7: ProjProcess
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
#.........這裏部分代碼省略.........
err = subprocess.call([scriptFile, target])
if err == 0 :
self.log.writeToLog(self.errorCodes['1210'], [self.tools.fName(target), self.tools.fName(scriptFile)])
else :
self.log.writeToLog(self.errorCodes['1220'], [self.tools.fName(target), self.tools.fName(scriptFile), str(err)])
return False
return True
def scriptInstall (self, source, target) :
'''Install a script. A script can be a collection of items in
a zip file or a single .py script file.'''
scriptTargetFolder, fileName = os.path.split(target)
if self.tools.isExecutable(source) :
shutil.copy(source, target)
self.tools.makeExecutable(target)
elif self.tools.fName(source).split('.')[1].lower() == 'zip' :
myZip = zipfile.ZipFile(source, 'r')
for f in myZip.namelist() :
data = myZip.read(f, source)
# Pretty sure zip represents directory separator char as "/" regardless of OS
myPath = os.path.join(scriptTargetFolder, f.split("/")[-1])
try :
myFile = open(myPath, "wb")
myFile.write(data)
myFile.close()
except :
pass
myZip.close()
return True
else :
self.tools.dieNow('Script is an unrecognized type: ' + self.tools.fName(source) + ' Cannot continue with installation.')
def installPostProcess (self, cType, script, force = None) :
'''Install a post process script into the main components processing
folder for a specified component type. This script will be run on
every file of that type that is imported into the project. Some
projects will have their own specially developed post process
script. Use the "script" var to specify a process (which should be
bundled in a system compatable way). If "script" is not specified
we will copy in a default script that the user can modify. This is
currently limited to Python scripts only which do in-place processes
on the target files. The script needs to have the same name as the
zip file it is bundled in, except the extention is .py instead of
the bundle .zip extention.'''
# Define some internal vars
Ctype = cType.capitalize()
oldScript = ''
scriptName = os.path.split(script)[1]
scriptSourceFolder = os.path.split(script)[0]
scriptTarget = os.path.join(self.local.projScriptFolder, self.tools.fName(script).split('.')[0] + '.py')
if scriptName in self.projectConfig['CompTypes'][Ctype]['postprocessScripts'] :
oldScript = scriptName
# First check for prexsisting script record
if not force :
if oldScript :
self.log.writeToLog('POST-080', [oldScript])
return False
# In case this is a new project we may need to install a component
# type and make a process (components) folder
示例8: Usfm
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
#.........這裏部分代碼省略.........
def updateCompAdjustmentConf (self) :
'''Update an adjustmentConfig based on changes in the projectConfig.'''
for gid in self.projectConfig['Groups'].keys() :
if gid not in self.adjustmentConfig.keys() :
self.tools.buildConfSection(self.adjustmentConfig, gid)
for comp in self.projectConfig['Groups'][gid]['cidList'] :
if not self.adjustmentConfig[gid].has_key(comp) :
self.tools.buildConfSection(self.adjustmentConfig[gid], comp)
self.adjustmentConfig[gid][comp]['%1.1'] = '1'
self.tools.writeConfFile(self.adjustmentConfig)
return True
###############################################################################
######################## USFM Component Text Functions ########################
###############################################################################
######################## Error Code Block Series = 0400 #######################
###############################################################################
def getComponentType (self, gid) :
'''Return the cType for a component.'''
# import pdb; pdb.set_trace()
try :
cType = self.projectConfig['Groups'][gid]['cType']
except Exception as e :
# If we don't succeed, we should probably quite here
self.log.writeToLog('COMP-200', ['Key not found ' + str(e)])
self.tools.dieNow()
return cType
def isCompleteComponent (self, gid, cid) :
'''A two-part test to see if a component has a config entry and a file.'''
if self.hasCidFile(gid, cid) :
return True
def hasUsfmCidInfo (self, cid) :
'''Return True if this cid is in the PT USFM cid info dictionary.'''
if cid in self.usfmCidInfo().keys() :
return True
def hasCidFile (self, gid, cid) :
'''Return True or False depending on if a working file exists
for a given cName.'''
cType = self.projectConfig['Groups'][gid]['cType']
return os.path.isfile(os.path.join(self.local.projComponentFolder, cid, cid + '.' + cType))
def usfmCidInfo (self) :
'''Return a dictionary of all valid information about USFMs used in PT. Note
that a couple special non-standard IDs have been added at the top of the list.'''
# ID Comp Name Comp ID PT ID Chps
return {
示例9: ProjEdit
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import dieNow [as 別名]
class ProjEdit (object) :
def __init__(self, pid) :
'''Intitate the whole class and create the object.'''
self.pid = pid
self.tools = Tools()
self.rapumaHome = os.environ.get('RAPUMA_BASE')
self.userHome = os.environ.get('RAPUMA_USER')
self.user = UserConfig(self.rapumaHome, self.userHome)
self.userConfig = self.user.userConfig
self.projectConfig = Config(pid).projectConfig
self.projHome = None
self.local = None
self.finishInit()
# Log messages for this module
self.errorCodes = {
'EDIT-000' : ['MSG', 'Messages for editing project and setting files.'],
'EDIT-005' : ['MSG', 'Unassigned error message ID.'],
'EDIT-010' : ['ERR', 'The component [<<1>>] has multiple subcomponents and cannot be opened for editing. Please work with the individual subcomponents.'],
'EDIT-020' : ['ERR', 'Working text file [<<1>>] not found.'],
'EDIT-030' : ['ERR', 'No files found to edit with the commands supplied.'],
'EDIT-040' : ['MSG', 'Component files for [<<1>>] have been opened in your file editor.'],
'0000' : ['MSG', 'Placeholder message'],
}
def finishInit (self, projHome = None) :
'''Finishing collecting settings that would be needed for most
functions in this module.'''
# Look for an existing project home path
if self.tools.isProject(self.pid) :
localProjHome = os.path.join(self.userConfig['Resources']['projects'], self.pid)
else :
localProjHome = ''
# Testing: The local project home wins over a user provided one
if localProjHome and not projHome :
self.projHome = localProjHome
elif projHome :
self.projHome = projHome
# If a projHome was succefully found, we can go on
if self.projHome :
self.local = ProjLocal(self.rapumaHome, self.userHome, self.projHome)
###############################################################################
################################ Edit Functions ###############################
###############################################################################
####################### Error Code Block Series = 0200 ########################
###############################################################################
# FIXME: Still lots to do on this next function
def edit (self, gid, cName = None, glob = False, sys = False) :
'''Call editing application to edit various project and system files.'''
editDocs = ['gedit']
# If a subcomponent is called, pull it up and its dependencies
# This will not work with components that have more than one
# subcomponent.
if cName :
# Probably need to create the component object now
self.createComponent(cName)
cid = self.components[cName].getUsfmCid(cName)
cType = self.groups[gid].getComponentType(gid)
self.buildComponentObject(cType, cid)
cidList = self.groups[gid].getSubcomponentList(gid)
if len(cidList) > 1 :
self.log.writeToLog('EDIT-010', [cid])
self.tools.dieNow()
self.createManager('text')
compWorkText = self.groups[gid].getCidPath(cid)
if os.path.isfile(compWorkText) :
editDocs.append(compWorkText)
compTextAdj = self.components[cName].getCidAdjPath(cid)
compTextIlls = self.components[cName].getCidPiclistPath(cid)
dep = [compTextAdj, compTextIlls]
for d in dep :
if os.path.isfile(d) :
editDocs.append(d)
else :
self.log.writeToLog('EDIT-020', [self.tools.fName(compWorkText)])
self.tools.dieNow()
# Look at project global settings
if glob :
for files in os.listdir(self.local.projConfFolder):
if files.endswith(".conf"):
editDocs.append(os.path.join(self.local.projConfFolder, files))
globSty = os.path.join(self.local.projStyleFolder, self.projectConfig['Managers']['usfm_Style']['mainStyleFile'])
#.........這裏部分代碼省略.........