From 3100f4b32a5ccebfaf7b099ddba68a38bda9c231 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 16:08:24 +0200 Subject: -L is now implemented --- ponysay.py | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 77 insertions(+), 5 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 46a3932..b7b3eb4 100755 --- a/ponysay.py +++ b/ponysay.py @@ -40,8 +40,9 @@ for ponydir in _ponydirs: parser = argparse.ArgumentParser(description = 'Ponysay, like cowsay with ponies') parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ("ponysay", VERSION)) -parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') -parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') +parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') +parser.add_argument('-L', '--altlist', action = 'store_true', dest = 'linklist', help = 'list pony files with alternatives') +parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') parser.add_argument('message', nargs = '?', help = 'message to ponysay') args = parser.parse_args() @@ -49,8 +50,9 @@ args = parser.parse_args() class ponysay(): def __init__(self, args): - if args.list: self.list() - else: self.print_pony(args) + if args.list: self.list() + elif args.linklist: self.linklist() + else: self.print_pony(args) ''' @@ -121,12 +123,82 @@ class ponysay(): print(('\033[1m' + pony + '\033[21m' if (pony in quoters) else pony) + spacing, end="") # Print ponyfilename x += width if x > (termsize[1] - width): # If too wide, make new line - print(); + print() x = 0 print("\n"); + ''' + Lists the available ponies with alternatives inside brackets + ''' + def linklist(self): + termsize = Popen(['stty', 'size'], stdout=PIPE).communicate()[0].decode('utf8', 'replace')[:-1].split(" ") + termsize = [int(item) for item in termsize] + + quoters = self.__quoters() + + for ponydir in ponydirs: # Loop ponydirs + print('\033[1mponyfiles located in ' + ponydir + '\033[21m') + + files = os.listdir(ponydir) + files = [item[:-5] for item in files] # remove .pony from file name + files.sort() + pairs = [(item, os.readlink(ponydir + item + ".pony") if os.path.islink(ponydir + item + ".pony") else '') for item in files] + + ponymap = {} + for pair in pairs: + if 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]] + + width = 0 + ponies = [] + widths = [] + for pony in ponymap: + w = len(pony) + item = '\033[1m' + pony + '\033[21m' if (pony in quoters) else pony + syms = ponymap[pony] + if len(syms) > 0: + w += 2 + len(syms) + item += " (" + first = True + for sym in syms: + w += len(sym) + if not first: + item += " " + else: + first = False + item += '\033[1m' + sym + '\033[21m' if (sym in quoters) else sym + item += ")" + ponies.append(item) + widths.append(w) + if width < w: + width = w + + width += 2; + x = 0 + index = 0 + for pony in ponies: + spacing = ' ' * (width - widths[index]) + index += 1 + print(pony + spacing, end="") # Print ponyfilename + x += width + if x > (termsize[1] - width): # If too wide, make new line + print() + x = 0 + + print("\n"); + + def print_pony(self, args): if args.message == None: msg = sys.stdin.read().strip() -- cgit From c4f07a8b002b218d19b09f5d2ad06c491b275c98 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 16:20:49 +0200 Subject: support quotes in ~/.local/share/ponysay/quotes (new feature) --- ponysay.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index b7b3eb4..e7c671f 100755 --- a/ponysay.py +++ b/ponysay.py @@ -37,6 +37,17 @@ for ponydir in _ponydirs: if os.path.isdir(ponydir): ponydirs.append(ponydir) +''' +The directories where quotes files are stored +''' +quotedirs = [] +_quotedirs = [INSTALLDIR + '/share/ponysay/quotes/', os.environ['HOME'] + '/.local/share/ponysay/quotes/'] +for quotedir in _quotedirs: + if os.path.isdir(quotedir): + quotedirs.append(quotedir) + + + parser = argparse.ArgumentParser(description = 'Ponysay, like cowsay with ponies') parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ("ponysay", VERSION)) @@ -61,7 +72,9 @@ class ponysay(): def __quoters(self): quotes = [] quoteshash = set() - _quotes = [item[:item.index('.')] for item in os.listdir(INSTALLDIR + '/share/ponysay/quotes/')] + _quotes = [] + for quotedir in quotedirs: + _quotes += [item[:item.index('.')] for item in os.listdir(INSTALLDIR + '/share/ponysay/quotes/')] for quote in _quotes: if not quote == '': if not quote in quoteshash: @@ -85,7 +98,9 @@ class ponysay(): Returns a list with all (pony, quote file) pairs ''' def __quotes(self): - quotes = os.listdir(INSTALLDIR + '/share/ponysay/quotes/') + quotes = [] + for quotedir in quotedirs: + quotes += [quotedir + item for item in os.listdir(quotedir)] rc = [] for ponydir in ponydirs: @@ -93,8 +108,9 @@ class ponysay(): if not pony[0] == '.': p = pony[:-5] # remove .pony for quote in quotes: - if ('+' + p + '+') in ('+' + quote + '+'): - rc.append((p, qoute)) + q = quote[quote.rindex('/') + 1:] + if ('+' + p + '+') in ('+' + q + '+'): + rc.append((p, quote)) return rc -- cgit From f9663c7b1bb21922efb775136e6c75dda9ba83ce Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 16:43:22 +0200 Subject: forgot to commit python script --- ponysay.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index e7c671f..f8b7723 100755 --- a/ponysay.py +++ b/ponysay.py @@ -53,6 +53,8 @@ parser = argparse.ArgumentParser(description = 'Ponysay, like cowsay with ponies parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ("ponysay", VERSION)) parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') parser.add_argument('-L', '--altlist', action = 'store_true', dest = 'linklist', help = 'list pony files with alternatives') +parser.add_argument( '--quoters', action = 'store_true', dest = 'quoters', help = 'list ponies with quotes (visible in -l and -L)') # for shell completions +parser.add_argument( '--onelist', action = 'store_true', dest = 'onelist', help = 'list pony files in one columns') # for shell completions parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') parser.add_argument('message', nargs = '?', help = 'message to ponysay') @@ -63,11 +65,13 @@ class ponysay(): def __init__(self, args): if args.list: self.list() elif args.linklist: self.linklist() + elif args.quoters: self.quoters() + elif args.onelist: self.onelist() else: self.print_pony(args) ''' - Returns a set with all ponies that have quotes and is displayable + Returns a set with all ponies that have quotes and are displayable ''' def __quoters(self): quotes = [] @@ -215,6 +219,37 @@ class ponysay(): print("\n"); + ''' + Lists with all ponies that have quotes and are displayable + ''' + def quoters(self): + last = "" + ponies = [] + for pony in self.__quoters(): + ponies.append(pony) + ponies.sort() + for pony in ponies: + if not pony == last: + last = pony + print(pony) + + + ''' + Lists the available ponies one one column without anything bold + ''' + def onelist(self): + last = "" + ponies = [] + for ponydir in ponydirs: # Loop ponydirs + ponies += os.listdir(ponydir) + ponies = [item[:-5] for item in ponies] # remove .pony from file name + ponies.sort() + for pony in ponies: + if not pony == last: + last = pony + print(pony) + + def print_pony(self, args): if args.message == None: msg = sys.stdin.read().strip() -- cgit From 3a65390937e4bfd7cdd859dea24c728ab3b66063 Mon Sep 17 00:00:00 2001 From: Elis Axelsson Date: Sat, 18 Aug 2012 16:46:38 +0200 Subject: Created method to get which ponyfile you should render, includes randomizing and looking for files. --- ponysay.py | 58 +++++++++++++++++++++++++++++++--------------------------- 1 file changed, 31 insertions(+), 27 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index b7b3eb4..1c3bef2 100755 --- a/ponysay.py +++ b/ponysay.py @@ -18,7 +18,7 @@ from subprocess import Popen, PIPE ''' The version of ponysay ''' -VERSION = "2.0-alpha" +VERSION = '2.0-alpha' ''' @@ -37,9 +37,13 @@ for ponydir in _ponydirs: if os.path.isdir(ponydir): ponydirs.append(ponydir) + +''' +Argument parsing +''' parser = argparse.ArgumentParser(description = 'Ponysay, like cowsay with ponies') -parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ("ponysay", VERSION)) +parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ('ponysay', VERSION)) parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') parser.add_argument('-L', '--altlist', action = 'store_true', dest = 'linklist', help = 'list pony files with alternatives') parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') @@ -80,6 +84,18 @@ class ponysay(): return ponies + def __getponypath(self, names = None): + ponies = {} + + for name in names: + if os.path.isfile(name): + return name + + for ponydir in ponydirs: + for ponyfile in os.listdir(ponydir): + ponies[ponyfile[:-5]] = ponydir + ponyfile + + return ponies[names[random.randrange(0, len(names))]] ''' Returns a list with all (pony, quote file) pairs @@ -103,7 +119,7 @@ class ponysay(): Lists the available ponies ''' def list(self): - termsize = Popen(['stty', 'size'], stdout=PIPE).communicate()[0].decode('utf8', 'replace')[:-1].split(" ") + termsize = Popen(['stty', 'size'], stdout=PIPE).communicate()[0].decode('utf8', 'replace')[:-1].split(' ') termsize = [int(item) for item in termsize] quoters = self.__quoters() @@ -120,20 +136,20 @@ class ponysay(): x = 0 for pony in ponies: spacing = ' ' * (width - len(pony)) - print(('\033[1m' + pony + '\033[21m' if (pony in quoters) else pony) + spacing, end="") # Print ponyfilename + print(('\033[1m' + pony + '\033[21m' if (pony in quoters) else pony) + spacing, end='') # Print ponyfilename x += width if x > (termsize[1] - width): # If too wide, make new line print() x = 0 - print("\n"); + print('\n'); ''' Lists the available ponies with alternatives inside brackets ''' def linklist(self): - termsize = Popen(['stty', 'size'], stdout=PIPE).communicate()[0].decode('utf8', 'replace')[:-1].split(" ") + termsize = Popen(['stty', 'size'], stdout=PIPE).communicate()[0].decode('utf8', 'replace')[:-1].split(' ') termsize = [int(item) for item in termsize] quoters = self.__quoters() @@ -144,11 +160,11 @@ class ponysay(): files = os.listdir(ponydir) files = [item[:-5] for item in files] # remove .pony from file name files.sort() - pairs = [(item, os.readlink(ponydir + item + ".pony") if os.path.islink(ponydir + item + ".pony") else '') for item in files] + pairs = [(item, os.readlink(ponydir + item + '.pony') if os.path.islink(ponydir + item + '.pony') else '') for item in files] ponymap = {} for pair in pairs: - if pair[1] == "": + if pair[1] == '': if pair[0] not in ponymap: ponymap[pair[0]] = [] else: @@ -169,16 +185,16 @@ class ponysay(): syms = ponymap[pony] if len(syms) > 0: w += 2 + len(syms) - item += " (" + item += ' (' first = True for sym in syms: w += len(sym) if not first: - item += " " + item += ' ' else: first = False item += '\033[1m' + sym + '\033[21m' if (sym in quoters) else sym - item += ")" + item += ')' ponies.append(item) widths.append(w) if width < w: @@ -190,13 +206,13 @@ class ponysay(): for pony in ponies: spacing = ' ' * (width - widths[index]) index += 1 - print(pony + spacing, end="") # Print ponyfilename + print(pony + spacing, end='') # Print ponyfilename x += width if x > (termsize[1] - width): # If too wide, make new line print() x = 0 - print("\n"); + print('\n'); def print_pony(self, args): @@ -205,21 +221,9 @@ class ponysay(): else: msg = args.message + pony = self.__getponypath(args.pony) - if args.pony == None: - ponies = [] # Make array with direct paths to all ponies - for ponydir in ponydirs: - for ponyfile in os.listdir(ponydir): - ponies.append(ponydir + ponyfile) - - pony = ponies[random.randrange(0, len(ponies) - 1)] # Select random pony - - else: - for ponydir in ponydirs: - if os.path.isfile(ponydir + args.pony[0]): - pony = ponydir + args.pony[0] - - os.system('cowsay -f ' + pony + ' "' + msg + '"') + os.system('cowsay -f ' + pony + ' \'' + msg + '\'') -- cgit From fd099535cfa5f33ae6c1a55bd8a9dc590931a7b3 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 16:55:57 +0200 Subject: are there any ponies --- ponysay.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index f8b7723..a04e54d 100755 --- a/ponysay.py +++ b/ponysay.py @@ -27,21 +27,28 @@ The directory where ponysay is installed, this is modified when building with ma INSTALLDIR = '/usr' +''' +The user's home directory +''' +HOME = os.environ['HOME'] + + ''' The directories where pony files are stored, ttyponies/ are used if the terminal is Linux VT (also known as TTY) ''' ponydirs = [] -if os.environ['TERM'] == 'linux': _ponydirs = [INSTALLDIR + '/share/ponysay/ttyponies/', os.environ['HOME'] + '/.local/share/ponysay/ttyponies/'] -else: _ponydirs = [INSTALLDIR + '/share/ponysay/ponies/', os.environ['HOME'] + '/.local/share/ponysay/ponies/' ] +if os.environ['TERM'] == 'linux': _ponydirs = [INSTALLDIR + '/share/ponysay/ttyponies/', HOME + '/.local/share/ponysay/ttyponies/'] +else: _ponydirs = [INSTALLDIR + '/share/ponysay/ponies/', HOME + '/.local/share/ponysay/ponies/' ] for ponydir in _ponydirs: if os.path.isdir(ponydir): ponydirs.append(ponydir) + ''' The directories where quotes files are stored ''' quotedirs = [] -_quotedirs = [INSTALLDIR + '/share/ponysay/quotes/', os.environ['HOME'] + '/.local/share/ponysay/quotes/'] +_quotedirs = [INSTALLDIR + '/share/ponysay/quotes/', HOME + '/.local/share/ponysay/quotes/'] for quotedir in _quotedirs: if os.path.isdir(quotedir): quotedirs.append(quotedir) @@ -251,20 +258,25 @@ class ponysay(): def print_pony(self, args): + ponycount = 0 + for ponydir in ponydirs: + ponycount = len(os.listdir(ponydir)) + if ponycount == 0: + sys.stderr.write('All the ponies are missing! Call the Princess!') + exit(1); + if args.message == None: - msg = sys.stdin.read().strip() + msg = sys.stdin.read() else: msg = args.message - if args.pony == None: ponies = [] # Make array with direct paths to all ponies for ponydir in ponydirs: for ponyfile in os.listdir(ponydir): ponies.append(ponydir + ponyfile) - pony = ponies[random.randrange(0, len(ponies) - 1)] # Select random pony - + pony = ponies[random.randrange(0, len(ponies) - 1)] # Select random pony else: for ponydir in ponydirs: if os.path.isfile(ponydir + args.pony[0]): -- cgit From e4fb245e364a5d0e89d2fff988a10324356a0a58 Mon Sep 17 00:00:00 2001 From: Elis Axelsson Date: Sat, 18 Aug 2012 17:02:03 +0200 Subject: Fix stuff. --- ponysay.py | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index a75d44c..0728666 100755 --- a/ponysay.py +++ b/ponysay.py @@ -27,18 +27,12 @@ The directory where ponysay is installed, this is modified when building with ma INSTALLDIR = '/usr' -''' -The user's home directory -''' -HOME = os.environ['HOME'] - - ''' The directories where pony files are stored, ttyponies/ are used if the terminal is Linux VT (also known as TTY) ''' ponydirs = [] -if os.environ['TERM'] == 'linux': _ponydirs = [INSTALLDIR + '/share/ponysay/ttyponies/', HOME + '/.local/share/ponysay/ttyponies/'] -else: _ponydirs = [INSTALLDIR + '/share/ponysay/ponies/', HOME + '/.local/share/ponysay/ponies/' ] +if os.environ['TERM'] == 'linux': _ponydirs = [INSTALLDIR + '/share/ponysay/ttyponies/', os.environ['HOME'] + '/.local/share/ponysay/ttyponies/'] +else: _ponydirs = [INSTALLDIR + '/share/ponysay/ponies/', os.environ['HOME'] + '/.local/share/ponysay/ponies/' ] for ponydir in _ponydirs: if os.path.isdir(ponydir): ponydirs.append(ponydir) @@ -48,7 +42,7 @@ for ponydir in _ponydirs: The directories where quotes files are stored ''' quotedirs = [] -_quotedirs = [INSTALLDIR + '/share/ponysay/quotes/', HOME + '/.local/share/ponysay/quotes/'] +_quotedirs = [INSTALLDIR + '/share/ponysay/quotes/', os.environ['HOME'] + '/.local/share/ponysay/quotes/'] for quotedir in _quotedirs: if os.path.isdir(quotedir): quotedirs.append(quotedir) @@ -113,15 +107,19 @@ class ponysay(): def __getponypath(self, names = None): ponies = {} - for name in names: - if os.path.isfile(name): - return name + if names != None: + for name in names: + if os.path.isfile(name): + return name for ponydir in ponydirs: for ponyfile in os.listdir(ponydir): ponies[ponyfile[:-5]] = ponydir + ponyfile - return ponies[names[random.randrange(0, len(names))]] + if names == None: + names = list(ponies.keys()) + + return ponies[names[random.randrange(0, len(names) - 1)]] ''' Returns a list with all (pony, quote file) pairs @@ -276,15 +274,8 @@ class ponysay(): def print_pony(self, args): - ponycount = 0 - for ponydir in ponydirs: - ponycount = len(os.listdir(ponydir)) - if ponycount == 0: - sys.stderr.write('All the ponies are missing! Call the Princess!') - exit(1); - if args.message == None: - msg = sys.stdin.read() + msg = sys.stdin.read().strip() else: msg = args.message -- cgit From 10268235a99b1ef3ff72ed8268f857db045ca2aa Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:03:30 +0200 Subject: home dirs before sys dirs for priority + moving a method --- ponysay.py | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index a75d44c..feb584b 100755 --- a/ponysay.py +++ b/ponysay.py @@ -37,8 +37,8 @@ HOME = os.environ['HOME'] The directories where pony files are stored, ttyponies/ are used if the terminal is Linux VT (also known as TTY) ''' ponydirs = [] -if os.environ['TERM'] == 'linux': _ponydirs = [INSTALLDIR + '/share/ponysay/ttyponies/', HOME + '/.local/share/ponysay/ttyponies/'] -else: _ponydirs = [INSTALLDIR + '/share/ponysay/ponies/', HOME + '/.local/share/ponysay/ponies/' ] +if os.environ['TERM'] == 'linux': _ponydirs = [HOME + '/.local/share/ponysay/ttyponies/', INSTALLDIR + '/share/ponysay/ttyponies/'] +else: _ponydirs = [HOME + '/.local/share/ponysay/ponies/', INSTALLDIR + '/share/ponysay/ponies/' ] for ponydir in _ponydirs: if os.path.isdir(ponydir): ponydirs.append(ponydir) @@ -48,7 +48,7 @@ for ponydir in _ponydirs: The directories where quotes files are stored ''' quotedirs = [] -_quotedirs = [INSTALLDIR + '/share/ponysay/quotes/', HOME + '/.local/share/ponysay/quotes/'] +_quotedirs = [HOME + '/.local/share/ponysay/quotes/', INSTALLDIR + '/share/ponysay/quotes/'] for quotedir in _quotedirs: if os.path.isdir(quotedir): quotedirs.append(quotedir) @@ -80,6 +80,23 @@ class ponysay(): else: self.print_pony(args) + ''' + Returns one .pony-file with full path, names is filter for names, also accepts filepaths + ''' + def __getponypath(self, names = None): + ponies = {} + + for name in names: + if os.path.isfile(name): + return name + + for ponydir in ponydirs: + for ponyfile in os.listdir(ponydir): + ponies[ponyfile[:-5]] = ponydir + ponyfile + + return ponies[names[random.randrange(0, len(names))]] + + ''' Returns a set with all ponies that have quotes and are displayable ''' @@ -107,21 +124,6 @@ class ponysay(): return ponies - ''' - Returns one .pony-file with full path, names is filter for names, also accepts filepaths - ''' - def __getponypath(self, names = None): - ponies = {} - - for name in names: - if os.path.isfile(name): - return name - - for ponydir in ponydirs: - for ponyfile in os.listdir(ponydir): - ponies[ponyfile[:-5]] = ponydir + ponyfile - - return ponies[names[random.randrange(0, len(names))]] ''' Returns a list with all (pony, quote file) pairs -- cgit From f16a89ffffbc323262f6dc9f959ea9a3cf9dbc3d Mon Sep 17 00:00:00 2001 From: Elis Axelsson Date: Sat, 18 Aug 2012 17:05:26 +0200 Subject: Avoid 'empty range for randrage()' --- ponysay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 0728666..c6c83f8 100755 --- a/ponysay.py +++ b/ponysay.py @@ -119,7 +119,7 @@ class ponysay(): if names == None: names = list(ponies.keys()) - return ponies[names[random.randrange(0, len(names) - 1)]] + return ponies[names[random.randrange(0, len(names))]] ''' Returns a list with all (pony, quote file) pairs -- cgit From 1ea6043b1dccdbeb313f925352df8e4317656893 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:09:52 +0200 Subject: whops --- ponysay.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 96acfbe..e1a47a5 100755 --- a/ponysay.py +++ b/ponysay.py @@ -27,6 +27,12 @@ The directory where ponysay is installed, this is modified when building with ma INSTALLDIR = '/usr' +''' +The user's home directory +''' +HOME = os.environ['HOME'] + + ''' The directories where pony files are stored, ttyponies/ are used if the terminal is Linux VT (also known as TTY) ''' @@ -65,7 +71,13 @@ parser.add_argument('message', nargs = '?', help = 'message to ponysay') args = parser.parse_args() +''' +This is the mane class of ponysay +''' class ponysay(): + ''' + Starts the part of the program the arguments indicate + ''' def __init__(self, args): if args.list: self.list() elif args.linklist: self.linklist() @@ -80,7 +92,7 @@ class ponysay(): def __getponypath(self, names = None): ponies = {} - if names != None: + if not names == None: for name in names: if os.path.isfile(name): return name -- cgit From 2e4e6474a5aa679a59521373b95b0742671b84f1 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:14:00 +0200 Subject: m --- ponysay.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index e1a47a5..ffb2b0b 100755 --- a/ponysay.py +++ b/ponysay.py @@ -99,7 +99,9 @@ class ponysay(): for ponydir in ponydirs: for ponyfile in os.listdir(ponydir): - ponies[ponyfile[:-5]] = ponydir + ponyfile + pony = ponyfile[:-5] + if pony not in ponies: + ponies[pony] = ponydir + ponyfile if names == None: names = list(ponies.keys()) -- cgit From d870bf7a6544d6175b69585a3cae74bfc40dae04 Mon Sep 17 00:00:00 2001 From: Elis Axelsson Date: Sat, 18 Aug 2012 17:22:22 +0200 Subject: Support for ponythink --- ponysay.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index ffb2b0b..3e6ccd1 100755 --- a/ponysay.py +++ b/ponysay.py @@ -297,7 +297,10 @@ class ponysay(): pony = self.__getponypath(args.pony) - os.system('cowsay -f ' + pony + ' \'' + msg + '\'') + if "think" in __file__: cmd = 'cowthink' + else: cmd = 'cowsay' + + os.system(cmd + ' -f ' + pony + ' \'' + msg + '\'') -- cgit From 9eee469cf62809b99efa94f4ac2ee064d0f546ba Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:34:10 +0200 Subject: setting erkin as copyright holder, as specified in the copying file, and listing all contributors of ponysay(.sh) and ponysay.py in alphabetical order --- ponysay.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index ffb2b0b..93cee89 100755 --- a/ponysay.py +++ b/ponysay.py @@ -3,7 +3,14 @@ ''' ponysay.py - POC of ponysay in python -Copyright (C) 2012 Elis "etu" Axelsson, Mattias "maandree" Andrée +Copyright (C) 2012 Erkin Batu Altunbaş + +Authors: Erkin Batu Altunbaş: Project leader, helped write the first implementation + Mattias "maandree" Andrée: Major contributor of both implementions + Elis "etu" Axelsson Major contributor of current implemention and patcher of first implementation + Sven-Hendrik "svenstaro" Haase: Helped write the first implementation + Kyah "L-four" Rindlisbacher: Patched the first implementation + Jan Alexander "heftig" Steffens: Helped write the first implementation License: WTFPL ''' -- cgit From e598badd9b4bfdb77510f00102487da310f7f385 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:36:12 +0200 Subject: m --- ponysay.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index a0326d7..9e159b8 100755 --- a/ponysay.py +++ b/ponysay.py @@ -8,9 +8,9 @@ Copyright (C) 2012 Erkin Batu Altunbaş Authors: Erkin Batu Altunbaş: Project leader, helped write the first implementation Mattias "maandree" Andrée: Major contributor of both implementions Elis "etu" Axelsson Major contributor of current implemention and patcher of first implementation - Sven-Hendrik "svenstaro" Haase: Helped write the first implementation + Sven-Hendrik "svenstaro" Haase: Major contributor first implementation Kyah "L-four" Rindlisbacher: Patched the first implementation - Jan Alexander "heftig" Steffens: Helped write the first implementation + Jan Alexander "heftig" Steffens: Major contributor first implementation License: WTFPL ''' -- cgit From 2ff4e42e199a1d3c42fd8dd44b131d63a58a7c13 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:39:29 +0200 Subject: m --- ponysay.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 9e159b8..92f1fac 100755 --- a/ponysay.py +++ b/ponysay.py @@ -5,12 +5,12 @@ ponysay.py - POC of ponysay in python Copyright (C) 2012 Erkin Batu Altunbaş -Authors: Erkin Batu Altunbaş: Project leader, helped write the first implementation - Mattias "maandree" Andrée: Major contributor of both implementions - Elis "etu" Axelsson Major contributor of current implemention and patcher of first implementation - Sven-Hendrik "svenstaro" Haase: Major contributor first implementation - Kyah "L-four" Rindlisbacher: Patched the first implementation - Jan Alexander "heftig" Steffens: Major contributor first implementation +Authors: Erkin Batu Altunbaş: Project leader, helped write the first implementation + Mattias "maandree" Andrée: Major contributor of both implementions + Elis "etu" Axelsson: Major contributor of current implemention and patcher of first implementation + Sven-Hendrik "svenstaro" Haase: Major contributor first implementation + Kyah "L-four" Rindlisbacher: Patched the first implementation + Jan Alexander "heftig" Steffens: Major contributor first implementation License: WTFPL ''' @@ -304,8 +304,8 @@ class ponysay(): pony = self.__getponypath(args.pony) - if "think" in __file__: cmd = 'cowthink' - else: cmd = 'cowsay' + if "think.py" in __file__: cmd = 'cowthink' + else: cmd = 'cowsay' os.system(cmd + ' -f ' + pony + ' \'' + msg + '\'') -- cgit From 5ff733fddac0d682a25acf8bd3f6de4339d6c9f7 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:42:36 +0200 Subject: doc --- ponysay.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 92f1fac..adc1264 100755 --- a/ponysay.py +++ b/ponysay.py @@ -93,6 +93,10 @@ class ponysay(): else: self.print_pony(args) + ## + ## Auxiliary methods + ## + ''' Returns one .pony-file with full path, names is filter for names, also accepts filepaths ''' @@ -165,6 +169,10 @@ class ponysay(): return rc + ## + ## Listing methods + ## + ''' Lists the available ponies ''' @@ -296,6 +304,13 @@ class ponysay(): print(pony) + ## + ## Displaying methods + ## + + ''' + Print the pony with a speech or though bubble + ''' def print_pony(self, args): if args.message == None: msg = sys.stdin.read().strip() -- cgit From 6e754c5509228f7c9b7d2aa3eca0ab6fb4e211d6 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:52:25 +0200 Subject: wrap support --- ponysay.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index adc1264..23e8f39 100755 --- a/ponysay.py +++ b/ponysay.py @@ -67,11 +67,12 @@ Argument parsing ''' parser = argparse.ArgumentParser(description = 'Ponysay, like cowsay with ponies') -parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ('ponysay', VERSION)) +parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ('ponysay', VERSION)) parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') parser.add_argument('-L', '--altlist', action = 'store_true', dest = 'linklist', help = 'list pony files with alternatives') parser.add_argument( '--quoters', action = 'store_true', dest = 'quoters', help = 'list ponies with quotes (visible in -l and -L)') # for shell completions parser.add_argument( '--onelist', action = 'store_true', dest = 'onelist', help = 'list pony files in one columns') # for shell completions +parser.add_argument('-W', '--wrap', action = 'store', dest = 'wrap', help = 'specify the column when the message should be wrapped') parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') parser.add_argument('message', nargs = '?', help = 'message to ponysay') @@ -322,7 +323,7 @@ class ponysay(): if "think.py" in __file__: cmd = 'cowthink' else: cmd = 'cowsay' - os.system(cmd + ' -f ' + pony + ' \'' + msg + '\'') + os.system(cmd + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg + '\'') -- cgit From 1dc737fb8b51e224ed29e60ae3c1751e3d54f31f Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:57:50 +0200 Subject: m misc --- ponysay.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 23e8f39..1714e77 100755 --- a/ponysay.py +++ b/ponysay.py @@ -40,12 +40,18 @@ The user's home directory HOME = os.environ['HOME'] +''' +Whether the program is execute in Linux VT (TTY) +''' +linuxvt = os.environ['TERM'] == 'linux' + + ''' The directories where pony files are stored, ttyponies/ are used if the terminal is Linux VT (also known as TTY) ''' ponydirs = [] -if os.environ['TERM'] == 'linux': _ponydirs = [HOME + '/.local/share/ponysay/ttyponies/', INSTALLDIR + '/share/ponysay/ttyponies/'] -else: _ponydirs = [HOME + '/.local/share/ponysay/ponies/', INSTALLDIR + '/share/ponysay/ponies/' ] +if linuxvt: _ponydirs = [HOME + '/.local/share/ponysay/ttyponies/', INSTALLDIR + '/share/ponysay/ttyponies/'] +else: _ponydirs = [HOME + '/.local/share/ponysay/ponies/', INSTALLDIR + '/share/ponysay/ponies/' ] for ponydir in _ponydirs: if os.path.isdir(ponydir): ponydirs.append(ponydir) @@ -320,9 +326,11 @@ class ponysay(): pony = self.__getponypath(args.pony) - if "think.py" in __file__: cmd = 'cowthink' + if 'think.py' in __file__: cmd = 'cowthink' else: cmd = 'cowsay' + if linuxvt: + print('\033[H\033[2J', end='') os.system(cmd + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg + '\'') -- cgit From 57ceac45a4891e0045c0aec91902ca6741ccf274 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 17:59:53 +0200 Subject: Message can now contain ':s --- ponysay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 1714e77..a55fbca 100755 --- a/ponysay.py +++ b/ponysay.py @@ -331,7 +331,7 @@ class ponysay(): if linuxvt: print('\033[H\033[2J', end='') - os.system(cmd + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg + '\'') + os.system(cmd + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg.replace('\'', '\'\\\'\'') + '\'') -- cgit From 88baa565a0be9f623d0aa52c0d3148c234b51516 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 18:24:00 +0200 Subject: ponyquotes support --- ponysay.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index a55fbca..632445d 100755 --- a/ponysay.py +++ b/ponysay.py @@ -71,7 +71,7 @@ for quotedir in _quotedirs: ''' Argument parsing ''' -parser = argparse.ArgumentParser(description = 'Ponysay, like cowsay with ponies') +parser = argparse.ArgumentParser(prog = 'ponysay', description = 'Like cowsay with ponies.') parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ('ponysay', VERSION)) parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') @@ -80,6 +80,7 @@ parser.add_argument( '--quoters', action = 'store_true', dest = 'quoters', parser.add_argument( '--onelist', action = 'store_true', dest = 'onelist', help = 'list pony files in one columns') # for shell completions parser.add_argument('-W', '--wrap', action = 'store', dest = 'wrap', help = 'specify the column when the message should be wrapped') parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') +parser.add_argument('-q', '--quote', nargs = '*', dest = 'quote', help = 'select a pony which will quote herself') parser.add_argument('message', nargs = '?', help = 'message to ponysay') args = parser.parse_args() @@ -97,6 +98,7 @@ class ponysay(): elif args.linklist: self.linklist() elif args.quoters: self.quoters() elif args.onelist: self.onelist() + elif args.quote: self.quote(args) else: self.print_pony(args) @@ -332,6 +334,32 @@ class ponysay(): if linuxvt: print('\033[H\033[2J', end='') os.system(cmd + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg.replace('\'', '\'\\\'\'') + '\'') + + + ''' + Print the pony with a speech or though bubble and a self quote + ''' + def quote(self, args): + pairs = self.__quotes() + if len(args.quote) > 0: + ponyset = set(args.quote) + alts = [] + for pair in pairs: + if pair[0] in ponyset: + alts.append(pair) + pairs = alts + + pair = pairs[random.randrange(0, len(pairs))] + qfile = None + try: + qfile = open(pair[1], 'r') + args.message = '\n'.join(qfile.readlines()) + finally: + if qfile is not None: + qfile.close() + args.pony = [pair[0]] + + self.print_pony(args) -- cgit From 3bb5a68d7f081225fa6a77e2537fe62650c872fc Mon Sep 17 00:00:00 2001 From: Elis Axelsson Date: Sat, 18 Aug 2012 18:47:02 +0200 Subject: Drop newline at end of file of ponyquotes --- ponysay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 632445d..5c45ed9 100755 --- a/ponysay.py +++ b/ponysay.py @@ -353,7 +353,7 @@ class ponysay(): qfile = None try: qfile = open(pair[1], 'r') - args.message = '\n'.join(qfile.readlines()) + args.message = '\n'.join(qfile.readlines()).strip() finally: if qfile is not None: qfile.close() -- cgit From 2301f094ad3227e49d3def485448660301f60dac Mon Sep 17 00:00:00 2001 From: Elis Axelsson Date: Sat, 18 Aug 2012 18:54:04 +0200 Subject: Fallback quote for ponies without quotes --- ponysay.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 5c45ed9..33a4b01 100755 --- a/ponysay.py +++ b/ponysay.py @@ -349,15 +349,19 @@ class ponysay(): alts.append(pair) pairs = alts - pair = pairs[random.randrange(0, len(pairs))] - qfile = None - try: - qfile = open(pair[1], 'r') - args.message = '\n'.join(qfile.readlines()).strip() - finally: - if qfile is not None: - qfile.close() - args.pony = [pair[0]] + if not len(pairs) == 0: + pair = pairs[random.randrange(0, len(pairs))] + qfile = None + try: + qfile = open(pair[1], 'r') + args.message = '\n'.join(qfile.readlines()).strip() + finally: + if qfile is not None: + qfile.close() + args.pony = [pair[0]] + else: + args.pony = args.quote + args.message = 'I got nuthin\' good to say :(' self.print_pony(args) -- cgit From de1f27a73accf24642399597749781d88a6a4ad6 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 18:56:44 +0200 Subject: cowsay replacement env vars + can get terminal if stdin is piped in --- ponysay.py | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 632445d..1f52558 100755 --- a/ponysay.py +++ b/ponysay.py @@ -86,6 +86,7 @@ parser.add_argument('message', nargs = '?', help = 'message to ponysay') args = parser.parse_args() + ''' This is the mane class of ponysay ''' @@ -178,6 +179,16 @@ class ponysay(): return rc + ''' + Gets the size of the terminal in (rows, columns) + ''' + def __gettermsize(self): + termsize = Popen(['stty', 'size'], stdout=PIPE, stdin=sys.stderr).communicate()[0] + termsize = termsize.decode('utf8', 'replace')[:-1].split(' ') # [:-1] removes a \n + termsize = [int(item) for item in termsize] + return termsize + + ## ## Listing methods ## @@ -186,9 +197,7 @@ class ponysay(): Lists the available ponies ''' def list(self): - termsize = Popen(['stty', 'size'], stdout=PIPE).communicate()[0].decode('utf8', 'replace')[:-1].split(' ') - termsize = [int(item) for item in termsize] - + termsize = self.__gettermsize() quoters = self.__quoters() for ponydir in ponydirs: # Loop ponydirs @@ -216,9 +225,7 @@ class ponysay(): Lists the available ponies with alternatives inside brackets ''' def linklist(self): - termsize = Popen(['stty', 'size'], stdout=PIPE).communicate()[0].decode('utf8', 'replace')[:-1].split(' ') - termsize = [int(item) for item in termsize] - + termsize = self.__gettermsize() quoters = self.__quoters() for ponydir in ponydirs: # Loop ponydirs @@ -317,6 +324,20 @@ class ponysay(): ## Displaying methods ## + ''' + Returns the cowsay command + ''' + def __getcowsay(self): + isthink = 'think.py' in __file__ + + if isthink: + cowthink = os.environ['PONYSAY_COWTHINK'] if 'PONYSAY_COWTHINK' in os.environ else None + return 'cowthink' if (cowthink is None) or (cowthink == "") else cowthink + + cowsay = os.environ['PONYSAY_COWSAY'] if 'PONYSAY_COWSAY' in os.environ else None + return 'cowsay' if (cowsay is None) or (cowsay == "") else cowsay + + ''' Print the pony with a speech or though bubble ''' @@ -328,12 +349,9 @@ class ponysay(): pony = self.__getponypath(args.pony) - if 'think.py' in __file__: cmd = 'cowthink' - else: cmd = 'cowsay' - if linuxvt: print('\033[H\033[2J', end='') - os.system(cmd + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg.replace('\'', '\'\\\'\'') + '\'') + os.system(self.__getcowsay() + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg.replace('\'', '\'\\\'\'') + '\'') ''' -- cgit From e8864eb219201d6b3218ebf59897c942dff42f30 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 19:06:38 +0200 Subject: further improving quote fallback (you change may fallback quote ☹) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ponysay.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 969ecb6..09d44e6 100755 --- a/ponysay.py +++ b/ponysay.py @@ -84,6 +84,10 @@ parser.add_argument('-q', '--quote', nargs = '*', dest = 'quote', parser.add_argument('message', nargs = '?', help = 'message to ponysay') args = parser.parse_args() +# TODO implement if [ -t 0 ] && [ $# == 0 ]; then +# usage +# exit +# fi @@ -377,8 +381,11 @@ class ponysay(): if qfile is not None: qfile.close() args.pony = [pair[0]] + elif len(args.quote) == 0: + sys.stderr.write('All the ponies are mute! Call the Princess!') + exit 1 else: - args.pony = args.quote + args.pony = args.quote[random.randrange(0, len(args.quote))] args.message = 'I got nuthin\' good to say :(' self.print_pony(args) -- cgit From ee3c5532b8e0330b7bbed6d013489cbb4748a0ca Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 19:27:59 +0200 Subject: m --- ponysay.py | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 09d44e6..ea9ecc0 100755 --- a/ponysay.py +++ b/ponysay.py @@ -329,17 +329,17 @@ class ponysay(): ## ''' - Returns the cowsay command + Returns (the cowsay command, whether it is a custom program) ''' def __getcowsay(self): isthink = 'think.py' in __file__ if isthink: cowthink = os.environ['PONYSAY_COWTHINK'] if 'PONYSAY_COWTHINK' in os.environ else None - return 'cowthink' if (cowthink is None) or (cowthink == "") else cowthink + return ('cowthink', False) if (cowthink is None) or (cowthink == '') else (cowthink, True) cowsay = os.environ['PONYSAY_COWSAY'] if 'PONYSAY_COWSAY' in os.environ else None - return 'cowsay' if (cowsay is None) or (cowsay == "") else cowsay + return ('cowsay', False) if (cowsay is None) or (cowsay == '') else (cowsay, True) ''' @@ -352,10 +352,34 @@ class ponysay(): msg = args.message pony = self.__getponypath(args.pony) + (cowsay, customcowsay) = self.__getcowsay() + wrap_arg = ' -W ' + args.wrap if args.wrap is not None else '' + file_arg = ' -f ' + pony; + message_arg = ' \'' + msg.replace('\'', '\'\\\'\'') + '\'' # ' in message is replaces by '\'', this (combined by '..') ensures it will always be one argument + cowsay_args = wrap_arg + file_arg + message_arg if linuxvt: print('\033[H\033[2J', end='') - os.system(self.__getcowsay() + (' -W ' + args.wrap if args.wrap is not None else '') + ' -f ' + pony + ' \'' + msg.replace('\'', '\'\\\'\'') + '\'') + + if customcowsay: + exit_value = os.system(cowsay + cowsay_args) + else: + exit_value = os.system(cowsay + cowsay_args) + ## TODO not implement, but it will be obsolete if we rewrite cowsay + ''' + pcmd='#!/usr/bin/perl\nuse utf8;' + ccmd=$(for c in $(echo $PATH":" | sed -e 's/:/\/'"$cmd"' /g'); do if [ -f $c ]; then echo $c; break; fi done) + + if [ ${0} == *ponythink ]; then + cat <(echo -e $pcmd) $ccmd > "/tmp/ponythink" + perl '/tmp/ponythink' "$@" + rm '/tmp/ponythink' + else + perl <(cat <(echo -e $pcmd) $ccmd) "$@" + fi + ''' + if not exit_value == 0: + sys.stderr.write('Unable to successfully execute' + (' custom ' if customcowsay else ' ') + 'cowsay [' + cowsay + ']\n') ''' @@ -383,7 +407,7 @@ class ponysay(): args.pony = [pair[0]] elif len(args.quote) == 0: sys.stderr.write('All the ponies are mute! Call the Princess!') - exit 1 + exit(1) else: args.pony = args.quote[random.randrange(0, len(args.quote))] args.message = 'I got nuthin\' good to say :(' -- cgit From fec01d46460d7a117edba91856ae467a7754402d Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 19:55:00 +0200 Subject: height trunction --- ponysay.py | 72 ++++++++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 51 insertions(+), 21 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index ea9ecc0..800343e 100755 --- a/ponysay.py +++ b/ponysay.py @@ -353,33 +353,63 @@ class ponysay(): pony = self.__getponypath(args.pony) (cowsay, customcowsay) = self.__getcowsay() - wrap_arg = ' -W ' + args.wrap if args.wrap is not None else '' - file_arg = ' -f ' + pony; - message_arg = ' \'' + msg.replace('\'', '\'\\\'\'') + '\'' # ' in message is replaces by '\'', this (combined by '..') ensures it will always be one argument - cowsay_args = wrap_arg + file_arg + message_arg + + cmd = [cowsay, '-f', pony] + if args.wrap is not None: + cmd += ['-W', args.wrap] + cmd.append(msg) if linuxvt: print('\033[H\033[2J', end='') - if customcowsay: - exit_value = os.system(cowsay + cowsay_args) - else: - exit_value = os.system(cowsay + cowsay_args) - ## TODO not implement, but it will be obsolete if we rewrite cowsay - ''' - pcmd='#!/usr/bin/perl\nuse utf8;' - ccmd=$(for c in $(echo $PATH":" | sed -e 's/:/\/'"$cmd"' /g'); do if [ -f $c ]; then echo $c; break; fi done) - - if [ ${0} == *ponythink ]; then - cat <(echo -e $pcmd) $ccmd > "/tmp/ponythink" - perl '/tmp/ponythink' "$@" - rm '/tmp/ponythink' - else - perl <(cat <(echo -e $pcmd) $ccmd) "$@" - fi - ''' + proc = Popen(cmd, stdout=PIPE, stdin=sys.stderr) + output = proc.communicate()[0].decode('utf8', 'replace') + if (len(output) > 0) and (output[-1] == '\n'): + output = output[:-1] + exit_value = proc.returncode + + + env_bottom = os.environ['PONYSAY_BOTTOM'] if 'PONYSAY_BOTTOM' in os.environ else None + if (env_bottom is None) or (env_bottom == ''): env_bottom = '' + + env_height = os.environ['PONYSAY_TRUNCATE_HEIGHT'] if 'PONYSAY_TRUNCATE_HEIGHT' in os.environ else None + if (env_height is None) or (env_height == ''): env_height = '' + + env_lines = os.environ['PONYSAY_SHELL_LINES'] if 'PONYSAY_SHELL_LINES' in os.environ else None + if (env_lines is None) or (env_lines == ''): env_lines = '2' + + lines = self.__gettermsize()[1] - int(env_lines) + + if not exit_value == 0: sys.stderr.write('Unable to successfully execute' + (' custom ' if customcowsay else ' ') + 'cowsay [' + cowsay + ']\n') + else: + if linuxvt or (env_height is ("yes", "y", "1")): + if env_bottom is ("yes", "y", "1"): + for line in output[: -lines]: + print(line) + else: + for line in output[: lines]: + print(line) + else: + print(output); + + + ## TODO not implement, but it will be obsolete if we rewrite cowsay + ''' + (if not customcowsay) + + pcmd='#!/usr/bin/perl\nuse utf8;' + ccmd=$(for c in $(echo $PATH":" | sed -e 's/:/\/'"$cmd"' /g'); do if [ -f $c ]; then echo $c; break; fi done) + + if [ ${0} == *ponythink ]; then + cat <(echo -e $pcmd) $ccmd > "/tmp/ponythink" + perl '/tmp/ponythink' "$@" + rm '/tmp/ponythink' + else + perl <(cat <(echo -e $pcmd) $ccmd) "$@" + fi + ''' ''' -- cgit From 62a3d88d58bc5be870587012d74e28d57529356e Mon Sep 17 00:00:00 2001 From: Elis Axelsson Date: Sat, 18 Aug 2012 20:10:46 +0200 Subject: Check if script is being launched in subshell or being redirected to file, and make -l to --onelist. This more or less depricates '--onelist' as flag --- ponysay.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 800343e..dcfb6b0 100755 --- a/ponysay.py +++ b/ponysay.py @@ -46,6 +46,12 @@ Whether the program is execute in Linux VT (TTY) linuxvt = os.environ['TERM'] == 'linux' +''' +Whether the program is launched in subshell/beeing redirected +''' +redirected = not sys.stdout.isatty() + + ''' The directories where pony files are stored, ttyponies/ are used if the terminal is Linux VT (also known as TTY) ''' @@ -81,7 +87,7 @@ parser.add_argument( '--onelist', action = 'store_true', dest = 'onelist', parser.add_argument('-W', '--wrap', action = 'store', dest = 'wrap', help = 'specify the column when the message should be wrapped') parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') parser.add_argument('-q', '--quote', nargs = '*', dest = 'quote', help = 'select a pony which will quote herself') -parser.add_argument('message', nargs = '?', help = 'message to ponysay') +parser.add_argument('message', nargs = '?', help = 'message to ponysay') args = parser.parse_args() # TODO implement if [ -t 0 ] && [ $# == 0 ]; then @@ -99,6 +105,10 @@ class ponysay(): Starts the part of the program the arguments indicate ''' def __init__(self, args): + if args.list and redirected: + args.list = False + args.onelist = True + if args.list: self.list() elif args.linklist: self.linklist() elif args.quoters: self.quoters() -- cgit From 496b980a388e92f47a774d868140c6c5dbb6d678 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 20:36:05 +0200 Subject: kms ponies --- ponysay.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 800343e..495bf5b 100755 --- a/ponysay.py +++ b/ponysay.py @@ -354,7 +354,7 @@ class ponysay(): pony = self.__getponypath(args.pony) (cowsay, customcowsay) = self.__getcowsay() - cmd = [cowsay, '-f', pony] + cmd = [cowsay, '-f', self.__kms(pony)] if args.wrap is not None: cmd += ['-W', args.wrap] cmd.append(msg) @@ -370,10 +370,10 @@ class ponysay(): env_bottom = os.environ['PONYSAY_BOTTOM'] if 'PONYSAY_BOTTOM' in os.environ else None - if (env_bottom is None) or (env_bottom == ''): env_bottom = '' + if env_bottom is None: env_bottom = '' env_height = os.environ['PONYSAY_TRUNCATE_HEIGHT'] if 'PONYSAY_TRUNCATE_HEIGHT' in os.environ else None - if (env_height is None) or (env_height == ''): env_height = '' + if env_height is None: env_height = '' env_lines = os.environ['PONYSAY_SHELL_LINES'] if 'PONYSAY_SHELL_LINES' in os.environ else None if (env_lines is None) or (env_lines == ''): env_lines = '2' @@ -443,7 +443,53 @@ class ponysay(): args.message = 'I got nuthin\' good to say :(' self.print_pony(args) - + + + ''' + Returns the file name of the input pony converted to a KMS pony, or if KMS is not used, the input pony itself + ''' + def __kms(self, pony): + if not linuxvt: + return pony + + env_kms = os.environ['PONYSAY_KMS_PALETTE'] if 'PONYSAY_KMS_PALETTE' in os.environ else None + if env_kms is None: env_kms = '' + + env_kms_cmd = os.environ['PONYSAY_KMS_PALETTE_CMD'] if 'PONYSAY_KMS_PALETTE_CMD' in os.environ else None + if (env_kms_cmd is not None) and (not env_kms_cmd == ''): + env_kms = Popen(shlex.split(env_kms_cmd), stdout=PIPE, stdin=sys.stderr).communicate()[0].decode('utf8', 'replace') + if env_kms[-1] == '\n': + env_kms = env_kms[:-1] + + if env_kms == '': + return pony + + palette = env_kms + palettefile = env_kms.replace('\033]P', '') + + kmsponies = '/var/cache/ponysay/kmsponies/' + palettefile + kmspony = kmsponies + pony + + if not os.path.isfile(kmspony): + protokmsponies = '/var/cache/ponysay/protokmsponies/' + protokmspony = protokmsponies + pony + + _protokmspony = '\'' + protokmspony.replace('\'', '\'\\\'\'') + '\'' + _kmspony = '\'' + kmspony.replace('\'', '\'\\\'\'') + '\'' + _pony = '\'' + pony.replace('\'', '\'\\\'\'') + '\'' + + if not os.path.isfile(protokmspony): + os.makedirs(protokmsponies) + if not os.system('ponysay2ttyponysay < ' + _pony + ' > ' + _protokmspony) == 0: + sys.stderr.write('Unable to run ponysay2ttyponysay successfully, you need util-say for KMS support\n') + exit(1) + + os.makedirs(kmsponies) + if not os.system('tty2colourfultty -e -p ' + palette + ' < ' + _protokmspony + ' > ' + _kmspony) == 0: + sys.stderr.write('Unable to run tty2colourfultty successfully, you need util-say for KMS support\n') + exit(1) + + return kmspony -- cgit From f41a0244c694b0ba24ffc4bbfb80e21388852fa8 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 20:38:48 +0200 Subject: typo --- ponysay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 9d05e10..f6ba701 100755 --- a/ponysay.py +++ b/ponysay.py @@ -47,7 +47,7 @@ linuxvt = os.environ['TERM'] == 'linux' ''' -Whether the program is launched in subshell/beeing redirected +Whether the program is launched in subshell/being redirected ''' redirected = not sys.stdout.isatty() -- cgit From 3d7768e2efd138e089850d0e41b7f5a12d0f6fc9 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 21:05:45 +0200 Subject: make fix + m --- ponysay.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index f6ba701..6284dd7 100755 --- a/ponysay.py +++ b/ponysay.py @@ -25,7 +25,7 @@ from subprocess import Popen, PIPE ''' The version of ponysay ''' -VERSION = '2.0-alpha' +VERSION = '2.0-rc1' ''' @@ -49,7 +49,7 @@ linuxvt = os.environ['TERM'] == 'linux' ''' Whether the program is launched in subshell/being redirected ''' -redirected = not sys.stdout.isatty() +redirected = False #not sys.stdout.isatty() # currently impossible, we need to get rid of the little shell script first ''' @@ -77,7 +77,7 @@ for quotedir in _quotedirs: ''' Argument parsing ''' -parser = argparse.ArgumentParser(prog = 'ponysay', description = 'Like cowsay with ponies.') +parser = argparse.ArgumentParser(prog = 'ponysay', description = 'cowsay wrapper for ponies') parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ('ponysay', VERSION)) parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') -- cgit From 23f071aa2eadca7f640cb762f949c44721b50f2e Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 18 Aug 2012 21:21:34 +0200 Subject: m doc --- ponysay.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 6284dd7..b5cc2b2 100755 --- a/ponysay.py +++ b/ponysay.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- ''' -ponysay.py - POC of ponysay in python +ponysay.py - Ponysay, a cowsay wrapper for ponies Copyright (C) 2012 Erkin Batu Altunbaş Authors: Erkin Batu Altunbaş: Project leader, helped write the first implementation @@ -353,7 +353,7 @@ class ponysay(): ''' - Print the pony with a speech or though bubble + Print the pony with a speech or though bubble. message, pony and wrap from args are used. ''' def print_pony(self, args): if args.message == None: -- cgit From eac35c124a30c2cc02ceb72129a4180239dcab57 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 04:55:38 +0200 Subject: .png files in -f if util-say is installed --- ponysay.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index b5cc2b2..8d41cba 100755 --- a/ponysay.py +++ b/ponysay.py @@ -25,7 +25,7 @@ from subprocess import Popen, PIPE ''' The version of ponysay ''' -VERSION = '2.0-rc1' +VERSION = '2.0-rc2' ''' @@ -122,7 +122,7 @@ class ponysay(): ## ''' - Returns one .pony-file with full path, names is filter for names, also accepts filepaths + Returns one file with full path, names is filter for names, also accepts filepaths. ''' def __getponypath(self, names = None): ponies = {} @@ -130,7 +130,7 @@ class ponysay(): if not names == None: for name in names: if os.path.isfile(name): - return name + ponies[name] = name for ponydir in ponydirs: for ponyfile in os.listdir(ponydir): @@ -342,7 +342,7 @@ class ponysay(): Returns (the cowsay command, whether it is a custom program) ''' def __getcowsay(self): - isthink = 'think.py' in __file__ + isthink = (len(__file__) >= 8) and (__file__[-8:] == 'think.py') if isthink: cowthink = os.environ['PONYSAY_COWTHINK'] if 'PONYSAY_COWTHINK' in os.environ else None @@ -361,9 +361,17 @@ class ponysay(): else: msg = args.message + pony = self.__getponypath(args.pony) (cowsay, customcowsay) = self.__getcowsay() + if (len(pony) > 4) and (pony[-4:].lower() == '.png'): + pony = '\'' + pony.replace('\'', '\'\\\'\'') + '\'' + pngcmd = ('img2ponysay -p -- ' if linuxvt else 'img2ponysay -- ') + pony + pngpipe = os.pipe() + Popen(pngcmd, stdout=os.fdopen(pngpipe[1], 'w'), shell=True).wait() + pony = '/proc/' + str(os.getpid()) + '/fd/' + str(pngpipe[0]) + cmd = [cowsay, '-f', self.__kms(pony)] if args.wrap is not None: cmd += ['-W', args.wrap] -- cgit From 80044cd05c7b6842ac3c3501b20af360102c8986 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 18:02:05 +0200 Subject: bug fixes + a better fitting argument parse (--help is not implemented yet) --- ponysay.py | 298 ++++++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 244 insertions(+), 54 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 8d41cba..00e71f3 100755 --- a/ponysay.py +++ b/ponysay.py @@ -15,7 +15,6 @@ Authors: Erkin Batu Altunbaş: Project leader, helped write the fir License: WTFPL ''' -import argparse import os import sys import random @@ -25,7 +24,7 @@ from subprocess import Popen, PIPE ''' The version of ponysay ''' -VERSION = '2.0-rc2' +VERSION = '2.0-rc3' ''' @@ -46,6 +45,12 @@ Whether the program is execute in Linux VT (TTY) linuxvt = os.environ['TERM'] == 'linux' +''' +Whether the script is executed as ponythink +''' +isthink = (len(__file__) >= 8) and (__file__[-8:] == 'think.py') + + ''' Whether the program is launched in subshell/being redirected ''' @@ -74,47 +79,25 @@ for quotedir in _quotedirs: -''' -Argument parsing -''' -parser = argparse.ArgumentParser(prog = 'ponysay', description = 'cowsay wrapper for ponies') - -parser.add_argument('-v', '--version', action = 'version', version = '%s %s' % ('ponysay', VERSION)) -parser.add_argument('-l', '--list', action = 'store_true', dest = 'list', help = 'list pony files') -parser.add_argument('-L', '--altlist', action = 'store_true', dest = 'linklist', help = 'list pony files with alternatives') -parser.add_argument( '--quoters', action = 'store_true', dest = 'quoters', help = 'list ponies with quotes (visible in -l and -L)') # for shell completions -parser.add_argument( '--onelist', action = 'store_true', dest = 'onelist', help = 'list pony files in one columns') # for shell completions -parser.add_argument('-W', '--wrap', action = 'store', dest = 'wrap', help = 'specify the column when the message should be wrapped') -parser.add_argument('-f', '--pony', action = 'append', dest = 'pony', help = 'select a pony (either a file name or a pony name)') -parser.add_argument('-q', '--quote', nargs = '*', dest = 'quote', help = 'select a pony which will quote herself') -parser.add_argument('message', nargs = '?', help = 'message to ponysay') - -args = parser.parse_args() -# TODO implement if [ -t 0 ] && [ $# == 0 ]; then -# usage -# exit -# fi - - - ''' This is the mane class of ponysay ''' -class ponysay(): +class Ponysay(): ''' Starts the part of the program the arguments indicate ''' def __init__(self, args): - if args.list and redirected: - args.list = False - args.onelist = True - - if args.list: self.list() - elif args.linklist: self.linklist() - elif args.quoters: self.quoters() - elif args.onelist: self.onelist() - elif args.quote: self.quote(args) - else: self.print_pony(args) + if (args.opts['-l'] is not None) and redirected: + args.opts['--onelist'] = args.opts['-l'] + args.opts['-l'] = None + + if args.opts['--quoters'] is not None: self.quoters() + elif args.opts['--onelist'] is not None: self.onelist() + elif args.opts['-v'] is not None: self.version() + elif args.opts['-l'] is not None: self.list() + elif args.opts['-L'] is not None: self.linklist() + elif args.opts['-q'] is not None: self.quote(args) + else: self.print_pony(args) ## @@ -141,7 +124,12 @@ class ponysay(): if names == None: names = list(ponies.keys()) - return ponies[names[random.randrange(0, len(names))]] + pony = names[random.randrange(0, len(names))] + if pony not in ponies: + sys.stderr.write('I have never heared of any pony named %s\n' % (pony)); + exit(1) + else: + return ponies[pony] ''' @@ -187,6 +175,7 @@ class ponysay(): p = pony[:-5] # remove .pony for quote in quotes: q = quote[quote.rindex('/') + 1:] + q = q[:q.rindex('.')] if ('+' + p + '+') in ('+' + q + '+'): rc.append((p, quote)) @@ -307,7 +296,7 @@ class ponysay(): Lists with all ponies that have quotes and are displayable ''' def quoters(self): - last = "" + last = '' ponies = [] for pony in self.__quoters(): ponies.append(pony) @@ -322,7 +311,7 @@ class ponysay(): Lists the available ponies one one column without anything bold ''' def onelist(self): - last = "" + last = '' ponies = [] for ponydir in ponydirs: # Loop ponydirs ponies += os.listdir(ponydir) @@ -338,12 +327,17 @@ class ponysay(): ## Displaying methods ## + ''' + Prints the name of the program and the version of the program + ''' + def version(self): + print('%s %s' % ('ponysay', VERSION)) + + ''' Returns (the cowsay command, whether it is a custom program) ''' def __getcowsay(self): - isthink = (len(__file__) >= 8) and (__file__[-8:] == 'think.py') - if isthink: cowthink = os.environ['PONYSAY_COWTHINK'] if 'PONYSAY_COWTHINK' in os.environ else None return ('cowthink', False) if (cowthink is None) or (cowthink == '') else (cowthink, True) @@ -362,7 +356,7 @@ class ponysay(): msg = args.message - pony = self.__getponypath(args.pony) + pony = self.__getponypath(args.opts['-f']) (cowsay, customcowsay) = self.__getcowsay() if (len(pony) > 4) and (pony[-4:].lower() == '.png'): @@ -373,8 +367,8 @@ class ponysay(): pony = '/proc/' + str(os.getpid()) + '/fd/' + str(pngpipe[0]) cmd = [cowsay, '-f', self.__kms(pony)] - if args.wrap is not None: - cmd += ['-W', args.wrap] + if args.opts['-W'] is not None: + cmd += ['-W', args.opts['-W']] cmd.append(msg) if linuxvt: @@ -402,8 +396,8 @@ class ponysay(): if not exit_value == 0: sys.stderr.write('Unable to successfully execute' + (' custom ' if customcowsay else ' ') + 'cowsay [' + cowsay + ']\n') else: - if linuxvt or (env_height is ("yes", "y", "1")): - if env_bottom is ("yes", "y", "1"): + if linuxvt or (env_height is ('yes', 'y', '1')): + if env_bottom is ('yes', 'y', '1'): for line in output[: -lines]: print(line) else: @@ -435,14 +429,14 @@ class ponysay(): ''' def quote(self, args): pairs = self.__quotes() - if len(args.quote) > 0: - ponyset = set(args.quote) + if len(args.opts['-q']) > 0: + ponyset = set(args.opts['-q']) alts = [] for pair in pairs: if pair[0] in ponyset: alts.append(pair) pairs = alts - + if not len(pairs) == 0: pair = pairs[random.randrange(0, len(pairs))] qfile = None @@ -452,12 +446,12 @@ class ponysay(): finally: if qfile is not None: qfile.close() - args.pony = [pair[0]] - elif len(args.quote) == 0: - sys.stderr.write('All the ponies are mute! Call the Princess!') + args.opts['-f'] = [pair[0]] + elif len(args.opts['-q']) == 0: + sys.stderr.write('All the ponies are mute! Call the Princess!\n') exit(1) else: - args.pony = args.quote[random.randrange(0, len(args.quote))] + args.opts['-f'] = [args.opts['-q'][random.randrange(0, len(args.opts['-q']))]] args.message = 'I got nuthin\' good to say :(' self.print_pony(args) @@ -511,8 +505,204 @@ class ponysay(): +ARGUMENTLESS = 0 +ARGUMENTED = 1 +VARIADIC = 2 +''' +Simple argument parser +''' +class ArgParser: + ''' + Constructor. + The short description is printed on same line as the program name + ''' + def __init__(self, program, description, usage, longdescription = None): + self.__program = program + self.__description = description + self.__usage = usage + self.__longdescription = longdescription + self.__arguments = [] + self.opts = {} + self.optmap = {} + + + ''' + Add option that takes no arguments + ''' + def add_argumentless(self, alternatives, help = None): + ARGUMENTLESS + self.__arguments.append((ARGUMENTLESS, alternatives, help)) + stdalt = alternatives[0] + self.opts[stdalt] = None + for alt in alternatives: + self.optmap[alt] = (stdalt, ARGUMENTLESS) + + ''' + Add option that takes one argument + ''' + def add_argumented(self, alternatives, help = None): + self.__arguments.append((ARGUMENTED, alternatives, help)) + stdalt = alternatives[0] + self.opts[stdalt] = None + for alt in alternatives: + self.optmap[alt] = (stdalt, ARGUMENTED) + + ''' + Add option that takes all following argument + ''' + def add_variadic(self, alternatives, help = None): + self.__arguments.append((VARIADIC, alternatives, help)) + stdalt = alternatives[0] + self.opts[stdalt] = None + for alt in alternatives: + self.optmap[alt] = (stdalt, VARIADIC) + + + ''' + Parse arguments + ''' + def parse(self, argv = sys.argv): + self.argcount = len(argv) - 1 + self.files = [] + + argqueue = [] + optqueue = [] + deque = [] + for arg in argv[1:]: + deque.append(arg) + + dashed = False + tmpdashed = False + get = 0 + dontget = 0 + + def unrecognised(arg): + sys.stderr.write('%s: warning: unrecognised option %s\n' % (self.__program, arg)) + + while len(deque) != 0: + arg = deque[0] + deque = deque[1:] + if (get > 0) and (dontget == 0): + get -= 1 + argqueue.append(arg) + elif tmpdashed: + self.files.append(arg) + tmpdashed = False + elif dashed: self.files.append(arg) + elif arg == '++': tmpdashed = True + elif arg == '--': dashed = True + elif (len(arg) > 1) and ((arg[0] == '-') or (arg[0] == '+')): + if (len(arg) > 2) and ((arg[:2] == '--') or (arg[:2] == '++')): + if dontget > 0: + dontget -= 1 + elif (arg in self.optmap) and (self.optmap[arg][1] == ARGUMENTLESS): + optqueue.append(arg) + argqueue.append(None) + elif '=' in arg: + arg_opt = arg[:arg.index('=')] + if (arg_opt in self.optmap) and (self.optmap[arg_opt][1] >= ARGUMENTED): + optqueue.append(arg_opt) + argqueue.append(arg[arg.index('=') + 1:]) + if self.optmap[arg_opt][1] == VARIADIC: + dashed = True + else: + unrecognised(arg) + elif (arg in self.optmap) and (self.optmap[arg][1] == ARGUMENTED): + optqueue.append(arg) + get += 1 + elif (arg in self.optmap) and (self.optmap[arg][1] == VARIADIC): + optqueue.append(arg) + argqueue.append(None) + dashed = True + else: + unrecognised(arg) + else: + sign = arg[0] + i = 1 + n = len(arg) + while i < n: + narg = sign + arg[i] + i += 1 + if (narg in self.optmap): + if self.optmap[narg][1] == ARGUMENTLESS: + optqueue.append(narg) + argqueue.append(None) + elif self.optmap[narg][1] == ARGUMENTED: + optqueue.append(narg) + nargarg = arg[i:] + if len(nargarg) == 0: + get += 1 + else: + argqueue.append(nargarg) + break + elif self.optmap[narg][1] == VARIADIC: + optqueue.append(narg) + nargarg = arg[i:] + argqueue.append(nargarg if len(nargarg) > 0 else None) + dashed = True + break + else: + unrecognised(arg) + else: + self.files.append(arg) + + i = 0 + n = len(optqueue) + while i < n: + opt = optqueue[i] + arg = argqueue[i] + i += 1 + opt = self.optmap[opt][0] + if (opt not in self.opts) or (self.opts[opt] is None): + self.opts[opt] = [] + self.opts[opt].append(arg) + + for arg in self.__arguments: + if (arg[0] == VARIADIC): + varopt = self.opts[arg[1][0]] + if varopt is not None: + additional = ','.join(self.files).split(',') if len(self.files) > 0 else [] + if varopt[0] is None: + self.opts[arg[1][0]] = additional + else: + self.opts[arg[1][0]] = varopt[0].split(',') + additional + self.files = [] + break + + self.message = ' '.join(self.files) if len(self.files) > 0 else None + #print('files = ' + str(self.files)) + #print('message = ' + str(self.message)) + #print('opts = ' + str(self.opts)) + + + +''' +Argument parsing +''' +opts = ArgParser(program = 'ponythink' if isthink else 'ponysay', + description = 'cowsay wrapper for ponies', + usage = '-l | -L | [-W] [[-f PONY]* [message] | -q [PONY*]]') + +opts.add_argumentless(['--quoters']) +opts.add_argumentless(['--onelist']) + +opts.add_argumentless(['-h', '--help'], help = 'Print this help message') +opts.add_argumentless(['-v', '--version'], help = 'Print the version of the program') +opts.add_argumentless(['-l', '--list'], help = 'List pony files') +opts.add_argumentless(['-L', '--altlist'], help = 'List pony files with alternatives') +opts.add_argumented( ['-W', '--wrap'], help = 'Specify the column when the message should be wrapped') +opts.add_argumented( ['-f', '--pony'], help = 'Select a pony (either a file name or a pony name)') +opts.add_variadic( ['-q', '--quote'], help = 'Select a ponies which will quote themself') + +opts.parse() +# TODO implement if [ -t 0 ] && [ $# == 0 ]; then +# usage +# exit +# fi + + ''' Start the program from ponysay.__init__ if this is the executed file ''' if __name__ == '__main__': - ponysay(args) + Ponysay(opts) -- cgit From 7686726b1298d3577f85bdf9e5c8dbbb9d93b1fa Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 19:05:13 +0200 Subject: help message --- ponysay.py | 113 ++++++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 93 insertions(+), 20 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 00e71f3..ca89c5d 100755 --- a/ponysay.py +++ b/ponysay.py @@ -52,9 +52,19 @@ isthink = (len(__file__) >= 8) and (__file__[-8:] == 'think.py') ''' -Whether the program is launched in subshell/being redirected +Whether stdin is piped ''' -redirected = False #not sys.stdout.isatty() # currently impossible, we need to get rid of the little shell script first +pipelinein = not sys.stdin.isatty() + +''' +Whether stdout is piped +''' +pipelineout = False #not sys.stdout.isatty() # currently impossible, we need to get rid of the little shell script first + +''' +Whether stderr is piped +''' +pipelineerr = not sys.stderr.isatty() ''' @@ -87,11 +97,12 @@ class Ponysay(): Starts the part of the program the arguments indicate ''' def __init__(self, args): - if (args.opts['-l'] is not None) and redirected: + if (args.opts['-l'] is not None) and pipelineout: args.opts['--onelist'] = args.opts['-l'] args.opts['-l'] = None - if args.opts['--quoters'] is not None: self.quoters() + if args.opts['-h'] is not None: args.help() + elif args.opts['--quoters'] is not None: self.quoters() elif args.opts['--onelist'] is not None: self.onelist() elif args.opts['-v'] is not None: self.version() elif args.opts['-l'] is not None: self.list() @@ -531,7 +542,7 @@ class ArgParser: ''' def add_argumentless(self, alternatives, help = None): ARGUMENTLESS - self.__arguments.append((ARGUMENTLESS, alternatives, help)) + self.__arguments.append((ARGUMENTLESS, alternatives, None, help)) stdalt = alternatives[0] self.opts[stdalt] = None for alt in alternatives: @@ -540,8 +551,8 @@ class ArgParser: ''' Add option that takes one argument ''' - def add_argumented(self, alternatives, help = None): - self.__arguments.append((ARGUMENTED, alternatives, help)) + def add_argumented(self, alternatives, arg, help = None): + self.__arguments.append((ARGUMENTED, alternatives, arg, help)) stdalt = alternatives[0] self.opts[stdalt] = None for alt in alternatives: @@ -550,8 +561,8 @@ class ArgParser: ''' Add option that takes all following argument ''' - def add_variadic(self, alternatives, help = None): - self.__arguments.append((VARIADIC, alternatives, help)) + def add_variadic(self, alternatives, arg, help = None): + self.__arguments.append((VARIADIC, alternatives, arg, help)) stdalt = alternatives[0] self.opts[stdalt] = None for alt in alternatives: @@ -670,29 +681,91 @@ class ArgParser: break self.message = ' '.join(self.files) if len(self.files) > 0 else None - #print('files = ' + str(self.files)) - #print('message = ' + str(self.message)) - #print('opts = ' + str(self.opts)) + + + ''' + Prints a colourful help message + ''' + def help(self): + print('\033[1m%s\033[21m %s %s' % (self.__program, '-' if linuxvt else '—', self.__description)) + print() + if self.__longdescription is not None: + print(self.__longdescription) + print() + print() + + print('\033[1mUSAGE:\033[21m', end='') + first = True + for line in self.__usage.split('\n'): + if first: + first = False + else: + print(' or', end="") + print('\t%s' % (line)) + print() + + print('\033[1mSYNOPSIS:\033[21m') + print() + for opt in self.__arguments: + opt_type = opt[0] + opt_alts = opt[1] + opt_arg = opt[2] + opt_help = opt[3] + if opt_help is None: + continue + for opt_alt in opt_alts: + if opt_alt is opt_alts[-1]: + print('\t' + opt_alt, end='') + if opt_type == ARGUMENTED: print(' \033[4m%s\033[24m' % (opt_arg)) + elif opt_type == VARIADIC: print(' [\033[4m%s\033[24m...]' % (opt_arg)) + else: print() + else: + print('\t\033[2m' + opt_alt + '\033[22m') + first = True + for line in opt_help.split('\n'): + if first: + first = False + print('\t\t\033[32;1m%s\033[21;39m' % (line)) + else: + print('\t\t%s' % (line)) + print() + + print() + + + +usage_saythink = '\033[34;1m(ponysay | ponythink)\033[21;39m' +usage_wrap = '--wrap \033[4mCOLUMN\033[24m' +usage_listhelp = '(--list | ---altlist | --version | --help)' +usage_file = '[--pony \033[4mPONY\033[24m]... ([--] \033[4mmessage\033[24m | <<<\033[4mmessage\033[24m)' +usage_quote = '--quote [\033[4mPONY\033[24m...]' +usage = '%s %s\n%s [%s] %s\n%s [%s] %s' % (usage_saythink, usage_listhelp, + usage_saythink, usage_wrap, usage_file, + usage_saythink, usage_wrap, usage_quote) +usage = usage.replace('\033[', '\0') +for sym in ('[', ']', '(', ')', '|', '...'): + usage = usage.replace(sym, '\033[2m' + sym + '\033[22m') +usage = usage.replace('\0', '\033[') ''' Argument parsing ''' opts = ArgParser(program = 'ponythink' if isthink else 'ponysay', description = 'cowsay wrapper for ponies', - usage = '-l | -L | [-W] [[-f PONY]* [message] | -q [PONY*]]') + usage = usage) opts.add_argumentless(['--quoters']) opts.add_argumentless(['--onelist']) -opts.add_argumentless(['-h', '--help'], help = 'Print this help message') -opts.add_argumentless(['-v', '--version'], help = 'Print the version of the program') -opts.add_argumentless(['-l', '--list'], help = 'List pony files') -opts.add_argumentless(['-L', '--altlist'], help = 'List pony files with alternatives') -opts.add_argumented( ['-W', '--wrap'], help = 'Specify the column when the message should be wrapped') -opts.add_argumented( ['-f', '--pony'], help = 'Select a pony (either a file name or a pony name)') -opts.add_variadic( ['-q', '--quote'], help = 'Select a ponies which will quote themself') +opts.add_argumentless(['-h', '--help'], help = 'Print this help message.') +opts.add_argumentless(['-v', '--version'], help = 'Print the version of the program.') +opts.add_argumentless(['-l', '--list'], help = 'List pony files.') +opts.add_argumentless(['-L', '--altlist'], help = 'List pony files with alternatives.') +opts.add_argumented( ['-W', '--wrap'], arg = "COLUMN", help = 'Specify the column when the message should be wrapped.') +opts.add_argumented( ['-f', '--pony'], arg = "PONY", help = 'Select a pony.\nEither a file name or a pony name.') +opts.add_variadic( ['-q', '--quote'], arg = "PONY", help = 'Select a ponies which will quote themself.') opts.parse() # TODO implement if [ -t 0 ] && [ $# == 0 ]; then -- cgit From c4b5146873f681544d21339bf6278c2b89e85790 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 19:10:33 +0200 Subject: help message complete --- ponysay.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index ca89c5d..4696b01 100755 --- a/ponysay.py +++ b/ponysay.py @@ -754,7 +754,12 @@ Argument parsing ''' opts = ArgParser(program = 'ponythink' if isthink else 'ponysay', description = 'cowsay wrapper for ponies', - usage = usage) + usage = usage, + longdescription = +'''Ponysay displays an image of a pony saying some text provided by the user. +If \033[4mmessage\033[24m is not provided, it accepts standard input. For an extensive +documentation run `info ponysay`, or for just a little more help than this +run `man ponysay`. Ponysay has so much more to offer than described here.''') opts.add_argumentless(['--quoters']) opts.add_argumentless(['--onelist']) -- cgit From 5dde58685012ffaa5e280e025b088a0dd3395ddc Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 19:36:00 +0200 Subject: kms fix (however not working because of some bug in util-say) --- ponysay.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 4696b01..65b8235 100755 --- a/ponysay.py +++ b/ponysay.py @@ -491,23 +491,28 @@ class Ponysay(): palettefile = env_kms.replace('\033]P', '') kmsponies = '/var/cache/ponysay/kmsponies/' + palettefile - kmspony = kmsponies + pony + kmspony = (kmsponies + pony).replace('//', '/') if not os.path.isfile(kmspony): protokmsponies = '/var/cache/ponysay/protokmsponies/' - protokmspony = protokmsponies + pony + protokmspony = (protokmsponies + pony).replace('//', '/') + + protokmsponydir = protokmspony[:protokmspony.rindex('/')] + kmsponydir = kmspony[: kmspony.rindex('/')] _protokmspony = '\'' + protokmspony.replace('\'', '\'\\\'\'') + '\'' _kmspony = '\'' + kmspony.replace('\'', '\'\\\'\'') + '\'' _pony = '\'' + pony.replace('\'', '\'\\\'\'') + '\'' if not os.path.isfile(protokmspony): - os.makedirs(protokmsponies) + if not os.path.isdir(protokmsponydir): + os.makedirs(protokmsponydir) if not os.system('ponysay2ttyponysay < ' + _pony + ' > ' + _protokmspony) == 0: sys.stderr.write('Unable to run ponysay2ttyponysay successfully, you need util-say for KMS support\n') exit(1) - os.makedirs(kmsponies) + if not os.path.isdir(kmsponydir): + os.makedirs(kmsponydir) if not os.system('tty2colourfultty -e -p ' + palette + ' < ' + _protokmspony + ' > ' + _kmspony) == 0: sys.stderr.write('Unable to run tty2colourfultty successfully, you need util-say for KMS support\n') exit(1) -- cgit From 24eb3cbcf68e1ed034432d107aa6519386a99307 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 19:41:16 +0200 Subject: display help if no arguments and not piped --- ponysay.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 65b8235..6fb522a 100755 --- a/ponysay.py +++ b/ponysay.py @@ -97,6 +97,10 @@ class Ponysay(): Starts the part of the program the arguments indicate ''' def __init__(self, args): + if (args.argcount == 0) and not pipelinein: + args.help() + return + if (args.opts['-l'] is not None) and pipelineout: args.opts['--onelist'] = args.opts['-l'] args.opts['-l'] = None @@ -778,10 +782,6 @@ opts.add_argumented( ['-f', '--pony'], arg = "PONY", help = 'Select a po opts.add_variadic( ['-q', '--quote'], arg = "PONY", help = 'Select a ponies which will quote themself.') opts.parse() -# TODO implement if [ -t 0 ] && [ $# == 0 ]; then -# usage -# exit -# fi ''' -- cgit From ab6f498c9f60dd5d914134a387144beabf6ce48c Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 19:49:06 +0200 Subject: better (yes this is weird) --- ponysay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 6fb522a..357ed46 100755 --- a/ponysay.py +++ b/ponysay.py @@ -366,7 +366,7 @@ class Ponysay(): ''' def print_pony(self, args): if args.message == None: - msg = sys.stdin.read().strip() + msg = ''.join(sys.stdin.readlines()).strip() else: msg = args.message -- cgit From 6dc632a155db800997e0eb2dec420a6233a2d141 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sun, 19 Aug 2012 19:50:58 +0200 Subject: stable --- ponysay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ponysay.py') diff --git a/ponysay.py b/ponysay.py index 357ed46..f9a87e6 100755 --- a/ponysay.py +++ b/ponysay.py @@ -24,7 +24,7 @@ from subprocess import Popen, PIPE ''' The version of ponysay ''' -VERSION = '2.0-rc3' +VERSION = '2.0' ''' -- cgit