list.py: Moved static functions to module level.

This commit is contained in:
Michael Schwarz 2014-08-24 18:17:09 +02:00
parent 5e87dadc02
commit 69461d20fc
2 changed files with 217 additions and 224 deletions

View file

@ -28,195 +28,79 @@ whether or not you may commercially redistribute an image make use
that line FREE: yes, is included inside the image between two $$$ that line FREE: yes, is included inside the image between two $$$
lines and the FREE is and upper case and directly followed by lines and the FREE is and upper case and directly followed by
the colon. the colon.
File listing functions.
''' '''
from ucs import * from ucs import *
def _columnise(ponies):
class List():
''' '''
File listing functions Columnise a list and prints it
@param ponies:list<(str, str)> All items to list, each item should have to elements: unformated name, formated name
''' '''
## Get terminal width, and a 2 which is the space between columns
termwidth = gettermsize()[1] + 2
## Sort the ponies, and get the cells' widths, and the largest width + 2
ponies.sort(key = lambda pony : pony[0])
widths = [UCS.dispLen(pony[0]) for pony in ponies]
width = max(widths) + 2 # longest pony file name + space between columns
@staticmethod ## Calculate the number of rows and columns, can create a list of empty columns
def __columnise(ponies): cols = termwidth // width # do not believe electricians, this means ⌊termwidth / width⌋
''' rows = (len(ponies) + cols - 1) // cols
Columnise a list and prints it columns = []
for c in range(0, cols): columns.append([])
@param ponies:list<(str, str)> All items to list, each item should have to elements: unformated name, formated name ## Fill the columns with cells of ponies
''' (y, x) = (0, 0)
## Get terminal width, and a 2 which is the space between columns for j in range(0, len(ponies)):
termwidth = gettermsize()[1] + 2 cell = ponies[j][1] + ' ' * (width - widths[j]);
## Sort the ponies, and get the cells' widths, and the largest width + 2 columns[x].append(cell)
ponies.sort(key = lambda pony : pony[0]) y += 1
widths = [UCS.dispLen(pony[0]) for pony in ponies] if y == rows:
width = max(widths) + 2 # longest pony file name + space between columns x += 1
y = 0
## Calculate the number of rows and columns, can create a list of empty columns ## Make the columnisation nicer by letting the last row be partially empty rather than the last column
cols = termwidth // width # do not believe electricians, this means ⌊termwidth / width⌋ diff = rows * cols - len(ponies)
rows = (len(ponies) + cols - 1) // cols if (diff > 2) and (rows > 1):
columns = [] c = cols - 1
for c in range(0, cols): columns.append([]) diff -= 1
while diff > 0:
## Fill the columns with cells of ponies columns[c] = columns[c - 1][-diff:] + columns[c]
(y, x) = (0, 0) c -= 1
for j in range(0, len(ponies)): columns[c] = columns[c][:-diff]
cell = ponies[j][1] + ' ' * (width - widths[j]);
columns[x].append(cell)
y += 1
if y == rows:
x += 1
y = 0
## Make the columnisation nicer by letting the last row be partially empty rather than the last column
diff = rows * cols - len(ponies)
if (diff > 2) and (rows > 1):
c = cols - 1
diff -= 1 diff -= 1
while diff > 0:
columns[c] = columns[c - 1][-diff:] + columns[c]
c -= 1
columns[c] = columns[c][:-diff]
diff -= 1
## Create rows from columns ## Create rows from columns
lines = [] lines = []
for r in range(0, rows): for r in range(0, rows):
lines.append([]) lines.append([])
for c in range(0, cols): for c in range(0, cols):
if r < len(columns[c]): if r < len(columns[c]):
line = lines[r].append(columns[c][r]) line = lines[r].append(columns[c][r])
## Print the matrix, with one extra blank row ## Print the matrix, with one extra blank row
print('\n'.join([''.join(line)[:-2] for line in lines])) print('\n'.join([''.join(line)[:-2] for line in lines]))
print() print()
@staticmethod def simplelist(ponydirs, quoters = [], ucsiser = None):
def simplelist(ponydirs, quoters = [], ucsiser = None): '''
''' Lists the available ponies
Lists the available ponies
@param ponydirs:itr<str> The pony directories to use @param ponydirs:itr<str> The pony directories to use
@param quoters:__in__(str)bool Set of ponies that of quotes @param quoters:__in__(str)bool Set of ponies that of quotes
@param ucsiser:(list<str>)?void Function used to UCS:ise names @param ucsiser:(list<str>)?void Function used to UCS:ise names
''' '''
for ponydir in ponydirs: # Loop ponydirs for ponydir in ponydirs: # Loop ponydirs
## Get all ponies in the directory ## Get all ponies in the directory
_ponies = os.listdir(ponydir) _ponies = os.listdir(ponydir)
## Remove .pony from all files and skip those that does not have .pony
ponies = []
for pony in _ponies:
if endswith(pony, '.pony'):
ponies.append(pony[:-5])
## UCS:ise pony names, they are already sorted
if ucsiser is not None:
ucsiser(ponies)
## If ther directory is not empty print its name and all ponies, columnised
if len(ponies) == 0:
continue
print('\033[1mponies located in ' + ponydir + '\033[21m')
List.__columnise([(pony, '\033[1m' + pony + '\033[21m' if pony in quoters else pony) for pony in ponies])
@staticmethod
def linklist(ponydirs = None, quoters = [], ucsiser = None):
'''
Lists the available ponies with alternatives inside brackets
@param ponydirs:itr<str> The pony directories to use
@param quoters:__in__(str)bool Set of ponies that of quotes
@param ucsiser:(list<str>, map<str, str>)?void Function used to UCS:ise names
'''
## Get the size of the terminal
termsize = gettermsize()
for ponydir in ponydirs: # Loop ponydirs
## Get all pony files in the directory
_ponies = os.listdir(ponydir)
## Remove .pony from all files and skip those that does not have .pony
ponies = []
for pony in _ponies:
if endswith(pony, '.pony'):
ponies.append(pony[:-5])
## If there are no ponies in the directory skip to next directory, otherwise, print the directories name
if len(ponies) == 0:
continue
print('\033[1mponies located in ' + ponydir + '\033[21m')
## UCS:ise pony names
pseudolinkmap = {}
if ucsiser is not None:
ucsiser(ponies, pseudolinkmap)
## Create targetlink-pair, with `None` as link if the file is not a symlink or in `pseudolinkmap`
pairs = []
for pony in ponies:
if pony in pseudolinkmap:
pairs.append((pony, pseudolinkmap[pony] + '.pony'));
else:
pairs.append((pony, os.path.realpath(ponydir + pony + '.pony') if os.path.islink(ponydir + pony + '.pony') else None))
## Create map from source pony to alias ponies for each pony
ponymap = {}
for pair in pairs:
if (pair[1] is None) or (pair[1] == ''):
if pair[0] not in ponymap:
ponymap[pair[0]] = []
else:
target = pair[1][:-5]
if '/' in target:
target = target[target.rindex('/') + 1:]
if target in ponymap:
ponymap[target].append(pair[0])
else:
ponymap[target] = [pair[0]]
## Create list of source ponies concatenated with alias ponies in brackets
ponies = {}
for pony in ponymap:
w = UCS.dispLen(pony)
item = '\033[1m' + pony + '\033[21m' if (pony in quoters) else pony
syms = ponymap[pony]
syms.sort()
if len(syms) > 0:
w += 2 + len(syms)
item += ' ('
first = True
for sym in syms:
w += UCS.dispLen(sym)
if first: first = False
else: item += ' '
item += '\033[1m' + sym + '\033[21m' if (sym in quoters) else sym
item += ')'
ponies[(item.replace('\033[1m', '').replace('\033[21m', ''), item)] = w
## Print the ponies, columnised
List.__columnise(list(ponies))
@staticmethod
def onelist(standarddirs, extradirs = None, ucsiser = None):
'''
Lists the available ponies on one column without anything bold or otherwise formated
@param standard:itr<str>? Include standard ponies
@param extra:itr<str>? Include extra ponies
@param ucsiser:(list<str>)?void Function used to UCS:ise names
'''
## Get all pony files
_ponies = []
if standarddirs is not None:
for ponydir in standarddirs:
_ponies += os.listdir(ponydir)
if extradirs is not None:
for ponydir in extradirs:
_ponies += os.listdir(ponydir)
## Remove .pony from all files and skip those that does not have .pony ## Remove .pony from all files and skip those that does not have .pony
ponies = [] ponies = []
@ -224,46 +108,155 @@ class List():
if endswith(pony, '.pony'): if endswith(pony, '.pony'):
ponies.append(pony[:-5]) ponies.append(pony[:-5])
## UCS:ise and sort ## UCS:ise pony names, they are already sorted
if ucsiser is not None: if ucsiser is not None:
ucsiser(ponies) ucsiser(ponies)
ponies.sort()
## Print each one on a seperate line, but skip duplicates ## If ther directory is not empty print its name and all ponies, columnised
last = '' if len(ponies) == 0:
continue
print('\033[1mponies located in ' + ponydir + '\033[21m')
_columnise([(pony, '\033[1m' + pony + '\033[21m' if pony in quoters else pony) for pony in ponies])
def linklist(ponydirs = None, quoters = [], ucsiser = None):
'''
Lists the available ponies with alternatives inside brackets
@param ponydirs:itr<str> The pony directories to use
@param quoters:__in__(str)bool Set of ponies that of quotes
@param ucsiser:(list<str>, map<str, str>)?void Function used to UCS:ise names
'''
## Get the size of the terminal
termsize = gettermsize()
for ponydir in ponydirs: # Loop ponydirs
## Get all pony files in the directory
_ponies = os.listdir(ponydir)
## Remove .pony from all files and skip those that does not have .pony
ponies = []
for pony in _ponies:
if endswith(pony, '.pony'):
ponies.append(pony[:-5])
## If there are no ponies in the directory skip to next directory, otherwise, print the directories name
if len(ponies) == 0:
continue
print('\033[1mponies located in ' + ponydir + '\033[21m')
## UCS:ise pony names
pseudolinkmap = {}
if ucsiser is not None:
ucsiser(ponies, pseudolinkmap)
## Create targetlink-pair, with `None` as link if the file is not a symlink or in `pseudolinkmap`
pairs = []
for pony in ponies: for pony in ponies:
if not pony == last: if pony in pseudolinkmap:
last = pony pairs.append((pony, pseudolinkmap[pony] + '.pony'));
print(pony) else:
pairs.append((pony, os.path.realpath(ponydir + pony + '.pony') if os.path.islink(ponydir + pony + '.pony') else None))
## Create map from source pony to alias ponies for each pony
@staticmethod ponymap = {}
def balloonlist(balloondirs, isthink): for pair in pairs:
''' if (pair[1] is None) or (pair[1] == ''):
Prints a list of all balloons if pair[0] not in ponymap:
ponymap[pair[0]] = []
@param balloondirs:itr<str> The balloon directories to use else:
@param isthink:bool Whether the ponythink command is used target = pair[1][:-5]
''' if '/' in target:
## Get the size of the terminal target = target[target.rindex('/') + 1:]
termsize = gettermsize() if target in ponymap:
ponymap[target].append(pair[0])
## Get all balloons
balloonset = set()
for balloondir in balloondirs:
for balloon in os.listdir(balloondir):
## Use .think if running ponythink, otherwise .say
if isthink and endswith(balloon, '.think'):
balloon = balloon[:-6]
elif (not isthink) and endswith(balloon, '.say'):
balloon = balloon[:-4]
else: else:
continue ponymap[target] = [pair[0]]
## Add the balloon if there is none with the same name ## Create list of source ponies concatenated with alias ponies in brackets
if balloon not in balloonset: ponies = {}
balloonset.add(balloon) for pony in ponymap:
w = UCS.dispLen(pony)
item = '\033[1m' + pony + '\033[21m' if (pony in quoters) else pony
syms = ponymap[pony]
syms.sort()
if len(syms) > 0:
w += 2 + len(syms)
item += ' ('
first = True
for sym in syms:
w += UCS.dispLen(sym)
if first: first = False
else: item += ' '
item += '\033[1m' + sym + '\033[21m' if (sym in quoters) else sym
item += ')'
ponies[(item.replace('\033[1m', '').replace('\033[21m', ''), item)] = w
## Print all balloos, columnised ## Print the ponies, columnised
List.__columnise([(balloon, balloon) for balloon in list(balloonset)]) _columnise(list(ponies))
def onelist(standarddirs, extradirs = None, ucsiser = None):
'''
Lists the available ponies on one column without anything bold or otherwise formated
@param standard:itr<str>? Include standard ponies
@param extra:itr<str>? Include extra ponies
@param ucsiser:(list<str>)?void Function used to UCS:ise names
'''
## Get all pony files
_ponies = []
if standarddirs is not None:
for ponydir in standarddirs:
_ponies += os.listdir(ponydir)
if extradirs is not None:
for ponydir in extradirs:
_ponies += os.listdir(ponydir)
## Remove .pony from all files and skip those that does not have .pony
ponies = []
for pony in _ponies:
if endswith(pony, '.pony'):
ponies.append(pony[:-5])
## UCS:ise and sort
if ucsiser is not None:
ucsiser(ponies)
ponies.sort()
## Print each one on a seperate line, but skip duplicates
last = ''
for pony in ponies:
if not pony == last:
last = pony
print(pony)
def balloonlist(balloondirs, isthink):
'''
Prints a list of all balloons
@param balloondirs:itr<str> The balloon directories to use
@param isthink:bool Whether the ponythink command is used
'''
## Get the size of the terminal
termsize = gettermsize()
## Get all balloons
balloonset = set()
for balloondir in balloondirs:
for balloon in os.listdir(balloondir):
## Use .think if running ponythink, otherwise .say
if isthink and endswith(balloon, '.think'):
balloon = balloon[:-6]
elif (not isthink) and endswith(balloon, '.say'):
balloon = balloon[:-4]
else:
continue
## Add the balloon if there is none with the same name
if balloon not in balloonset:
balloonset.add(balloon)
## Print all balloos, columnised
_columnise([(balloon, balloon) for balloon in balloonset])

View file

@ -35,7 +35,7 @@ from balloon import *
from spellocorrecter import * from spellocorrecter import *
from ucs import * from ucs import *
from kms import * from kms import *
from list import * import list as _list
from metadata import * from metadata import *
@ -739,7 +739,7 @@ class Ponysay():
@param ponydirs:itr<str>? The pony directories to use @param ponydirs:itr<str>? The pony directories to use
''' '''
List.simplelist(self.ponydirs if ponydirs is None else ponydirs, _list.simplelist(self.ponydirs if ponydirs is None else ponydirs,
self.__quoters(), lambda x : self.__ucsise(x)) self.__quoters(), lambda x : self.__ucsise(x))
@ -749,7 +749,7 @@ class Ponysay():
@param ponydirs:itr<str> The pony directories to use @param ponydirs:itr<str> The pony directories to use
''' '''
List.linklist(self.ponydirs if ponydirs is None else ponydirs, _list.linklist(self.ponydirs if ponydirs is None else ponydirs,
self.__quoters(), lambda x, y : self.__ucsise(x, y)) self.__quoters(), lambda x, y : self.__ucsise(x, y))
@ -760,7 +760,7 @@ class Ponysay():
@param standard:bool Include standard ponies @param standard:bool Include standard ponies
@param extra:bool Include extra ponies @param extra:bool Include extra ponies
''' '''
List.onelist(self.ponydirs if standard else None, _list.onelist(self.ponydirs if standard else None,
self.extraponydirs if extra else None, self.extraponydirs if extra else None,
lambda x : self.__ucsise(x)) lambda x : self.__ucsise(x))
@ -801,7 +801,7 @@ class Ponysay():
''' '''
Prints a list of all balloons Prints a list of all balloons
''' '''
List.balloonlist(self.balloondirs, self.isthink) _list.balloonlist(self.balloondirs, self.isthink)
def __getBalloonPath(self, names, alt = False): def __getBalloonPath(self, names, alt = False):