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