-
Notifications
You must be signed in to change notification settings - Fork 130
/
main.py
executable file
·3097 lines (2721 loc) · 105 KB
/
main.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
"""Implement a remote shell which talks to a MicroPython board.
This program uses the raw-repl feature of the pyboard to send small
programs to the pyboard to carry out the required tasks.
"""
# Take a look at https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/
# to see if we can use those ideas here.
# from __future__ import print_function
# To run rshell from the git repository, cd into the top level rshell directory
# and run:
# python3 -m rshell.main
#
# that sets things up so that the "from rshell.xxx" will import from the git
# tree and not from some installed version.
import sys
try:
from rshell.getch import getch
from rshell.pyboard import Pyboard, PyboardError
from rshell.version import __version__
except ImportError as err:
print('sys.path =', sys.path)
raise err
if sys.platform == 'win32':
# This is a workaround for Windows 10/Python 3.7, that allows the colorized output to
# work. See: https://stackoverflow.com/questions/12492810/python-how-can-i-make-the-ansi-escape-codes-to-work-also-in-windows
import subprocess
subprocess.call('', shell=True)
import argparse
import binascii
import calendar
import cmd
import inspect
import io
import fnmatch
import os
import re
import select
import serial
import shutil
import socket
import tempfile
import time
import threading
import token
import tokenize
import shlex
import itertools
from serial.tools import list_ports
import traceback
if sys.platform == 'win32':
EXIT_STR = 'Use the exit command to exit rshell.'
else:
EXIT_STR = 'Use Control-D (or the exit command) to exit rshell.'
# I got the following from: http://www.farmckon.net/2009/08/rlcompleter-how-do-i-get-it-to-work/
# Under OSX, if you call input with a prompt which contains ANSI escape
# sequences for colors, and readline is installed, then the escape sequences
# do not get rendered properly as colors.
#
# One solution would be to not use readline, but then you'd lose TAB completion.
# So I opted to print the colored prompt before calling input, which makes
# things work most of the time. If you try to backspace when at the first
# column of the input it wipes out the prompt, but everything returns to normal
# if you hit return.
BROKEN_READLINE = True
FAKE_INPUT_PROMPT = False
import readline
import rlcompleter
if readline.__doc__ and 'libedit' in readline.__doc__:
readline.parse_and_bind ("bind ^I rl_complete")
BROKEN_READLINE = True
else:
readline.parse_and_bind("tab: complete")
MONTH = ('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
# Attributes
# 0 Reset all attributes
# 1 Bright
# 2 Dim
# 4 Underscore
# 5 Blink
# 7 Reverse
# 8 Hidden
LT_BLACK = "\x1b[1;30m"
LT_RED = "\x1b[1;31m"
LT_GREEN = "\x1b[1;32m"
LT_YELLOW = "\x1b[1;33m"
LT_BLUE = "\x1b[1;34m"
LT_MAGENTA = "\x1b[1;35m"
LT_CYAN = "\x1b[1;36m"
LT_WHITE = "\x1b[1;37m"
DK_BLACK = "\x1b[2;30m"
DK_RED = "\x1b[2;31m"
DK_GREEN = "\x1b[2;32m"
DK_YELLOW = "\x1b[2;33m"
DK_BLUE = "\x1b[2;34m"
DK_MAGENTA = "\x1b[2;35m"
DK_CYAN = "\x1b[2;36m"
DK_WHITE = "\x1b[2;37m"
NO_COLOR = "\x1b[0m"
BG_LT_BLACK = "\x1b[1;40m"
BG_LT_RED = "\x1b[1;41m"
BG_LT_GREEN = "\x1b[1;42m"
BG_LT_YELLOW = "\x1b[1;43m"
BG_LT_BLUE = "\x1b[1;44m"
BG_LT_MAGENTA = "\x1b[1;45m"
BG_LT_CYAN = "\x1b[1;46m"
BG_LT_WHITE = "\x1b[1;47m"
BG_DK_BLACK = "\x1b[2;40m"
BG_DK_RED = "\x1b[2;41m"
BG_DK_GREEN = "\x1b[2;42m"
BG_DK_YELLOW = "\x1b[2;43m"
BG_DK_BLUE = "\x1b[2;44m"
BG_DK_MAGENTA = "\x1b[2;45m"
BG_DK_CYAN = "\x1b[2;46m"
BG_DK_WHITE = "\x1b[2;47m"
DIR_COLOR = LT_CYAN
PROMPT_COLOR = LT_GREEN
PY_COLOR = DK_GREEN
END_COLOR = NO_COLOR
cur_dir = ''
HAS_BUFFER = False
IS_UPY = False
DEBUG = False
USB_BUFFER_SIZE = 512
RPI_PICO_USB_BUFFER_SIZE = 32
UART_BUFFER_SIZE = 32
BUFFER_SIZE = USB_BUFFER_SIZE
QUIET = False
RTS = ''
DTR = ''
# It turns out that just because pyudev is installed doesn't mean that
# it can actually be used. So we only bother to try if we're running
# under linux.
#
# When running under WSL, sys.platform returns 'linux' so we do a further check
# on 'Microsoft' in platform.uname().release to detect if we're running under WSL.
# Currently, there is no serial port enumeration availbale under WSL.
import platform
USE_AUTOCONNECT = sys.platform == 'linux' and 'Microsoft' not in platform.uname().release
SIX_MONTHS = 183 * 24 * 60 * 60
QUIT_REPL_CHAR = 'X'
QUIT_REPL_BYTE = bytes((ord(QUIT_REPL_CHAR) - ord('@'),)) # Control-X
# DELIMS is used by readline for determining word boundaries.
DELIMS = ' \t\n>;'
TIME_OFFSET = 0
DEVS = []
DEFAULT_DEV = None
DEV_IDX = 1
DEV_LOCK = threading.RLock()
def add_device(dev):
"""Adds a device to the list of devices we know about."""
global DEV_IDX, DEFAULT_DEV
with DEV_LOCK:
for idx in range(len(DEVS)):
test_dev = DEVS[idx]
if test_dev.dev_name_short == dev.dev_name_short:
# This device is already in our list. Delete the old one
if test_dev is DEFAULT_DEV:
DEFAULT_DEV = None
del DEVS[idx]
break
if find_device_by_name(dev.name):
# This name is taken - make it unique
dev.name += '-%d' % DEV_IDX
dev.name_path = '/' + dev.name + '/'
DEVS.append(dev)
DEV_IDX += 1
if DEFAULT_DEV is None:
DEFAULT_DEV = dev
def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev
return None
def find_serial_device_by_port(port):
"""Tries to find a board by port name."""
with DEV_LOCK:
for dev in DEVS:
if dev.is_serial_port(port):
return dev
return None
def num_devices():
with DEV_LOCK:
return len(DEVS)
def is_micropython_usb_device(port):
"""Checks a USB device to see if it looks like a MicroPython device.
"""
if type(port).__name__ == 'Device':
# Assume its a pyudev.device.Device
if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or
'SUBSYSTEM' not in port or port['SUBSYSTEM'] != 'tty'):
return False
usb_id = 'usb vid:pid={}:{}'.format(port['ID_VENDOR_ID'], port['ID_MODEL_ID'])
else:
# Assume its a port from serial.tools.list_ports.comports()
usb_id = port[2].lower()
# We don't check the last digit of the PID since there are 3 possible
# values.
if usb_id.startswith('usb vid:pid=f055:980'):
return True
# Check Raspberry Pi Pico
if usb_id.startswith('usb vid:pid=2e8a:0005'):
global USB_BUFFER_SIZE
USB_BUFFER_SIZE = RPI_PICO_USB_BUFFER_SIZE
return True
# Check for Teensy VID:PID
if usb_id.startswith('usb vid:pid=16c0:0483'):
return True
# Check for LEGO Technic Large Hub
if usb_id.startswith('usb vid:pid=0694:0010'):
return True
return False
def is_micropython_usb_port(portName):
"""Checks to see if the indicated portname is a MicroPython device
or not.
"""
for port in serial.tools.list_ports.comports():
if port.device == portName:
return is_micropython_usb_device(port)
return False
def autoconnect():
"""Sets up a thread to detect when USB devices are plugged and unplugged.
If the device looks like a MicroPython board, then it will automatically
connect to it.
"""
if not USE_AUTOCONNECT:
return
try:
import pyudev
except ImportError:
return
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
connect_thread = threading.Thread(target=autoconnect_thread, args=(monitor,), name='AutoConnect')
connect_thread.daemon = True
connect_thread.start()
def autoconnect_thread(monitor):
"""Thread which detects USB Serial devices connecting and disconnecting."""
monitor.start()
monitor.filter_by('tty')
epoll = select.epoll()
epoll.register(monitor.fileno(), select.POLLIN)
while True:
try:
events = epoll.poll()
except InterruptedError:
continue
for fileno, _ in events:
if fileno == monitor.fileno():
usb_dev = monitor.poll()
print('autoconnect: {} action: {}'.format(usb_dev.device_node, usb_dev.action))
dev = find_serial_device_by_port(usb_dev.device_node)
if usb_dev.action == 'add':
# Try connecting a few times. Sometimes the serial port
# reports itself as busy, which causes the connection to fail.
for i in range(8):
if dev:
connected = connect_serial(dev.port, dev.baud, dev.wait)
elif is_micropython_usb_device(usb_dev):
connected = connect_serial(usb_dev.device_node)
else:
connected = False
if connected:
break
time.sleep(0.25)
elif usb_dev.action == 'remove':
print('')
print("USB Serial device '%s' disconnected" % usb_dev.device_node)
if dev:
dev.close()
break
def autoscan():
"""autoscan will check all of the serial ports to see if they have
a matching VID:PID for a MicroPython board.
"""
for port in serial.tools.list_ports.comports():
if is_micropython_usb_device(port):
connect_serial(port[0])
def extra_info(port):
"""Collects the serial nunber and manufacturer into a string, if
the fields are available."""
extra_items = []
if port.manufacturer:
extra_items.append("vendor '{}'".format(port.manufacturer))
if port.serial_number:
extra_items.append("serial '{}'".format(port.serial_number))
if port.interface:
extra_items.append("intf '{}'".format(port.interface))
if extra_items:
return ' with ' + ' '.join(extra_items)
return ''
def listports():
"""listports will display a list of all of the serial ports.
"""
detected = False
for port in serial.tools.list_ports.comports():
detected = True
if port.vid:
micropythonPort = ''
if is_micropython_usb_device(port):
micropythonPort = ' *'
print('USB Serial Device {:04x}:{:04x}{} found @{}{}\r'.format(
port.vid, port.pid,
extra_info(port), port.device, micropythonPort))
else:
print('Serial Device:', port.device)
if not detected:
print('No serial devices detected')
def escape(str):
"""Precede all special characters with a backslash."""
out = ''
for char in str:
if char in '\\ ':
out += '\\'
out += char
return out
def unescape(str):
"""Undoes the effects of the escape() function."""
out = ''
prev_backslash = False
for char in str:
if not prev_backslash and char == '\\':
prev_backslash = True
continue
out += char
prev_backslash = False
return out
def align_cell(fmt, elem, width):
"""Returns an aligned element."""
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem
def column_print(fmt, rows, print_func):
"""Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column may be a space which implies left
justification and no padding.
"""
# Figure out the max width of each column
num_cols = len(fmt)
width = [max(0 if isinstance(row, str) else len(row[i]) for row in rows)
for i in range(num_cols)]
for row in rows:
if isinstance(row, str):
# Print a separator line
print_func(' '.join([row * width[i] for i in range(num_cols)]))
else:
print_func(' '.join([align_cell(fmt[i], row[i], width[i])
for i in range(num_cols)]))
def find_macthing_files(match):
"""Finds all of the files which match (used for completion)."""
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
match_prefix = match
result_prefix = ''
else:
dirname = match[0:last_slash]
match_prefix = match[last_slash + 1:]
result_prefix = dirname + '/'
return [result_prefix + filename for filename in os.listdir(dirname) if filename.startswith(match_prefix)]
def print_err(*args, end='\n'):
"""Similar to print, but prints to stderr.
"""
print(*args, end=end, file=sys.stderr)
sys.stderr.flush()
def is_pattern(s):
"""Return True if a string contains Unix wildcard pattern characters.
"""
return not set('*?[{').intersection(set(s)) == set()
# Disallow patterns like path/t*/bar* because handling them on remote
# system is difficult without the glob library.
def parse_pattern(s):
"""Parse a string such as 'foo/bar/*.py'
Assumes is_pattern(s) has been called and returned True
1. directory to process
2. pattern to match"""
if '{' in s:
return None, None # Unsupported by fnmatch
if s and s[0] == '~':
s = os.path.expanduser(s)
parts = s.split('/')
absolute = len(parts) > 1 and not parts[0]
if parts[-1] == '': # # Outcome of trailing /
parts = parts[:-1] # discard
if len(parts) == 0:
directory = ''
pattern = ''
else:
directory = '/'.join(parts[:-1])
pattern = parts[-1]
if not is_pattern(directory): # Check for e.g. /abc/*/def
if is_pattern(pattern):
if not directory:
directory = '/' if absolute else '.'
return directory, pattern
return None, None # Invalid or nonexistent pattern
def validate_pattern(fn):
"""On success return an absolute path and a pattern.
Otherwise print a message and return None, None
"""
directory, pattern = parse_pattern(fn)
if directory is None:
print_err("Invalid pattern {}.".format(fn))
return None, None
target = resolve_path(directory)
mode = auto(get_mode, target)
if not mode_exists(mode):
print_err("cannot access '{}': No such file or directory".format(fn))
return None, None
if not mode_isdir(mode):
print_err("cannot access '{}': Not a directory".format(fn))
return None, None
return target, pattern
def process_pattern(fn):
"""Return a list of paths matching a pattern (or None on error).
"""
directory, pattern = validate_pattern(fn)
if directory is not None:
filenames = fnmatch.filter(auto(listdir, directory), pattern)
if filenames:
return [directory + '/' + sfn for sfn in filenames]
else:
print_err("cannot access '{}': No such file or directory".format(fn))
def resolve_path(path):
"""Resolves path and converts it into an absolute path."""
if path[0] == '~':
# ~ or ~user
path = os.path.expanduser(path)
if path[0] != '/':
# Relative path
if cur_dir[-1] == '/':
path = cur_dir + path
else:
path = cur_dir + '/' + path
comps = path.split('/')
new_comps = []
for comp in comps:
# We strip out xxx/./xxx and xxx//xxx, except that we want to keep the
# leading / for absolute paths. This also removes the trailing slash
# that autocompletion adds to a directory.
if comp == '.' or (comp == '' and len(new_comps) > 0):
continue
if comp == '..':
if len(new_comps) > 1:
new_comps.pop()
else:
new_comps.append(comp)
if len(new_comps) == 1 and new_comps[0] == '':
return '/'
return '/'.join(new_comps)
def get_dev_and_path(filename):
"""Determines if a given file is located locally or remotely. We assume
that any directories from the pyboard take precedence over local
directories of the same name. /flash and /sdcard are associated with
the default device. /dev_name/path where dev_name is the name of a
given device is also considered to be associated with the named device.
If the file is associated with a remote device, then this function
returns a tuple (dev, dev_filename) where dev is the device and
dev_filename is the portion of the filename relative to the device.
If the file is not associated with the remote device, then the dev
portion of the returned tuple will be None.
"""
if DEFAULT_DEV:
if DEFAULT_DEV.is_root_path(filename):
return (DEFAULT_DEV, filename)
test_filename = filename + '/'
with DEV_LOCK:
for dev in DEVS:
if test_filename.startswith(dev.name_path):
dev_filename = filename[len(dev.name_path)-1:]
if dev_filename == '':
dev_filename = '/'
return (dev, dev_filename)
return (None, filename)
def remote_repr(i):
"""Helper function to deal with types which we can't send to the pyboard."""
repr_str = repr(i)
if repr_str and repr_str[0] == '<':
return 'None'
return repr_str
def print_bytes(byte_str):
"""Prints a string or converts bytes to a string and then prints."""
if isinstance(byte_str, str):
print(byte_str)
else:
print(str(byte_str, encoding='utf8'))
def extra_funcs(*funcs):
"""Decorator which adds extra functions to be downloaded to the pyboard."""
def extra_funcs_decorator(real_func):
def wrapper(*args, **kwargs):
return real_func(*args, **kwargs)
wrapper.extra_funcs = list(funcs)
wrapper.source = inspect.getsource(real_func)
wrapper.name = real_func.__name__
return wrapper
return extra_funcs_decorator
def auto(func, filename, *args, **kwargs):
"""If `filename` is a remote file, then this function calls func on the
micropython board, otherwise it calls it locally.
"""
dev, dev_filename = get_dev_and_path(filename)
if dev is None:
if len(dev_filename) > 0 and dev_filename[0] == '~':
dev_filename = os.path.expanduser(dev_filename)
return func(dev_filename, *args, **kwargs)
return dev.remote_eval(func, dev_filename, *args, **kwargs)
def board_name(default):
"""Returns the boards name (if available)."""
try:
import board
try:
name = board.name
except AttributeError:
# There was a board.py file, but it didn't have an name attribute
# We also ignore this as an error
name = default
except ImportError:
# No board.py file on the pyboard - not an error
name = default
except BaseException as err:
print('Error encountered executing board.py')
import sys
sys.print_exception(err)
name = default
return repr(name)
def cat(src_filename, dst_file):
"""Copies the contents of the indicated file to an already opened file."""
(dev, dev_filename) = get_dev_and_path(src_filename)
if dev is None:
with open(dev_filename, 'rb') as txtfile:
for line in txtfile:
dst_file.write(line)
else:
filesize = dev.remote_eval(get_filesize, dev_filename)
return dev.remote(send_file_to_host, dev_filename, dst_file, filesize,
xfer_func=recv_file_from_remote)
def chdir(dirname):
"""Changes the current working directory."""
import os
os.chdir(dirname)
def copy_file(src_filename, dst_filename):
"""Copies a file from one place to another. Both the source and destination
files must exist on the same machine.
"""
try:
with open(src_filename, 'rb') as src_file:
with open(dst_filename, 'wb') as dst_file:
while True:
buf = src_file.read(BUFFER_SIZE)
if len(buf) > 0:
dst_file.write(buf)
if len(buf) < BUFFER_SIZE:
break
return True
except:
return False
def cp(src_filename, dst_filename):
"""Copies one file to another. The source file may be local or remote and
the destination file may be local or remote.
"""
src_dev, src_dev_filename = get_dev_and_path(src_filename)
dst_dev, dst_dev_filename = get_dev_and_path(dst_filename)
if src_dev is dst_dev:
# src and dst are either on the same remote, or both are on the host
return auto(copy_file, src_filename, dst_dev_filename)
filesize = auto(get_filesize, src_filename)
if dst_dev is None:
# Copying from remote to host
with open(dst_dev_filename, 'wb') as dst_file:
return src_dev.remote(send_file_to_host, src_dev_filename, dst_file,
filesize, xfer_func=recv_file_from_remote)
if src_dev is None:
# Copying from host to remote
with open(src_dev_filename, 'rb') as src_file:
return dst_dev.remote(recv_file_from_host, src_file, dst_dev_filename,
filesize, xfer_func=send_file_to_remote)
# Copying from remote A to remote B. We first copy the file
# from remote A to the host and then from the host to remote B
host_temp_file = tempfile.TemporaryFile()
if src_dev.remote(send_file_to_host, src_dev_filename, host_temp_file,
filesize, xfer_func=recv_file_from_remote):
host_temp_file.seek(0)
return dst_dev.remote(recv_file_from_host, host_temp_file, dst_dev_filename,
filesize, xfer_func=send_file_to_remote)
return False
def date():
import time
tm = time.localtime()
dow = ('Mon', 'Tue', 'Web', 'Thu', 'Fri', 'Sat', 'Sun')
mon = ('???', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
return repr('{} {} {:2d} {:02d}:{:02d}:{:02d} {}'.format(dow[tm[6]], mon[tm[1]], tm[2], tm[3], tm[4], tm[5], tm[0]))
def eval_str(string):
"""Executes a string containing python code."""
output = eval(string)
return output
def get_filesize(filename):
"""Returns the size of a file, in bytes."""
import os
try:
# Since this function runs remotely, it can't depend on other functions,
# so we can't call stat_mode.
return os.stat(filename)[6]
except OSError:
return -1
def get_mode(filename):
"""Returns the mode of a file, which can be used to determine if a file
exists, if a file is a file or a directory.
"""
import os
try:
# Since this function runs remotely, it can't depend on other functions,
# so we can't call stat_mode.
return os.stat(filename)[0]
except OSError:
return 0
def lstat(filename):
"""Returns os.lstat for a given file, adjusting the timestamps as appropriate.
This function will not follow symlinks."""
import os
try:
# on the host, lstat won't try to follow symlinks
rstat = os.lstat(filename)
except:
rstat = os.stat(filename)
return rstat[:7] + tuple(tim + TIME_OFFSET for tim in rstat[7:])
def stat(filename):
"""Returns os.stat for a given file, adjusting the timestamps as appropriate."""
import os
rstat = os.stat(filename)
return rstat[:7] + tuple(tim + TIME_OFFSET for tim in rstat[7:])
def sysname():
"""Returns the os.uname().sysname field."""
try:
import os
return repr(os.uname().sysname)
except:
return repr('unknown')
def is_visible(filename):
"""Determines if the file should be considered to be a non-hidden file."""
return filename[0] != '.' and filename[-1] != '~'
@extra_funcs(stat)
def get_stat(filename):
"""Returns the stat array for a given file. Returns all 0's if the file
doesn't exist.
"""
try:
return stat(filename)
except OSError:
return (0,) * 10
@extra_funcs(lstat)
def get_lstat(filename):
"""Returns the stat array for a given file. Returns all 0's if the file
doesn't exist.
"""
try:
return lstat(filename)
except OSError:
return (0,) * 10
def listdir(dirname):
"""Returns a list of filenames contained in the named directory."""
import os
return os.listdir(dirname)
def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
import os
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
match_prefix = match
result_prefix = ''
else:
match_prefix = match[last_slash + 1:]
if last_slash == 0:
dirname = '/'
result_prefix = '/'
else:
dirname = match[0:last_slash]
result_prefix = dirname + '/'
def add_suffix_if_dir(filename):
try:
if (os.stat(filename)[0] & 0x4000) != 0:
return filename + '/'
except FileNotFoundError:
# This can happen when a symlink points to a non-existant file.
pass
return filename
matches = [add_suffix_if_dir(result_prefix + filename)
for filename in os.listdir(dirname) if filename.startswith(match_prefix)]
return matches
@extra_funcs(is_visible, lstat)
def listdir_lstat(dirname, show_hidden=True):
"""Returns a list of tuples for each file contained in the named
directory, or None if the directory does not exist. Each tuple
contains the filename, followed by the tuple returned by
calling os.stat on the filename.
"""
import os
try:
files = os.listdir(dirname)
except OSError:
return None
if dirname == '/':
return list((file, lstat('/' + file)) for file in files if is_visible(file) or show_hidden)
return list((file, lstat(dirname + '/' + file)) for file in files if is_visible(file) or show_hidden)
@extra_funcs(is_visible, stat)
def listdir_stat(dirname, show_hidden=True):
"""Returns a list of tuples for each file contained in the named
directory, or None if the directory does not exist. Each tuple
contains the filename, followed by the tuple returned by
calling os.stat on the filename.
"""
import os
try:
files = os.listdir(dirname)
except OSError:
return None
if dirname == '/':
return list((file, stat('/' + file)) for file in files if is_visible(file) or show_hidden)
return list((file, stat(dirname + '/' + file)) for file in files if is_visible(file) or show_hidden)
def make_directory(dirname):
"""Creates one or more directories."""
import os
try:
os.mkdir(dirname)
except:
return False
return True
def mkdir(filename):
"""Creates a directory."""
return auto(make_directory, filename)
def remove_file(filename, recursive=False, force=False):
"""Removes a file or directory."""
import os
try:
mode = os.stat(filename)[0]
if mode & 0x4000 != 0:
# directory
if recursive:
for file in os.listdir(filename):
success = remove_file(filename + '/' + file, recursive, force)
if not success and not force:
return False
os.rmdir(filename) # PGH Work like Unix: require recursive
else:
if not force:
return False
else:
os.remove(filename)
except:
if not force:
return False
return True
def rm(filename, recursive=False, force=False):
"""Removes a file or directory tree."""
return auto(remove_file, filename, recursive, force)
def make_dir(dst_dir, dry_run, print_func, recursed):
"""Creates a directory. Produces information in case of dry run.
Issues error where necessary.
"""
parent = os.path.split(dst_dir.rstrip('/'))[0] # Check for nonexistent parent
parent_files = auto(listdir_lstat, parent) if parent else True # Relative dir
if dry_run:
if recursed: # Assume success: parent not actually created yet
print_func("Creating directory {}".format(dst_dir))
elif parent_files is None:
print_func("Unable to create {}".format(dst_dir))
return True
if not mkdir(dst_dir):
print_err("Unable to create {}".format(dst_dir))
return False
return True
def rsync(src_dir, dst_dir, mirror, dry_run, print_func, recursed, sync_hidden):
"""Synchronizes 2 directory trees."""
# This test is a hack to avoid errors when accessing /flash. When the
# cache synchronisation issue is solved it should be removed
if not isinstance(src_dir, str) or not len(src_dir):
return
sstat = auto(get_stat, src_dir)
smode = stat_mode(sstat)
if mode_isfile(smode):
print_err('Source {} is a file not a directory.'.format(src_dir))
return
d_src = {} # Look up stat tuple from name in current directory
src_files = auto(listdir_stat, src_dir, show_hidden=sync_hidden)
if src_files is None:
print_err('Source directory {} does not exist.'.format(src_dir))
return
for name, stat in src_files:
d_src[name] = stat
d_dst = {}
dst_files = auto(listdir_stat, dst_dir, show_hidden=sync_hidden)
if dst_files is None: # Directory does not exist
if not make_dir(dst_dir, dry_run, print_func, recursed):
return
else: # dest exists
for name, stat in dst_files:
d_dst[name] = stat
set_dst = set(d_dst.keys())
set_src = set(d_src.keys())
to_add = set_src - set_dst # Files to copy to dest
to_del = set_dst - set_src # To delete from dest
to_upd = set_dst.intersection(set_src) # In both: may need updating
for src_basename in to_add: # Name in source but absent from destination
src_filename = src_dir + '/' + src_basename
dst_filename = dst_dir + '/' + src_basename
print_func("Adding %s" % dst_filename)
src_stat = d_src[src_basename]
src_mode = stat_mode(src_stat)
if not dry_run:
if not mode_isdir(src_mode):
cp(src_filename, dst_filename)
if mode_isdir(src_mode):
rsync(src_filename, dst_filename, mirror=mirror, dry_run=dry_run,
print_func=print_func, recursed=True, sync_hidden=sync_hidden)
if mirror: # May delete
for dst_basename in to_del: # In dest but not in source
dst_filename = dst_dir + '/' + dst_basename
print_func("Removing %s" % dst_filename)
if not dry_run:
rm(dst_filename, recursive=True, force=True)
for src_basename in to_upd: # Names are identical
src_stat = d_src[src_basename]
dst_stat = d_dst[src_basename]
src_filename = src_dir + '/' + src_basename
dst_filename = dst_dir + '/' + src_basename
src_mode = stat_mode(src_stat)
dst_mode = stat_mode(dst_stat)
if mode_isdir(src_mode):
if mode_isdir(dst_mode):
# src and dst are both directories - recurse
rsync(src_filename, dst_filename, mirror=mirror, dry_run=dry_run,
print_func=print_func, recursed=True, sync_hidden=sync_hidden)
else:
msg = "Source '{}' is a directory and destination " \
"'{}' is a file. Ignoring"
print_err(msg.format(src_filename, dst_filename))
else:
if mode_isdir(dst_mode):
msg = "Source '{}' is a file and destination " \
"'{}' is a directory. Ignoring"
print_err(msg.format(src_filename, dst_filename))
else: