1import datetime
2import io
3import logging
4import os
5import os.path as osp
6import shutil
7import stat
8import tempfile
9from functools import lru_cache
10
11from fsspec import AbstractFileSystem
12from fsspec.compression import compr
13from fsspec.core import get_compression
14from fsspec.utils import isfilelike, stringify_path
15
16logger = logging.getLogger("fsspec.local")
17
18
19class LocalFileSystem(AbstractFileSystem):
20 """Interface to files on local storage
21
22 Parameters
23 ----------
24 auto_mkdir: bool
25 Whether, when opening a file, the directory containing it should
26 be created (if it doesn't already exist). This is assumed by pyarrow
27 code.
28 """
29
30 root_marker = "/"
31 protocol = "file", "local"
32 local_file = True
33
34 def __init__(self, auto_mkdir=False, **kwargs):
35 super().__init__(**kwargs)
36 self.auto_mkdir = auto_mkdir
37
38 @property
39 def fsid(self):
40 return "local"
41
42 def mkdir(self, path, create_parents=True, **kwargs):
43 path = self._strip_protocol(path)
44 if self.exists(path):
45 raise FileExistsError(path)
46 if create_parents:
47 self.makedirs(path, exist_ok=True)
48 else:
49 os.mkdir(path, **kwargs)
50
51 def makedirs(self, path, exist_ok=False):
52 path = self._strip_protocol(path)
53 os.makedirs(path, exist_ok=exist_ok)
54
55 def rmdir(self, path):
56 path = self._strip_protocol(path)
57 os.rmdir(path)
58
59 def ls(self, path, detail=False, **kwargs):
60 path = self._strip_protocol(path)
61 path_info = self.info(path)
62 infos = []
63 if path_info["type"] == "directory":
64 with os.scandir(path) as it:
65 for f in it:
66 try:
67 # Only get the info if requested since it is a bit expensive (the stat call inside)
68 # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths
69 info = self.info(f) if detail else self._strip_protocol(f.path)
70 infos.append(info)
71 except FileNotFoundError:
72 pass
73 else:
74 infos = [path_info] if detail else [path_info["name"]]
75
76 return infos
77
78 def info(self, path, **kwargs):
79 if isinstance(path, os.DirEntry):
80 # scandir DirEntry
81 out = path.stat(follow_symlinks=False)
82 link = path.is_symlink()
83 if path.is_dir(follow_symlinks=False):
84 t = "directory"
85 elif path.is_file(follow_symlinks=False):
86 t = "file"
87 else:
88 t = "other"
89
90 size = out.st_size
91 if link:
92 try:
93 out2 = path.stat(follow_symlinks=True)
94 size = out2.st_size
95 except OSError:
96 size = 0
97 path = self._strip_protocol(path.path)
98 else:
99 # str or path-like
100 path = self._strip_protocol(path)
101 out = os.stat(path, follow_symlinks=False)
102 link = stat.S_ISLNK(out.st_mode)
103 if link:
104 out = os.stat(path, follow_symlinks=True)
105 size = out.st_size
106 if stat.S_ISDIR(out.st_mode):
107 t = "directory"
108 elif stat.S_ISREG(out.st_mode):
109 t = "file"
110 else:
111 t = "other"
112
113 # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime
114 created_time = getattr(out, "st_birthtime", out.st_ctime)
115
116 result = {
117 "name": path,
118 "size": size,
119 "type": t,
120 "created": created_time,
121 "islink": link,
122 }
123 for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]:
124 result[field] = getattr(out, f"st_{field}")
125 if link:
126 result["destination"] = os.readlink(path)
127 return result
128
129 def lexists(self, path, **kwargs):
130 return osp.lexists(path)
131
132 def cp_file(self, path1, path2, **kwargs):
133 path1 = self._strip_protocol(path1)
134 path2 = self._strip_protocol(path2)
135 if self.auto_mkdir:
136 self.makedirs(self._parent(path2), exist_ok=True)
137 if self.isfile(path1):
138 shutil.copyfile(path1, path2)
139 elif self.isdir(path1):
140 self.mkdirs(path2, exist_ok=True)
141 else:
142 raise FileNotFoundError(path1)
143
144 def isfile(self, path):
145 path = self._strip_protocol(path)
146 return os.path.isfile(path)
147
148 def isdir(self, path):
149 path = self._strip_protocol(path)
150 return os.path.isdir(path)
151
152 def get_file(self, path1, path2, callback=None, **kwargs):
153 if isfilelike(path2):
154 with open(path1, "rb") as f:
155 shutil.copyfileobj(f, path2)
156 else:
157 return self.cp_file(path1, path2, **kwargs)
158
159 def put_file(self, path1, path2, callback=None, **kwargs):
160 return self.cp_file(path1, path2, **kwargs)
161
162 def mv(self, path1, path2, recursive: bool = True, **kwargs):
163 """Move files/directories
164 For the specific case of local, all ops on directories are recursive and
165 the recursive= kwarg is ignored.
166 """
167 path1 = self._strip_protocol(path1)
168 path2 = self._strip_protocol(path2)
169
170 if self.auto_mkdir:
171 self.makedirs(self._parent(path2), exist_ok=True)
172
173 shutil.move(path1, path2)
174
175 def link(self, src, dst, **kwargs):
176 src = self._strip_protocol(src)
177 dst = self._strip_protocol(dst)
178 os.link(src, dst, **kwargs)
179
180 def symlink(self, src, dst, **kwargs):
181 src = self._strip_protocol(src)
182 dst = self._strip_protocol(dst)
183 os.symlink(src, dst, **kwargs)
184
185 def islink(self, path) -> bool:
186 return os.path.islink(self._strip_protocol(path))
187
188 def rm_file(self, path):
189 os.remove(self._strip_protocol(path))
190
191 def rm(self, path, recursive=False, maxdepth=None):
192 if not isinstance(path, list):
193 path = [path]
194
195 for p in path:
196 p = self._strip_protocol(p)
197 if self.isdir(p):
198 if not recursive:
199 raise ValueError("Cannot delete directory, set recursive=True")
200 if osp.abspath(p) == os.getcwd():
201 raise ValueError("Cannot delete current working directory")
202 shutil.rmtree(p)
203 else:
204 os.remove(p)
205
206 def unstrip_protocol(self, name):
207 name = self._strip_protocol(name) # normalise for local/win/...
208 return f"file://{name}"
209
210 def _open(self, path, mode="rb", block_size=None, **kwargs):
211 path = self._strip_protocol(path)
212 if self.auto_mkdir and "w" in mode:
213 self.makedirs(self._parent(path), exist_ok=True)
214 return LocalFileOpener(path, mode, fs=self, **kwargs)
215
216 def touch(self, path, truncate=True, **kwargs):
217 path = self._strip_protocol(path)
218 if self.auto_mkdir:
219 self.makedirs(self._parent(path), exist_ok=True)
220 if self.exists(path):
221 os.utime(path, None)
222 else:
223 open(path, "a").close()
224 if truncate:
225 os.truncate(path, 0)
226
227 def created(self, path):
228 info = self.info(path=path)
229 return datetime.datetime.fromtimestamp(
230 info["created"], tz=datetime.timezone.utc
231 )
232
233 def modified(self, path):
234 info = self.info(path=path)
235 return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
236
237 @classmethod
238 def _parent(cls, path):
239 path = cls._strip_protocol(path)
240 if os.sep == "/":
241 # posix native
242 return path.rsplit("/", 1)[0] or "/"
243 else:
244 # NT
245 path_ = path.rsplit("/", 1)[0]
246 if len(path_) <= 3:
247 if path_[1:2] == ":":
248 # nt root (something like c:/)
249 return path_[0] + ":/"
250 # More cases may be required here
251 return path_
252
253 @classmethod
254 def _strip_protocol(cls, path):
255 path = stringify_path(path)
256 if path.startswith("file://"):
257 path = path[7:]
258 elif path.startswith("file:"):
259 path = path[5:]
260 elif path.startswith("local://"):
261 path = path[8:]
262 elif path.startswith("local:"):
263 path = path[6:]
264
265 path = make_path_posix(path)
266 if os.sep != "/":
267 # This code-path is a stripped down version of
268 # > drive, path = ntpath.splitdrive(path)
269 if path[1:2] == ":":
270 # Absolute drive-letter path, e.g. X:\Windows
271 # Relative path with drive, e.g. X:Windows
272 drive, path = path[:2], path[2:]
273 elif path[:2] == "//":
274 # UNC drives, e.g. \\server\share or \\?\UNC\server\share
275 # Device drives, e.g. \\.\device or \\?\device
276 if (index1 := path.find("/", 2)) == -1 or (
277 index2 := path.find("/", index1 + 1)
278 ) == -1:
279 drive, path = path, ""
280 else:
281 drive, path = path[:index2], path[index2:]
282 else:
283 # Relative path, e.g. Windows
284 drive = ""
285
286 path = path.rstrip("/") or cls.root_marker
287 return drive + path
288
289 else:
290 return path.rstrip("/") or cls.root_marker
291
292 def _isfilestore(self):
293 # Inheriting from DaskFileSystem makes this False (S3, etc. were)
294 # the original motivation. But we are a posix-like file system.
295 # See https://github.com/dask/dask/issues/5526
296 return True
297
298 def chmod(self, path, mode):
299 path = stringify_path(path)
300 return os.chmod(path, mode)
301
302
303def make_path_posix(path):
304 """Make path generic and absolute for current OS"""
305 if not isinstance(path, str):
306 if isinstance(path, (list, set, tuple)):
307 return type(path)(make_path_posix(p) for p in path)
308 else:
309 path = stringify_path(path)
310 if not isinstance(path, str):
311 raise TypeError(f"could not convert {path!r} to string")
312 if os.sep == "/":
313 # Native posix
314 if path.startswith("/"):
315 # most common fast case for posix
316 return path
317 elif path.startswith("~"):
318 return osp.expanduser(path)
319 elif path.startswith("./"):
320 path = path[2:]
321 elif path == ".":
322 path = ""
323 return f"{os.getcwd()}/{path}"
324 else:
325 # NT handling
326 if path[0:1] == "/" and path[2:3] == ":":
327 # path is like "/c:/local/path"
328 path = path[1:]
329 if path[1:2] == ":":
330 # windows full path like "C:\\local\\path"
331 if len(path) <= 3:
332 # nt root (something like c:/)
333 return path[0] + ":/"
334 path = path.replace("\\", "/")
335 return path
336 elif path[0:1] == "~":
337 return make_path_posix(osp.expanduser(path))
338 elif path.startswith(("\\\\", "//")):
339 # windows UNC/DFS-style paths
340 return "//" + path[2:].replace("\\", "/")
341 elif path.startswith(("\\", "/")):
342 # windows relative path with root
343 path = path.replace("\\", "/")
344 return f"{osp.splitdrive(os.getcwd())[0]}{path}"
345 else:
346 path = path.replace("\\", "/")
347 if path.startswith("./"):
348 path = path[2:]
349 elif path == ".":
350 path = ""
351 return f"{make_path_posix(os.getcwd())}/{path}"
352
353
354def trailing_sep(path):
355 """Return True if the path ends with a path separator.
356
357 A forward slash is always considered a path separator, even on Operating
358 Systems that normally use a backslash.
359 """
360 # TODO: if all incoming paths were posix-compliant then separator would
361 # always be a forward slash, simplifying this function.
362 # See https://github.com/fsspec/filesystem_spec/pull/1250
363 return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
364
365
366@lru_cache(maxsize=1)
367def get_umask(mask: int = 0o666) -> int:
368 """Get the current umask.
369
370 Follows https://stackoverflow.com/a/44130549 to get the umask.
371 Temporarily sets the umask to the given value, and then resets it to the
372 original value.
373 """
374 value = os.umask(mask)
375 os.umask(value)
376 return value
377
378
379class LocalFileOpener(io.IOBase):
380 def __init__(
381 self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
382 ):
383 logger.debug("open file: %s", path)
384 self.path = path
385 self.mode = mode
386 self.fs = fs
387 self.f = None
388 self.autocommit = autocommit
389 self.compression = get_compression(path, compression)
390 self.blocksize = io.DEFAULT_BUFFER_SIZE
391 self._open()
392
393 def _open(self):
394 if self.f is None or self.f.closed:
395 if self.autocommit or "w" not in self.mode:
396 self.f = open(self.path, mode=self.mode)
397 if self.compression:
398 compress = compr[self.compression]
399 self.f = compress(self.f, mode=self.mode)
400 else:
401 # TODO: check if path is writable?
402 i, name = tempfile.mkstemp()
403 os.close(i) # we want normal open and normal buffered file
404 self.temp = name
405 self.f = open(name, mode=self.mode)
406 if "w" not in self.mode:
407 self.size = self.f.seek(0, 2)
408 self.f.seek(0)
409 self.f.size = self.size
410
411 def _fetch_range(self, start, end):
412 # probably only used by cached FS
413 if "r" not in self.mode:
414 raise ValueError
415 self._open()
416 self.f.seek(start)
417 return self.f.read(end - start)
418
419 def __setstate__(self, state):
420 self.f = None
421 loc = state.pop("loc", None)
422 self.__dict__.update(state)
423 if "r" in state["mode"]:
424 self.f = None
425 self._open()
426 self.f.seek(loc)
427
428 def __getstate__(self):
429 d = self.__dict__.copy()
430 d.pop("f")
431 if "r" in self.mode:
432 d["loc"] = self.f.tell()
433 else:
434 if not self.f.closed:
435 raise ValueError("Cannot serialise open write-mode local file")
436 return d
437
438 def commit(self):
439 if self.autocommit:
440 raise RuntimeError("Can only commit if not already set to autocommit")
441 try:
442 shutil.move(self.temp, self.path)
443 except PermissionError as e:
444 # shutil.move raises PermissionError if os.rename
445 # and the default copy2 fallback with shutil.copystats fail.
446 # The file should be there nonetheless, but without copied permissions.
447 # If it doesn't exist, there was no permission to create the file.
448 if not os.path.exists(self.path):
449 raise e
450 else:
451 # If PermissionError is not raised, permissions can be set.
452 try:
453 mask = 0o666
454 os.chmod(self.path, mask & ~get_umask(mask))
455 except RuntimeError:
456 pass
457
458 def discard(self):
459 if self.autocommit:
460 raise RuntimeError("Cannot discard if set to autocommit")
461 os.remove(self.temp)
462
463 def readable(self) -> bool:
464 return True
465
466 def writable(self) -> bool:
467 return "r" not in self.mode
468
469 def read(self, *args, **kwargs):
470 return self.f.read(*args, **kwargs)
471
472 def write(self, *args, **kwargs):
473 return self.f.write(*args, **kwargs)
474
475 def tell(self, *args, **kwargs):
476 return self.f.tell(*args, **kwargs)
477
478 def seek(self, *args, **kwargs):
479 return self.f.seek(*args, **kwargs)
480
481 def seekable(self, *args, **kwargs):
482 return self.f.seekable(*args, **kwargs)
483
484 def readline(self, *args, **kwargs):
485 return self.f.readline(*args, **kwargs)
486
487 def readlines(self, *args, **kwargs):
488 return self.f.readlines(*args, **kwargs)
489
490 def close(self):
491 return self.f.close()
492
493 def truncate(self, size=None) -> int:
494 return self.f.truncate(size)
495
496 @property
497 def closed(self):
498 return self.f.closed
499
500 def fileno(self):
501 return self.raw.fileno()
502
503 def flush(self) -> None:
504 self.f.flush()
505
506 def __iter__(self):
507 return self.f.__iter__()
508
509 def __getattr__(self, item):
510 return getattr(self.f, item)
511
512 def __enter__(self):
513 self._incontext = True
514 return self
515
516 def __exit__(self, exc_type, exc_value, traceback):
517 self._incontext = False
518 self.f.__exit__(exc_type, exc_value, traceback)