def test_basename_set_b(self): d = os.path.join('a', 'b', 'c') act = os.path.join(d, 'name.ext') exp = 'name' self.assertEqual(exp, genutils.basename(act, { '.ext' })) self.assertEqual(exp, genutils.basename(act, {'.ext', '.a' })) self.assertEqual(exp, genutils.basename(act, {'.a', '.ext' }))
def test_basename_tuple_b(self): d = os.path.join('a', 'b', 'c') act = os.path.join(d, 'name.ext') exp = 'name' exp2 = 'name.ext' self.assertEqual(exp, genutils.basename(act, ('.ext'))) self.assertEqual(exp, genutils.basename(act, ('.ext', '.a'))) self.assertEqual(exp, genutils.basename(act, ('.a', '.ext'))) self.assertEqual(exp2, genutils.basename(act, ('.a')))
def __findPicture(self, texname : str): ''' Find a picture. :param texname: The name of the picture in the TeX document. :type texname: str :return: the tuple (target filename, the prefix to add before the macro) :rtype: ''' # Search in the registered/found bitmaps if self.__source2target: for src in self.__source2target: if src == texname: return (os.path.basename(self.__source2target), '') prefix = '' filename = self.__makeFilename(texname) if not os.path.isfile(filename): texexts = ('.pdftex_t', '.pstex_t', '.pdf_tex', '.ps_tex', '.tex') figexts = ( '.pdf', '.eps', '.ps', '.png', '.jpeg', '.jpg', '.gif', '.bmp') exts = figexts + texexts ofilename = filename obasename = genutils.basename(texname, *exts) filenames = {} # Search in the registered paths template = obasename for path in self.includePaths: for ext in figexts: fullname = os.path.join(path, template + ext) fullname = self.__makeFilename(fullname) if os.path.isfile(fullname): filenames[fullname] = False for ext in texexts: fullname = os.path.join(path, template + ext) fullname = self.__makeFilename(fullname, '') if os.path.isfile(fullname): filenames[fullname] = True # Search in the folder, i.e. the document directory. if not filenames: template = os.path.join(os.path.dirname(ofilename), genutils.basename(ofilename, exts)) for ext in figexts: fn = template + ext if os.path.isfile(fn): filenames[fn] = False for ext in texexts: fn = template + ext if os.path.isfile(fn): filenames[fn] = True if not filenames: logging.error(_T('Picture not found: %s'), texname) else: selectedName1 = None selectedName2 = None for filename in filenames: ext = os.path.splitext(filename)[1] or '' texname = self.__createMapping(filename, ext) + ext if filenames[filename]: if not selectedName1: selectedName1 = (texname, filename) else: self.__filesToCopy.add(filename) selectedName2 = texname if selectedName1: texname, filename = selectedName1 logging.trace(_T('Embedding %s'), filename) with open(filename) as f: filecontent = f.read() # Replacing the filename in the newly embedded TeX file if self.__source2target: for source in self.__source2target: filecontent = filecontent.replace('{' + source + '}', '{' + self.__source2target[source] + '}') prefix += textwrap.dedent(""" %%======================================================= %%== BEGIN FILE: %s %%======================================================= \\begin{filecontents*}{%s} %s \\end{filecontents*} %%======================================================= """) % (os.path.basename(texname), os.path.basename(texname), filecontent) self.__dynamicPreamble.append(r'\usepackage{filecontents}') elif selectedName2: texname = selectedName2 else: ext = os.path.splitext(texname)[1] or '' texname = self.__createMapping(filename, ext) + ext self.__filesToCopy.add(filename) return (texname, prefix)
def test_basename_texfilename(self): d = os.path.join('a', 'b', 'c') act = os.path.join(d, 'name+endname+tex.plot') exp = 'name+endname' self.assertEqual(exp, genutils.basename(act, { '.plott', '.plot_tex', '.plottex', '.plot+tex', '.tex.plot', '+tex.plot', '.gnut', '.gnu_tex', '.gnutex', '.gnu+tex', '.tex.gnu', '+tex.gnu' }))
def test_basename_set_a(self): self.assertEqual('name', genutils.basename('name.ext', { '.ext' })) self.assertEqual('name', genutils.basename('name.ext', {'.ext', '.a' })) self.assertEqual('name', genutils.basename('name.ext', {'.a', '.ext' }))
def test_basename_list_a(self): self.assertEqual('name', genutils.basename('name.ext', [ '.ext' ])) self.assertEqual('name', genutils.basename('name.ext', ['.ext', '.a' ])) self.assertEqual('name', genutils.basename('name.ext', ['.a', '.ext' ]))
def test_basename_tuple_a(self): self.assertEqual('name', genutils.basename('name.ext', ('.ext'))) self.assertEqual('name', genutils.basename('name.ext', ('.ext', '.a'))) self.assertEqual('name', genutils.basename('name.ext', ('.a', '.ext'))) self.assertEqual('name.ext', genutils.basename('name.ext', ('.a')))
def generateImage(self, *, infile: str, translatorName: str = None, outfile: str = None, onlymorerecent: bool = True, failOnError: bool = True, ignoreDebugFeature: bool = False) -> str: ''' Generate the image from the given source file by running the appropriate translator. :param infile: The name of the source file. :type infile: str :param translatorName: Name of the translator to run. Default value: None. :type translatorName: str :param outfile: The name of the output file. Default value: None :type outfile: str :param onlymorerecent: Indicates if the translation is always run (False) or only if the source file is more recent than the target file. Default value: True :type onlymorerecent: bool :param failOnError: Indicates if the translator generates a Python exception on error during the run. Default value: True. :type failOnError: bool :return: The output filename on success; otherwise None on error or if the file is up-to-date :rtype: str ''' if not infile: return None translator = None if translatorName: translator = self._repository._getObjectFor(translatorName) if translator is None: translator = self.getTranslatorFor(infile, outfile) if translator is None: raise TranslatorError( _T("Unable to find a translator for the source image %s") % (infile)) if not os.access(infile, os.R_OK): errmsg = _T("%s: file not found or not readable.") % (infile) if failOnError: raise TranslatorError(errmsg) else: logging.error(errmsg) return None inexts = translator.getInputExtensions() inext = None for e in inexts: if infile.endswith(e): inext = e break if not inext: inext = translator.getInputExtensions()[0] outexts = translator.getOutputExtensions() if len(outexts) > 0 and outexts[0]: outext = outexts[0] else: outext = '' if not outfile: outfile = genutils.basename2(infile, inexts) + outext # Try to avoid the translation if the source file is no more recent than the target file. if onlymorerecent: inchange = genutils.getFileLastChange(infile) outchange = genutils.getFileLastChange(outfile) if outchange is None: # No out file, try to detect other types of generated files dirname = os.path.dirname(outfile) for filename in os.listdir(dirname): absPath = os.path.join(dirname, filename) if not os.path.isdir( absPath) and not genutils.isHiddenFile(absPath): bn = genutils.basename(filename, outexts) m = re.match( '^(' + re.escape(bn + '_') + '.*)' + re.escape(outext) + '$', filename, re.S) if m: t = genutils.getFileLastChange(absPath) if t is not None and (outchange is None or t < outchange): outchange = t break if outchange is not None and inchange <= outchange: # No need to translate again logging.fine_info( _T("%s is up-to-date") % (os.path.basename(outfile))) return None logging.info( _T("%s -> %s") % (os.path.basename(infile), os.path.basename(outfile))) logging.debug(_T("In: %s") % (infile)) logging.debug(_T("Out: %s") % (outfile)) commandLine = translator.getCommandLine() embeddedFunction = translator.getEmbeddedFunction() environment = translator.getConstants() environment['in'] = infile environment['indir'] = os.path.dirname(infile) environment['inexts'] = inexts environment['inext'] = inext environment['out'] = outfile environment['outdir'] = os.path.dirname(outfile) environment['outexts'] = outexts environment['outext'] = outext environment['ext'] = outext environment['outbasename'] = genutils.basename(outfile, outexts) environment['outwoext'] = os.path.join(os.path.dirname(outfile), environment['outbasename']) environment[ 'outmode'] = 'pdf' if translator.configuration.generation.pdfMode else 'eps' if not ignoreDebugFeature and debugtranslator.python_translator_debugger_enable( ): environment['runner'] = self environment[ 'python_script_dependencies'] = translator.getPythonDependencies( ) environment['global_configuration'] = translator.configuration return debugtranslator.python_translator_debugger_code( self, environment) elif commandLine: ################################ # Run an external command line # ################################ # Create the environment of variables for the CLI # Create the CLI to run cli = genutils.expandenv(commandLine, environment) # Run the cli if logging.getLogger().isEnabledFor(logging.DEBUG): shCmd = list() for e in cli: shCmd.append(shlex.quote(e)) logging.debug(_T("Run: %s") % (' '.join(shCmd))) out = subprocess.Popen(cli, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (sout, serr) = out.communicate() if out.returncode != 0: errmsg = _T("%s\nReturn code: %d") % ( (serr or ''), out.returncode) if failOnError: raise TranslatorError(errmsg) else: logging.error(errmsg) return None return outfile elif embeddedFunction: ######################### # Run the embedded code # ######################### interpreter = translator.getEmbeddedFunctionInterpreter() if not interpreter: interpreter = translator.configuration.pythonInterpreter else: interpreter = interpreter.lower() if interpreter == translator.configuration.pythonInterpreter: environment['runner'] = self environment[ 'python_script_dependencies'] = translator.getPythonDependencies( ) environment['global_configuration'] = translator.configuration execEnv = { 'interpreterObject': None, 'global_configuration': translator.configuration, } if translator.configuration is None: raise Exception('No configuration specification') package_name = "autolatex2.translator.interpreters." + interpreter + "interpreter" if importlib.util.find_spec(package_name) is None: m = re.match('^(.*?)[0-9]+$', interpreter) if m: package_name = "autolatex2.translator.interpreters." + m.group( 1) + "interpreter" exec( "from " + package_name + " import TranslatorInterpreter\n" "interpreterObject = TranslatorInterpreter(global_configuration)", None, execEnv) if not execEnv['interpreterObject'].runnable: errmsg = _T("Cannot execute the translator '%s'.") % ( translatorName) if failOnError: raise TranslatorError(errmsg) else: logging.error(errmsg) return None execEnv['interpreterObject'].globalVariables.update(environment) (sout, serr, exception, retcode) = execEnv['interpreterObject'].run(embeddedFunction) if exception is not None or retcode != 0: errmsg = _T("%s\nReturn code: %s") % ((serr or ''), retcode) if failOnError: raise (TranslatorError(errmsg)) else: logging.error(errmsg) return None return outfile else: errmsg = _T("Unable to find the method of translation for '%s'." ) % (translatorName) if failOnError: raise TranslatorError(errmsg) else: logging.error(errmsg) return None
def getTargetFiles(self, *, infile: str, translatorName: str = None, outfile: str = None, failOnError: bool = True) -> list: ''' Replies the list of the generated files that are by the translator. The replied files exist in the file system. :param infile: The name of the source file. Preferably, it should be absolute filename. :type infile: str :param translatorName: Name of the translator to run. Default value: None. :type translatorName: str :param outfile: The name of the output file. Default value: None :type outfile: str :param failOnError: Indicates if the translator generates a Python exception on error during the run. Default value: True. :type failOnError: bool :return: The list of the target files. :rtype: list ''' if not infile: return list() translator = None if translatorName: translator = self._repository._getObjectFor(translatorName) if translator is None: translator = self.getTranslatorFor(infile) if translator is None: raise TranslatorError( _T("Unable to find a translator for the source image %s") % (infile)) inexts = translator.getInputExtensions() inext = None len_inext = 0 for e in inexts: if infile.endswith(e) and len(e) > len_inext: inext = e len_inext = len(e) if not inext: inext = translator.getInputExtensions()[0] outexts = translator.getOutputExtensions() if len(outexts) > 0 and outexts[0]: outext = outexts[0] else: outext = '' if not outfile: outfile = genutils.basename2(infile, inexts) + outext environment = translator.getConstants() environment['in'] = infile indir = os.path.dirname(infile) environment['indir'] = indir environment['inexts'] = inexts environment['inext'] = inext environment['out'] = outfile outdir = os.path.dirname(outfile) environment['outdir'] = outdir environment['outexts'] = outexts environment['outext'] = outext environment['ext'] = outext environment['outbasename'] = genutils.basename(outfile, outexts) environment['outwoext'] = os.path.join(outdir, environment['outbasename']) environment[ 'outmode'] = 'pdf' if translator.configuration.generation.pdfMode else 'eps' fixed_patterns = genutils.expandenv(translator.getTargetFilePatterns(), environment) target_files = list() for pattern in fixed_patterns: if os.path.isabs(pattern): pt0 = pattern pt1 = pattern else: pt0 = os.path.join(indir, pattern) pt1 = os.path.join(outdir, pattern) target_files.extend(glob.glob(pathname=pt0, recursive=False)) if indir != outdir: target_files.extend(glob.glob(pathname=pt1, recursive=False)) return target_files