File size: 11,457 Bytes
5452d2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import builtins
import glob
import os
import os.path

from cloudpathlib.exceptions import InvalidGlobArgumentsError

from .cloudpath import CloudPath


def _check_first_arg(*args, **kwargs):
    return isinstance(args[0], CloudPath)


def _check_first_arg_first_index(*args, **kwargs):
    return isinstance(args[0][0], CloudPath)


def _check_first_arg_or_root_dir(*args, **kwargs):
    return isinstance(args[0], CloudPath) or isinstance(kwargs.get("root_dir", None), CloudPath)


def _patch_factory(original_version, cpl_version, cpl_check=_check_first_arg):
    _original = original_version

    def _patched_version(*args, **kwargs):
        if cpl_check(*args, **kwargs):
            return cpl_version(*args, **kwargs)
        else:
            return _original(*args, **kwargs)

    original_version = _patched_version
    return _patched_version


class _OpenPatch:
    def __init__(self, original_open=None):
        if original_open is None:
            original_open = builtins.open

        self._orig_open = original_open
        self._orig_fspath = CloudPath.__fspath__
        self.patched = _patch_factory(
            original_open,
            CloudPath.open,
        )

        # patch immediately so a plain call works
        builtins.open = self.patched
        CloudPath.__fspath__ = lambda x: x

    def __enter__(self):
        return builtins.open

    def __exit__(self, exc_type, exc_value, traceback):
        builtins.open = self._orig_open
        CloudPath.__fspath__ = self._orig_fspath


def patch_open(original_open=None):
    return _OpenPatch(original_open)


def _cloudpath_fspath(path):
    return path  # no op, since methods should all handle cloudpaths when patched


def _cloudpath_os_listdir(path="."):
    return list(path.iterdir())


def _cloudpath_lstat(path, *, dir_fd=None):
    return path.stat()


def _cloudpath_mkdir(path, *, dir_fd=None):
    return path.mkdir()


def _cloudpath_os_makedirs(name, mode=0o777, exist_ok=False):
    return CloudPath.mkdir(name, parents=True, exist_ok=exist_ok)


def _cloudpath_os_remove(path, *, dir_fd=None):
    return path.unlink(missing_ok=False)  # os.remove raises if missing


def _cloudpath_os_removedirs(name):
    for d in name.parents:
        d.rmdir()


def _cloudpath_os_rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None):
    return src.rename(dst)


def _cloudpath_os_renames(old, new):
    old.rename(new)  # move file
    _cloudpath_os_removedirs(old)  # remove previous directories if empty


def _cloudpath_os_replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None):
    return src.rename(dst)


def _cloudpath_os_rmdir(path, *, dir_fd=None):
    return path.rmdir()


def _cloudpath_os_scandir(path="."):
    return path.iterdir()


def _cloudpath_os_stat(path, *, dir_fd=None, follow_symlinks=True):
    return path.stat()


def _cloudpath_os_unlink(path, *, dir_fd=None):
    return path.unlink()


def _cloudpath_os_walk(top, topdown=True, onerror=None, followlinks=False):
    # pathlib.Path.walk returns dirs and files as string, not Path objects
    # we follow the same convention, but since these could get used downstream,
    # this method may need to be changed to return absolute CloudPath objects
    # if it becomes a compatibility problem with major downstream libraries
    yield from top.walk(top_down=topdown, on_error=onerror, follow_symlinks=followlinks)


def _cloudpath_os_path_basename(path):
    return path.name


def __common(parts):
    i = 0

    try:
        while all(item[i] == parts[0][i] for item in parts[1:]):
            i += 1
    except IndexError:
        pass

    return parts[0][:i]


def _cloudpath_os_path_commonpath(paths):
    common = __common([p.parts for p in paths])
    return paths[0].client.CloudPath(*common)


def _cloudpath_os_path_commonprefix(list):
    common = __common([str(p) for p in list])
    return common


def _cloudpath_os_path_dirname(path):
    return path.parent


def _cloudpath_os_path_getatime(path):
    return (path.stat().st_atime,)


def _cloudpath_os_path_getmtime(path):
    return (path.stat().st_mtime,)


def _cloudpath_os_path_getctime(path):
    return (path.stat().st_ctime,)


def _cloudpath_os_path_getsize(path):
    return (path.stat().st_size,)


def _cloudpath_os_path_join(path, *paths):
    for p in paths:
        path /= p
    return path


def _cloudpath_os_path_split(path):
    return path.parent, path.name


def _cloudpath_os_path_splitext(path):
    return str(path)[: -len(path.suffix)], path.suffix


class _OSPatch:
    def __init__(self):
        os_level = [
            ("fspath", os.fspath, _cloudpath_fspath),
            ("listdir", os.listdir, _cloudpath_os_listdir),
            ("lstat", os.lstat, _cloudpath_lstat),
            ("mkdir", os.mkdir, _cloudpath_mkdir),
            ("makedirs", os.makedirs, _cloudpath_os_makedirs),
            ("remove", os.remove, _cloudpath_os_remove),
            ("removedirs", os.removedirs, _cloudpath_os_removedirs),
            ("rename", os.rename, _cloudpath_os_rename),
            ("renames", os.renames, _cloudpath_os_renames),
            ("replace", os.replace, _cloudpath_os_replace),
            ("rmdir", os.rmdir, _cloudpath_os_rmdir),
            ("scandir", os.scandir, _cloudpath_os_scandir),
            ("stat", os.stat, _cloudpath_os_stat),
            ("unlink", os.unlink, _cloudpath_os_unlink),
            ("walk", os.walk, _cloudpath_os_walk),
        ]

        self.os_originals = {}

        for name, original, cloud in os_level:
            self.os_originals[name] = original
            patched = _patch_factory(original, cloud)
            setattr(os, name, patched)

        os_path_level = [
            ("basename", os.path.basename, _cloudpath_os_path_basename, _check_first_arg),
            (
                "commonpath",
                os.path.commonpath,
                _cloudpath_os_path_commonpath,
                _check_first_arg_first_index,
            ),
            (
                "commonprefix",
                os.path.commonprefix,
                _cloudpath_os_path_commonprefix,
                _check_first_arg_first_index,
            ),
            ("dirname", os.path.dirname, _cloudpath_os_path_dirname, _check_first_arg),
            ("exists", os.path.exists, CloudPath.exists, _check_first_arg),
            ("getatime", os.path.getatime, _cloudpath_os_path_getatime, _check_first_arg),
            ("getmtime", os.path.getmtime, _cloudpath_os_path_getmtime, _check_first_arg),
            ("getctime", os.path.getctime, _cloudpath_os_path_getctime, _check_first_arg),
            ("getsize", os.path.getsize, _cloudpath_os_path_getsize, _check_first_arg),
            ("isfile", os.path.isfile, CloudPath.is_file, _check_first_arg),
            ("isdir", os.path.isdir, CloudPath.is_dir, _check_first_arg),
            ("join", os.path.join, _cloudpath_os_path_join, _check_first_arg),
            ("split", os.path.split, _cloudpath_os_path_split, _check_first_arg),
            ("splitext", os.path.splitext, _cloudpath_os_path_splitext, _check_first_arg),
        ]

        self.os_path_originals = {}

        for name, original, cloud, check in os_path_level:
            self.os_path_originals[name] = original
            patched = _patch_factory(original, cloud, cpl_check=check)
            setattr(os.path, name, patched)

    def __enter__(self):
        return

    def __exit__(self, exc_type, exc_value, traceback):
        for name, original in self.os_originals.items():
            setattr(os, name, original)

        for name, original in self.os_path_originals.items():
            setattr(os.path, name, original)


def patch_os_functions():
    return _OSPatch()


def _get_root_dir_pattern_from_pathname(pathname):
    # get first wildcard
    for i, part in enumerate(pathname.parts):
        if "*" in part or "?" in part or "[" in part:
            root_parts = pathname.parts[:i]
            pattern_parts = pathname.parts[i:]
            break
    else:
        # No wildcards found, treat the entire path as root_dir with empty pattern
        root_parts = pathname.parts
        pattern_parts = []

    root_dir = pathname._new_cloudpath(*root_parts)

    # Handle empty pattern case - use "*" to match all files in directory
    if not pattern_parts:
        pattern = "*"
    else:
        pattern = "/".join(pattern_parts)

    return root_dir, pattern


def _cloudpath_glob_iglob(
    pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False
):
    # if both are cloudpath, root_dir and pathname must share a parent, otherwise we don't know
    # where to start the pattern
    if isinstance(pathname, CloudPath) and isinstance(root_dir, CloudPath):
        if not pathname.is_relative_to(root_dir):
            raise InvalidGlobArgumentsError(
                f"If both are CloudPaths, root_dir ({root_dir}) must be a parent of pathname ({pathname})."
            )

        else:
            pattern = pathname.relative_to(root_dir)

    elif isinstance(pathname, CloudPath):
        if root_dir is not None:
            raise InvalidGlobArgumentsError(
                "If pathname is a CloudPath, root_dir must also be a CloudPath or None."
            )

        root_dir, pattern = _get_root_dir_pattern_from_pathname(pathname)

    elif isinstance(root_dir, CloudPath):
        pattern = pathname

    else:
        raise InvalidGlobArgumentsError(
            "At least one of pathname or root_dir must be a CloudPath."
        )

    # CloudPath automatically detects recursive patterns from ** or / in the pattern
    # No need to pass recursive parameter
    return root_dir.glob(pattern)


def _cloudpath_glob_glob(
    pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False
):
    return list(
        _cloudpath_glob_iglob(
            pathname,
            root_dir=root_dir,
            dir_fd=dir_fd,
            recursive=recursive,
            include_hidden=include_hidden,
        )
    )


class _GlobPatch:
    def __init__(self):
        self.original_glob = glob.glob
        self.original_iglob = glob.iglob

        self.patched_glob = _patch_factory(
            self.original_glob,
            _cloudpath_glob_glob,
            cpl_check=_check_first_arg_or_root_dir,
        )

        self.patched_iglob = _patch_factory(
            self.original_iglob,
            _cloudpath_glob_iglob,
            cpl_check=_check_first_arg_or_root_dir,
        )

    def __enter__(self):
        glob.glob = self.patched_glob
        glob.iglob = self.patched_iglob
        return

    def __exit__(self, exc_type, exc_value, traceback):
        glob.glob = self.original_glob
        glob.iglob = self.original_iglob


def patch_glob():
    return _GlobPatch()


class _PatchAllBuiltins:
    def __init__(self):
        self.patch_open = patch_open()
        self.patch_os_functions = patch_os_functions()
        self.patch_glob = patch_glob()

    def __enter__(self):
        self.patch_open.__enter__()
        self.patch_os_functions.__enter__()
        self.patch_glob.__enter__()
        return

    def __exit__(self, exc_type, exc_value, traceback):
        self.patch_open.__exit__(exc_type, exc_value, traceback)
        self.patch_os_functions.__exit__(exc_type, exc_value, traceback)
        self.patch_glob.__exit__(exc_type, exc_value, traceback)


def patch_all_builtins():
    return _PatchAllBuiltins()