File: shell.py

package info (click to toggle)
python-watchdog 6.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 808 kB
  • sloc: python: 6,384; ansic: 609; xml: 155; makefile: 124; sh: 8
file content (105 lines) | stat: -rw-r--r-- 2,123 bytes parent folder | download
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
"""
:module: tests.shell
:synopsis: Common shell operations for testing.
:author: yesudeep@google.com (Yesudeep Mangalapilly)
:author: contact@tiger-222.fr (Mickaƫl Schoentgen)
"""

from __future__ import annotations

import errno
import os
import os.path
import shutil
import tempfile
import time


def cd(path):
    os.chdir(path)


def pwd():
    return os.getcwd()


def mkfile(path):
    """Creates a file"""
    with open(path, "ab"):
        pass


def mkdir(path, *, parents=False):
    """Creates a directory (optionally also creates all the parent directories
    in the path)."""
    if parents:
        try:
            os.makedirs(path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
    else:
        os.mkdir(path)


def rm(path, *, recursive=False):
    """Deletes files or directories."""
    if os.path.isdir(path):
        if recursive:
            shutil.rmtree(path)
        else:
            raise OSError(errno.EISDIR, os.strerror(errno.EISDIR), path)
    else:
        os.remove(path)


def touch(path, times=None):
    """Updates the modified timestamp of a file or directory."""
    if os.path.isdir(path):
        os.utime(path, times)
    else:
        with open(path, "ab"):
            os.utime(path, times)


def truncate(path):
    """Truncates a file."""
    with open(path, "wb"):
        os.utime(path, None)


def mv(src_path, dest_path):
    """Moves files or directories."""
    try:
        os.rename(src_path, dest_path)
    except OSError:
        # this will happen on windows
        os.remove(dest_path)
        os.rename(src_path, dest_path)


def mkdtemp():
    return tempfile.mkdtemp()


def ls(path="."):
    return os.listdir(path)


def msize(path):
    """Modify the file size without updating the modified time."""
    with open(path, "w") as w:
        w.write("")
    os.utime(path, (0, 0))
    time.sleep(0.4)
    with open(path, "w") as w:
        w.write("0")
    os.utime(path, (0, 0))


def mount_tmpfs(path):
    os.system(f"sudo mount -t tmpfs none {path}")


def unmount(path):
    os.system(f"sudo umount {path}")