def check_and_call_extract_file(filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath=None): """Checks if the given file matches an extraction method mapping, and if so, calls extract_from_file. Note that the extraction method mappings are based relative to dirpath. So, given an absolute path to a file `filepath`, we want to check using just the relative path from `dirpath` to `filepath`. Yields 5-tuples (filename, lineno, messages, comments, context). :param filepath: An absolute path to a file that exists. :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :param dirpath: the path to the directory to extract messages from. :return: iterable of 5-tuples (filename, lineno, messages, comments, context) :rtype: Iterable[tuple[str, int, str|tuple[str], list[str], str|None] """ # filename is the relative path from dirpath to the actual file filename = relpath(filepath, dirpath) for pattern, method in method_map: if not pathmatch(pattern, filename): continue options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for message_tuple in extract_from_file( method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): yield (filename, ) + message_tuple break
def check_and_call_extract_file(filepath, method_map, options_map, callback, keywords, comment_tags, strip_comment_tags, dirpath=None): """Checks if the given file matches an extraction method mapping, and if so, calls extract_from_file. Note that the extraction method mappings are based relative to dirpath. So, given an absolute path to a file `filepath`, we want to check using just the relative path from `dirpath` to `filepath`. Yields 5-tuples (filename, lineno, messages, comments, context). :param filepath: An absolute path to a file that exists. :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :param dirpath: the path to the directory to extract messages from. :return: iterable of 5-tuples (filename, lineno, messages, comments, context) :rtype: Iterable[tuple[str, int, str|tuple[str], list[str], str|None] """ # filename is the relative path from dirpath to the actual file filename = relpath(filepath, dirpath) for pattern, method in method_map: if not pathmatch(pattern, filename): continue options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for message_tuple in extract_from_file( method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags ): yield (filename, ) + message_tuple break
def test_pathmatch(): assert util.pathmatch('**.py', 'bar.py') assert util.pathmatch('**.py', 'foo/bar/baz.py') assert not util.pathmatch('**.py', 'templates/index.html') assert util.pathmatch('**/templates/*.html', 'templates/index.html') assert not util.pathmatch('**/templates/*.html', 'templates/foo/bar.html') assert util.pathmatch('^foo/**.py', 'foo/bar/baz/blah.py') assert not util.pathmatch('^foo/**.py', 'blah/foo/bar/baz.py') assert util.pathmatch('./foo/**.py', 'foo/bar/baz/blah.py') assert util.pathmatch('./blah.py', 'blah.py') assert not util.pathmatch('./foo/**.py', 'blah/foo/bar/baz.py')
def Extract (dirname, template_file, config, cmd) : absname = os.path.abspath (dirname) po_file = TFL.Babel.PO_File \ ( project = cmd.project , version = cmd.version , bugs_address = cmd.bugs_address , copyright_holder = cmd.copyright_holder , charset = cmd.charset , width = cmd.width , no_location = cmd.no_location , omit_header = cmd.omit_header , sort = cmd.sort ) keywords = Default_Keywords.copy () keywords.update (dict (k, None) for k in cmd.keywords) for root, dirnames, filenames in os.walk (absname) : dirnames.sort () for filename in sorted (filenames) : filename = os.path.relpath \ (os.path.join (root, filename).replace (os.sep, '/'), dirname) try : for method_name, pattern in config.patterns.items () : if pathmatch (pattern, filename) : for pattern in config.get_list \ ("ignore_patterns", method_name, set (), True) : if pathmatch (pattern, filename) : raise Skip filepath = os.path.join (absname, filename) rfp = TFL.relative_to_python_path (filepath) print ("Method `%-10s`: `%s" % (method_name, filename)) trans = config.get ("loaded_translations", method_name) for lineno, message, comments, found_in in \ _extract_from_file \ ( method_name , filepath , config , cmd , keywords ) : fn = rfp if found_in : fn = TFL.relative_to_python_path (found_in) if message not in trans : po_file.add \ ( message, None, [(fn, lineno)] , auto_comments = comments ) break except Skip : print ("Ignore : `%s" % (filename, )) print ("Create template file", template_file, file = sys.stderr) po_file.save (template_file)
def Extract(dirname, template_file, config, cmd): absname = os.path.abspath(dirname) po_file = TFL.Babel.PO_File \ ( project = cmd.project , version = cmd.version , bugs_address = cmd.bugs_address , copyright_holder = cmd.copyright_holder , charset = cmd.charset , width = cmd.width , no_location = cmd.no_location , omit_header = cmd.omit_header , sort = cmd.sort ) keywords = Default_Keywords.copy() keywords.update(dict(k, None) for k in cmd.keywords) for root, dirnames, filenames in os.walk(absname): dirnames.sort() for filename in sorted(filenames): filename = os.path.relpath \ (os.path.join (root, filename).replace (os.sep, '/'), dirname) try: for method_name, pattern in config.patterns.items(): if pathmatch(pattern, filename): for pattern in config.get_list \ ("ignore_patterns", method_name, set (), True) : if pathmatch(pattern, filename): raise Skip filepath = os.path.join(absname, filename) rfp = TFL.relative_to_python_path(filepath) print("Method `%-10s`: `%s" % (method_name, filename)) trans = config.get("loaded_translations", method_name) for lineno, message, comments, found_in in \ _extract_from_file \ ( method_name , filepath , config , cmd , keywords ) : fn = rfp if found_in: fn = TFL.relative_to_python_path(found_in) if message not in trans: po_file.add \ ( message, None, [(fn, lineno)] , auto_comments = comments ) break except Skip: print("Ignore : `%s" % (filename, )) print("Create template file", template_file, file=sys.stderr) po_file.save(template_file)
def glob(self, expr): if not hasattr(self, "_files"): # @fixme: Remove hg f = subprocess.Popen(["git", "ls-files"], stdout=subprocess.PIPE).stdout self._files = f.read().splitlines() return [p for p in self._files if pathmatch(expr, p)]
def scanFolder(folderPath): """ Scan a folder that is found on the provided path. @param folderPath: string The folder path. @return: tuple(string, string, generator) Returns a tuple containing: (filePath, method, generator(@see: process)) """ assert isinstance(folderPath, str), "Invalid folder path %s" % folderPath for root, _dirnames, filenames in os.walk(folderPath): filenames.sort() for name in filenames: name = path.relpath(os.path.join(root, name)).replace(os.sep, "/") for pattern, method in METHOD_MAP: if pathmatch(pattern, name): filePath = name.replace("/", os.sep) yield filePath, method, process(partial(open, name, "rb"), method)
def scanFolder(folderPath): ''' Scan a folder that is found on the provided path. @param folderPath: string The folder path. @return: tuple(string, string, generator) Returns a tuple containing: (filePath, method, generator(@see: process)) ''' assert isinstance(folderPath, str), 'Invalid folder path %s' % folderPath for root, _dirnames, filenames in os.walk(folderPath): filenames.sort() for name in filenames: name = path.relpath(os.path.join(root, name)).replace(os.sep, '/') for pattern, method in METHOD_MAP: if pathmatch(pattern, name): filePath = name.replace('/', os.sep) yield filePath, method, process(partial(open, name, 'rb'), method)
def scanZip(zipFilePath): ''' Scan a zip that is found on the provided path. @param zipFilePath: string The zip path. @return: tuple(string, string, generator) Returns a tuple containing: (filePath, method, generator(@see: process)) ''' zipFile = ZipFile(zipFilePath) names = zipFile.namelist() names.sort() for name in names: for pattern, method in METHOD_MAP: if pathmatch(pattern, name): filePath = zipFilePath + '/' + name def openZip(): with zipFile.open(name, 'r') as f: return BytesIO(f.read()) yield filePath, method, process(openZip, method)
def test_pathmatch(): assert util.pathmatch("**.py", "bar.py") assert util.pathmatch("**.py", "foo/bar/baz.py") assert not util.pathmatch("**.py", "templates/index.html") assert util.pathmatch("**/templates/*.html", "templates/index.html") assert not util.pathmatch("**/templates/*.html", "templates/foo/bar.html")
def extract_from_dir(dirname=os.getcwd(), method_map=DEFAULT_MAPPING, options_map=None, keywords=DEFAULT_KEYWORDS, comment_tags=(), callback=None, strip_comment_tags=False): """Extract messages from any source files found in the given directory. This function generates tuples of the form: ``(filename, lineno, message, comments)`` Which extraction method is used per file is determined by the `method_map` parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping: >>> method_map = [ ... ('**.py', 'python') ... ] This basically says that files with the filename extension ".py" at any level inside the directory should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the `pathmatch` function for details on the pattern syntax. The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory: >>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ] The dictionary provided by the optional `options_map` parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings). The glob patterns of the `options_map` do not necessarily need to be the same as those used in the method mapping. For example, while all files in the ``templates`` folders in an application may be Genshi applications, the options for those files may differ based on extension: >>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... } :param dirname: the path to the directory to extract messages from :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :return: an iterator over ``(filename, lineno, funcname, message)`` tuples :rtype: ``iterator`` :see: `pathmatch` """ if options_map is None: options_map = {} absname = os.path.abspath(dirname) for root, dirnames, filenames in os.walk(absname): for subdir in dirnames: if subdir.startswith('.') or subdir.startswith('_'): dirnames.remove(subdir) dirnames.sort() filenames.sort() for filename in filenames: filename = relpath( os.path.join(root, filename).replace(os.sep, '/'), dirname ) for pattern, method in method_map: if pathmatch(pattern, filename): filepath = os.path.join(absname, filename) options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for lineno, message, comments in \ extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags= strip_comment_tags): yield filename, lineno, message, comments break
def is_template(name): full_name = os.path.join(cli.templates, name) for path in search_paths: if pathmatch(path, full_name): return True
def extract_from_dir(dirname=os.getcwd(), method_map=DEFAULT_MAPPING, options_map=None, keywords=DEFAULT_KEYWORDS, comment_tags=(), callback=None, strip_comment_tags=False): """Extract messages from any source files found in the given directory. This function generates tuples of the form: ``(filename, lineno, message, comments)`` Which extraction method is used per file is determined by the `method_map` parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping: >>> method_map = [ ... ('**.py', 'python') ... ] This basically says that files with the filename extension ".py" at any level inside the directory should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the `pathmatch` function for details on the pattern syntax. The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory: >>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ] The dictionary provided by the optional `options_map` parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings). The glob patterns of the `options_map` do not necessarily need to be the same as those used in the method mapping. For example, while all files in the ``templates`` folders in an application may be Genshi applications, the options for those files may differ based on extension: >>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... } :param dirname: the path to the directory to extract messages from :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :return: an iterator over ``(filename, lineno, funcname, message, context)`` tuples :rtype: ``iterator`` :see: `pathmatch` """ if options_map is None: options_map = {} absname = os.path.abspath(dirname) for root, dirnames, filenames in os.walk(absname): for subdir in dirnames: if subdir.startswith('.') or subdir.startswith('_'): dirnames.remove(subdir) dirnames.sort() filenames.sort() for filename in filenames: filename = relpath( os.path.join(root, filename).replace(os.sep, '/'), dirname) for pattern, method in method_map: if pathmatch(pattern, filename): filepath = os.path.join(absname, filename) options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for lineno, message, comments, context in \ extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags= strip_comment_tags): yield filename, lineno, message, comments, context break
def extract_from_files(filenames, method_map=METHODS, options_map=generate_options_map(), keywords=get_setting('KEYWORDS'), comment_tags=get_setting('COMMENT_TAGS'), callback=extract_callback, strip_comment_tags=False): """Extract messages from any source files found in the given iterable. This function generates tuples of the form: ``(filename, lineno, message, comments)`` Which extraction method is used per file is determined by the `method_map` parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping: >>> method_map = [ ... ('**.py', 'python') ... ] This basically says that files with the filename extension ".py" should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the `pathmatch` function for details on the pattern syntax. The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory: >>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ] The dictionary provided by the optional `options_map` parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings). The glob patterns of the `options_map` do not necessarily need to be the same as those used in the method mapping. For example, while all files in the ``templates`` folders in an application may be Genshi applications, the options for those files may differ based on extension: >>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... } :param filenames: an iterable of filenames relative to the ROOT of the project :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :return: an iterator over ``(filename, lineno, funcname, message)`` tuples :rtype: ``iterator`` :see: `pathmatch` """ # adapted from babel.messages.extract.extract_from_dir for filename in filenames: matched = False for pattern, method in method_map: if pathmatch(pattern, filename): matched = True filepath = os.path.join(settings.ROOT, filename) if not os.path.exists(filepath): print('! %s does not exist!' % filename) break options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for lineno, message, comments, context in\ extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): yield filename, lineno, message, comments, context break if not matched: print('! %s does not match any domain methods!' % filename)
def extract_from_files(filenames, method_map=METHODS, options_map=extract.OPTIONS_MAP, keywords=extract.TOWER_KEYWORDS, comment_tags=extract.COMMENT_TAGS, callback=extract_callback, strip_comment_tags=False): """Extract messages from any source files found in the given iterable. This function generates tuples of the form: ``(filename, lineno, message, comments)`` Which extraction method is used per file is determined by the `method_map` parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping: >>> method_map = [ ... ('**.py', 'python') ... ] This basically says that files with the filename extension ".py" should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the `pathmatch` function for details on the pattern syntax. The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory: >>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ] The dictionary provided by the optional `options_map` parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings). The glob patterns of the `options_map` do not necessarily need to be the same as those used in the method mapping. For example, while all files in the ``templates`` folders in an application may be Genshi applications, the options for those files may differ based on extension: >>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... } :param filenames: an iterable of filenames relative to the ROOT of the project :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :return: an iterator over ``(filename, lineno, funcname, message)`` tuples :rtype: ``iterator`` :see: `pathmatch` """ # adapted from babel.messages.extract.extract_from_dir for filename in filenames: matched = False for pattern, method in method_map: if pathmatch(pattern, filename): matched = True filepath = os.path.join(settings.ROOT, filename) if not os.path.exists(filepath): print '! %s does not exist!' % filename break options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for lineno, message, comments in\ extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): yield filename, lineno, message, comments break if not matched: print '! %s does not match any domain methods!' % filename