/
ponysay
executable file
·1735 lines (1479 loc) · 59.9 KB
/
ponysay
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
ponysay.py - Ponysay, a cowsay reimplementation for ponies
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 the first implementation
Sven-Hendrik "svenstaro" Haase: Major contributor of the first implementation
Jan Alexander "heftig" Steffens: Major contributor of the first implementation
Kyah "L-four" Rindlisbacher: Patched the first implementation
License: WTFPL
'''
import os
import shutil
import sys
import random
from subprocess import Popen, PIPE
'''
The version of ponysay
'''
VERSION = '2.3'
'''
The directory where ponysay is installed, this is modified when building with make
'''
INSTALLDIR = '/usr'
'''
This is the mane class of ponysay
'''
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['-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()
elif args.opts['-L'] is not None: self.linklist()
elif args.opts['-B'] is not None: self.balloonlist()
elif args.opts['++onelist'] is not None: self.__extraponies(); self.onelist()
elif args.opts['+l'] is not None: self.__extraponies(); self.list()
elif args.opts['+L'] is not None: self.__extraponies(); self.linklist()
else:
self.__extraponies(args)
self.__bestpony(args)
self.__ucsremap(args)
if args.opts['-q'] is not None: self.quote(args)
else: self.print_pony(args)
##
## Methods that run before the mane methods
##
'''
Use extra ponies
'''
def __extraponies(self, args = None):
if args is None:
ponydirs[:] = extraponydirs
elif args.opts['-F'] is not None:
args.opts['-f'] = args.opts['-F']
ponydirs[:] = extraponydirs
'''
Use best.pony if nothing else is set
'''
def __bestpony(self, args):
if (args.opts['-f'] is None) or (args.opts['-q'] is None) or (len(args.opts['-q']) == 0):
for ponydir in ponydirs:
if os.path.isfile(ponydir + 'best.pony') or os.path.islink(ponydir + 'best.pony'):
pony = os.path.realpath(ponydir + 'best.pony') # Canonical path
args.opts['-f' if args.opts['-q'] is None else '-q'] = [pony]
break
'''
Apply pony name remapping to args according to UCS settings
'''
def __ucsremap(self, args):
env_ucs = os.environ['PONYSAY_UCS_ME'] if 'PONYSAY_UCS_ME' in os.environ else ''
ucs_conf = 0
if env_ucs in ('yes', 'y', '1'): ucs_conf = 1
elif env_ucs in ('harder', 'h', '2'): ucs_conf = 2
if ucs_conf == 0:
return
maplines = []
for sharedir in sharedirs:
if os.path.isfile(sharedir + 'ucsmap'):
mapfile = None
try:
mapfile = open(sharedir + 'ucsmap', 'r')
maplines += [line.replace('\n', '') for line in mapfile.readlines()]
finally:
if mapfile is not None:
mapfile.close()
map = {}
stripset = ' \t' # must be string, wtf! and way doesn't python's doc say so
for line in maplines:
if (len(line) > 0) and not (line[0] == '#'):
s = line.index('→')
ucs = line[:s] .strip(stripset)
ascii = line[s + 1:].strip(stripset)
map[ucs] = ascii
for flag in ('-f', '-q'):
if args.opts[flag] is not None:
for i in range(0, len(args.opts[flag])):
if args.opts[flag][i] in map:
args.opts[flag][i] = map[args.opts[flag][i]]
##
## Auxiliary methods
##
'''
Apply USC:ise pony names according to UCS settings
'''
def __ucsise(self, ponies, links = None):
env_ucs = os.environ['PONYSAY_UCS_ME'] if 'PONYSAY_UCS_ME' in os.environ else ''
ucs_conf = 0
if env_ucs in ('yes', 'y', '1'): ucs_conf = 1
elif env_ucs in ('harder', 'h', '2'): ucs_conf = 2
if ucs_conf == 0:
return
maplines = []
for sharedir in sharedirs:
if os.path.isfile(sharedir + 'ucsmap'):
mapfile = None
try:
mapfile = open(sharedir + 'ucsmap', 'r')
maplines += [line.replace('\n', '') for line in mapfile.readlines()]
finally:
if mapfile is not None:
mapfile.close()
map = {}
stripset = ' \t' # must be string, wtf! and way doesn't python's doc say so
for line in maplines:
if (len(line) > 0) and not (line[0] == '#'):
s = line.index('→')
ucs = line[:s] .strip(stripset)
ascii = line[s + 1:].strip(stripset)
map[ascii] = ucs
if ucs_conf == 1:
for pony in ponies:
if pony in map:
ponies.append(map[pony])
if links is not None:
links[map[pony]] = pony
else:
for j in range(0, len(ponies)):
if ponies[j] in map:
ponies[j] = map[ponies[j]]
'''
Returns one file with full path, names is filter for names, also accepts filepaths
'''
def __getponypath(self, names = None):
ponies = {}
for ponydir in ponydirs:
for ponyfile in os.listdir(ponydir):
pony = ponyfile[:-5]
if pony not in ponies:
ponies[pony] = ponydir + ponyfile
if not names == None:
for name in names:
if os.path.exists(name):
ponies[name] = name
if names == None:
names = list(ponies.keys())
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]
'''
Returns a set with all ponies that have quotes and are displayable
'''
def __quoters(self):
quotes = []
quoteshash = set()
_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:
quoteshash.add(quote)
quotes.append(quote)
ponies = set()
for ponydir in ponydirs:
for pony in os.listdir(ponydir):
if not pony[0] == '.':
p = pony[:-5] # remove .pony
for quote in quotes:
if ('+' + p + '+') in ('+' + quote + '+'):
if not p in ponies:
ponies.add(p)
return ponies
'''
Returns a list with all (pony, quote file) pairs
'''
def __quotes(self):
quotes = []
for quotedir in quotedirs:
quotes += [quotedir + item for item in os.listdir(quotedir)]
rc = []
for ponydir in ponydirs:
for pony in os.listdir(ponydir):
if not pony[0] == '.':
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))
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
##
'''
Columnise a list and prints it
'''
def __columnise(self, ponies):
termwidth = self.__gettermsize()[1] + 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
cols = termwidth // width
rows = (len(ponies) + cols - 1) // cols
columns = []
for c in range(0, cols): columns.append([])
(y, x) = (0, 0)
for j in range(0, len(ponies)):
cell = ponies[j][1] + ' ' * (width - widths[j]);
columns[x].append(cell)
y += 1
if y == rows:
x += 1
y = 0
diff = rows * cols - len(ponies)
if diff > 2:
c = cols - 1
diff -= 1
while diff > 0:
columns[c] = columns[c - 1][-diff:] + columns[c]
c -= 1
columns[c] = columns[c][:-diff]
diff -= 1
pass
lines = []
for r in range(0, rows):
lines.append([])
for c in range(0, cols):
if r < len(columns[c]):
line = lines[r].append(columns[c][r])
print('\n'.join([''.join(line)[:-2] for line in lines]));
print()
'''
Lists the available ponies
'''
def list(self):
quoters = self.__quoters()
for ponydir in ponydirs: # Loop ponydirs
_ponies = os.listdir(ponydir)
ponies = []
for pony in _ponies:
if (len(pony) > 5) and (pony[-5:] == '.pony'):
ponies.append(pony[:-5])
self.__ucsise(ponies)
if len(ponies) == 0:
continue
print('\033[1mponies located in ' + ponydir + '\033[21m')
self.__columnise([(pony, '\033[1m' + pony + '\033[21m' if pony in quoters else pony) for pony in ponies])
'''
Lists the available ponies with alternatives inside brackets
'''
def linklist(self):
termsize = self.__gettermsize()
quoters = self.__quoters()
for ponydir in ponydirs: # Loop ponydirs
_ponies = os.listdir(ponydir)
ponies = []
for pony in _ponies:
if (len(pony) > 5) and (pony[-5:] == '.pony'):
ponies.append(pony[:-5])
if len(ponies) == 0:
continue
print('\033[1mponies located in ' + ponydir + '\033[21m')
pseudolinkmap = {}
self.__ucsise(ponies, 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))
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]]
width = 0
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
if width < w:
width = w
self.__columnise(list(ponies))
'''
Lists with all ponies that have quotes and are displayable
'''
def quoters(self):
last = ''
ponies = []
for pony in self.__quoters():
ponies.append(pony)
self.__ucsise(ponies)
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 = []
for pony in _ponies:
if (len(pony) > 5) and (pony[-5:] == '.pony'):
ponies.append(pony[:-5])
self.__ucsise(ponies)
ponies.sort()
for pony in ponies:
if not pony == last:
last = pony
print(pony)
##
## Balloon methods
##
'''
Prints a list of all balloons
'''
def balloonlist(self):
termsize = self.__gettermsize()
balloonset = set()
for balloondir in balloondirs:
for balloon in os.listdir(balloondir):
if isthink and (len(balloon) > 6) and (balloon[-6:] == '.think'):
balloon = balloon[:-6]
elif (not isthink) and (len(balloon) > 4) and (balloon[-4:] == '.say'):
balloon = balloon[:-4]
else:
continue
if balloon not in balloonset:
balloonset.add(balloon)
self.__columnise([(balloon, balloon) for balloon in list(balloonset)])
'''
Returns one file with full path, names is filter for style names, also accepts filepaths
'''
def __getballoonpath(self, names):
if names is None:
return None
balloons = {}
for balloondir in balloondirs:
for balloon in os.listdir(balloondir):
balloonfile = balloon
if isthink and (len(balloon) > 6) and (balloon[-6:] == '.think'):
balloon = balloon[:-6]
elif (not isthink) and (len(balloon) > 4) and (balloon[-4:] == '.say'):
balloon = balloon[:-4]
else:
continue
if balloon not in balloons:
balloons[balloon] = balloondir + balloonfile
for name in names:
if os.path.exists(name):
balloons[name] = name
if names == None:
names = list(balloons.keys())
balloon = names[random.randrange(0, len(names))]
if balloon not in balloons:
sys.stderr.write('That balloon style %s does not exist\n' % (balloon));
exit(1)
else:
return balloons[balloon]
'''
Creates the balloon style object
'''
def __getballoon(self, balloonfile):
if balloonfile is None:
if isthink:
return Balloon('o', 'o', '( ', ' )', [' _'], ['_'], ['_'], ['_'], ['_ '], ' )', ' )', ' )', ['- '], ['-'], ['-'], ['-'], [' -'], '( ', '( ', '( ')
return Balloon('\\', '/', '< ', ' >', [' _'], ['_'], ['_'], ['_'], ['_ '], ' \\', ' |', ' /', ['- '], ['-'], ['-'], ['-'], [' -'], '\\ ', '| ', '/ ')
map = {}
for elem in ('\\', '/', 'ww', 'ee', 'nw', 'nnw', 'n', 'nne', 'ne', 'nee', 'e', 'see', 'se', 'sse', 's', 'ssw', 'sw', 'sww', 'w', 'nww'):
map[elem] = []
balloonstream = None
try:
balloonstream = open(balloonfile, 'r')
data = [line.replace('\n', '') for line in balloonstream.readlines()]
finally:
if balloonstream is not None:
balloonstream.close()
last = None
for line in data:
if len(line) > 0:
if line[0] == ':':
map[last].append(line[1:])
else:
last = line[:line.index(':')]
value = line[len(last) + 1:]
map[last].append(value)
return Balloon(map['\\'][0], map['/'][0], map['ww'][0], map['ee'][0], map['nw'], map['nnw'], map['n'],
map['nne'], map['ne'], map['nee'][0], map['e'][0], map['see'][0], map['se'], map['sse'],
map['s'], map['ssw'], map['sw'], map['sww'][0], map['w'][0], map['nww'][0])
##
## Displaying methods
##
'''
Prints the name of the program and the version of the program
'''
def version(self):
print('%s %s' % ('ponysay', VERSION))
'''
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:
msg = ''.join(sys.stdin.readlines()).rstrip()
else:
msg = args.message
if args.opts['-c'] is not None: ## This algorithm should give some result as cowsay's (according to tests)
buf = ''
last = ' '
CHARS = '\t \n'
for c in msg:
if (c in CHARS) and (last in CHARS):
if last == '\n':
buf += last
last = c
else:
buf += c
last = c
msg = buf.strip(CHARS)
buf = ''
for c in msg:
if (c != '\n') or (last != '\n'):
buf += c
last = c
msg = buf.replace('\n', '\n\n')
pony = self.__getponypath(args.opts['-f'])
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])
pony = self.__kms(pony)
if linuxvt:
print('\033[H\033[2J', end='')
env_width = os.environ['PONYSAY_FULL_WIDTH'] if 'PONYSAY_FULL_WIDTH' in os.environ else None
if env_width is None: env_width = ''
widthtruncation = self.__gettermsize()[1] if env_width not in ('yes', 'y', '1') else None
messagewrap = int(args.opts['-W'][0]) if args.opts['-W'] is not None else None
balloon = self.__getballoon(self.__getballoonpath(args.opts['-b']))
backend = Backend(message = msg, ponyfile = pony, wrapcolumn = messagewrap if messagewrap is not None else 40, width = widthtruncation, balloon = balloon)
backend.parse()
output = backend.output
if (len(output) > 0) and (output[-1] == '\n'):
output = output[:-1]
env_bottom = os.environ['PONYSAY_BOTTOM'] if 'PONYSAY_BOTTOM' in os.environ else None
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: 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()[0] - int(env_lines)
if linuxvt or (env_height is ('yes', 'y', '1')):
if env_bottom is ('yes', 'y', '1'):
for line in output.split('\n')[: -lines]:
print(line)
else:
for line in output.split('\n')[: lines]:
print(line)
else:
print(output);
'''
Print the pony with a speech or though bubble and a self quote
'''
def quote(self, args):
pairs = self.__quotes()
if len(args.opts['-q']) > 0:
ponyset = {}
for pony in args.opts['-q']:
if (len(pony) > 5) and (pony[-5:] == '.pony'):
ponyname = pony[:-5]
if '/' in ponyname:
ponyname = ponyname[ponyname.rindex('/') + 1:]
ponyset[ponyname] = pony
else:
ponyset[pony] = pony
alts = []
for pair in pairs:
if pair[0] in ponyset:
alts.append((ponyset[pair[0]], pair[1]))
pairs = alts
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.opts['-f'] = [pair[0]]
elif len(args.opts['-q']) == 0:
sys.stderr.write('Princess Celestia! All the ponies are mute!\n')
exit(1)
else:
args.opts['-f'] = [args.opts['-q'][random.randrange(0, len(args.opts['-q']))]]
args.message = 'Zecora! Help me, I am mute!'
self.print_pony(args)
'''
Indentifies whether KMS support is utilised
'''
@staticmethod
def isUsingKMS():
if not linuxvt:
return False
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]
return env_kms != ''
'''
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
KMS_VERSION = '1'
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', '')
cachedir = '/var/cache/ponysay'
if not os.path.isdir(cachedir):
cachedir = HOME + '/.cache/ponysay'
if not os.path.isdir(cachedir):
os.makedirs(cachedir)
newversion = False
if not os.path.isfile(cachedir + '/.version'):
newversion = True
else:
cachev = None
try:
cachev = open(cachedir + '/.version', 'r')
if ''.join(cachev.readlines()) == KMS_VERSION:
newversion = True
finally:
if cachev is not None:
cachev.close()
if newversion:
for cached in os.listdir(cachedir):
cached = cachedir + '/' + cached
if os.path.isdir(cached) and not os.path.islink(cached):
shutil.rmtree(cached, False)
else:
os.remove(cached)
cachev = None
try:
cachev = open(cachedir + '/.version', 'w+')
cachev.write(KMS_VERSION)
finally:
if cachev is not None:
cachev.close()
kmsponies = cachedir + '/kmsponies/' + palettefile
kmspony = (kmsponies + pony).replace('//', '/')
if not os.path.isfile(kmspony):
protokmsponies = cachedir + '/protokmsponies/'
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):
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)
if not os.path.isdir(kmsponydir):
os.makedirs(kmsponydir)
if not os.system('tty2colourfultty -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
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, None, 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, arg, help = None):
self.__arguments.append((ARGUMENTED, alternatives, arg, 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, arg, help = None):
self.__arguments.append((VARIADIC, alternatives, arg, 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
'''
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()
'''
Balloon format class