当前位置: 首页>>代码示例>>Python>>正文


Python Tools.fName方法代码示例

本文整理汇总了Python中rapuma.core.tools.Tools.fName方法的典型用法代码示例。如果您正苦于以下问题:Python Tools.fName方法的具体用法?Python Tools.fName怎么用?Python Tools.fName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rapuma.core.tools.Tools的用法示例。


在下文中一共展示了Tools.fName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Pdftk

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........
                self.tools.pdftkPullPages(self.local.gidPdfFile, self.local.gidPdfFile, pgRange)

            # The gidPdfFile is the residue of the last render and if approved, can be
            # used for the binding process. In regard to saving and file naming, the
            # gidPdfFile will be copied but never renamed. It must remain intact.

            # If the user wants to save this file or use a custom name, do that now
            if save and not override :
                saveFileName = self.pid + '_' + gid
                if cidListSubFileName :
                    saveFileName = saveFileName + '_' + cidListSubFileName
                if pgRange :
                    saveFileName = saveFileName + '_pg(' + pgRange + ')'
                # Add date stamp
                saveFileName = saveFileName + '_' + self.tools.ymd()
                # Add render file extention
                saveFileName = saveFileName + '.pdf'
                # Save this to the Deliverable folder (Make sure there is one)
                if not os.path.isdir(self.local.projDeliverableFolder) :
                    os.makedirs(self.local.projDeliverableFolder)
                # Final file name and path
                saveFile = os.path.join(self.local.projDeliverableFolder, saveFileName)
                # Copy, no news is good news
                if shutil.copy(self.local.gidPdfFile, saveFile) :
                    self.log.writeToLog(self.errorCodes['5730'], [saveFileName])
                else :
                    self.log.writeToLog(self.errorCodes['5720'], [saveFileName])            

            # If given, the override file name becomes the file name 
            if override :
                saveFile = override
                # With shutil.copy(), no news is good news
                if shutil.copy(self.local.gidPdfFile, saveFile) :
                    self.log.writeToLog(self.errorCodes['5730'], [saveFileName])
                else :
                    self.log.writeToLog(self.errorCodes['5720'], [saveFileName])

            # Once we know the file is successfully generated, add a background if defined
            if self.useBackground :
                if saveFile :
                    viewFile = self.pg_back.addBackground(saveFile)
                else :
                    viewFile = self.pg_back.addBackground(self.local.gidPdfFile)
                    
            # Add a timestamp and doc info if requested in addition to background
            if self.useDocInfo :
                if saveFile :
                    if os.path.isfile(viewFile) :
                        viewFile = self.pg_back.addDocInfo(viewFile)
                    else :
                        viewFile = self.pg_back.addDocInfo(saveFile)
                else :
                    if os.path.isfile(viewFile) :
                        viewFile = self.pg_back.addDocInfo(viewFile)
                    else :
                        viewFile = self.pg_back.addDocInfo(self.local.gidPdfFile)

            # To avoid confusion with file names, if this is a saved file,
            # and it has a background, we need to remove the original, non-
            # background file (remembering originals are kept in the group
            # Component folder), then rename the -view version to whatever
            # the saved name should be
            if save or override :
                if os.path.isfile(saveFile) and os.path.isfile(viewFile) :
                    # First remove
                    os.remove(saveFile)
                    # Next rename
                    os.rename(viewFile, saveFile)

            ##### Viewing #####
            # First get the right file name to view
            if saveFile :
                # If there was a saveFile, that will be the viewFile
                viewFile = saveFile
                self.log.writeToLog(self.errorCodes['5020'], [saveFile])
            else :
                # The view file in this case is just temporary
                if not os.path.isfile(viewFile) :
                    viewFile = self.local.gidPdfFile.replace(gid + '.pdf', gid + '-view.pdf')
                    shutil.copy(self.local.gidPdfFile, viewFile)
                    self.log.writeToLog(self.errorCodes['5020'], [self.tools.fName(viewFile)])

            if os.path.isfile(viewFile) :
                if self.pdfViewerCmd :
                    # Add the file to the viewer command
                    self.pdfViewerCmd.append(viewFile)
                    # Run the XeTeX and collect the return code for analysis
                    try :
                        subprocess.Popen(self.pdfViewerCmd)
                        return True
                    except Exception as e :
                        # If we don't succeed, we should probably quite here
                        self.log.writeToLog(self.errorCodes['5010'], [str(e)])
                else :
                    self.log.writeToLog(self.errorCodes['5210'])
            else :
                self.log.writeToLog(self.errorCodes['5200'], [self.tools.fName(viewFile)])
                
            # If we made it this far, return True
            return True
开发者ID:sillsdev,项目名称:rapuma,代码行数:104,代码来源:pdftk.py

示例2: Xetex

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........
            pGrp = str(self.projectConfig['Groups'][self.gid]['precedingGroup'])
            if pGrp == 'None' :
                self.projectConfig['Groups'][self.gid]['startPageNumber'] = 1
                self.tools.writeConfFile(self.projectConfig)
                return '1'
            else :
                # Calculate the suggested number based on the preceeding group
                try :
                    cStrPgNo    = str(self.projectConfig['Groups'][self.gid]['startPageNumber'])
                except :
                    cStrPgNo    = 1
                    self.projectConfig['Groups'][self.gid]['startPageNumber'] = 1
                try :
                    pGrpPgs     = int(self.projectConfig['Groups'][pGrp]['totalPages'])
                    pGrpStrPgNo = int(self.projectConfig['Groups'][pGrp]['startPageNumber'])
                except :
                    # FIXME: Maybe this could go out and find out exactly how many pages were in the preceeding group
                    pGrpPgs     = 1
                    pGrpStrPgNo = 1
                    self.projectConfig['Groups'][pGrp]['totalPages'] = 1
                    self.projectConfig['Groups'][pGrp]['startPageNumber'] = 1
                # Whether this is right or wrong set it the way it is
                self.projectConfig['Groups'][self.gid]['startPageNumber'] = (pGrpStrPgNo + pGrpPgs)
                self.tools.writeConfFile(self.projectConfig)
                return self.projectConfig['Groups'][pGrp]['startPageNumber']


    def makeExtFile (self, fileName, description) :
        '''Generic function to create an extension file if one does not already exist.'''

        if not os.path.exists(fileName) :
            with codecs.open(fileName, "w", encoding='utf_8') as writeObject :
                writeObject.write(self.tools.makeFileHeader(fileName, description, False))
            self.log.writeToLog(self.errorCodes['1040'], [self.tools.fName(fileName)])
            return True


    def makeCmpExtTexFileOn (self, fileName) :
        '''Create a component TeX extention macro "on" file for a specified component. A matching "off"
        file will be created as well.'''

        description = 'This is a component (on) TeX macro extension file which may override any macros \
        which were loaded for this rendering process. This file is read just before the component \
        working file. After the component is rendered, the accompanying off TeX file will be \
        loaded which will turn off any modified macro commands that this TeX file has set. The \
        user must edit this file in order for it to work right.'

        return self.makeExtFile(fileName, description)


    def makeCmpExtTexFileOff (self, fileName) :
        '''Create a component TeX extention macro "off" file for a specified component. This is to
        match the "on" file that was created.'''

        description = 'This is a component (off) style extension file which overrides the settings \
        that were loaded for this rendering process just prior to loading the component working \
        file. The commands in this style file will off-set the "on" settings causing the macro to \
        render as it did before the "on" styles were loaded. The user must edit this file for it \
        to work properly.'

        return self.makeExtFile(fileName, description)


    def makeCmpExtStyFileOn (self, fileName) :
        '''Create a component style extentions "on" file for a specified component. A matching "off"
        file will be created as well.'''
开发者ID:sillsdev,项目名称:rapuma,代码行数:70,代码来源:xetex.py

示例3: ProjBackground

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........

        # Initialize the process
        docInfoText         = self.layoutConfig['DocumentFeatures']['docInfoText']
        timestamp           = self.tools.tStamp()
        if self.gid :
            headerLine          = self.pid + ' / ' + self.gid + ' / ' + timestamp
        else :
            headerLine          = self.pid + ' / ' + timestamp
        svgFile             = tempfile.NamedTemporaryFile().name

        ## RENDERED PAGE DIMENSIONS (body)
        # This can be determined with the pyPdf element 
        # "pdf.getPage(0).mediaBox", which returns a 
        # RectangleObject([0, 0, Width, Height]). The
        # width and height are in points. Hopefully we will
        # always be safe by measuring the gidPdfFile size.
        #pdf         = PdfFileReader(open(self.local.gidPdfFile,'rb'))
        #var2        = pdf.getPage(0).mediaBox
        #trimWidth     = float(var2.getWidth())
        #trimHeight    = float(var2.getHeight())
        trimWidth = float(self.layoutConfig['PageLayout']['pageWidth'])
        trimHeight = float(self.layoutConfig['PageLayout']['pageHeight'])
        # Printer page size
        pps         = self.printerPageSize()
        ppsWidth    = pps[0]
        ppsHeight   = pps[1]
        ppsCenter   = ppsWidth/2

        #   Write out SVG document text 
        with codecs.open(svgFile, 'wb') as fbackgr :            # open file for writing 
            fbackgr.write( '''<svg xmlns="http://www.w3.org/2000/svg"
                version="1.1" width = "''' + str(ppsWidth) + '''" height = "''' + str(ppsHeight) + '''">
                <g><text x = "''' + str(ppsCenter) + '''" y = "''' + str(20) + '''" style="font-family:DejaVu Sans;font-style:regular;font-size:8;text-anchor:middle;fill:#000000;fill-opacity:1">''' + headerLine + '''</text></g>
                <g><text x = "''' + str(ppsCenter) + '''" y = "''' + str(ppsHeight-30) + '''" style="font-family:DejaVu Sans;font-style:regular;font-size:8;text-anchor:middle;fill:#000000;fill-opacity:1">''' + self.tools.fName(target) + '''</text></g>
                <g><text x = "''' + str(ppsCenter) + '''" y = "''' + str(ppsHeight-20) + '''" style="font-family:DejaVu Sans;font-style:regular;font-size:8;text-anchor:middle;fill:#000000;fill-opacity:1">''' + docInfoText + '''</text></g>
                </svg>''')

        # Merge target with the background
        self.log.writeToLog(self.errorCodes['1305'])

        # Create a special name for the file with the background
        viewFile = self.tools.alterFileName(target, 'view')
        # Compare the new file name with the target to see if we are
        # already working with a background file
        if viewFile == target :
            # If the target is a BG file all we need to do is merge it
            self.tools.mergePdfFilesPdftk(viewFile, self.tools.convertSvgToPdfRsvg(svgFile))
        else :
            # If not a BG file, we need to be sure the target is the same
            # size as the print page to merge with pdftk
            shutil.copy(self.tools.mergePdfFilesPdftk(self.centerOnPrintPage(target), self.tools.convertSvgToPdfRsvg(svgFile)), viewFile)

        # Not returning a file name would mean it failed
        if os.path.exists(viewFile) :
            return viewFile


    ##### Background Creation Functions #####

    def createBackground (self) :
        '''Create a background file. This will overwrite any existing
        background file and will add each recognized background type
        found in the bacgroundComponents config setting.'''

        self.createBlankBackground()
开发者ID:sillsdev,项目名称:rapuma,代码行数:69,代码来源:proj_background.py

示例4: ProjScript

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]
class ProjScript (object) :

    def __init__(self, pid, gid) :
        '''Do the primary initialization for this class.'''

        self.pid                        = pid
        self.gid                        = gid
        self.tools                      = Tools()
        self.local                      = ProjLocal(pid)
        self.user                       = UserConfig()
        self.userConfig                 = self.user.userConfig
        self.proj_config                = Config(pid, gid)
        self.proj_config.getProjectConfig()
        self.projectConfig              = self.proj_config.projectConfig
        self.cType                      = self.projectConfig['Groups'][gid]['cType']
        self.Ctype                      = self.cType.capitalize()
        self.log                        = ProjLog(pid)



        # Log messages for this module
        self.errorCodes     = {

            '0000' : ['MSG', 'Placeholder message'],

            '1010' : ['MSG', 'Script install process for [<<1>>] Succeeded.'],
            '1020' : ['ERR', 'Script install process for [<<1>>] failed.'],
            '1030' : ['ERR', 'Script type [<<1>>] not supported.'],
            '1040' : ['ERR', 'Script install cannot proceed for [<<1>>] because this script already exists in the project. You must remove it first before you can add another script.'],

            '2010' : ['MSG', 'Script remove process for [<<1>>] Succeeded.'],
            '2020' : ['ERR', 'Script remove process for [<<1>>] failed.'],

            '4210' : ['MSG', 'Processes completed successfully on: [<<1>>] by [<<2>>]'],
            '4220' : ['ERR', 'Processes for [<<1>>] failed. Script [<<2>>] returned this error: [<<3>>]'],
            '4260' : ['ERR', 'Installed the default component preprocessing script. Editing will be required for it to work with your project.'],
            '4265' : ['LOG', 'Component preprocessing script is already installed.'],
            '4310' : ['ERR', 'Script is an unrecognized type: [<<1>>] Cannot continue with installation.']


        }

###############################################################################
############################# Script Add Functions ############################
###############################################################################
######################## Error Code Block Series = 1000 #######################
###############################################################################


    def addScriptFiles (self, path, scriptType) :
        '''Import/add processing script files for a group that are found
        in the given path. Assumes valid path. Will fail if a copy
        doesn't succeed. If the file is already there, give a warning and
        will not copy.'''

#        import pdb; pdb.set_trace()

        source = path
        fileName = self.tools.fName(path)
        target = os.path.join(self.local.projScriptFolder, fileName)
        
        # Do an initial check to see if the script is already there
        # Never copy over the top of an existing script
        if os.path.isfile(target) :
            self.log.writeToLog(self.errorCodes['1040'], [fileName])
        # Make script folder if needed
        if not os.path.isdir(self.local.projScriptFolder) :
            os.makedirs(self.local.projScriptFolder)
        # Copy in the script
        if self.scriptInstall(source, target) :
            # Record the script file name
            if scriptType == 'preprocess' :
                self.projectConfig['Groups'][self.gid]['preprocessScript'] = fileName
            elif scriptType == 'postprocess' :
                self.projectConfig['Groups'][self.gid]['postprocessScript'] = fileName
            else :
                self.log.writeToLog(self.errorCodes['1030'], [scriptType])

            self.tools.writeConfFile(self.projectConfig)
            self.log.writeToLog(self.errorCodes['1010'], [fileName])
            return True
        else :
            self.log.writeToLog(self.errorCodes['1020'], [fileName])


###############################################################################
############################ Script Remove Functions ##########################
###############################################################################
######################## Error Code Block Series = 2000 #######################
###############################################################################


    def removeScriptFiles (self, scriptType) :
        '''Remove processing script files for a group.'''

        if scriptType == 'preprocess' :
            fileName = self.projectConfig['Groups'][self.gid]['preprocessScript']
        elif scriptType == 'postprocess' :
            fileName = self.projectConfig['Groups'][self.gid]['postprocessScript']
        else :
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_script.py

示例5: ProjProcess

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........

        self.projectConfig['Groups'][gid]['usePreprocessScript'] = onOff
        self.tools.writeConfFile(self.projectConfig)
        self.log.writeToLog(self.errorCodes['1240'], [str(onOff), gid])


    def checkForPreprocessScript (self, gid) :
        '''Check to see if a preprocess script is installed. If not, install the
        default script and give a warning that the script is not complete.'''

        # First make sure the Scripts folder is there
        if not os.path.isdir(self.local.projScriptFolder) :
            os.makedirs(self.local.projScriptFolder)

        # Check and copy if needed
        if not os.path.isfile(self.local.groupPreprocessFile) :
            shutil.copy(self.local.rpmPreprocessFile, self.local.groupPreprocessFile)
            self.tools.makeExecutable(self.local.groupPreprocessFile)
            self.log.writeToLog(self.errorCodes['1260'])
        else :
            self.log.writeToLog(self.errorCodes['1265'])


    def runProcessScript (self, target, scriptFile) :
        '''Run a text processing script on a component. This assumes the 
        component and the script are valid and the component lock is turned 
        off. If not, you cannot expect any good to come of this.'''

        # subprocess will fail if permissions are not set on the
        # script we want to run. The correct permission should have
        # been set when we did the installation.
        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.')
开发者ID:sillsdev,项目名称:rapuma,代码行数:69,代码来源:proj_process.py

示例6: ProjBinding

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........
        bgFile = ''
        if self.useBackground :
            bgFile = self.pg_back.addBackground(tempFile)
        if self.useDocInfo :
            if bgFile :
                bgFile = self.pg_back.addDocInfo(bgFile)
            else :
                bgFile = self.pg_back.addDocInfo(tempFile)

        # If we are saving this make a name for it
        if save :
            bindFileName = self.pid + '_contents_' + self.tools.ymd()
            # Save this to the Deliverable folder (Make sure there is one)
            if not os.path.isdir(self.local.projDeliverableFolder) :
                os.makedirs(self.local.projDeliverableFolder)
            bindFile = os.path.join(self.local.projDeliverableFolder, bindFileName + '.pdf')
            if os.path.exists(bgFile) :
                if shutil.copy(bgFile, bindFile) :
                    self.log.writeToLog(self.errorCodes['0220'], [bgFile,bindFile])
            else :
                if shutil.copy(tempFile, bindFile) :
                    self.log.writeToLog(self.errorCodes['0220'], [tempFile,bindFile])

            # Direct to viewFile
            viewFile = bindFile
                
        else :
            if os.path.exists(bgFile) :
                viewFile = bgFile
            else :
                viewFile = tempFile

        # Binding should have been successful, report it now
        self.log.writeToLog(self.errorCodes['0230'], [viewFile])

        # View the file
        if os.path.isfile(viewFile) :
            if self.pdfViewerCmd :
                # Add the file to the viewer command
                self.pdfViewerCmd.append(viewFile)
                # Run the viewer
                try :
                    subprocess.Popen(self.pdfViewerCmd)
                    return True
                except Exception as e :
                    # If we don't succeed, we should probably quite here
                    self.log.writeToLog(self.errorCodes['0260'], [str(e)])
            else :
                self.log.writeToLog(self.errorCodes['0270'])
        else :
            self.log.writeToLog(self.errorCodes['0265'], [self.tools.fName(viewFile)])


    def mergePdfFilesGs (self, sourceList) :
        '''Using GS, merge multiple PDF files into one. The advantage of
        using Gs is that the index will be maintained. pdftk strips out
        the index, which is bad...'''

        # This is our working file for this operation
        tempFile = tempfile.NamedTemporaryFile().name + '.pdf'

        # FIXME: Note/Warning, the use "-dPDFSETTINGS=/prepress" can cause an issue when
        # rendering. A segmentation fault may occur. This will cause the bind feature
        # to fail because gs failed. The segmentation fault seems to occure from graphics
        # embedded in the PDF that are either too big or not a true grayscale, but rather
        # RGB. The /prepress setting will then fail which means the doc will fail to test
        # out right in PDF x1a tests.
        
        # There does not seem to be any good way around this at this time. With more
        # development time and perhaps better options, we might someday be able to get
        # the bind process to be completely automated and be able to pass all Adobe tests
        # for x1a and other issues. As there is not any real demand for Rapuma, it isn't
        # worth putting any more effort into this section of code. Therefore, the
        # /prepress setting will be dropped from here and the user will be required to
        # Run any output through an Adobe product to get output that will be acceptable
        # to Adobe. Adobe wins, I quite. :-(
        
        # This command structure was in production until the segmenation fault issue was found:
        # cmd = ['gs', '-dBATCH', '-dNOPAUSE', '-q', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/prepress', '-sOutputFile=' + tempFile]

        # For issues with segmentation faults, the following should help 
        # with debugging. Adjust as needed. for more info go to:
        #    http://ghostscript.com/doc/8.54/Use.htm#Debugging
        # cmd = ['gs', '-dBATCH', '-dNOPAUSE', '-q', '-sDEVICE=pdfwrite', '-sOutputFile=' + tempFile, '-dPDFWRDEBUG', '-E']; print cmd

        # This is the non-x1a compatable command that will normally be used
        cmd = ['gs', '-dBATCH', '-dNOPAUSE', '-q', '-sDEVICE=pdfwrite', '-sOutputFile=' + tempFile]

        # Continueing on, now add the files we want to bind together
        cmd = cmd + sourceList

        # Now bind the files
        try :
            self.log.writeToLog(self.errorCodes['0300'])
            subprocess.call(cmd)
            # Return our file name for further processing
            return tempFile
        except Exception as e :
            # If we don't succeed, we should probably quite here
            self.log.writeToLog(self.errorCodes['0280'], [str(e)])
开发者ID:sillsdev,项目名称:rapuma,代码行数:104,代码来源:proj_binding.py

示例7: Usfm

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........
            # Clean up old file if there is one so we can start fresh
            if os.path.exists(adjFile) :
                os.remove(adjFile)
            # Nothing to do if no gid section is found
            if not self.adjustmentConfig.has_key(self.gid) :
                self.tools.buildConfSection(self.adjustmentConfig, self.gid)
            if not self.adjustmentConfig[self.gid].has_key(cid) :
                self.tools.buildConfSection(self.adjustmentConfig[self.gid], cid)
                self.adjustmentConfig[self.gid][cid]['%1.1'] = '1'
                self.tools.writeConfFile(self.adjustmentConfig)
                self.log.writeToLog(self.errorCodes['0240'], [cid])
                return False
            # Sort through commented adjustment lines ()
            if self.adjustmentConfig[self.gid].has_key(cid) :
                c = False
                for k in self.adjustmentConfig[self.gid][cid].keys() :
                    if not re.search(r'%|#', k) :
                        c = True
                if not c :
                    self.log.writeToLog(self.errorCodes['0245'], [cid])
                    return False
            # If we make it this far, create the new adjustment file
            with codecs.open(adjFile, "w", encoding='utf_8') as writeObject :
                writeObject.write(self.tools.makeFileHeader(adjFile, description, True))
                # Output like this: JAS 1.13 +1
                for k, v in self.adjustmentConfig[self.gid][cid].iteritems() :
                    if re.search(r'%|#', k) :
                        continue
                    adj = v
                    if int(v) > 0 : 
                        adj = '+' + str(v)
                    writeObject.write(cid.upper() + ' ' + k + ' ' + adj + '\n')

                self.log.writeToLog(self.errorCodes['0230'], [self.tools.fName(adjFile)])

            return True


    def createProjAdjustmentConfFile (self) :
        '''Create a project master component adjustment file that group component
        ajustment files will be created automatically from. This will run every 
        time preprocess is run but after the first time it will only add a sections
        for new groups or components.'''

        if not os.path.exists(self.adjustmentConfFile) :
            self.adjustmentConfig = ConfigObj(self.adjustmentConfFile, encoding='utf-8')
            self.adjustmentConfig.filename = self.adjustmentConfFile
            self.updateCompAdjustmentConf()
        return True


    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


###############################################################################
开发者ID:jstnlth,项目名称:rapuma,代码行数:70,代码来源:usfm.py

示例8: ProjCompare

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]
class ProjCompare (object) :

    def __init__(self, pid) :
        '''Intitate the whole class and create the object.'''

        self.pid                            = pid
        self.log                            = ProjLog(self.pid)
        self.tools                          = Tools()
        self.user                           = UserConfig()
        self.config                         = Config(pid)
        self.local                          = ProjLocal(self.pid)
        self.userConfig                     = self.user.userConfig
        self.config.getProjectConfig()
        self.projectConfig                  = self.config.projectConfig
        if self.userConfig['System']['textDifferentialViewerCommand'] == '' :
            self.diffViewCmd                = None
        else :
            self.diffViewCmd                = self.userConfig['System']['textDifferentialViewerCommand']
            # Make sure the diff view command is a list
            if type(self.diffViewCmd) != list :
                self.diffViewCmd            = [self.userConfig['System']['textDifferentialViewerCommand']]

        # Log messages for this module
        self.errorCodes     = {
            '0210' : ['WRN', 'File does not exist: [<<1>>] compare cannot be done.'],
            '0280' : ['ERR', 'Failed to compare files with error: [<<1>>]'],
            '0285' : ['ERR', 'Cannot compare component [<<1>>] because a coresponding subcomponent could not be found.'],
            '0290' : ['ERR', 'Compare test type: [<<1>>] is not valid.'],
            '0295' : ['MSG', 'Comparing: [<<1>>] with parent: [<<2>>] Close the viewer to return to the terminal prompt.'],
            '0220' : ['MSG', 'Comparison not needed, files seem to be the same.'],
            '0300' : ['WRN', 'Files are different but visual compare is not enabled.']
        }


###############################################################################
############################## Compare Functions ##############################
###############################################################################
######################## Error Code Block Series = 0200 ########################
###############################################################################

    def compareComponent (self, gid, cid, parent='backup') :
        '''Compare a component with its source which was copied into the project
        when the component was created. This will pull up the user's differential
        viewer and compare the two files.'''

        cType       = self.projectConfig['Groups'][gid]['cType']
        pFile       = self.local.getComponentFiles(gid, cid, cType)[parent.lower()]
        wFile       = self.local.getComponentFiles(gid, cid, cType)['working']
        # Do a quick check between the current and the source
        # Run the compare app if a difference is found
        if self.isDifferent(wFile, pFile) :
            self.compare(wFile, pFile)
        else :
            self.log.writeToLog(self.errorCodes['0220'])


    def isDifferent (self, new, old) :
        '''Return True if the contents of the files are different.'''

        # If one file is missing, return True
        if not os.path.exists(new) or not os.path.exists(old) :
            return True

        # Inside of diffl() open both files with universial line endings then
        # check each line for differences.
        diff = difflib.ndiff(open(new, 'rU').readlines(), open(old, 'rU').readlines())
        for d in diff :
            if d[:1] == '+' or d[:1] == '-' :
                return True
        # FIXME: Is returning False better than None?
        return False


    def compare (self, old, new) :
        '''Run a compare on two files.'''

#        import pdb; pdb.set_trace()

        # If there are any differences, open the diff viewer
        if self.isDifferent(old, new) :
            # If no diffViewCmd is found this may be running headless
            # in that case just report that the file is different and
            # and leave the function
            if not self.diffViewCmd :
                self.log.writeToLog(self.errorCodes['0300'])
            else :
                # To prevent file names being pushed back to the list ref
                # we need to use extend() rather than append()
                cmd = []
                cmd.extend(self.diffViewCmd)
                cmd.extend([old, new])
                try :
                    self.log.writeToLog(self.errorCodes['0295'], [self.tools.fName(old),self.tools.fName(new)])
                    subprocess.call(cmd)
                except Exception as e :
                    # If we don't succeed, we should probably quite here
                    self.log.writeToLog(self.errorCodes['0280'], [str(e)])
        else :
            self.log.writeToLog(self.errorCodes['0220'])
开发者ID:jstnlth,项目名称:rapuma,代码行数:101,代码来源:proj_compare.py

示例9: ProjEdit

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [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'])
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_edit.py

示例10: Macro

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]
class Macro (object) :

    def __init__(self, pid, cType, gid=None) :
        '''Do the primary initialization for this class.'''

        self.pid                            = pid
        self.gid                            = gid
        self.cType                          = cType
        self.user                           = UserConfig()
        self.userConfig                     = self.user.userConfig
        self.projHome                       = os.path.join(os.path.expanduser(os.environ['RAPUMA_PROJECTS']), self.pid)
        self.local                          = ProjLocal(pid, gid, cType)


#        import pdb; pdb.set_trace()


        self.proj_config                    = Config(pid)
        self.proj_config.getProjectConfig()
        self.projectConfig                  = self.proj_config.projectConfig
        self.layoutConfig                   = self.proj_config.layoutConfig
        self.tools                          = Tools()
        self.log                            = ProjLog(pid)
        # Create config placeholders
        self.layoutConfig                   = None
        self.illustrationConfig             = None
        self.macroConfig                    = self.tools.loadConfig(self.local.macroConfFile, self.local.macroConfXmlFile)

        # Log messages for this module
        self.errorCodes     = {
            '3010' : ['ERR', 'No macro package is registered for the [<<1>>] component type.'],
            '3020' : ['ERR', 'Cannot update! No macro package is registered for the [<<1>>] component type.'],
            '3050' : ['ERR', 'Macro package file not found: [<<1>>]'],
            '3100' : ['ERR', 'Macro package: [<<1>>] already exists in the project. I am not allowed to copy over an existing package.'],
            '3200' : ['ERR', 'Failed to install macro package: [<<1>>]'],
            '3300' : ['MSG', 'Installed macro package: [<<1>>], Reinitialized [<<2>>]'],
            '3310' : ['ERR', 'Failed to copy [<<1>>] to folder [<<2>>].'],
            '3400' : ['MSG', 'Removed macro package configuration settings for: [<<1>>] from the macro.conf file.'],
            '3500' : ['MSG', 'Removed macro package [<<1>>] folder and all files contained.'],
            '3600' : ['MSG', 'Updated component type [<<1>>] with macro package [<<2>>]'],
            '3650' : ['ERR', 'Failed to updated macro package [<<1>>]']
        }

###############################################################################
###################### Macro Package Handling Functions #######################
###############################################################################
######################## Error Code Block Series = 3000 #######################
###############################################################################

    def createMacroFiles (self, macPackId) :
        '''Create all the necessary macro file names with their assigned paths.'''

        self.projMacPackFolder = os.path.join(self.local.projMacPackFolder, macPackId)

        texFileIds = {'preStyTexExtFile':'preSty-ext.tex', 'macSettingsFile':'settings.tex', 
                        'extTexFile':'extension.tex', 'grpExtTexFile': self.gid + '-extension.tex', 
                        '':'', '':'', '':'', '':'', '':'', }
        styFileIds = {'glbExtStyFile':'extension.sty', 'grpExtStyFile': self.gid + '-extension.sty', 
                        '':'', '':'', '':'', '':'', '':''}


    def getMacPackIdFromFileName (self, fileName) :
        '''Return the macPack ID based on the file name'''

        # File name less ext is the ID
        parts = len(fileName.split('.'))
        return '.'.join(fileName.split('.')[:parts-1])
    
    
    def getMacPackIdFromSource (self, source) :
        '''Return the macPack ID based on the complete path and file name.'''

        # Get the file name from the path
        fileName = self.tools.fName(source)
        # Return the ID
        return self.getMacPackIdFromFileName(fileName)


    def addMacPack (self, source) :
        '''Add a macro package to the project. It will not work if
        the same package is already present. Remove must be used
        to get rid of the existing one first.'''

#        import pdb; pdb.set_trace()

        macPackId = self.getMacPackIdFromSource(source)
        confXml = os.path.join(self.local.projMacroFolder, macPackId, macPackId + '.xml')
        if not os.path.isfile(source) :
            self.log.writeToLog(self.errorCodes['3050'], [source])

        # Do not add/install if there seems to be a macro package there already
        if self.projectConfig['CompTypes'][self.cType.capitalize()]['macroPackage'] and os.path.exists(self.local.macroConfFile) :
            self.log.writeToLog(self.errorCodes['3100'], [macPackId])
            return False

        # Set the projectConf to the new/same package
        self.projectConfig['CompTypes'][self.cType.capitalize()]['macroPackage'] = macPackId
        self.tools.writeConfFile(self.projectConfig)

        # If we got this far, install the a fresh copy of the macPack
#.........这里部分代码省略.........
开发者ID:sillsdev,项目名称:rapuma,代码行数:103,代码来源:proj_macro.py

示例11: Macro

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........

        # <file>
        # <name>TeX lccode Definition File</name>
        # <description>The TeX file that contains lccode definitions and is linked with the hypenation exclusions file.</description>
        # <fileID>lccodeTexFile</fileID>
        # <fileName>[self:gid]-lccode.tex</fileName>
        # <filePath>[self:projGidFolder]</filePath>
        # <depends></depends>
        # <relies></relies>
        # <note>This file is located in the component group folder to allow more segregated processing.</note>
        # </file>
        # <file>
        # <name>TeX Group Hyphenation Exclusions File</name>
        # <description>The file that contains the hypenation words exclusions list for the current group that TeX will use to render the text.</description>
        # <fileID>grpHyphExcTexFile</fileID>
        # <fileName>[self:gid]-hyphenation.tex</fileName>
        # <filePath>[self:projGidFolder]</filePath>
        # <depends></depends>
        # <relies></relies>
        # <note>This file is located in the component group folder to allow more segregated processing.</note>
        # </file>

    def getMacPackIdFromFileName(self, fileName):
        """Return the macPack ID based on the file name"""

        # File name less ext is the ID
        parts = len(fileName.split("."))
        return ".".join(fileName.split(".")[: parts - 1])

    def getMacPackIdFromSource(self, source):
        """Return the macPack ID based on the complete path and file name."""

        # Get the file name from the path
        fileName = self.tools.fName(source)
        # Return the ID
        return self.getMacPackIdFromFileName(fileName)

    def addMacPack(self, source):
        """Add a macro package to the project. It will not work if
        the same package is already present. Remove must be used
        to get rid of the existing one first."""

        #        import pdb; pdb.set_trace()

        macPackId = self.getMacPackIdFromSource(source)
        confXml = os.path.join(self.local.projMacroFolder, macPackId, macPackId + ".xml")
        if not os.path.isfile(source):
            self.log.writeToLog(self.errorCodes["3050"], [source])

        # Do not add/install if there seems to be a macro package there already
        if self.projectConfig["CompTypes"][self.cType.capitalize()]["macroPackage"] and os.path.exists(
            self.local.macroConfFile
        ):
            self.log.writeToLog(self.errorCodes["3100"], [macPackId])
            return False

        # Set the projectConf to the new/same package
        self.projectConfig["CompTypes"][self.cType.capitalize()]["macroPackage"] = macPackId
        self.tools.writeConfFile(self.projectConfig)

        # If we got this far, install the a fresh copy of the macPack
        self.installMacPackOnly(source)
        # Move the style files and custom TeX files out of the macPack
        self.moveMacStyles(macPackId)
        self.moveMacTex(macPackId)
开发者ID:jstnlth,项目名称:rapuma,代码行数:69,代码来源:proj_macro.py

示例12: ProjBinding

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........
        if bindGrpNum == 0 :
            self.log.writeToLog(self.errorCodes['0210'])
            return False

        # Make an ordered key list
        keyList = bindOrder.keys()
        keyList.sort()

        # Output the bind files in order according to the list we made
        fileList = []
        for key in keyList :
            fileList.append(bindOrder[key])

        # First merge the master pages together
        tempFile = self.mergePdfFilesGs(fileList)

        # Now add background and doc info if requested
        bgFile = ''
        if self.useBackground :
            bgFile = self.pg_back.addBackground(tempFile)
        if self.useDocInfo :
            if bgFile :
                bgFile = self.pg_back.addDocInfo(bgFile)
            else :
                bgFile = self.pg_back.addDocInfo(tempFile)

        # If we are saving this make a name for it
        if save :
            bindFileName = self.pid + '_contents_' + self.tools.ymd()
            # Save this to the Deliverable folder (Make sure there is one)
            if not os.path.isdir(self.local.projDeliverableFolder) :
                os.makedirs(self.local.projDeliverableFolder)
            bindFile = os.path.join(self.local.projDeliverableFolder, bindFileName + '.pdf')
            if os.path.exists(bgFile) :
                if shutil.copy(bgFile, bindFile) :
                    self.log.writeToLog(self.errorCodes['0220'], [bgFile,bindFile])
            else :
                if shutil.copy(tempFile, bindFile) :
                    self.log.writeToLog(self.errorCodes['0220'], [tempFile,bindFile])

            # Direct to viewFile
            viewFile = bindFile
                
        else :
            if os.path.exists(bgFile) :
                viewFile = bgFile
            else :
                viewFile = tempFile

        # Binding should have been successful, report it now
        self.log.writeToLog(self.errorCodes['0230'], [viewFile])

        # View the file
        if os.path.isfile(viewFile) :
            if not len(self.pdfViewerCmd[0]) == 0 :
                # Add the file to the viewer command
                self.pdfViewerCmd.append(viewFile)
                # Run the viewer
                try :
                    subprocess.Popen(self.pdfViewerCmd)
                    return True
                except Exception as e :
                    # If we don't succeed, we should probably quite here
                    self.log.writeToLog(self.errorCodes['0260'], [str(e)])
            else :
                self.log.writeToLog(self.errorCodes['0270'])
        else :
            self.log.writeToLog(self.errorCodes['0265'], [self.tools.fName(viewFile)])


    def mergePdfFilesGs (self, sourceList) :
        '''Using GS, merge multiple PDF files into one. The advantage of
        using Gs is that the index will be maintained. pdftk strips out
        the index, which is bad...'''

        # This is our working file for this operation
        tempFile = tempfile.NamedTemporaryFile().name + '.pdf'

        # FIXME: Note/Warning, the use "-dPDFSETTINGS=/prepress" can cause an issue when
        # rendering. A segmentation fault may occur. This will cause the bind feature
        # to fail and gs will fail. There does not seem to be any way around this
        # as getting feedback from gs while processing is not possible, or at least
        # not very easy. It will have to stay this way for now.
        cmd = ['gs', '-dBATCH', '-dNOPAUSE', '-q', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/prepress', '-sOutputFile=' + tempFile]

        # If there issues with segmentation faults, the following should help with debugging
        # cmd = ['gs', '-dBATCH', '-dNOPAUSE', '-q', '-sDEVICE=pdfwrite', '-sOutputFile=' + tempFile]

        # Now add the files we want to bind together
        cmd = cmd + sourceList

        # Now bind the files
        try :
            self.log.writeToLog(self.errorCodes['0300'])
            subprocess.call(cmd)
            # Return our file name for further processing
            return tempFile
        except Exception as e :
            # If we don't succeed, we should probably quite here
            self.log.writeToLog(self.errorCodes['0280'], [str(e)])
开发者ID:jstnlth,项目名称:rapuma,代码行数:104,代码来源:proj_binding.py

示例13: ProjFont

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]
class ProjFont (object) :

    def __init__(self, pid) :
        '''Do the primary initialization for this class.'''

        self.pid                            = pid
        self.tools                          = Tools()
        self.user                           = UserConfig()
        self.log                            = ProjLog(pid)
        self.userConfig                     = self.user.userConfig
        self.proj_config                    = Config(pid)
        self.proj_config.getProjectConfig()
        self.projectConfig                  = self.proj_config.projectConfig
        self.proj_config.getFontConfig()
        self.fontConfig                     = self.proj_config.fontConfig
        self.local                          = ProjLocal(pid, self.projectConfig)

        # Load all font settings for use in this module
        if self.fontConfig :
            for k, v in self.fontConfig['GeneralSettings'].iteritems() :
                setattr(self, k, v)

        # Log messages for this module
        self.errorCodes     = {
            'FONT-000' : ['MSG', 'Font module messages'],
            'FONT-005' : ['MSG', 'FONT-005 - Unassigned error message ID.'],
            'FONT-015' : ['MSG', 'FONT-015 - Unassigned error message ID.'],
            'FONT-020' : ['ERR', 'Failed to find font setting in ParaTExt project (.ssf file). A primary font must be set before this component can be successfully rendered.'],
            'FONT-025' : ['ERR', 'No source editor was found for this project. Please enter this setting before continuing.'],
            'FONT-042' : ['MSG', 'The [<<1>>] font setup information was added to project config'],
            'FONT-050' : ['ERR', 'Halt! [<<1>>] not found. - font.copyInFont()'],
            'FONT-070' : ['LOG', 'Copied the [<<1>>] font file into the project. - proj_font.copyInFont()'],
            'FONT-100' : ['ERR', 'This function has not been implemented yet!.  - proj_font.setGlyphMap()'],

            '0010' : ['LOG', 'Wrote out new font configuration (font.__init__())'],

            '1220' : ['ERR', 'The Font bundle file [<<1>>] could not be found. Process halted.'],
            '1235' : ['MSG', 'Font [<<1>>] has been installed into the project.'],
            '1237' : ['MSG', 'Font [<<1>>] has been updated.'],
            '1240' : ['ERR', 'Font bundle file [<<1>>] not found.'],
            '1241' : ['ERR', 'Font bundle [<<1>>] not found.'],
            '1245' : ['LOG', '<<1>> font setup information added to project config'],
            '1250' : ['ERR', 'The [<<1>>] font is apparently part of this project. Please remove before trying to re-add this font.'],
            '1260' : ['MSG', 'The <<1>> font bundle has been copied into the project font folder.'],
            '1262' : ['LOG', 'The <<1>> font bundle already exsits in the font folder.'],
            '1265' : ['ERR', 'Failed to extract the [<<1>>] font bundle into the project. Font install process failed.'],
            '1267' : ['LOG', 'The <<1>> font bundle has been copied into the project font folder.'],
            '1280' : ['MSG', 'Failed to install the font: [<<1>>] into the project.'],
            '1370' : ['LOG', 'Removed [<<1>>] font name from project component type: [<<2>>].'],
            '1380' : ['MSG', 'Removed the [<<1>>] font from the project.'],
            '1382' : ['MSG', 'Force switch was set (-f). This process has completely removed the [<<1>>] font and settings from the project. - proj_font.removeFont()'],
            '1390' : ['LOG', 'Removed the [<<1>>] font package.'],
            '1395' : ['MSG', 'Could not remove the [<<1>>] font package. It may be used by another group. Use force (-f) to remove the package from the font folder.']

        }


###############################################################################
############################ Project Level Functions ##########################
###############################################################################
######################## Error Code Block Series = 1000 #######################
###############################################################################


    def setGlyphMap (self, cType, font) :
        '''If needed, set the glyph map used for this component type font.'''

        self.log.writeToLog('FONT-100')


    def getFontIdFromFileName (self, fileName) :
        '''Return the font ID based on the file name'''

        # File name less ext is the font ID
        parts = len(fileName.split('.'))
        return '.'.join(fileName.split('.')[:parts-1])
    
    
    def getFontIdFromSource (self, source) :
        '''Return the font ID based on the complete path and file name.'''

        # Get the file name from the path
        fileName = self.tools.fName(source)
        # Return the font ID
        return self.getFontIdFromFileName(fileName)


    def recordFont (self, fontId, cType=None) :
        '''Check for the exsitance of the specified font in the font folder.
        Then extract the meta data into the appropreate configurations.'''

#        import pdb; pdb.set_trace()

        # Set vars do initial checks
        metaDataSource = os.path.join(self.local.projFontFolder, fontId, fontId + '.xml')
        if not os.path.isfile(metaDataSource) :
            self.log.writeToLog(self.errorCodes['1240'], [fontId + '.xml', 'proj_font.recordFont():1240'])
        
        # Build the Fonts section in the config (if needed)
        self.tools.buildConfSection(self.fontConfig, 'Fonts')
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_font.py

示例14: ProjData

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]

#.........这里部分代码省略.........
        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'''

#        import pdb; pdb.set_trace()

        # In case an exclude list is not given
        if not excludeFiles :
            excludeFiles = []

        # Do the zip magic here
        root_len = len(self.local.projHome)
        with zipfile.ZipFile(target, 'w', compression=zipfile.ZIP_DEFLATED) as myzip :
            sys.stdout.write('Backing up files')
            sys.stdout.flush()
            for root, dirs, files in os.walk(self.local.projHome) :
                # 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 os.path.join(root, f) in excludeFiles :
                        continue
                    if not f[-1] == '~' :
开发者ID:jstnlth,项目名称:rapuma,代码行数:70,代码来源:proj_data.py

示例15: ProjIllustration

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import fName [as 别名]
class ProjIllustration (object) :

    def __init__(self, pid, gid) :
        '''Do the primary initialization for this class.'''

        self.pid                        = pid
        self.gid                        = gid
        self.tools                      = Tools()
        self.local                      = ProjLocal(pid)
        self.user                       = UserConfig()
        self.userConfig                 = self.user.userConfig
        self.proj_config                = Config(pid, gid)
        self.proj_config.getProjectConfig()
        self.proj_config.getLayoutConfig()
        self.proj_config.getIllustrationConfig()
        self.projectConfig              = self.proj_config.projectConfig
        self.layoutConfig               = self.proj_config.layoutConfig
        self.illustrationConfig         = self.proj_config.illustrationConfig
        self.cType                      = self.projectConfig['Groups'][gid]['cType']
        self.Ctype                      = self.cType.capitalize()
        self.log                        = ProjLog(pid)
        self.backgroundTypes            = ['watermark', 'lines']

        # Folder paths
        self.projComponentFolder        = self.local.projComponentFolder
        self.projIllustrationFolder     = self.local.projIllustrationFolder
        self.projConfFolder             = self.local.projConfFolder

        # Log messages for this module
        self.errorCodes     = {

            '0000' : ['MSG', 'Placeholder message'],
            '0010' : ['ERR', 'Component type [<<1>>] not recognized!'],
            '0210' : ['WRN', 'Cannot copy [<<1>>] into the project Illustration folder. File already exists. Please use remove or update commands if the file needs to be replaced.'],
            '0220' : ['MSG', 'Copied [<<1>>] into the project Illustration folder.'],
            '0230' : ['ERR', 'Failed to Copy [<<1>>] into the project Illustration folder.'],
            '0240' : ['MSG', 'Illustration add operation complete!'],
            '0265' : ['LOG', 'Piclist file for [<<1>>] has been created.'],
            '0270' : ['WRN', 'Illustration file [<<1>>] not found in Illustration folder.'],
            '0280' : ['ERR', 'There was a problem trying to import the illustration file(s). A possible cause could be that there was no \\fig markers in the source imported into the project. I\'m just say\'n.'],

            '1010' : ['MSG', 'Removed illustration file [<<1>>] from project Illustration folder.'],
            '1020' : ['LOG', 'Request to removed illustration file [<<1>>] from project Illustration folder. File not found. Operation not complete'],
            '1030' : ['MSG', 'Illustration remove operation complete!'],

            '2010' : ['MSG', 'Updated illustration file [<<1>>] in project Illustration folder.'],
            '2020' : ['ERR', 'Update failed, file [<<1>>] not found in project Illustration folder. Use add illustration command to install the illustration.'],
            '2030' : ['ERR', 'Update failed on file [<<1>>]. Copy proceedure failed.'],
            '2040' : ['MSG', 'Illustration update operation complete!']

        }

###############################################################################
############################ Illustration Functions ###########################
###############################################################################
######################## Error Code Block Series = 0200 #######################
###############################################################################


    def addIllustrationFiles (self, path) :
        '''Import all the illustrations for a group that are found in
        the given path. This assumes illustrations are being used in
        one or more components in this group. Assumes valid path. Will
        fail if a copy doesn't succeed. If the file is already there,
        give a warning and do not copy.'''

#        import pdb; pdb.set_trace()

        try :
            for i in self.illustrationConfig[self.gid].keys() :
                cid = self.illustrationConfig[self.gid][i]['bid']
                fileName = self.illustrationConfig[self.gid][i]['fileName']
                target = os.path.join(self.projIllustrationFolder, fileName)
                # Check to see if the target exists
                if not os.path.isfile(target) :
                    source = os.path.join(path, fileName)
                    if os.path.isfile(source) :
                        # Make sure we have a target dir
                        if not os.path.isdir(self.projIllustrationFolder) :
                            os.makedirs(self.projIllustrationFolder)
                        # Copy in the source to the project
                        if not shutil.copy(source, target) :
                            self.log.writeToLog(self.errorCodes['0220'], [self.tools.fName(source)])
                        # Double check that it happened
                        if not os.path.isfile(target) :
                            self.log.writeToLog(self.errorCodes['0230'], [self.tools.fName(source)])
                else :
                    self.log.writeToLog(self.errorCodes['0210'], [self.tools.fName(target)])

            # If nothing above failed, we can return True now
            self.log.writeToLog(self.errorCodes['0240'])
            return True
        except :
            self.log.writeToLog(self.errorCodes['0280'])
            return False


    def missingIllustrations (self, bid) :
        '''Check for any missing illustration files for this component and
        report them. The assumption is that this component is supposed to
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_illustration.py


注:本文中的rapuma.core.tools.Tools.fName方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。