def test_basename2_set_b(self): d = os.path.join('a', 'b', 'c') act = os.path.join(d, 'name.ext') exp = os.path.join(d, 'name') self.assertEqual(exp, genutils.basename2(act, { '.ext' })) self.assertEqual(exp, genutils.basename2(act, {'.ext', '.a' })) self.assertEqual(exp, genutils.basename2(act, {'.a', '.ext' }))
def test_basename2_tuple_b(self): d = os.path.join('a', 'b', 'c') act = os.path.join(d, 'name.ext') exp = os.path.join(d, 'name') exp2 = os.path.join(d, 'name.ext') self.assertEqual(exp, genutils.basename2(act, ('.ext'))) self.assertEqual(exp, genutils.basename2(act, ('.ext', '.a'))) self.assertEqual(exp, genutils.basename2(act, ('.a', '.ext'))) self.assertEqual(exp2, genutils.basename2(act, ('.a')))
def _is_deletable_in_root_folder_only(self, root_dir: str, tex_filename: str, filename: str) -> bool: ''' Replies if the given filename is for a deletable file in the root folder. ''' basename = genutils.basename2(os.path.join(root_dir, tex_filename), texutils.getTeXFileExtensions()) candidates = [ os.path.join(root_dir, '.autolatex_stamp'), os.path.join(root_dir, 'autolatex_stamp'), os.path.join( root_dir, 'autolatex_exec_stderr.log'), # For old version of AutoLaTeX os.path.join( root_dir, 'autolatex_exec_stdout.log'), # For old version of AutoLaTeX os.path.join( root_dir, 'autolatex_exec_stdin.log'), # For old version of AutoLaTeX os.path.join(root_dir, 'autolatex_autogenerated.tex'), basename + ".pdf", basename + ".dvi", basename + ".xdvi", basename + ".xdv", basename + ".ps", basename + ".synctex.gz", basename + ".synctex", ] return filename in candidates
def run(self, args) -> bool: ''' Callback for running the command. :param args: the arguments. :return: True if the process could continue. False if an error occurred and the process should stop. ''' ddir = self.configuration.documentDirectory if ddir and not args.nochdir: os.chdir(ddir) maker = AutoLaTeXMaker.create(self.configuration) idxExt = texutils.getIndexFileExtensions()[0] for root_file in maker.rootFiles: idxFile = genutils.basename2( root_file, texutils.getTeXFileExtensions()) + idxExt if not maker.run_makeindex(idxFile): logging.error(_T("Error when running the indexing tool")) return False return True
def python_translator_debugger_code(runner: object, environment: dict): ''' The code to debug. ''' # Initialization of the script _in = environment['in'] _indir = environment['indir'] _inexts = environment['inexts'] _inext = environment['inext'] _out = environment['out'] _outdir = environment['outdir'] _outmode = environment['outmode'] _outexts = environment['outexts'] _outext = environment['outext'] _ext = environment['ext'] _outbasename = environment['outbasename'] _outwoext = environment['outwoext'] _runner = runner _python_script_dependencies = environment['python_script_dependencies'] _global_configuration = environment['global_configuration'] ############################################################### ############################################################### ## Code to debug ############################################################### ############################################################### epsFile = genutils.basename2(_in, _inexts) + '.eps' try: (sout, serr, sex, retcode) = Runner.runCommand('asy', '-o', epsFile, _in) Runner.checkRunnerStatus(serr, sex, retcode) if _global_configuration.generation.pdfMode: _runner.generateImage(infile=epsFile, outfile=_out, onlymorerecent=False, ignoreDebugFeature=True) finally: genutils.unlink(epsFile) ############################################################### ############################################################### return _out
def _internal_run_viewer(self, maker: AutoLaTeXMaker, args) -> bool: ''' Run the internal viewer of the 'view' command. :param maker: the AutoLaTeX maker. :param args: the arguments. :return: True to continue process. False to stop the process. ''' files = maker.rootFiles if not files: logging.error( _T("Unable to find the name of the generated file for the viewer" )) return False for input_file in files: if not input_file: logging.error( _T("Unable to find the name of the generated file for the viewer" )) return False pdf_file = genutils.basename2( input_file, texutils.getTeXFileExtensions()) + '.pdf' logging.debug(_T("VIEWER: %s") % (pdf_file)) cli = self.configuration.view.viewerCLI if not cli: logging.error( _T("Unable to find the command-line for the viewing action. Did you set the configuration?" )) sys.exit(255) cmd = list(cli) cmd.append(pdf_file) cmd = Runner.normalizeCommand(cmd) if self.configuration.view.asyncview: if not Runner.startCommandWithoutRedirect(*cmd): return False else: if not Runner.runCommandWithoutRedirect(*cmd): return False return True
def test_basename2_texfilename(self): d = os.path.join('a', 'b', 'c') act = os.path.join(d, 'name+endname+tex.plot') exp = os.path.join(d, 'name+endname') self.assertEqual(exp, genutils.basename2(act, { '.plott', '.plot_tex', '.plottex', '.plot+tex', '.tex.plot', '+tex.plot', '.gnut', '.gnu_tex', '.gnutex', '.gnu+tex', '.tex.gnu', '+tex.gnu' }))
def test_basename2_set_a(self): self.assertEqual('name', genutils.basename2('name.ext', { '.ext' })) self.assertEqual('name', genutils.basename2('name.ext', {'.ext', '.a' })) self.assertEqual('name', genutils.basename2('name.ext', {'.a', '.ext' }))
def test_basename2_list_a(self): self.assertEqual('name', genutils.basename2('name.ext', [ '.ext' ])) self.assertEqual('name', genutils.basename2('name.ext', ['.ext', '.a' ])) self.assertEqual('name', genutils.basename2('name.ext', ['.a', '.ext' ]))
def test_basename2_tuple_a(self): self.assertEqual('name', genutils.basename2('name.ext', ('.ext'))) self.assertEqual('name', genutils.basename2('name.ext', ('.ext', '.a'))) self.assertEqual('name', genutils.basename2('name.ext', ('.a', '.ext'))) self.assertEqual('name.ext', genutils.basename2('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