Module geode.utils
Expand source code
# ------------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Modules
# ------------------------------------------------------------------------------
# Filesystem
from os.path import exists
from os.path import expanduser
from os.path import join as path_join
# Regex
from re import sub as re_sub
# System
from os import environ
# ------------------------------------------------------------------------------
# Modules - Packages
# ------------------------------------------------------------------------------
try:
from pkg_resources import resource_filename
from pkg_resources import DistributionNotFound
except ImportError as error:
sys_exit("Import error with python3-setuptools module: %s" % str(error))
# ------------------------------------------------------------------------------
# Methods
# ------------------------------------------------------------------------------
def get_data(*args):
""" Provides easy access to data in a python egg or local folder
This function search a path in a specific python egg or in local folder. The
local folder is check before egg to allow quick debugging.
Thanks Deluge :)
Parameters
----------
path : str
File path
Returns
-------
str or None
Path
"""
path = path_join(*args)
try:
data = resource_filename("geode", path)
if exists(expanduser(data)):
return data
return path
except DistributionNotFound as error:
return path
except KeyError as error:
return path
return None
def get_binary_path(binary):
""" Get a list of available binary paths from $PATH variable
This function get all the path from $PATH variable which match binary
request.
Parameters
----------
binary : str
Binary name or path
Returns
-------
list
List of available path
Examples
--------
>>> get_binary_path("ls")
['/bin/ls']
"""
available = list()
if len(binary) == 0:
return available
if exists(expanduser(binary)):
available.append(binary)
binary = basename(binary)
for path in set(environ["PATH"].split(':')):
binary_path = expanduser(path_join(path, binary))
if exists(binary_path) and not binary_path in available:
available.append(binary_path)
return available
def generate_identifier(filepath):
""" Generate an identifier from a name string
Parameters
----------
filepath : pathlib.Path
Path to parse into indentifier
Returns
-------
str
Identifier string
Examples
--------
>>> generate_identifier("Double Dragon II - The Sacred Stones (Europe).nes")
'double-dragon-ii-the-sacred-stones-europe-nes-25953832'
"""
# Retrieve only alphanumeric element from filename
name = re_sub(r"[^\w\d]+", ' ', filepath.name.lower())
# Remove useless spaces and replace the others with a dash
name = re_sub(r"[\s|_]+", '-', name.strip())
# Retrieve file inode number
inode = filepath.stat().st_ino
if inode > 0:
name = "%s-%d" % (name, filepath.stat().st_ino)
return name
def generate_extension(extension):
""" Generate a regex pattern to check lower and upper case extensions
Thanks to https://stackoverflow.com/a/10148272
Parameters
----------
extension : str
Extension to parse without the first dot
Returns
-------
str
Regex pattern
Examples
--------
>>> generate_extensions("nes")
'[nN][eE][sS]'
"""
pattern = str()
for character in extension:
if not character == '.':
pattern += "[%s%s]" % (character.lower(), character.upper())
else:
pattern += '.'
return pattern
Functions
def generate_extension(extension)
-
Generate a regex pattern to check lower and upper case extensions
Thanks to https://stackoverflow.com/a/10148272
Parameters
extension
:str
- Extension to parse without the first dot
Returns
str
- Regex pattern
Examples
>>> generate_extensions("nes") '[nN][eE][sS]'
Expand source code
def generate_extension(extension): """ Generate a regex pattern to check lower and upper case extensions Thanks to https://stackoverflow.com/a/10148272 Parameters ---------- extension : str Extension to parse without the first dot Returns ------- str Regex pattern Examples -------- >>> generate_extensions("nes") '[nN][eE][sS]' """ pattern = str() for character in extension: if not character == '.': pattern += "[%s%s]" % (character.lower(), character.upper()) else: pattern += '.' return pattern
def generate_identifier(filepath)
-
Generate an identifier from a name string
Parameters
filepath
:pathlib.Path
- Path to parse into indentifier
Returns
str
- Identifier string
Examples
>>> generate_identifier("Double Dragon II - The Sacred Stones (Europe).nes") 'double-dragon-ii-the-sacred-stones-europe-nes-25953832'
Expand source code
def generate_identifier(filepath): """ Generate an identifier from a name string Parameters ---------- filepath : pathlib.Path Path to parse into indentifier Returns ------- str Identifier string Examples -------- >>> generate_identifier("Double Dragon II - The Sacred Stones (Europe).nes") 'double-dragon-ii-the-sacred-stones-europe-nes-25953832' """ # Retrieve only alphanumeric element from filename name = re_sub(r"[^\w\d]+", ' ', filepath.name.lower()) # Remove useless spaces and replace the others with a dash name = re_sub(r"[\s|_]+", '-', name.strip()) # Retrieve file inode number inode = filepath.stat().st_ino if inode > 0: name = "%s-%d" % (name, filepath.stat().st_ino) return name
def get_binary_path(binary)
-
Get a list of available binary paths from $PATH variable
This function get all the path from $PATH variable which match binary request.
Parameters
binary
:str
- Binary name or path
Returns
list
- List of available path
Examples
>>> get_binary_path("ls") ['/bin/ls']
Expand source code
def get_binary_path(binary): """ Get a list of available binary paths from $PATH variable This function get all the path from $PATH variable which match binary request. Parameters ---------- binary : str Binary name or path Returns ------- list List of available path Examples -------- >>> get_binary_path("ls") ['/bin/ls'] """ available = list() if len(binary) == 0: return available if exists(expanduser(binary)): available.append(binary) binary = basename(binary) for path in set(environ["PATH"].split(':')): binary_path = expanduser(path_join(path, binary)) if exists(binary_path) and not binary_path in available: available.append(binary_path) return available
def get_data(*args)
-
Provides easy access to data in a python egg or local folder
This function search a path in a specific python egg or in local folder. The local folder is check before egg to allow quick debugging.
Thanks Deluge :)
Parameters
path
:str
- File path
Returns
str
orNone
- Path
Expand source code
def get_data(*args): """ Provides easy access to data in a python egg or local folder This function search a path in a specific python egg or in local folder. The local folder is check before egg to allow quick debugging. Thanks Deluge :) Parameters ---------- path : str File path Returns ------- str or None Path """ path = path_join(*args) try: data = resource_filename("geode", path) if exists(expanduser(data)): return data return path except DistributionNotFound as error: return path except KeyError as error: return path return None