Skip to content

Commit

Permalink
micropython/upysh: Add the cp() function and improve ls and rm.
Browse files Browse the repository at this point in the history
- cp() copies a file. If the target is a directory, the file is copied
  into that directory.  It uses a small buffer, so it's not fast.
- ls uses ilistdir and creates a sorted output with directories listed as
  the first group.
- rm optionally deletes recursive, if the target is a directory.
  • Loading branch information
robert-hh authored and dpgeorge committed Mar 23, 2022
1 parent 22cd7fd commit 760bfef
Showing 1 changed file with 54 additions and 20 deletions.
74 changes: 54 additions & 20 deletions micropython/upysh/upysh.py
Expand Up @@ -8,14 +8,22 @@ def __repr__(self):
return ""

def __call__(self, path="."):
l = os.listdir(path)
l = list(os.ilistdir(path))
l.sort()
for f in l:
st = os.stat("%s/%s" % (path, f))
if st[0] & 0x4000: # stat.S_IFDIR
print(" <dir> %s" % f)
else:
print("% 8d %s" % (st[6], f))
if f[1] == 0x4000: # stat.S_IFDIR
print(" <dir> %s" % f[0])
for f in l:
if f[1] != 0x4000:
if len(f) > 3:
print("% 9d %s" % (f[3], f[0]))
else:
print(" %s" % f[0])
try:
st = os.statvfs(path)
print("\n{:,d}k free".format(st[1] * st[3] // 1024))
except:
pass


class PWD:
Expand All @@ -34,17 +42,6 @@ def __call__(self):
return self.__repr__()


pwd = PWD()
ls = LS()
clear = CLEAR()

cd = os.chdir
mkdir = os.mkdir
mv = os.rename
rm = os.remove
rmdir = os.rmdir


def head(f, n=10):
with open(f) as f:
for i in range(n):
Expand All @@ -58,6 +55,22 @@ def cat(f):
head(f, 1 << 30)


def cp(s, t):
try:
if os.stat(t)[0] & 0x4000: # is directory
t = t.rstrip("/") + "/" + s
except OSError:
pass
buf = bytearray(512)
buf_mv = memoryview(buf)
with open(s, "rb") as s, open(t, "wb") as t:
while True:
n = s.readinto(buf)
if n <= 0:
break
t.write(buf_mv[:n])


def newfile(path):
print("Type file contents line by line, finish with EOF (Ctrl+D).")
with open(path, "w") as f:
Expand All @@ -70,6 +83,19 @@ def newfile(path):
f.write("\n")


def rm(d, recursive=False): # Remove file or tree
try:
if (os.stat(d)[0] & 0x4000) and recursive: # Dir
for f in os.ilistdir(d):
if f[0] != "." and f[0] != "..":
rm("/".join((d, f[0]))) # File or Dir
os.rmdir(d)
else: # File
os.remove(d)
except:
print("rm of '%s' failed" % d)


class Man:
def __repr__(self):
return """
Expand All @@ -79,12 +105,20 @@ def __repr__(self):
To see this help text again, type "man".
upysh commands:
pwd, cd("new_dir"), ls, ls(...), head(...), cat(...)
newfile(...), mv("old", "new"), rm(...), mkdir(...), rmdir(...),
clear
clear, ls, ls(...), head(...), cat(...), newfile(...)
cp('src', 'dest'), mv('old', 'new'), rm(...)
pwd, cd(...), mkdir(...), rmdir(...)
"""


man = Man()
pwd = PWD()
ls = LS()
clear = CLEAR()

cd = os.chdir
mkdir = os.mkdir
mv = os.rename
rmdir = os.rmdir

print(man)

0 comments on commit 760bfef

Please sign in to comment.