-
Notifications
You must be signed in to change notification settings - Fork 2
/
dragonsuite.py
1840 lines (1545 loc) · 65 KB
/
dragonsuite.py
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 python3
# -*- coding: utf-8 -*-
'''
spike – a package manager running on top of git
Copyright © 2012, 2013, 2014 Mattias Andrée ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import sys
import os
import re as regex
import grp as groupmodule
import pwd as usermodule
from subprocess import Popen, PIPE
'''
Dragon Suite
A collection of utilities mimicing standard unix commands, however not full-blown
'''
_dragonsuite_directory_stack = []
'''
Keeps track of `pushd`:s
'''
_dragonsuite_verbose = True
'''
Whether to be verbose
'''
_dragonsuite_output = None
'''
Output channel for dragonsuite
'''
def __print(text):
'''
Print what is happening
@param text:__str__()→str The string to print
'''
if _dragonsuite_output is not None:
_dragonsuite_output.write(('\033[34m' + str(text) + '\033[00m\n').encode('utf-8'))
_dragonsuite_output.flush()
def pipe(data, *commands):
'''
Process data through a filter pipeline
@param data:? Input data
@param commands:*(?)→? List of functions
@return :? Output data
'''
if (len(commands) == 1) and (isinstance(commands[0], list) or isinstance(commands[0], tuple)):
commands = commands[0]
rc = data
for command in commands:
rc = command(rc)
return rc
def basename(path):
'''
Strip the directory form one or more filenames
@param path:str|itr<str> A filename or a list, or otherwise iteratable, of filenames
@return :str|list<str> The filename strip, or if multiple, a list of stripped filenames
'''
if isinstance(path, str):
return path[path.rfind(os.sep) + 1:] if os.sep in path else path
else:
return [(p[p.rfind(os.sep) + 1:] if os.sep in p else p) for p in path]
def dirname(path):
'''
Strip last component from one or more filenames
@param path:str|itr<str> A filename or a list, or otherwise iteratable, of filenames
@return :str|list<str> The filename strip, or if multiple, a list of stripped filenames
'''
def _dirname(p):
if os.sep in p[:-1]:
rc = p[:p[:-1].rfind(os.sep)]
return rc[:-1] if p.endswith(os.sep) else rc
else:
return '.'
if isinstance(path, str):
return _dirname(path)
else:
return [_dirname(p) for p in path]
def uniq(items, is_sorted = True):
'''
Remove duplicates
@param items:itr<¿E?> An iteratable of items
@param is_sorted:bool Whether the items are already sorted, otherwise a standard sort is preform
@return :list<¿E?> A list with the input items but without duplicates
'''
if len(items) == 0:
return []
rc = [items[0]]
last = items[0]
sorteditems = items if is_sorted else sorted(items)
for item in sorteditems:
if item != last:
rc.append(item)
last = item
return rc
def sort(items, reverse = True):
'''
Sort a list of items
@param items:list<¿E?> Unsorted list of items
@param reverse:bool Whether to sort in descending order
@return :list<¿E?> Sort list of items
'''
return sorted(items, reverse = reverse)
def tac(items):
'''
Reverse a list of items
@param items:list<¿E?> The list of items
@return :list<¿E?> The list of items in reversed order
'''
return reversed(items)
def readlink(path):
'''
Gets the file one or more link is directly pointing to, this is not the realpath, but if
you do this recursively you should either get the realpath or get stuck in an infinite loop
@param path:str|itr<str> A filename or a list, or otherwise iteratable, of filenames
@return :str|list<str> The filename strip, or if multiple, a list of stripped filenames
'''
if isinstance(path, str):
return os.readlink(path)
else:
return [os.readlink(p) for p in path]
def cut(items, delimiter, fields, complement = False, only_delimited = False, output_delimiter = None):
'''
Remove sections of items by delimiters
@param items:itr<str> The items to modify
@param delimiter:str Delimiter
@param fields:int|list<int> Fields to join, in joining order
@param complement:bool Join the fields as in order when not in `fields`
@param only_delimited:bool Whether to remove items that do not have the delimiter
@param output_delimiter:str? Joiner, set to same as delimiter if `None`
@return :list<str> The items after the modification
'''
rc = []
od = delimiter if output_delimiter is None else output_delimiter
f = fields if isinstance(fields, list) else [fields]
if complement:
f = set(f)
for item in items:
if only_delimited and delimiter not in item:
continue
item = item.split(delimiter)
if complement:
x = []
for i in range(0, len(item)):
if i not in f:
x.append(item[x])
item = x
else:
item = [item[i] for i in f]
rc.append(od.join(item))
return rc
def cat(files, encoding = None):
'''
Read one or more files and create a list of all their combined LF lines in order
@param files:str|itr<str> The file or files to read
@param encoding:str? The encoding to use, default if `None`
@return :list<str> All lines in all files
'''
rc = []
mode = 'r' if encoding is None else 'rb'
fs = [files] if isinstance(files, str) else files
for f in fs:
with open(f, mode):
if encoding is None:
rc += f.read().split('\n')
else:
rc += f.read().encode(encoding, 'replace').split('\n')
return rc
def pwd():
'''
Gets the current working directory
@return :str The current working directory
'''
return os.getcwd()
def cd(path):
'''
Changes the current working directory
@param path:str The new current working directory
'''
__print('cd ' + path)
os.chdir(path)
def pushd(path):
'''
Stores the current working directory in a stack change it
@param path:str The new current working directory
'''
__print('pushd ' + path)
_dragonsuite_directory_stack.append(os.path.abspath(os.getcwd()))
os.chdir(path)
def popd():
'''
Changes the current working directory to the one in the top of the `pushd` stack and pop it
'''
__print('popd')
os.chdir(_dragonsuite_directory_stack.pop())
def umask(mask = 0o22):
'''
Sets the current umask and return the previous umask
@param mask:int The new umask
@return :int The previous umask
'''
__print('umask ' + oct(mask).replace('0o', ''))
return os.umask(mask)
def comm(list1, list2, mode):
'''
Compare two list
@param list1:itr<¿E?> The first list
@param list2:itr<¿E?> The second list
@param mode:int 0: Keep elements that do not appear in both lists
1: Keep elements that only appear in the first list
2: Keep elements that only appear in the second list
3: Keep elements that only appear in both lists
@return :list<¿E?> The result it will be sorted and contain no duplicates
'''
items = [(e, 1) for e in list1] + [(e, 2) for e in list2]
items = sorted(rc, key = lambda x : x[0])
last = items[0]
(rc, tmp) = ([], [])
for item in items:
if item[0] == last[0]:
tmp.pop()
tmp.append((item[0], item[1] | last[1]))
else:
tmp.append(item)
mode0 = mode == 0;
for item in tmp:
if item[1] == mode:
rc.append(item[0])
elif mode0 and item[1] != 3:
rc.append(item[0])
return rc
def unset(var):
'''
Deletes an environment variable
@param var:str The environment variable
'''
__print('unset ' + var)
os.unsetenv(var)
if var in os.environ:
del os.environ[var]
def export(var, value):
'''
Sets an environment variable
@param var:str The environment variable
@param value:str? The environment variable's new value, deletes it if `None`
'''
if value is None:
unset(var)
else:
__print('export %s=%s' % (var, value))
os.putenv(var, value)
if var not in os.environ or os.environ[var] != value:
os.environ[var] = value
def defvar(var, value):
'''
Sets an environment variable to a default value if it is empty or non-existant
@param var:str The environment variable
@param value:str The environment variable's default value
'''
if get(var, '') == '':
export(var, value)
def get(var, default = ''):
'''
Gets an environment variable
@param var:str The environment variable
@param default:str? Default value to use if not defined
@return :str? The environment variable's value
'''
return os.getenv(var, default)
def which(command):
'''
Locates file in PATH
@param file:str The file to locate
@return :str? The location of the file, `None` if not found
'''
PATH = get('PATH').split(':')
for p in PATH:
if len(p) > 0:
f = '%s/%s' % (p, command)
if os.path.exists(f):
return f
return None
def chmod(path, mode, mask = ~0):
'''
Changes the protection bits of one or more files
@param path:str|itr<str> The file or files
@param mode:int The desired protection bits
@param mask:int The portions of `mode` to apply
'''
__print('chmod %s~%s %s' % (oct(mode).replace('0o', ''), oct(~mask).replace('0o', ''), str(path)))
for p in ([path] if isinstance(path, str) else path):
if mask == ~0:
os.chmod(p, mode)
else:
cur = os.lstat(path).st_mode
os.chmod(p, mode | (cur & ~mask))
def chown(path, owner = -1, group = -1):
'''
Changes the owner or group of one or more files
@param path:str|itr<str> The file or files
@param owner:int|str The new owner, `-1` for ignored
@param group:int|str The new group, `-1` for ignored, `-2` to select by owner
'''
__print('lchown %s:%s %s' % (str('' if isinstance(owner, int) and (owner == -1) else owner), str(('' if group == -1 else ('$' if group == -2 else group)) if isinstance(group, int) else group), str(path)))
u = owner if isinstance(owner, int) else usermodule.getpwnam(owner).pw_uid
g = group if isinstance(group, int) else groupmodule.getgrnam(group).gr_gid
for p in ([path] if isinstance(path, str) else path):
os.lchown(p, u, usermodule.getpwuid(os.lstat(path).st_uid).pw_gid if g == -2 else g)
def chgrp(path, group):
'''
Changes the group of one or more files
@param path:str|itr<str> The file or files
@param group:int|str The new group
'''
chown(path, group = group)
def ln_s(source, link, parents = False):
'''
Create a symbolic link
@param source:str The target of the new link
@param link:str The path of the new link
@param parents:bool Create missing parent directories
'''
ln(source, link, hard = False, parents = parents)
def ln(source, link, hard = False, parents = False):
'''
Create a symbolic or hard link
@param source:str The target of the new link
@param link:str The path of the new link
@param hard:bool Whether to create a hard link
@param parents:bool Create missing parent directories
'''
if os.path.lexists(link) and os.path.isdir(link):
link += os.sep + basename(source)
elif parents and not os.path.lexists(link):
parent = dirname(link)
if not os.path.lexists(parent):
mkdir_p(parent)
if hard:
__print('ln --hard %s %s' % (source, link))
os.link(source, link)
else:
__print('ln --symbolic %s %s' % (source, link))
if os.path.lexists(link) and os.path.islink(link):
if os.readlink(link) == source:
return
os.symlink(source, link)
def touch(path, settime = False, parents = False):
'''
Create one or more files if missing
@param path:str|itr<str> The file of files
@param settime:bool Whether to set the timestamps on the files if they already exists
@param parents:bool Create missing parent directories
'''
__print('touch %s' + str(path))
for p in ([path] if isinstance(path, str) else path):
if parents:
if not os.path.lexists(path):
parent = dirname(path)
if not os.path.lexists(parent):
mkdir_p(parent)
if os.path.lexists(p):
if settime:
os.utime(p, None)
else:
open(p, 'a').close()
def rm(path, recursive = False, directories = False):
'''
Remove one or more file
@param path:str|itr<str> Files to remove
@param recursive:bool Remove directories recursively
@param directories:bool Attempt to remove directories with rmdir, this is forced for recursive removes
'''
__print(('rm -r' if recursive else 'rm') + (' ' if directories else ' --directories ') + str(path))
for p in ([path] if isinstance(path, str) else path):
if not recursive:
if directories and os.path.isdir(p):
os.rmdir(p)
elif get('shred', None) is not None:
execute(get('shred').split(' ') + [p], fail = True)
else:
os.remove(p)
else:
rm(tac(find(p)), directories = True)
def rm_r(path):
'''
Remove a file or recursively a directory, multile are also possible
@param path:str|itr<str> The files to remove
'''
rm(path, recursive = True)
def rmdir(path):
'''
Remove one or more directories
@param path:str|itr<str> The directories to remove
'''
__print('rmdir' + str(path))
for p in ([path] if isinstance(path, str) else path):
os.rmdir(p)
def mkdir(path, recursive = False):
'''
Create one or more directories, it will not fail if the path already exists and is a directory
@param path:str|itr<str> The directories to create
@param recursive:bool Whether to create all missing intermediate-level directories
'''
__print('mkdir' + (' -p ' if recursive else ' ') + str(path))
for p in ([path] if isinstance(path, str) else path):
if not recursive:
if not (os.path.lexists(p) and os.path.isdir(p)):
os.mkdir(p)
else:
ps = p.split(os.sep)
pp = ps[0]
if len(pp) > 0:
if not (os.path.lexists(pp) and os.path.isdir(pp)):
os.mkdir(pp)
for _p in ps[1:]:
pp += os.sep + _p
if not (os.path.lexists(pp) and os.path.isdir(pp)):
os.mkdir(pp)
def mkdir_p(path):
'''
Create on ore more directories, and create all missing intermediate-level directories
@param path:str|itr<str> The directories to create
'''
mkdir(path, recursive = True)
def mkcd(path, recursive = False):
'''
Create a directory and `cd` into it, it will not fail if the path already exists and is a directory
@param path:str The directory to create and move into
@param recursive:bool Whether to create all missing intermediate-level directories
'''
mkdir(path, recursive)
cd(path)
def git(*params):
'''
Execute git
@param params:*str Arguments for the command
'''
if (len(params) == 1) and (isinstance(params[0], list) or isinstance(params[0], tuple)):
params = params[0]
execute(['git'] + list(params), fail = True)
def curl(*params):
'''
Execute curl
@param params:*str Arguments for the command
'''
if (len(params) == 1) and (isinstance(params[0], list) or isinstance(params[0], tuple)):
params = params[0]
execute(['curl'] + list(params), fail = True)
def wget(*params):
'''
Execute wget
@param params:*str Arguments for the command
'''
if (len(params) == 1) and (isinstance(params[0], list) or isinstance(params[0], tuple)):
params = params[0]
execute(['wget'] + list(params), fail = True)
def make(*params):
'''
Execute make
@param params:*str Arguments for the command
'''
if (len(params) == 1) and (isinstance(params[0], list) or isinstance(params[0], tuple)):
params = params[0]
execute(['make'] + list(params), fail = True)
def rename(path, expression, replacement):
'''
Rename multiple files with a pattern using util-linux's command rename
@param path:str|list<str> File or files to rename
@param expression:str Matching expression
@param replacement:str Replacement
'''
files = [path] if isinstance(path, str) else path
execute(['rename', '--', expression, replacement] + files, fail = True)
def upx(path, level = 8, overlay = 1, brute = 0):
'''
Compress one or more files using the command upx
@param path:str|list<str> The files to compress
@param level:int Compression level, [1; 10], 10 for --best
@param overlay:int 0: --overlay=skip
1: --overlay=copy
2: --overlay=strip
@param brute:int 0: no addition parameter
1: --brute
2: --ultra-brute
'''
params = ['upx', '-%i' % level if level < 10 else '--best']
if overlay == 0: params += ['--overlay=skip']
if overlay == 2: params += ['--overlay=strip']
if brute == 1: params += ['--brute']
if brute == 2: params += ['--ultra-brute']
paths = [path] if isinstance(path, str) else path
params += ['--'] + paths
sticky = []
for p in paths:
if (os.stat(p).st_mode & 0o1000) == 0o1000:
sticky.append(p)
# Remove sticky bit from command so UPX will not complain
chmod(p, 0, 0o1000)
execute(params, fail = False)
for p in sticky:
# Resetting sticky bit so the command is preserved in swap space
chmod(p, 0o1000, 0o1000)
def strip(path, *params):
'''
Strip symbols from binaries and libraries using the command strip
@param path:str|list<str> The files to compress
@param params:*str Arguments for strip
'''
if (len(params) == 1) and (isinstance(params[0], list) or isinstance(params[0], tuple)):
params = params[0]
cmd = ['strip'] + list(params) + (['--', path] if isinstance(path, str) else (['--'] + path))
execute(cmd, fail = False)
def install_info(path, infodir = None):
'''
Update info/dir entries
@param path:str|list<str> New or updated entries
@param infodir:str? Directory for info manuals
'''
if infodir is None:
infodir = get('infodir', '%susr%sshare%sinfo%s' % (os.sep, os.sep, os.sep, os.sep))
infodir = get('PINPAL') + infodir
if infodir.endswith(os.sep):
infodir += 'dir'
else:
infodir += os.sep + 'dir'
for p in ([path] if isinstance(path, str) else path):
execute(['install-info', '--dir-file', infodir, '--', p], fail = False)
def uninstall_info(path, infodir = None):
'''
Delete info/dir entries
@param path:str|list<str> Removed entries
@param infodir:str? Directory for info manuals
'''
if infodir is None:
infodir = get('infodir', '%susr%sshare%sinfo%s' % (os.sep, os.sep, os.sep, os.sep))
infodir = get('PINPAL') + infodir
if infodir.endswith(os.sep):
infodir += 'dir'
else:
infodir += os.sep + 'dir'
for p in ([path] if isinstance(path, str) else path):
execute(['install-info', '--delete', '--dir-file', infodir, '--', p], fail = False)
def mv(source, destination, parents = False, cleanup = False):
'''
Move one or more files
@param source:str|itr<str> The files to move
@param destination:str The destination, either directory or new file
@param parents:bool Create missing parent directories
@param cleanup:bool Remove the parent of the source file if its gets empty
'''
def mv_(src, dest):
if parents:
if not os.path.lexists(dest):
parent = dirname(dest)
if not os.path.lexists(parent):
mkdir_p(parent)
os.rename(src, dest)
if cleanup:
src = dirname(src)
if os.path.lexists(src) and os.path.isdir(src):
if len(os.listdir(src)) == 0:
if os.path.islink(src):
rm(src)
else:
rmdir(src)
__print('mv %s %s' % (str(source), destination))
ps = [source] if isinstance(source, str) else source
d = destination if destination.endswith(os.sep) else (destination + os.sep)
if len(ps) == 1:
if os.path.lexists(destination) and os.path.isdir(destination):
os.rename(source, d + basename(source))
else:
mv_(source, destination)
else:
if not os.path.lexists(destination):
raise OSError('Destination %s does not exist but must be a directory' % destination)
elif not os.path.isdir(destination):
raise OSError('Destination %s exists and is not a directory' % destination)
else:
for p in ps:
mv_(p, d + basename(p))
def echo(text, newline = True, stderr = False):
'''
Display a line of text
@param text:str|list<str> The text
@param newline:bool Whether to end with a line break
@param stderr:bool Whether to print to stderr
'''
s = sys.stdout.buffer if not stderr else sys.stderr.buffer
if isinstance(text, str):
s.write((text + ('\n' if newline else '')).encode('utf-8'))
else:
s.write(('\n'.join(text) + ('\n' if newline else '')).encode('utf-8'))
def msg(text, submessage = False):
'''
Display status message
@param text:str The message
@param submessage:bool Whether this is a submessage
'''
message = '\033[01;3%im%s\033[00;01m %s\033[00m\n'
message %= (2, ' -->', text) if submessage else (4, '==>', text)
sys.stdout.buffer.write(message.encode('utf-8'))
def cp(source, destination, recursive = True):
'''
Copies files and directories, note that you can do so much more with GNU ocreutils's cp
@param source:str|itr<str> Files to copy
@param destination:str Destination filename or directory
'''
install(source, destination, parents = False, recursive = recursive, savemode = True)
def cp_r(source, destination):
'''
Copies files and directories, recursively
@param source:str|itr<str> Files to copy
@param destination:str Destination filename or directory
'''
cp(source, destination, True)
def install(source, destination, owner = -1, group = -1, mode = -1, strip = False, directory = False, parents = True, recursive = True, savemode = True):
'''
Copies files and set attributes
@param source:str|itr<str> Files to copy
@param destination:str Destination filename or directory
@param owner:int|str The new owner, `-1` for preserved
@param group:int|str The new group, `-1` for preserved, `-2` to select by owner
@param mode:int The desired protection bits, `-1` for preserved
@param strip:bool Whether to strip symbol table
@param directory:bool Whether treat all source files is directory names
@param parents:bool Whether create missing directories
@param recursive:bool Copy directories resursively
@param savemode:bool Whether to use the protection bits of already installed versions
'''
_print_info = (destination,
' -D' if parents else '',
' -r' if recursive else '',
' -s' if strip else '',
' --savemode' if savemode else '',
('' if mode == -1 else (' -m ' + oct(mode).replace('0o', ''))) if isinstance(mode, int) else (' -m ' + mode),
('' if owner == -1 else (' -u ' + str(owner))) if isinstance(owner, int) else (' -u ' + owner),
('' if group == -1 else (' -g $' if group == -2 else (' -g ' + str(group)))) if isinstance(group, int) else (' -g ' + group),
' -d' if directory else '',
str(source))
__print('install -T %s%s%s%s%s%s%s%s%s %s' % _print_info)
ps = [source] if isinstance(source, str) else source
d = destination if destination.endswith(os.sep) else (destination + os.sep)
pairs = None
if len(ps) == 1:
if os.path.lexists(destination) and os.path.isdir(destination):
if directory:
pairs = [(s, d + s) for s in ps]
else:
pairs = [(s, d + basename(s)) for s in ps]
else:
pairs = [(s, destination) for s in ps]
else:
if not os.path.lexists(destination):
if parents:
mkdir_p(destination)
else:
raise OSError('Destination %s does not exist but must be a directory' % destination)
elif not os.path.isdir(destination):
raise OSError('Destination %s exists and is not a directory' % destination)
if directory:
pairs = [(p, d + p) for p in ps]
else:
pairs = [(p, d + basename(p)) for p in ps]
for (src, dest) in pairs:
protection = mode
if savemode and os.path.lexists(dest):
protection = os.lstat(dest).st_mode
elif isinstance(mode, int) and (mode < 0):
protection = 0o755 if directory else os.lstat(src).st_mode
if directory or os.path.isdir(src):
if parents:
mkdir_p(dest)
else:
mkdir(dest)
elif os.path.islink(src):
ln(os.readlink(src), dest)
else:
blksize = 8192
try:
blksize = os.stat(os.path.realpath(ifile)).st_blksize
except:
pass
with open(src, 'rb') as ifile:
if parents and not os.path.lexists(dirname(dest)):
mkdir_p(dirname(dest))
with open(dest, 'wb') as ofile:
while True:
chunk = ifile.read(blksize)
if len(chunk) == 0:
break
ofile.write(chunk)
(u, g) = (owner, group)
if (isinstance(u, str) or (u != -1) or isinstance(g, str) or (g != -1)):
stat = os.lstat(dest) if directory else os.lstat(src)
u = u if isinstance(u, str) or (u != -1) else stat.st_uid
g = g if isinstance(g, str) or (g != -1) else stat.st_gid
chown(dest, u, g)
if not os.path.islink(dest):
os.chmod(dest, protection)
if strip and not directory:
strip(dest)
if recursive and os.path.isdir(src) and not directory:
d = src if src.endswith(os.sep) else (src + os.sep)
sources = [d + f for f in os.listdir(d)]
install(sources, dest, owner, group, mode, strip, False, False, True, savemode)
def find(path, maxdepth = -1, hardlinks = True):
'''
Gets all existing subfiles, does not follow links including hardlinks
@param path:str|itr<str> Search root or roots
@param maxdepth:int Maximum search depth, `-1` for unbounded
@param hardlinks:bool Whether to list all files with same inode number rather than just the first
@return :list<str> Found files
'''
rc = []
visited = set()
stack = [path] if isinstance(path, str) else path
stack = [(e, 0) for e in stack]
while len(stack) > 0:
(f, d) = stack.pop()
if os.path.lexists(f):
f = f if not f.endswith(os.sep) else f[:-1]
if (not os.path.islink(f)) and os.path.isdir(f):
inode = os.lstat(f).st_ino
if inode not in visited:
visited.add(inode)
f += os.sep
if d != maxdepth:
d += 1
for sf in sorted(os.listdir(f)):
stack.append((f + sf, d))
elif not hardlinks:
continue
elif not hardlinks:
inode = os.lstat(f).st_ino
if inode in visited:
continue
visited.add(inode)
rc.append(f)
return rc
def l(elements):
'''
Encapsulates string and integers in lists and converts iteratables to lists
@param elements:¿E?=str|¿E?=list|itr<¿E?> The elements to make sure they are in a list
@return elements:list<¿E?> The elements in a list
'''
if isinstance(elements, str) or isinstance(elements, int):
return [elements]
return list(elements)
def path_escape(*filename):
'''
Escape a filename for dynamic include in a `path` expression without the risk of it being parsed as an expression, but rather be verbatim
@param filename:*str The filename or filenames
@return :str|tuple<str> The filename or filenames escaped, will be a list if a list or other iteratable type was used in the paramter
'''
if len(filename) == 1:
filename = filename[0]
files = [filename] if isinstance(filename, str) else filename
rc = []
for file in files:
for c in '\\.^+$[]|(){}*?@~':
file = file.replace(c, '\\' + c)
rc.append(file)
if isinstance(filename, str):
return rc[0]
else:
return tuple(rc)
def path(exprs, existing = False):
'''
Gets files matching a pattern, and expand ~
Here => Regular expression
{a,b,c} => (a|b|c)
{a..g} => [ag]
{1..11} => (1|2|3|4|5|6|7|8|9|10|11)
* => .*
? => .
TODO: add other expressions but for alternative function epath:
[abc] => (a|b|c)
[a-g] => [ag]
[a-zA-Z] => ([az]|[AZ])
?(a) => (a|)
@(a|b|c) => (a|b|c)
However they are only expanded if matched to an file
Everything else is matched verbosely and the matching is closed (regex: ^pattern$),
and \ is used to escape characters do that they are matched verbosely instead of
getting a special meaning.
Ending the pattern with / specified that it should be a directory.
@param exprs:str|itr<str> Expressions
@param existing:bool Whether to only match to existing files
@return :str|list<str> Matching files
'''
def __(expr):
ps = ['']
esc = False
buf = ''
d = 0
for c in expr.replace('\0', '').replace('/', ('\\' if os.sep in '?*{},.\\' else '') + os.sep):
if esc:
esc = False
if d > 0:
buf += '\\'
buf += c
elif c == '\\': esc = True
elif c == '?': buf += '\0?' if d == 0 else '?'
elif c == '*': buf += '\0*' if d == 0 else '*'
elif c == ',': buf += '\0,' if d == 1 else ','
elif c == '.': buf += '\0.' if d == 1 else '.'
elif c == '{':
if d == 0:
ps = [p + buf for p in ps]
buf = ''
else:
buf += '{'
d += 1
elif c == '}':
if d == 1:
flatten = [__(tp) for tp in buf.split('\0,')]
t = []
for f in flatten:
t += f
pz = []
for a in ps:
for b in t:
if '\0.' not in b:
pz.append(a + b)