Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

shutil.py 40 KB

You have to be logged in to leave a comment. Sign In
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
  1. """Utility functions for copying and archiving files and directory trees.
  2. XXX The functions here don't copy the resource fork or other metadata on Mac.
  3. """
  4. import os
  5. import sys
  6. import stat
  7. import fnmatch
  8. import collections
  9. import errno
  10. try:
  11. import zlib
  12. del zlib
  13. _ZLIB_SUPPORTED = True
  14. except ImportError:
  15. _ZLIB_SUPPORTED = False
  16. try:
  17. import bz2
  18. del bz2
  19. _BZ2_SUPPORTED = True
  20. except ImportError:
  21. _BZ2_SUPPORTED = False
  22. try:
  23. import lzma
  24. del lzma
  25. _LZMA_SUPPORTED = True
  26. except ImportError:
  27. _LZMA_SUPPORTED = False
  28. try:
  29. from pwd import getpwnam
  30. except ImportError:
  31. getpwnam = None
  32. try:
  33. from grp import getgrnam
  34. except ImportError:
  35. getgrnam = None
  36. __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
  37. "copytree", "move", "rmtree", "Error", "SpecialFileError",
  38. "ExecError", "make_archive", "get_archive_formats",
  39. "register_archive_format", "unregister_archive_format",
  40. "get_unpack_formats", "register_unpack_format",
  41. "unregister_unpack_format", "unpack_archive",
  42. "ignore_patterns", "chown", "which", "get_terminal_size",
  43. "SameFileError"]
  44. # disk_usage is added later, if available on the platform
  45. class Error(OSError):
  46. pass
  47. class SameFileError(Error):
  48. """Raised when source and destination are the same file."""
  49. class SpecialFileError(OSError):
  50. """Raised when trying to do a kind of operation (e.g. copying) which is
  51. not supported on a special file (e.g. a named pipe)"""
  52. class ExecError(OSError):
  53. """Raised when a command could not be executed"""
  54. class ReadError(OSError):
  55. """Raised when an archive cannot be read"""
  56. class RegistryError(Exception):
  57. """Raised when a registry operation with the archiving
  58. and unpacking registries fails"""
  59. def copyfileobj(fsrc, fdst, length=16*1024):
  60. """copy data from file-like object fsrc to file-like object fdst"""
  61. while 1:
  62. buf = fsrc.read(length)
  63. if not buf:
  64. break
  65. fdst.write(buf)
  66. def _samefile(src, dst):
  67. # Macintosh, Unix.
  68. if hasattr(os.path, 'samefile'):
  69. try:
  70. return os.path.samefile(src, dst)
  71. except OSError:
  72. return False
  73. # All other platforms: check for same pathname.
  74. return (os.path.normcase(os.path.abspath(src)) ==
  75. os.path.normcase(os.path.abspath(dst)))
  76. def copyfile(src, dst, *, follow_symlinks=True):
  77. """Copy data from src to dst.
  78. If follow_symlinks is not set and src is a symbolic link, a new
  79. symlink will be created instead of copying the file it points to.
  80. """
  81. if _samefile(src, dst):
  82. raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
  83. for fn in [src, dst]:
  84. try:
  85. st = os.stat(fn)
  86. except OSError:
  87. # File most likely does not exist
  88. pass
  89. else:
  90. # XXX What about other special files? (sockets, devices...)
  91. if stat.S_ISFIFO(st.st_mode):
  92. raise SpecialFileError("`%s` is a named pipe" % fn)
  93. if not follow_symlinks and os.path.islink(src):
  94. os.symlink(os.readlink(src), dst)
  95. else:
  96. with open(src, 'rb') as fsrc:
  97. with open(dst, 'wb') as fdst:
  98. copyfileobj(fsrc, fdst)
  99. return dst
  100. def copymode(src, dst, *, follow_symlinks=True):
  101. """Copy mode bits from src to dst.
  102. If follow_symlinks is not set, symlinks aren't followed if and only
  103. if both `src` and `dst` are symlinks. If `lchmod` isn't available
  104. (e.g. Linux) this method does nothing.
  105. """
  106. if not follow_symlinks and os.path.islink(src) and os.path.islink(dst):
  107. if hasattr(os, 'lchmod'):
  108. stat_func, chmod_func = os.lstat, os.lchmod
  109. else:
  110. return
  111. elif hasattr(os, 'chmod'):
  112. stat_func, chmod_func = os.stat, os.chmod
  113. else:
  114. return
  115. st = stat_func(src)
  116. chmod_func(dst, stat.S_IMODE(st.st_mode))
  117. if hasattr(os, 'listxattr'):
  118. def _copyxattr(src, dst, *, follow_symlinks=True):
  119. """Copy extended filesystem attributes from `src` to `dst`.
  120. Overwrite existing attributes.
  121. If `follow_symlinks` is false, symlinks won't be followed.
  122. """
  123. try:
  124. names = os.listxattr(src, follow_symlinks=follow_symlinks)
  125. except OSError as e:
  126. if e.errno not in (errno.ENOTSUP, errno.ENODATA):
  127. raise
  128. return
  129. for name in names:
  130. try:
  131. value = os.getxattr(src, name, follow_symlinks=follow_symlinks)
  132. os.setxattr(dst, name, value, follow_symlinks=follow_symlinks)
  133. except OSError as e:
  134. if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA):
  135. raise
  136. else:
  137. def _copyxattr(*args, **kwargs):
  138. pass
  139. def copystat(src, dst, *, follow_symlinks=True):
  140. """Copy file metadata
  141. Copy the permission bits, last access time, last modification time, and
  142. flags from `src` to `dst`. On Linux, copystat() also copies the "extended
  143. attributes" where possible. The file contents, owner, and group are
  144. unaffected. `src` and `dst` are path names given as strings.
  145. If the optional flag `follow_symlinks` is not set, symlinks aren't
  146. followed if and only if both `src` and `dst` are symlinks.
  147. """
  148. def _nop(*args, ns=None, follow_symlinks=None):
  149. pass
  150. # follow symlinks (aka don't not follow symlinks)
  151. follow = follow_symlinks or not (os.path.islink(src) and os.path.islink(dst))
  152. if follow:
  153. # use the real function if it exists
  154. def lookup(name):
  155. return getattr(os, name, _nop)
  156. else:
  157. # use the real function only if it exists
  158. # *and* it supports follow_symlinks
  159. def lookup(name):
  160. fn = getattr(os, name, _nop)
  161. if fn in os.supports_follow_symlinks:
  162. return fn
  163. return _nop
  164. st = lookup("stat")(src, follow_symlinks=follow)
  165. mode = stat.S_IMODE(st.st_mode)
  166. lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns),
  167. follow_symlinks=follow)
  168. try:
  169. lookup("chmod")(dst, mode, follow_symlinks=follow)
  170. except NotImplementedError:
  171. # if we got a NotImplementedError, it's because
  172. # * follow_symlinks=False,
  173. # * lchown() is unavailable, and
  174. # * either
  175. # * fchownat() is unavailable or
  176. # * fchownat() doesn't implement AT_SYMLINK_NOFOLLOW.
  177. # (it returned ENOSUP.)
  178. # therefore we're out of options--we simply cannot chown the
  179. # symlink. give up, suppress the error.
  180. # (which is what shutil always did in this circumstance.)
  181. pass
  182. if hasattr(st, 'st_flags'):
  183. try:
  184. lookup("chflags")(dst, st.st_flags, follow_symlinks=follow)
  185. except OSError as why:
  186. for err in 'EOPNOTSUPP', 'ENOTSUP':
  187. if hasattr(errno, err) and why.errno == getattr(errno, err):
  188. break
  189. else:
  190. raise
  191. _copyxattr(src, dst, follow_symlinks=follow)
  192. def copy(src, dst, *, follow_symlinks=True):
  193. """Copy data and mode bits ("cp src dst"). Return the file's destination.
  194. The destination may be a directory.
  195. If follow_symlinks is false, symlinks won't be followed. This
  196. resembles GNU's "cp -P src dst".
  197. If source and destination are the same file, a SameFileError will be
  198. raised.
  199. """
  200. if os.path.isdir(dst):
  201. dst = os.path.join(dst, os.path.basename(src))
  202. copyfile(src, dst, follow_symlinks=follow_symlinks)
  203. copymode(src, dst, follow_symlinks=follow_symlinks)
  204. return dst
  205. def copy2(src, dst, *, follow_symlinks=True):
  206. """Copy data and metadata. Return the file's destination.
  207. Metadata is copied with copystat(). Please see the copystat function
  208. for more information.
  209. The destination may be a directory.
  210. If follow_symlinks is false, symlinks won't be followed. This
  211. resembles GNU's "cp -P src dst".
  212. """
  213. if os.path.isdir(dst):
  214. dst = os.path.join(dst, os.path.basename(src))
  215. copyfile(src, dst, follow_symlinks=follow_symlinks)
  216. copystat(src, dst, follow_symlinks=follow_symlinks)
  217. return dst
  218. def ignore_patterns(*patterns):
  219. """Function that can be used as copytree() ignore parameter.
  220. Patterns is a sequence of glob-style patterns
  221. that are used to exclude files"""
  222. def _ignore_patterns(path, names):
  223. ignored_names = []
  224. for pattern in patterns:
  225. ignored_names.extend(fnmatch.filter(names, pattern))
  226. return set(ignored_names)
  227. return _ignore_patterns
  228. def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
  229. ignore_dangling_symlinks=False):
  230. """Recursively copy a directory tree.
  231. The destination directory must not already exist.
  232. If exception(s) occur, an Error is raised with a list of reasons.
  233. If the optional symlinks flag is true, symbolic links in the
  234. source tree result in symbolic links in the destination tree; if
  235. it is false, the contents of the files pointed to by symbolic
  236. links are copied. If the file pointed by the symlink doesn't
  237. exist, an exception will be added in the list of errors raised in
  238. an Error exception at the end of the copy process.
  239. You can set the optional ignore_dangling_symlinks flag to true if you
  240. want to silence this exception. Notice that this has no effect on
  241. platforms that don't support os.symlink.
  242. The optional ignore argument is a callable. If given, it
  243. is called with the `src` parameter, which is the directory
  244. being visited by copytree(), and `names` which is the list of
  245. `src` contents, as returned by os.listdir():
  246. callable(src, names) -> ignored_names
  247. Since copytree() is called recursively, the callable will be
  248. called once for each directory that is copied. It returns a
  249. list of names relative to the `src` directory that should
  250. not be copied.
  251. The optional copy_function argument is a callable that will be used
  252. to copy each file. It will be called with the source path and the
  253. destination path as arguments. By default, copy2() is used, but any
  254. function that supports the same signature (like copy()) can be used.
  255. """
  256. names = os.listdir(src)
  257. if ignore is not None:
  258. ignored_names = ignore(src, names)
  259. else:
  260. ignored_names = set()
  261. os.makedirs(dst)
  262. errors = []
  263. for name in names:
  264. if name in ignored_names:
  265. continue
  266. srcname = os.path.join(src, name)
  267. dstname = os.path.join(dst, name)
  268. try:
  269. if os.path.islink(srcname):
  270. linkto = os.readlink(srcname)
  271. if symlinks:
  272. # We can't just leave it to `copy_function` because legacy
  273. # code with a custom `copy_function` may rely on copytree
  274. # doing the right thing.
  275. os.symlink(linkto, dstname)
  276. copystat(srcname, dstname, follow_symlinks=not symlinks)
  277. else:
  278. # ignore dangling symlink if the flag is on
  279. if not os.path.exists(linkto) and ignore_dangling_symlinks:
  280. continue
  281. # otherwise let the copy occurs. copy2 will raise an error
  282. if os.path.isdir(srcname):
  283. copytree(srcname, dstname, symlinks, ignore,
  284. copy_function)
  285. else:
  286. copy_function(srcname, dstname)
  287. elif os.path.isdir(srcname):
  288. copytree(srcname, dstname, symlinks, ignore, copy_function)
  289. else:
  290. # Will raise a SpecialFileError for unsupported file types
  291. copy_function(srcname, dstname)
  292. # catch the Error from the recursive copytree so that we can
  293. # continue with other files
  294. except Error as err:
  295. errors.extend(err.args[0])
  296. except OSError as why:
  297. errors.append((srcname, dstname, str(why)))
  298. try:
  299. copystat(src, dst)
  300. except OSError as why:
  301. # Copying file access times may fail on Windows
  302. if getattr(why, 'winerror', None) is None:
  303. errors.append((src, dst, str(why)))
  304. if errors:
  305. raise Error(errors)
  306. return dst
  307. # version vulnerable to race conditions
  308. def _rmtree_unsafe(path, onerror):
  309. try:
  310. with os.scandir(path) as scandir_it:
  311. entries = list(scandir_it)
  312. except OSError:
  313. onerror(os.scandir, path, sys.exc_info())
  314. entries = []
  315. for entry in entries:
  316. fullname = entry.path
  317. try:
  318. is_dir = entry.is_dir(follow_symlinks=False)
  319. except OSError:
  320. is_dir = False
  321. if is_dir:
  322. try:
  323. if entry.is_symlink():
  324. # This can only happen if someone replaces
  325. # a directory with a symlink after the call to
  326. # os.scandir or entry.is_dir above.
  327. raise OSError("Cannot call rmtree on a symbolic link")
  328. except OSError:
  329. onerror(os.path.islink, fullname, sys.exc_info())
  330. continue
  331. _rmtree_unsafe(fullname, onerror)
  332. else:
  333. try:
  334. os.unlink(fullname)
  335. except OSError:
  336. onerror(os.unlink, fullname, sys.exc_info())
  337. try:
  338. os.rmdir(path)
  339. except OSError:
  340. onerror(os.rmdir, path, sys.exc_info())
  341. # Version using fd-based APIs to protect against races
  342. def _rmtree_safe_fd(topfd, path, onerror):
  343. try:
  344. with os.scandir(topfd) as scandir_it:
  345. entries = list(scandir_it)
  346. except OSError as err:
  347. err.filename = path
  348. onerror(os.scandir, path, sys.exc_info())
  349. return
  350. for entry in entries:
  351. fullname = os.path.join(path, entry.name)
  352. try:
  353. is_dir = entry.is_dir(follow_symlinks=False)
  354. if is_dir:
  355. orig_st = entry.stat(follow_symlinks=False)
  356. is_dir = stat.S_ISDIR(orig_st.st_mode)
  357. except OSError:
  358. is_dir = False
  359. if is_dir:
  360. try:
  361. dirfd = os.open(entry.name, os.O_RDONLY, dir_fd=topfd)
  362. except OSError:
  363. onerror(os.open, fullname, sys.exc_info())
  364. else:
  365. try:
  366. if os.path.samestat(orig_st, os.fstat(dirfd)):
  367. _rmtree_safe_fd(dirfd, fullname, onerror)
  368. try:
  369. os.rmdir(entry.name, dir_fd=topfd)
  370. except OSError:
  371. onerror(os.rmdir, fullname, sys.exc_info())
  372. else:
  373. try:
  374. # This can only happen if someone replaces
  375. # a directory with a symlink after the call to
  376. # os.scandir or stat.S_ISDIR above.
  377. raise OSError("Cannot call rmtree on a symbolic "
  378. "link")
  379. except OSError:
  380. onerror(os.path.islink, fullname, sys.exc_info())
  381. finally:
  382. os.close(dirfd)
  383. else:
  384. try:
  385. os.unlink(entry.name, dir_fd=topfd)
  386. except OSError:
  387. onerror(os.unlink, fullname, sys.exc_info())
  388. _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <=
  389. os.supports_dir_fd and
  390. os.scandir in os.supports_fd and
  391. os.stat in os.supports_follow_symlinks)
  392. def rmtree(path, ignore_errors=False, onerror=None):
  393. """Recursively delete a directory tree.
  394. If ignore_errors is set, errors are ignored; otherwise, if onerror
  395. is set, it is called to handle the error with arguments (func,
  396. path, exc_info) where func is platform and implementation dependent;
  397. path is the argument to that function that caused it to fail; and
  398. exc_info is a tuple returned by sys.exc_info(). If ignore_errors
  399. is false and onerror is None, an exception is raised.
  400. """
  401. if ignore_errors:
  402. def onerror(*args):
  403. pass
  404. elif onerror is None:
  405. def onerror(*args):
  406. raise
  407. if _use_fd_functions:
  408. # While the unsafe rmtree works fine on bytes, the fd based does not.
  409. if isinstance(path, bytes):
  410. path = os.fsdecode(path)
  411. # Note: To guard against symlink races, we use the standard
  412. # lstat()/open()/fstat() trick.
  413. try:
  414. orig_st = os.lstat(path)
  415. except Exception:
  416. onerror(os.lstat, path, sys.exc_info())
  417. return
  418. try:
  419. fd = os.open(path, os.O_RDONLY)
  420. except Exception:
  421. onerror(os.lstat, path, sys.exc_info())
  422. return
  423. try:
  424. if os.path.samestat(orig_st, os.fstat(fd)):
  425. _rmtree_safe_fd(fd, path, onerror)
  426. try:
  427. os.rmdir(path)
  428. except OSError:
  429. onerror(os.rmdir, path, sys.exc_info())
  430. else:
  431. try:
  432. # symlinks to directories are forbidden, see bug #1669
  433. raise OSError("Cannot call rmtree on a symbolic link")
  434. except OSError:
  435. onerror(os.path.islink, path, sys.exc_info())
  436. finally:
  437. os.close(fd)
  438. else:
  439. try:
  440. if os.path.islink(path):
  441. # symlinks to directories are forbidden, see bug #1669
  442. raise OSError("Cannot call rmtree on a symbolic link")
  443. except OSError:
  444. onerror(os.path.islink, path, sys.exc_info())
  445. # can't continue even if onerror hook returns
  446. return
  447. return _rmtree_unsafe(path, onerror)
  448. # Allow introspection of whether or not the hardening against symlink
  449. # attacks is supported on the current platform
  450. rmtree.avoids_symlink_attacks = _use_fd_functions
  451. def _basename(path):
  452. # A basename() variant which first strips the trailing slash, if present.
  453. # Thus we always get the last component of the path, even for directories.
  454. sep = os.path.sep + (os.path.altsep or '')
  455. return os.path.basename(path.rstrip(sep))
  456. def move(src, dst, copy_function=copy2):
  457. """Recursively move a file or directory to another location. This is
  458. similar to the Unix "mv" command. Return the file or directory's
  459. destination.
  460. If the destination is a directory or a symlink to a directory, the source
  461. is moved inside the directory. The destination path must not already
  462. exist.
  463. If the destination already exists but is not a directory, it may be
  464. overwritten depending on os.rename() semantics.
  465. If the destination is on our current filesystem, then rename() is used.
  466. Otherwise, src is copied to the destination and then removed. Symlinks are
  467. recreated under the new name if os.rename() fails because of cross
  468. filesystem renames.
  469. The optional `copy_function` argument is a callable that will be used
  470. to copy the source or it will be delegated to `copytree`.
  471. By default, copy2() is used, but any function that supports the same
  472. signature (like copy()) can be used.
  473. A lot more could be done here... A look at a mv.c shows a lot of
  474. the issues this implementation glosses over.
  475. """
  476. real_dst = dst
  477. if os.path.isdir(dst):
  478. if _samefile(src, dst):
  479. # We might be on a case insensitive filesystem,
  480. # perform the rename anyway.
  481. os.rename(src, dst)
  482. return
  483. real_dst = os.path.join(dst, _basename(src))
  484. if os.path.exists(real_dst):
  485. raise Error("Destination path '%s' already exists" % real_dst)
  486. try:
  487. os.rename(src, real_dst)
  488. except OSError:
  489. if os.path.islink(src):
  490. linkto = os.readlink(src)
  491. os.symlink(linkto, real_dst)
  492. os.unlink(src)
  493. elif os.path.isdir(src):
  494. if _destinsrc(src, dst):
  495. raise Error("Cannot move a directory '%s' into itself"
  496. " '%s'." % (src, dst))
  497. copytree(src, real_dst, copy_function=copy_function,
  498. symlinks=True)
  499. rmtree(src)
  500. else:
  501. copy_function(src, real_dst)
  502. os.unlink(src)
  503. return real_dst
  504. def _destinsrc(src, dst):
  505. src = os.path.abspath(src)
  506. dst = os.path.abspath(dst)
  507. if not src.endswith(os.path.sep):
  508. src += os.path.sep
  509. if not dst.endswith(os.path.sep):
  510. dst += os.path.sep
  511. return dst.startswith(src)
  512. def _get_gid(name):
  513. """Returns a gid, given a group name."""
  514. if getgrnam is None or name is None:
  515. return None
  516. try:
  517. result = getgrnam(name)
  518. except KeyError:
  519. result = None
  520. if result is not None:
  521. return result[2]
  522. return None
  523. def _get_uid(name):
  524. """Returns an uid, given a user name."""
  525. if getpwnam is None or name is None:
  526. return None
  527. try:
  528. result = getpwnam(name)
  529. except KeyError:
  530. result = None
  531. if result is not None:
  532. return result[2]
  533. return None
  534. def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
  535. owner=None, group=None, logger=None):
  536. """Create a (possibly compressed) tar file from all the files under
  537. 'base_dir'.
  538. 'compress' must be "gzip" (the default), "bzip2", "xz", or None.
  539. 'owner' and 'group' can be used to define an owner and a group for the
  540. archive that is being built. If not provided, the current owner and group
  541. will be used.
  542. The output tar file will be named 'base_name' + ".tar", possibly plus
  543. the appropriate compression extension (".gz", ".bz2", or ".xz").
  544. Returns the output filename.
  545. """
  546. if compress is None:
  547. tar_compression = ''
  548. elif _ZLIB_SUPPORTED and compress == 'gzip':
  549. tar_compression = 'gz'
  550. elif _BZ2_SUPPORTED and compress == 'bzip2':
  551. tar_compression = 'bz2'
  552. elif _LZMA_SUPPORTED and compress == 'xz':
  553. tar_compression = 'xz'
  554. else:
  555. raise ValueError("bad value for 'compress', or compression format not "
  556. "supported : {0}".format(compress))
  557. import tarfile # late import for breaking circular dependency
  558. compress_ext = '.' + tar_compression if compress else ''
  559. archive_name = base_name + '.tar' + compress_ext
  560. archive_dir = os.path.dirname(archive_name)
  561. if archive_dir and not os.path.exists(archive_dir):
  562. if logger is not None:
  563. logger.info("creating %s", archive_dir)
  564. if not dry_run:
  565. os.makedirs(archive_dir)
  566. # creating the tarball
  567. if logger is not None:
  568. logger.info('Creating tar archive')
  569. uid = _get_uid(owner)
  570. gid = _get_gid(group)
  571. def _set_uid_gid(tarinfo):
  572. if gid is not None:
  573. tarinfo.gid = gid
  574. tarinfo.gname = group
  575. if uid is not None:
  576. tarinfo.uid = uid
  577. tarinfo.uname = owner
  578. return tarinfo
  579. if not dry_run:
  580. tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
  581. try:
  582. tar.add(base_dir, filter=_set_uid_gid)
  583. finally:
  584. tar.close()
  585. return archive_name
  586. def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
  587. """Create a zip file from all the files under 'base_dir'.
  588. The output zip file will be named 'base_name' + ".zip". Returns the
  589. name of the output zip file.
  590. """
  591. import zipfile # late import for breaking circular dependency
  592. zip_filename = base_name + ".zip"
  593. archive_dir = os.path.dirname(base_name)
  594. if archive_dir and not os.path.exists(archive_dir):
  595. if logger is not None:
  596. logger.info("creating %s", archive_dir)
  597. if not dry_run:
  598. os.makedirs(archive_dir)
  599. if logger is not None:
  600. logger.info("creating '%s' and adding '%s' to it",
  601. zip_filename, base_dir)
  602. if not dry_run:
  603. with zipfile.ZipFile(zip_filename, "w",
  604. compression=zipfile.ZIP_DEFLATED) as zf:
  605. path = os.path.normpath(base_dir)
  606. if path != os.curdir:
  607. zf.write(path, path)
  608. if logger is not None:
  609. logger.info("adding '%s'", path)
  610. for dirpath, dirnames, filenames in os.walk(base_dir):
  611. for name in sorted(dirnames):
  612. path = os.path.normpath(os.path.join(dirpath, name))
  613. zf.write(path, path)
  614. if logger is not None:
  615. logger.info("adding '%s'", path)
  616. for name in filenames:
  617. path = os.path.normpath(os.path.join(dirpath, name))
  618. if os.path.isfile(path):
  619. zf.write(path, path)
  620. if logger is not None:
  621. logger.info("adding '%s'", path)
  622. return zip_filename
  623. _ARCHIVE_FORMATS = {
  624. 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
  625. }
  626. if _ZLIB_SUPPORTED:
  627. _ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')],
  628. "gzip'ed tar-file")
  629. _ARCHIVE_FORMATS['zip'] = (_make_zipfile, [], "ZIP file")
  630. if _BZ2_SUPPORTED:
  631. _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
  632. "bzip2'ed tar-file")
  633. if _LZMA_SUPPORTED:
  634. _ARCHIVE_FORMATS['xztar'] = (_make_tarball, [('compress', 'xz')],
  635. "xz'ed tar-file")
  636. def get_archive_formats():
  637. """Returns a list of supported formats for archiving and unarchiving.
  638. Each element of the returned sequence is a tuple (name, description)
  639. """
  640. formats = [(name, registry[2]) for name, registry in
  641. _ARCHIVE_FORMATS.items()]
  642. formats.sort()
  643. return formats
  644. def register_archive_format(name, function, extra_args=None, description=''):
  645. """Registers an archive format.
  646. name is the name of the format. function is the callable that will be
  647. used to create archives. If provided, extra_args is a sequence of
  648. (name, value) tuples that will be passed as arguments to the callable.
  649. description can be provided to describe the format, and will be returned
  650. by the get_archive_formats() function.
  651. """
  652. if extra_args is None:
  653. extra_args = []
  654. if not callable(function):
  655. raise TypeError('The %s object is not callable' % function)
  656. if not isinstance(extra_args, (tuple, list)):
  657. raise TypeError('extra_args needs to be a sequence')
  658. for element in extra_args:
  659. if not isinstance(element, (tuple, list)) or len(element) !=2:
  660. raise TypeError('extra_args elements are : (arg_name, value)')
  661. _ARCHIVE_FORMATS[name] = (function, extra_args, description)
  662. def unregister_archive_format(name):
  663. del _ARCHIVE_FORMATS[name]
  664. def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
  665. dry_run=0, owner=None, group=None, logger=None):
  666. """Create an archive file (eg. zip or tar).
  667. 'base_name' is the name of the file to create, minus any format-specific
  668. extension; 'format' is the archive format: one of "zip", "tar", "gztar",
  669. "bztar", or "xztar". Or any other registered format.
  670. 'root_dir' is a directory that will be the root directory of the
  671. archive; ie. we typically chdir into 'root_dir' before creating the
  672. archive. 'base_dir' is the directory where we start archiving from;
  673. ie. 'base_dir' will be the common prefix of all files and
  674. directories in the archive. 'root_dir' and 'base_dir' both default
  675. to the current directory. Returns the name of the archive file.
  676. 'owner' and 'group' are used when creating a tar archive. By default,
  677. uses the current owner and group.
  678. """
  679. save_cwd = os.getcwd()
  680. if root_dir is not None:
  681. if logger is not None:
  682. logger.debug("changing into '%s'", root_dir)
  683. base_name = os.path.abspath(base_name)
  684. if not dry_run:
  685. os.chdir(root_dir)
  686. if base_dir is None:
  687. base_dir = os.curdir
  688. kwargs = {'dry_run': dry_run, 'logger': logger}
  689. try:
  690. format_info = _ARCHIVE_FORMATS[format]
  691. except KeyError:
  692. raise ValueError("unknown archive format '%s'" % format) from None
  693. func = format_info[0]
  694. for arg, val in format_info[1]:
  695. kwargs[arg] = val
  696. if format != 'zip':
  697. kwargs['owner'] = owner
  698. kwargs['group'] = group
  699. try:
  700. filename = func(base_name, base_dir, **kwargs)
  701. finally:
  702. if root_dir is not None:
  703. if logger is not None:
  704. logger.debug("changing back to '%s'", save_cwd)
  705. os.chdir(save_cwd)
  706. return filename
  707. def get_unpack_formats():
  708. """Returns a list of supported formats for unpacking.
  709. Each element of the returned sequence is a tuple
  710. (name, extensions, description)
  711. """
  712. formats = [(name, info[0], info[3]) for name, info in
  713. _UNPACK_FORMATS.items()]
  714. formats.sort()
  715. return formats
  716. def _check_unpack_options(extensions, function, extra_args):
  717. """Checks what gets registered as an unpacker."""
  718. # first make sure no other unpacker is registered for this extension
  719. existing_extensions = {}
  720. for name, info in _UNPACK_FORMATS.items():
  721. for ext in info[0]:
  722. existing_extensions[ext] = name
  723. for extension in extensions:
  724. if extension in existing_extensions:
  725. msg = '%s is already registered for "%s"'
  726. raise RegistryError(msg % (extension,
  727. existing_extensions[extension]))
  728. if not callable(function):
  729. raise TypeError('The registered function must be a callable')
  730. def register_unpack_format(name, extensions, function, extra_args=None,
  731. description=''):
  732. """Registers an unpack format.
  733. `name` is the name of the format. `extensions` is a list of extensions
  734. corresponding to the format.
  735. `function` is the callable that will be
  736. used to unpack archives. The callable will receive archives to unpack.
  737. If it's unable to handle an archive, it needs to raise a ReadError
  738. exception.
  739. If provided, `extra_args` is a sequence of
  740. (name, value) tuples that will be passed as arguments to the callable.
  741. description can be provided to describe the format, and will be returned
  742. by the get_unpack_formats() function.
  743. """
  744. if extra_args is None:
  745. extra_args = []
  746. _check_unpack_options(extensions, function, extra_args)
  747. _UNPACK_FORMATS[name] = extensions, function, extra_args, description
  748. def unregister_unpack_format(name):
  749. """Removes the pack format from the registry."""
  750. del _UNPACK_FORMATS[name]
  751. def _ensure_directory(path):
  752. """Ensure that the parent directory of `path` exists"""
  753. dirname = os.path.dirname(path)
  754. if not os.path.isdir(dirname):
  755. os.makedirs(dirname)
  756. def _unpack_zipfile(filename, extract_dir):
  757. """Unpack zip `filename` to `extract_dir`
  758. """
  759. import zipfile # late import for breaking circular dependency
  760. if not zipfile.is_zipfile(filename):
  761. raise ReadError("%s is not a zip file" % filename)
  762. zip = zipfile.ZipFile(filename)
  763. try:
  764. for info in zip.infolist():
  765. name = info.filename
  766. # don't extract absolute paths or ones with .. in them
  767. if name.startswith('/') or '..' in name:
  768. continue
  769. target = os.path.join(extract_dir, *name.split('/'))
  770. if not target:
  771. continue
  772. _ensure_directory(target)
  773. if not name.endswith('/'):
  774. # file
  775. data = zip.read(info.filename)
  776. f = open(target, 'wb')
  777. try:
  778. f.write(data)
  779. finally:
  780. f.close()
  781. del data
  782. finally:
  783. zip.close()
  784. def _unpack_tarfile(filename, extract_dir):
  785. """Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir`
  786. """
  787. import tarfile # late import for breaking circular dependency
  788. try:
  789. tarobj = tarfile.open(filename)
  790. except tarfile.TarError:
  791. raise ReadError(
  792. "%s is not a compressed or uncompressed tar file" % filename)
  793. try:
  794. tarobj.extractall(extract_dir)
  795. finally:
  796. tarobj.close()
  797. _UNPACK_FORMATS = {
  798. 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
  799. 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file"),
  800. }
  801. if _ZLIB_SUPPORTED:
  802. _UNPACK_FORMATS['gztar'] = (['.tar.gz', '.tgz'], _unpack_tarfile, [],
  803. "gzip'ed tar-file")
  804. if _BZ2_SUPPORTED:
  805. _UNPACK_FORMATS['bztar'] = (['.tar.bz2', '.tbz2'], _unpack_tarfile, [],
  806. "bzip2'ed tar-file")
  807. if _LZMA_SUPPORTED:
  808. _UNPACK_FORMATS['xztar'] = (['.tar.xz', '.txz'], _unpack_tarfile, [],
  809. "xz'ed tar-file")
  810. def _find_unpack_format(filename):
  811. for name, info in _UNPACK_FORMATS.items():
  812. for extension in info[0]:
  813. if filename.endswith(extension):
  814. return name
  815. return None
  816. def unpack_archive(filename, extract_dir=None, format=None):
  817. """Unpack an archive.
  818. `filename` is the name of the archive.
  819. `extract_dir` is the name of the target directory, where the archive
  820. is unpacked. If not provided, the current working directory is used.
  821. `format` is the archive format: one of "zip", "tar", "gztar", "bztar",
  822. or "xztar". Or any other registered format. If not provided,
  823. unpack_archive will use the filename extension and see if an unpacker
  824. was registered for that extension.
  825. In case none is found, a ValueError is raised.
  826. """
  827. if extract_dir is None:
  828. extract_dir = os.getcwd()
  829. extract_dir = os.fspath(extract_dir)
  830. filename = os.fspath(filename)
  831. if format is not None:
  832. try:
  833. format_info = _UNPACK_FORMATS[format]
  834. except KeyError:
  835. raise ValueError("Unknown unpack format '{0}'".format(format)) from None
  836. func = format_info[1]
  837. func(filename, extract_dir, **dict(format_info[2]))
  838. else:
  839. # we need to look at the registered unpackers supported extensions
  840. format = _find_unpack_format(filename)
  841. if format is None:
  842. raise ReadError("Unknown archive format '{0}'".format(filename))
  843. func = _UNPACK_FORMATS[format][1]
  844. kwargs = dict(_UNPACK_FORMATS[format][2])
  845. func(filename, extract_dir, **kwargs)
  846. if hasattr(os, 'statvfs'):
  847. __all__.append('disk_usage')
  848. _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
  849. _ntuple_diskusage.total.__doc__ = 'Total space in bytes'
  850. _ntuple_diskusage.used.__doc__ = 'Used space in bytes'
  851. _ntuple_diskusage.free.__doc__ = 'Free space in bytes'
  852. def disk_usage(path):
  853. """Return disk usage statistics about the given path.
  854. Returned value is a named tuple with attributes 'total', 'used' and
  855. 'free', which are the amount of total, used and free space, in bytes.
  856. """
  857. st = os.statvfs(path)
  858. free = st.f_bavail * st.f_frsize
  859. total = st.f_blocks * st.f_frsize
  860. used = (st.f_blocks - st.f_bfree) * st.f_frsize
  861. return _ntuple_diskusage(total, used, free)
  862. elif os.name == 'nt':
  863. import nt
  864. __all__.append('disk_usage')
  865. _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
  866. def disk_usage(path):
  867. """Return disk usage statistics about the given path.
  868. Returned values is a named tuple with attributes 'total', 'used' and
  869. 'free', which are the amount of total, used and free space, in bytes.
  870. """
  871. total, free = nt._getdiskusage(path)
  872. used = total - free
  873. return _ntuple_diskusage(total, used, free)
  874. def chown(path, user=None, group=None):
  875. """Change owner user and group of the given path.
  876. user and group can be the uid/gid or the user/group names, and in that case,
  877. they are converted to their respective uid/gid.
  878. """
  879. if user is None and group is None:
  880. raise ValueError("user and/or group must be set")
  881. _user = user
  882. _group = group
  883. # -1 means don't change it
  884. if user is None:
  885. _user = -1
  886. # user can either be an int (the uid) or a string (the system username)
  887. elif isinstance(user, str):
  888. _user = _get_uid(user)
  889. if _user is None:
  890. raise LookupError("no such user: {!r}".format(user))
  891. if group is None:
  892. _group = -1
  893. elif not isinstance(group, int):
  894. _group = _get_gid(group)
  895. if _group is None:
  896. raise LookupError("no such group: {!r}".format(group))
  897. os.chown(path, _user, _group)
  898. def get_terminal_size(fallback=(80, 24)):
  899. """Get the size of the terminal window.
  900. For each of the two dimensions, the environment variable, COLUMNS
  901. and LINES respectively, is checked. If the variable is defined and
  902. the value is a positive integer, it is used.
  903. When COLUMNS or LINES is not defined, which is the common case,
  904. the terminal connected to sys.__stdout__ is queried
  905. by invoking os.get_terminal_size.
  906. If the terminal size cannot be successfully queried, either because
  907. the system doesn't support querying, or because we are not
  908. connected to a terminal, the value given in fallback parameter
  909. is used. Fallback defaults to (80, 24) which is the default
  910. size used by many terminal emulators.
  911. The value returned is a named tuple of type os.terminal_size.
  912. """
  913. # columns, lines are the working values
  914. try:
  915. columns = int(os.environ['COLUMNS'])
  916. except (KeyError, ValueError):
  917. columns = 0
  918. try:
  919. lines = int(os.environ['LINES'])
  920. except (KeyError, ValueError):
  921. lines = 0
  922. # only query if necessary
  923. if columns <= 0 or lines <= 0:
  924. try:
  925. size = os.get_terminal_size(sys.__stdout__.fileno())
  926. except (AttributeError, ValueError, OSError):
  927. # stdout is None, closed, detached, or not a terminal, or
  928. # os.get_terminal_size() is unsupported
  929. size = os.terminal_size(fallback)
  930. if columns <= 0:
  931. columns = size.columns
  932. if lines <= 0:
  933. lines = size.lines
  934. return os.terminal_size((columns, lines))
  935. def which(cmd, mode=os.F_OK | os.X_OK, path=None):
  936. """Given a command, mode, and a PATH string, return the path which
  937. conforms to the given mode on the PATH, or None if there is no such
  938. file.
  939. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  940. of os.environ.get("PATH"), or can be overridden with a custom search
  941. path.
  942. """
  943. # Check that a given file can be accessed with the correct mode.
  944. # Additionally check that `file` is not a directory, as on Windows
  945. # directories pass the os.access check.
  946. def _access_check(fn, mode):
  947. return (os.path.exists(fn) and os.access(fn, mode)
  948. and not os.path.isdir(fn))
  949. # If we're given a path with a directory part, look it up directly rather
  950. # than referring to PATH directories. This includes checking relative to the
  951. # current directory, e.g. ./script
  952. if os.path.dirname(cmd):
  953. if _access_check(cmd, mode):
  954. return cmd
  955. return None
  956. if path is None:
  957. path = os.environ.get("PATH", os.defpath)
  958. if not path:
  959. return None
  960. path = path.split(os.pathsep)
  961. if sys.platform == "win32":
  962. # The current directory takes precedence on Windows.
  963. if not os.curdir in path:
  964. path.insert(0, os.curdir)
  965. # PATHEXT is necessary to check on Windows.
  966. pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
  967. # See if the given file matches any of the expected path extensions.
  968. # This will allow us to short circuit when given "python.exe".
  969. # If it does match, only test that one, otherwise we have to try
  970. # others.
  971. if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
  972. files = [cmd]
  973. else:
  974. files = [cmd + ext for ext in pathext]
  975. else:
  976. # On other platforms you don't have things like PATHEXT to tell you
  977. # what file suffixes are executable, so just pass on cmd as-is.
  978. files = [cmd]
  979. seen = set()
  980. for dir in path:
  981. normdir = os.path.normcase(dir)
  982. if not normdir in seen:
  983. seen.add(normdir)
  984. for thefile in files:
  985. name = os.path.join(dir, thefile)
  986. if _access_check(name, mode):
  987. return name
  988. return None
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...