id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,800
|
test_volume_of_parent.py
|
andreafrancia_trash-cli/tests/test_put/components/test_volume_of_parent.py
|
import unittest
from typing import cast
import flexmock
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.fstab.volume_of import VolumeOf
from trashcli.put.fs.parent_realpath import ParentRealpathFs
from trashcli.put.fs.volume_of_parent import VolumeOfParent
class TestVolumeOfParent(unittest.TestCase):
def setUp(self):
self.fs = FakeFs()
self.volume_of_parent = VolumeOfParent(self.fs)
def test(self):
self.fs.add_volume('/path')
result = self.volume_of_parent.volume_of_parent('/path/to/file')
assert result == '/path'
| 595
|
Python
|
.py
| 15
| 34.933333
| 72
| 0.75
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,801
|
test_trash_put_reporter.py
|
andreafrancia_trash-cli/tests/test_put/components/test_trash_put_reporter.py
|
from tests.support.py2mock import Mock
from six import StringIO
from trashcli.put.describer import Describer
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.put.my_logger import MyLogger
from trashcli.put.my_logger import StreamBackend
from trashcli.put.reporting.trash_put_reporter import TrashPutReporter
class TestTrashPutReporter:
def setup_method(self):
self.stderr = StringIO()
self.backend = StreamBackend(self.stderr)
self.fs = FakeFs()
self.fs.touch("file")
self.reporter = TrashPutReporter(self.fs)
def test_it_should_record_failures(self):
result = "\n".join(
self.reporter.unable_to_trash_file_non_existent('file').
resolve_messages())
assert (result == "cannot trash regular empty file 'file'")
| 820
|
Python
|
.py
| 19
| 37.263158
| 70
| 0.727387
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,802
|
test_describer.py
|
andreafrancia_trash-cli/tests/test_put/components/test_describer.py
|
# Copyright (C) 2011-2022 Andrea Francia Bereguardo(PV) Italy
import unittest
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.put.describer import Describer
class TestDescriber(unittest.TestCase):
def setUp(self):
self.fs = FakeFs()
self.describer = Describer(self.fs)
def test_on_directories(self):
self.fs.mkdir('a-dir')
assert "directory" == self.describer.describe('.')
assert "directory" == self.describer.describe("..")
assert "directory" == self.describer.describe('a-dir')
def test_on_dot_directories(self):
self.fs.mkdir('a-dir')
assert "'.' directory" == self.describer.describe("a-dir/.")
assert "'.' directory" == self.describer.describe("./.")
def test_on_dot_dot_directories(self):
self.fs.mkdir('a-dir')
assert "'..' directory" == self.describer.describe("./..")
assert "'..' directory" == self.describer.describe("a-dir/..")
def test_name_for_regular_files_non_empty_files(self):
self.fs.make_file("non-empty", "contents")
assert "regular file" == self.describer.describe("non-empty")
def test_name_for_empty_file(self):
self.fs.make_file("empty")
assert "regular empty file" == self.describer.describe("empty")
def test_name_for_symbolic_links(self):
self.fs.symlink("nowhere", "/symlink")
assert "symbolic link" == self.describer.describe("symlink")
def test_name_for_non_existent_entries(self):
assert "non existent" == self.describer.describe('non-existent')
| 1,599
|
Python
|
.py
| 32
| 42.6875
| 72
| 0.659355
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,803
|
test_readlink.py
|
andreafrancia_trash-cli/tests/test_put/components/test_fake_fs/test_readlink.py
|
from tests.support.capture_error import capture_error
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.put.fs.real_fs import RealFs
from tests.support.dirs.temp_dir import temp_dir
temp_dir = temp_dir
class TestReadLinkOnRealFs:
def setup_method(self):
self.fs = RealFs()
def test_readlink(self, temp_dir):
self.fs.symlink("target", temp_dir / "link")
assert self.fs.readlink(temp_dir / "link") == "target"
def test_readlink_on_regular_file(self, temp_dir):
self.fs.make_file(temp_dir / "regular-file", 'contents')
exc = capture_error(lambda: self.fs.readlink(temp_dir / "regular-file"))
assert ((type(exc), str(exc).replace(temp_dir, '')) ==
(OSError, "[Errno 22] Invalid argument: '/regular-file'"))
def test_lexists(self, temp_dir):
self.fs.symlink("target", temp_dir / "link")
assert self.fs.lexists(temp_dir / "link") is True
class TestReadLink:
def setup_method(self):
self.fs = FakeFs()
def test_readlink(self):
self.fs.symlink("target", "link")
assert self.fs.readlink("link") == "target"
def test_readlink_for_non_links(self):
self.fs.make_file("regular-file")
exc = capture_error(lambda: self.fs.readlink("regular-file"))
assert ((type(exc), str(exc)) ==
(OSError, "[Errno 22] Invalid argument: '/regular-file'"))
def test_read_file(self):
self.fs.make_file("regular_file", "contents")
assert self.fs.read("regular_file") == "contents"
def test_read_linked_file(self):
self.fs.make_file("regular_file", "contents")
self.fs.symlink("regular_file", "link")
assert self.fs.read("link") == "contents"
def test_is_dir_for_links(self):
self.fs.symlink("target", "link")
assert self.fs.isdir("link") is False
def test_read_linked_file_with_relative_path(self):
self.fs.makedirs("/a/b/c/d", 0o777)
self.fs.make_file("/a/b/c/d/regular_file", "contents")
self.fs.symlink("c/d/regular_file", "/a/b/link")
assert self.fs.read("/a/b/link") == "contents"
def test_lexists(self):
self.fs.symlink("target", "link")
assert self.fs.lexists("link") is True
| 2,290
|
Python
|
.py
| 48
| 39.958333
| 80
| 0.636856
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,804
|
test_fake_fs.py
|
andreafrancia_trash-cli/tests/test_put/components/test_fake_fs/test_fake_fs.py
|
import unittest
from tests.support.put.fake_fs.fake_fs import FakeFs
from tests.support.put.format_mode import format_mode
from tests.support.capture_error import capture_error
class TestFakeFs(unittest.TestCase):
def setUp(self):
self.fs = FakeFs('/')
def test(self):
result = self.fs.ls_a("/")
assert result == [".", ".."]
def test_create_dir(self):
self.fs.mkdir("/foo")
result = self.fs.ls_a("/")
assert result == [".", "..", "foo"]
def test_find_dir_root(self):
assert '/' == self.fs.get_entity_at('/').name
def test_find_dir_root_subdir(self):
self.fs.mkdir("/foo")
assert 'foo' == self.fs.get_entity_at('/foo').name
def test_create_dir_in_dir(self):
self.fs.mkdir("/foo")
self.fs.mkdir("/foo/bar")
result = self.fs.ls_a("/foo")
assert result == [".", "..", "bar"]
def test_create_file(self):
self.fs.mkdir("/foo")
self.fs.mkdir("/foo/bar")
self.fs.atomic_write("/foo/bar/baz", "content")
result = self.fs.read("/foo/bar/baz")
assert result == "content"
def test_chmod(self):
self.fs.make_file("/foo")
self.fs.chmod("/foo", 0o755)
assert oct(self.fs.get_mod("/foo")) == oct(0o755)
def test_is_dir_when_file(self):
self.fs.make_file("/foo")
assert self.fs.isdir("/foo") is False
def test_is_dir_when_dir(self):
self.fs.mkdir("/foo")
assert self.fs.isdir("/foo") is True
def test_is_dir_when_it_does_not_exists(self):
assert self.fs.isdir("/does-not-exists") is False
def test_exists_false(self):
assert self.fs.exists("/foo") is False
def test_exists_true(self):
self.fs.make_file("/foo")
assert self.fs.exists("/foo") is True
def test_remove_file(self):
self.fs.make_file("/foo")
self.fs.remove_file("/foo")
assert self.fs.exists("/foo") is False
def test_move(self):
self.fs.make_file("/foo")
self.fs.move("/foo", "/bar")
assert self.fs.exists("/foo") is False
assert self.fs.exists("/bar") is True
def test_move_dir(self):
self.fs.mkdir("/fruits")
self.fs.make_file("/apple")
self.fs.move("/apple", "/fruits")
assert self.fs.ls_a('/fruits') == ['.', '..', 'apple']
def test_islink_on_a_file(self):
self.fs.make_file("/foo", "content")
assert self.fs.islink("/foo") is False
def test_islink_on_a_link(self):
self.fs.symlink("dest", "/foo")
assert self.fs.islink("/foo") is True
def test_set_sticky_bit_when_unset(self):
self.fs.make_file("/foo")
assert self.fs.has_sticky_bit("/foo") is False
def test_set_sticky_bit_when_set(self):
self.fs.make_file("/foo")
self.fs.set_sticky_bit("/foo")
assert self.fs.has_sticky_bit("/foo") is True
def test_islink_when_not_found(self):
assert self.fs.islink("/foo") is False
def test_islink_when_directory_not_exisiting(self):
assert self.fs.islink("/foo/bar/baz") is False
def test_absolute_path(self):
self.fs.make_file('/foo')
assert '' == self.fs.get_entity_at('/foo').content
def test_relativae_path(self):
self.fs.make_file('/foo', 'content')
assert 'content' == self.fs.get_entity_at('foo').content
def test_relativae_path_with_cd(self):
self.fs.makedirs('/foo/bar', 0o755)
self.fs.make_file('/foo/bar/baz', 'content')
self.fs.cd('/foo/bar')
assert 'content' == self.fs.get_entity_at('baz').content
def test_isfile_with_file(self):
self.fs.make_file('/foo')
assert self.fs.isfile("/foo") is True
def test_isfile_with_dir(self):
self.fs.mkdir('/foo')
assert self.fs.isfile("/foo") is False
def test_getsize_with_empty_file(self):
self.fs.make_file("foo")
assert 0 == self.fs.getsize("foo")
def test_getsize_with_non_empty_file(self):
self.fs.make_file("foo", "1234")
assert 4 == self.fs.getsize("foo")
def test_getsize_with_dir(self):
self.fs.mkdir("foo")
self.assertRaises(NotImplementedError, lambda: self.fs.getsize("foo"))
def test_mode_lets_create_a_file(self):
self.fs.makedirs("/foo/bar/baz", 0o755)
self.fs.make_file("/foo/bar/baz/1", "1")
assert self.fs.isfile("/foo/bar/baz/1") is True
def test_mode_does_not_let_create_a_file(self):
self.fs.makedirs("/foo/bar/baz", 0o755)
self.fs.chmod("/foo/bar/baz", 0o055)
error = capture_error(
lambda: self.fs.make_file("/foo/bar/baz/1", "1"))
assert str(error) == "[Errno 13] Permission denied: '/foo/bar/baz/1'"
def test_get_mod_s_1(self):
self.fs.make_file("/foo", "content")
assert format_mode(self.fs.get_mod("/foo")) == '0o644'
def test_get_mod_s_2(self):
self.fs.makedirs("/foo", 0o000)
assert format_mode(self.fs.get_mod("/foo")) == '0o000'
| 5,100
|
Python
|
.py
| 120
| 34.416667
| 78
| 0.597601
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,805
|
test_realpath.py
|
andreafrancia_trash-cli/tests/test_put/components/test_fake_fs/test_realpath.py
|
from tests.support.put.fake_fs.fake_fs import FakeFs
class TestRealpath:
def setup_method(self):
self.fs = FakeFs()
def test(self):
self.fs.touch("pippo")
assert self.fs.realpath("pippo") == "/pippo"
def test_cur_dir_with_several_paths(self):
self.fs.mkdir("music")
self.fs.cd("music")
self.fs.make_file_and_dirs("be/bop/a/lula")
assert self.fs.realpath("be/bop/a/lula") == "/music/be/bop/a/lula"
| 476
|
Python
|
.py
| 12
| 32.083333
| 74
| 0.629139
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,806
|
test_makedirs.py
|
andreafrancia_trash-cli/tests/test_put/components/test_fake_fs/test_makedirs.py
|
from tests.support.capture_error import capture_error
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.put.fs.fs import list_all
class TestMakeDirs:
def setup_method(self):
self.fs = FakeFs()
def test_makedirs(self):
self.fs.makedirs("/foo/bar/baz", 0o700)
assert [
self.fs.isdir("/foo/bar/baz"),
self.fs.get_mod("/foo/bar/baz"),
] == [True, 0o700]
def test_makedirs_2(self):
self.fs.makedirs("/foo/bar/baz", 0o700)
assert (list(list_all(self.fs, "/")) ==
['/foo', '/foo/bar', '/foo/bar/baz'])
def test_makedirs_with_relative_paths(self):
self.fs.makedirs("foo/bar/baz", 0o700)
assert (list(list_all(self.fs, "/")) ==
['/foo', '/foo/bar', '/foo/bar/baz'])
def test_makedirs_from_cur_dir_with_relative_paths(self):
self.fs.mkdir("/cur_dir")
self.fs.cd("/cur_dir")
self.fs.makedirs("foo/bar/baz", 0o700)
assert (list(list_all(self.fs, "/")) ==
['/cur_dir', '/cur_dir/foo', '/cur_dir/foo/bar',
'/cur_dir/foo/bar/baz'])
def test_makedirs_from_cur_dir_with_absolute_path(self):
self.fs.mkdir("/cur_dir")
self.fs.cd("/cur_dir")
self.fs.makedirs("/foo/bar/baz", 0o700)
assert (list(list_all(self.fs, "/")) ==
['/cur_dir', '/foo', '/foo/bar', '/foo/bar/baz'])
def test_makedirs_honor_file_permissions(self):
self.fs.makedirs("/foo", 0o000)
error = capture_error(
lambda: self.fs.makedirs("/foo/bar", 0o755))
assert str(error) == "[Errno 13] Permission denied: '/foo/bar'"
| 1,715
|
Python
|
.py
| 38
| 35.368421
| 71
| 0.56438
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,807
|
test_real_fs_permissions.py
|
andreafrancia_trash-cli/tests/test_put/components/real_fs/test_real_fs_permissions.py
|
import unittest
from tests.support.capture_error import capture_error
from tests.support.dirs.my_path import MyPath
from trashcli.put.fs.real_fs import RealFs
class TestRealFsPermissions(unittest.TestCase):
def setUp(self):
self.fs = RealFs()
self.tmp_dir = MyPath.make_temp_dir()
def test(self):
self.fs.makedirs(self.tmp_dir / 'dir', 0o000)
error = capture_error(
lambda: self.fs.make_file(self.tmp_dir / 'dir' / 'file', 'content'))
assert str(error) == "[Errno 13] Permission denied: '%s'" % (
self.tmp_dir / 'dir' / 'file')
self.fs.chmod(self.tmp_dir / 'dir', 0o755)
def test_chmod_and_get_mod(self):
path = self.tmp_dir / 'file'
self.fs.make_file(path, 'content')
self.fs.chmod(path, 0o123)
assert self.fs.get_mod(path) == 0o123
def tearDown(self):
self.tmp_dir.clean_up()
| 922
|
Python
|
.py
| 22
| 34.363636
| 80
| 0.628924
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,808
|
test_size_counter_on_fake_fs.py
|
andreafrancia_trash-cli/tests/test_put/components/real_fs/test_size_counter_on_fake_fs.py
|
import unittest
from tests.support.dirs.my_path import MyPath
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.put.fs.size_counter import SizeCounter
class TestSizeCounterOnFakeFs(unittest.TestCase):
def setUp(self):
self.fs = FakeFs()
self.counter = SizeCounter(self.fs)
self.fs.makedirs('/tmp', 0o777)
self.tmp_dir = MyPath('/tmp')
def test_a_single_file(self):
self.fs.make_file(self.tmp_dir / 'file', 10 * 'a')
assert self.counter.get_size_recursive(self.tmp_dir / 'file') == 10
def test_two_files(self):
self.fs.make_file(self.tmp_dir / 'a', 100 * 'a')
self.fs.make_file(self.tmp_dir / 'b', 23 * 'b')
assert self.counter.get_size_recursive(self.tmp_dir) == 123
def test_recursive(self):
self.fs.make_file(self.tmp_dir / 'a', 3 * '-')
self.fs.makedirs(self.tmp_dir / 'dir', 0o777)
self.fs.make_file(self.tmp_dir / 'dir' / 'a', 20 * '-')
self.fs.makedirs(self.tmp_dir / 'dir' / 'dir', 0o777)
self.fs.make_file(self.tmp_dir / 'dir' / 'dir' / 'b', 100 * '-')
assert self.counter.get_size_recursive(self.tmp_dir) == 123
| 1,183
|
Python
|
.py
| 24
| 42.25
| 75
| 0.629565
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,809
|
test_real_fs_is_accessible.py
|
andreafrancia_trash-cli/tests/test_put/components/real_fs/test_real_fs_is_accessible.py
|
import os
import unittest
from tests.support.dirs.my_path import MyPath
from trashcli.put.fs.real_fs import RealFs
class TestRealFsIsAccessible(unittest.TestCase):
def setUp(self):
self.fs = RealFs()
self.tmp_dir = MyPath.make_temp_dir()
def test_dangling_link(self):
os.symlink('non-existent', self.tmp_dir / 'link')
result = self.fs.is_accessible(self.tmp_dir / 'link')
assert result is False
def test_connected_link(self):
self.fs.make_file(self.tmp_dir / 'link-target', '')
os.symlink('link-target', self.tmp_dir / 'link')
result = self.fs.is_accessible(self.tmp_dir / 'link')
assert result is True
def test_dangling_link_with_lexists(self):
os.symlink('non-existent', self.tmp_dir / 'link')
result = self.fs.lexists(self.tmp_dir / 'link')
assert result is True
def test_connected_link_with_lexists(self):
self.fs.make_file(self.tmp_dir / 'link-target', '')
os.symlink('link-target', self.tmp_dir / 'link')
result = self.fs.lexists(self.tmp_dir / 'link')
assert result is True
| 1,144
|
Python
|
.py
| 26
| 36.730769
| 61
| 0.654578
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,810
|
test_real_fs_list_dir.py
|
andreafrancia_trash-cli/tests/test_put/components/real_fs/test_real_fs_list_dir.py
|
import unittest
from tests.support.dirs.my_path import MyPath
from trashcli.put.fs.real_fs import RealFs
class TestRealFsListDir(unittest.TestCase):
def setUp(self):
self.fs = RealFs()
self.tmp_dir = MyPath.make_temp_dir()
def test(self):
self.fs.make_file(self.tmp_dir / 'a' , 'content')
self.fs.make_file(self.tmp_dir / 'b' , 'content')
self.fs.make_file(self.tmp_dir / 'c', 'content')
self.fs.makedirs(self.tmp_dir / 'd', 0o700)
assert sorted(self.fs.listdir(self.tmp_dir)) == ['a', 'b', 'c', 'd']
def tearDown(self):
self.tmp_dir.clean_up()
| 627
|
Python
|
.py
| 15
| 35.333333
| 76
| 0.633663
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,811
|
test_fake_fs_list_dir.py
|
andreafrancia_trash-cli/tests/test_put/components/real_fs/test_fake_fs_list_dir.py
|
import unittest
from tests.support.dirs.my_path import MyPath
from tests.support.put.fake_fs.fake_fs import FakeFs
class TestFakeFsListDir(unittest.TestCase):
def setUp(self):
self.fs = FakeFs()
self.tmp_dir = MyPath('/tmp')
self.fs.makedirs(self.tmp_dir, 0o700)
def test(self):
self.fs.make_file(self.tmp_dir / 'a', 'content')
self.fs.make_file(self.tmp_dir / 'b', 'content')
self.fs.make_file(self.tmp_dir / 'c', 'content')
self.fs.makedirs(self.tmp_dir / 'd', 0o700)
assert sorted(self.fs.listdir(self.tmp_dir)) == ['a', 'b', 'c', 'd']
| 616
|
Python
|
.py
| 14
| 37.5
| 76
| 0.638191
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,812
|
test_fake_fs_walk_no_follow.py
|
andreafrancia_trash-cli/tests/test_put/components/real_fs/test_fake_fs_walk_no_follow.py
|
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.put.fs.fs import list_all
class TestWalkNoFollow:
def setup_method(self):
self.fs = FakeFs()
def test(self):
self.fs.make_file("pippo")
self.fs.makedirs("/a/b/c/d", 0o700)
assert "\n".join(list_all(self.fs, "/")) == '/a\n' \
'/pippo\n' \
'/a/b\n' \
'/a/b/c\n' \
'/a/b/c/d'
| 592
|
Python
|
.py
| 13
| 25.153846
| 64
| 0.386087
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,813
|
test_size_counter_on_real_fs.py
|
andreafrancia_trash-cli/tests/test_put/components/real_fs/test_size_counter_on_real_fs.py
|
import unittest
import pytest
from tests.support.dirs.my_path import MyPath
from trashcli.put.fs.size_counter import SizeCounter
from trashcli.put.fs.real_fs import RealFs
@pytest.mark.slow
class TestSizeCounterOnRealFs(unittest.TestCase):
def setUp(self):
self.fs = RealFs()
self.counter = SizeCounter(self.fs)
self.tmp_dir = MyPath.make_temp_dir()
def test_a_single_file(self):
self.fs.make_file(self.tmp_dir / 'file', 10 * 'a')
assert self.counter.get_size_recursive(self.tmp_dir / 'file') == 10
def test_two_files(self):
self.fs.make_file(self.tmp_dir / 'a', 100 * 'a')
self.fs.make_file(self.tmp_dir / 'b', 23 * 'b')
assert self.counter.get_size_recursive(self.tmp_dir) == 123
def test_recursive(self):
self.fs.make_file(self.tmp_dir / 'a', 3 * '-')
self.fs.makedirs(self.tmp_dir / 'dir', 0o777)
self.fs.make_file(self.tmp_dir / 'dir' / 'a', 20 * '-')
self.fs.makedirs(self.tmp_dir / 'dir' / 'dir', 0o777)
self.fs.make_file(self.tmp_dir / 'dir' / 'dir' / 'b', 100 * '-')
assert self.counter.get_size_recursive(self.tmp_dir) == 123
def tearDown(self):
self.tmp_dir.clean_up()
| 1,231
|
Python
|
.py
| 27
| 39
| 75
| 0.637049
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,814
|
test_names.py
|
andreafrancia_trash-cli/tests/test_put/components/test_lstat/test_names.py
|
import getpass
import os
import grp
from trashcli.put.fs.real_fs import Names
class TestNames:
def setup_method(self):
self.names = Names()
def test_username(self):
assert self.names.username(os.getuid()) == getpass.getuser()
def test_username_when_not_found(self):
assert self.names.username(-1) is None
def test_group(self):
assert self.names.groupname(os.getgid()) == _current_group()
def test_group_when_not_found(self):
# this test will fail if run on a system where 99999 is the gid of
# a group
assert self.names.groupname(99999) is None
def _current_group():
return grp.getgrgid(os.getgid()).gr_name
| 698
|
Python
|
.py
| 19
| 31
| 74
| 0.687593
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,815
|
test_trashing_checker.py
|
andreafrancia_trash-cli/tests/test_put/components/trashing_checker/test_trashing_checker.py
|
from trashcli.fstab.volumes import FakeVolumes
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.either import Left
from trashcli.put.core.trashee import Trashee
from trashcli.put.gate import Gate
from trashcli.put.janitor_tools.trash_dir_checker import TrashDirChecker, \
DifferentVolumes
from tests.support.put.fake_fs.fake_fs import FakeFs
class TestTrashingChecker:
def setup_method(self):
self.fs = FakeFs()
self.checker = TrashDirChecker(self.fs)
def test_trashing_checker_same(self):
self.fs.add_volume('/volume1')
result = self.checker.file_could_be_trashed_in(
Trashee('/path1', '/volume1'),
make_candidate('/volume1/trash-dir', Gate.SameVolume),
{})
assert result.is_valid() is True
def test_home_in_same_volume(self):
result = self.checker.file_could_be_trashed_in(
Trashee('/path1', '/volume1'),
make_candidate('/home-vol/trash-dir', Gate.HomeFallback),
{})
assert result.is_valid() is False
def test_trashing_checker_different(self):
self.fs.add_volume("/vol1")
self.fs.add_volume("/vol2")
result = self.checker.file_could_be_trashed_in(
Trashee('/path1', '/vol1'),
make_candidate('/vol2/trash-dir-path', Gate.SameVolume),
{})
assert result == Left(DifferentVolumes("/vol2", "/vol1"))
def make_candidate(trash_dir_path, gate):
return Candidate(trash_dir_path=trash_dir_path,
path_maker_type=None,
check_type=None,
gate=gate,
volume="ignored")
| 1,695
|
Python
|
.py
| 39
| 34.358974
| 75
| 0.641119
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,816
|
test_home_fallback_gate_impl.py
|
andreafrancia_trash-cli/tests/test_put/components/trashing_checker/test_home_fallback_gate_impl.py
|
from tests.support.put.fake_fs.fake_fs import FakeFs
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.check_type import NoCheck
from trashcli.put.core.either import Left
from trashcli.put.core.path_maker_type import PathMakerType
from trashcli.put.core.trashee import Trashee
from trashcli.put.gate import Gate
from trashcli.put.janitor_tools.trash_dir_checker import TrashDirChecker, \
make_ok, HomeFallBackNotEnabled
class TestHomeFallbackGate:
def setup_method(self):
self.fake_fs = FakeFs()
self.gate_impl = TrashDirChecker(self.fake_fs)
def test_not_enabled(self):
result = self.gate_impl.file_could_be_trashed_in(
make_trashee(),
make_candidate('/xdf/Trash'),
{})
assert result == Left(HomeFallBackNotEnabled())
def test_enabled(self):
result = self.gate_impl.file_could_be_trashed_in(
make_trashee(),
make_candidate('/xdf/Trash'),
{
"TRASH_ENABLE_HOME_FALLBACK": "1"
})
assert result == make_ok()
# def test(self):
# result = os.statvfs('/Users/andrea/trash-cli')
# print("")
# pprint(result.f_bavail / 1024 / 1024)
# pprint(result.f_bfree / 1024 / 1024)
# # pprint(psutil.disk_usage('/'))
def make_candidate(path):
return Candidate(path, '/disk2', PathMakerType.AbsolutePaths, NoCheck,
Gate.HomeFallback)
def make_trashee():
return Trashee('/disk1/foo', "/disk1")
| 1,541
|
Python
|
.py
| 38
| 33.631579
| 75
| 0.658194
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,817
|
check-python-dep
|
andreafrancia_trash-cli/scripts/lib/check-python-dep
|
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
COMMAND="$1"
test -x "$VIRTUAL_ENV/bin/$COMMAND" || {
>&2 echo "$COMMAND not installed
Please run:
pip install -r requirements.txt -r requirements-dev.txt
"
}
| 282
|
Python
|
.py
| 10
| 26
| 80
| 0.63806
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,818
|
fs.py
|
andreafrancia_trash-cli/trashcli/fs.py
|
import os
import shutil
import stat
from abc import abstractmethod
from typing import Iterable, List
from trashcli.compat import Protocol
class FileSize(Protocol):
@abstractmethod
def file_size(self, path):
raise NotImplementedError()
class MakeFileExecutable(Protocol):
@abstractmethod
def make_file_executable(self, path):
raise NotImplementedError()
class WriteFile(Protocol):
@abstractmethod
def write_file(self, name, contents):
raise NotImplementedError()
class ReadFile(Protocol):
@abstractmethod
def read_file(self, path):
raise NotImplementedError()
class Move(Protocol):
@abstractmethod
def move(self, path, dest):
raise NotImplementedError()
class RemoveFile2(Protocol):
@abstractmethod
def remove_file2(self, path):
raise NotImplementedError()
class RemoveFile(Protocol):
@abstractmethod
def remove_file(self, path):
raise NotImplementedError()
class RemoveFileIfExists(Protocol):
@abstractmethod
def remove_file_if_exists(self, path):
raise NotImplementedError()
class EntriesIfDirExists(Protocol):
@abstractmethod
def entries_if_dir_exists(self, path): # type: (str) -> List[str]
raise NotImplementedError()
class PathExists(Protocol):
@abstractmethod
def exists(self, path):
raise NotImplementedError()
class HasStickyBit(Protocol):
@abstractmethod
def has_sticky_bit(self, path): # type: (str) -> bool
raise NotImplementedError
class IsStickyDir(Protocol):
@abstractmethod
def is_sticky_dir(self, path): # type: (str) -> bool
raise NotImplementedError
class IsSymLink(Protocol):
@abstractmethod
def is_symlink(self, path): # type: (str) -> bool
raise NotImplementedError
class ContentsOf(Protocol):
@abstractmethod
def contents_of(self, path):
raise NotImplementedError()
class RealEntriesIfDirExists(EntriesIfDirExists):
def entries_if_dir_exists(self, path):
if os.path.exists(path):
for entry in os.listdir(path):
yield entry
class RealExists(PathExists):
def exists(self, path): # type: (str) -> bool
return os.path.exists(path)
class RealHasStickyBit(HasStickyBit):
def has_sticky_bit(self, path):
return (os.stat(path).st_mode & stat.S_ISVTX) == stat.S_ISVTX
class RealIsStickyDir(IsStickyDir, RealHasStickyBit):
def is_sticky_dir(self, path): # type: (str) -> bool
return os.path.isdir(path) and self.has_sticky_bit(path)
class RealIsSymLink(IsSymLink):
def is_symlink(self, path): # type: (str) -> bool
return os.path.islink(path)
class RealContentsOf(ContentsOf):
def contents_of(self, path):
return _read_file(path)
class RealRemoveFile(RemoveFile):
def remove_file(self, path):
if os.path.lexists(path):
try:
os.remove(path)
except:
return shutil.rmtree(path)
class RealRemoveFile2(RemoveFile2):
def remove_file2(self, path):
try:
os.remove(path)
except OSError:
shutil.rmtree(path)
class RealRemoveFileIfExists(RemoveFileIfExists, RemoveFile2):
def remove_file_if_exists(self, path):
if os.path.lexists(path): self.remove_file2(path)
class RealMove(Move):
def move(self, path, dest):
return shutil.move(path, str(dest))
class ListFilesInDir(Protocol):
@abstractmethod
def list_files_in_dir(self, path): # type: (str) -> Iterable[str]
raise NotImplementedError()
class RealListFilesInDir(ListFilesInDir):
def list_files_in_dir(self, path): # type: (str) -> Iterable[str]
for entry in os.listdir(path):
result = os.path.join(path, entry)
yield result
class MkDirs(Protocol):
@abstractmethod
def mkdirs(self, path):
raise NotImplementedError()
class RealMkDirs(MkDirs):
def mkdirs(self, path):
if os.path.isdir(path):
return
os.makedirs(path)
class AtomicWrite(Protocol):
@abstractmethod
def atomic_write(self, path, content):
raise NotImplementedError()
@abstractmethod
def open_for_write_in_exclusive_and_create_mode(self, path):
raise NotImplementedError()
class RealAtomicWrite(AtomicWrite):
def atomic_write(self, path, content):
file_handle = self.open_for_write_in_exclusive_and_create_mode(path)
os.write(file_handle, content)
os.close(file_handle)
def open_for_write_in_exclusive_and_create_mode(self, path):
return os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
class RealReadFile(ReadFile):
def read_file(self, path):
return _read_file(path)
class RealWriteFile(WriteFile):
def write_file(self, name, contents):
with open(name, 'w') as f:
f.write(contents)
class RealMakeFileExecutable(MakeFileExecutable):
def make_file_executable(self, path):
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
class RealFileSize(FileSize):
def file_size(self, path):
return os.stat(path).st_size
class FsMethods(
RealEntriesIfDirExists,
RealExists,
RealIsStickyDir,
RealIsSymLink,
RealContentsOf,
RealRemoveFile,
RealRemoveFile2,
RealRemoveFileIfExists,
RealMove,
RealListFilesInDir,
RealMkDirs,
RealAtomicWrite,
RealReadFile,
RealWriteFile,
RealMakeFileExecutable,
RealFileSize,
):
pass
def _read_file(path):
with open(path) as f:
return f.read()
has_sticky_bit = RealHasStickyBit().has_sticky_bit
contents_of = RealContentsOf().contents_of
remove_file = RealRemoveFile().remove_file
move = RealMove().move
list_files_in_dir = RealListFilesInDir().list_files_in_dir
mkdirs = RealMkDirs().mkdirs
atomic_write = RealAtomicWrite().atomic_write
open_for_write_in_exclusive_and_create_mode = RealAtomicWrite().open_for_write_in_exclusive_and_create_mode
read_file = RealReadFile().read_file
write_file = RealWriteFile().write_file
make_file_executable = RealMakeFileExecutable().make_file_executable
file_size = RealFileSize().file_size
remove_file2 = RealRemoveFile2().remove_file2
is_sticky_dir = RealIsStickyDir().is_sticky_dir
| 6,321
|
Python
|
.py
| 182
| 29.065934
| 107
| 0.707522
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,819
|
trash.py
|
andreafrancia_trash-cli/trashcli/trash.py
|
# Copyright (C) 2007-2011 Andrea Francia Trivolzio(PV) Italy
version = '0.24.5.26'
| 84
|
Python
|
.py
| 2
| 40.5
| 60
| 0.740741
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,820
|
trash_dirs_scanner.py
|
andreafrancia_trash-cli/trashcli/trash_dirs_scanner.py
|
import os
from typing import Iterable
from trashcli.compat import Protocol
from trashcli.fs import PathExists, IsStickyDir, IsSymLink
from trashcli.fstab.volume_listing import VolumesListing
from trashcli.lib.dir_checker import DirChecker
from trashcli.lib.user_info import UserInfoProvider
class MyEnum(str):
def __repr__(self):
return str(self)
trash_dir_found = MyEnum('trash_dir_found')
trash_dir_skipped_because_parent_not_sticky = \
MyEnum('trash_dir_skipped_because_parent_not_sticky')
trash_dir_skipped_because_parent_is_symlink = \
MyEnum('trash_dir_skipped_because_parent_is_symlink')
top_trash_dir_does_not_exist = MyEnum('top_trash_dir_does_not_exist')
top_trash_dir_invalid_because_not_sticky = \
MyEnum('top_trash_dir_invalid_because_not_sticky')
top_trash_dir_invalid_because_parent_is_symlink = \
MyEnum('top_trash_dir_invalid_because_parent_is_symlink')
top_trash_dir_valid = MyEnum('top_trash_dir_valid')
class TrashDir(tuple):
@property
def path(self):
return self[0]
@property
def volume(self):
return self[1]
def __new__(cls, path, volume):
return tuple.__new__(TrashDir, (path, volume))
def __repr__(self):
return 'TrashDir(%r, %r)' % (self.path, self.volume)
class TopTrashDirRules:
class Reader(PathExists, IsStickyDir, IsSymLink, Protocol):
pass
def __init__(self, reader): # type: (Reader) -> None
self.reader = reader
def valid_to_be_read(self, path):
parent_trashdir = os.path.dirname(path)
if not self.reader.exists(path):
return top_trash_dir_does_not_exist
if not self.reader.is_sticky_dir(parent_trashdir):
return top_trash_dir_invalid_because_not_sticky
if self.reader.is_symlink(parent_trashdir):
return top_trash_dir_invalid_because_parent_is_symlink
else:
return top_trash_dir_valid
class TrashDirsScanner:
def __init__(self,
user_info_provider, # type: UserInfoProvider
volumes_listing, # type: VolumesListing
top_trash_dir_rules, # type: TopTrashDirRules
dir_checker, # type: DirChecker
):
self.user_info_provider = user_info_provider
self.volumes_listing = volumes_listing # type: VolumesListing
self.top_trash_dir_rules = top_trash_dir_rules
self.dir_checker = dir_checker
def scan_trash_dirs(self, environ, uid):
for user_info in self.user_info_provider.get_user_info(environ, uid):
for path in user_info.home_trash_dir_paths:
yield trash_dir_found, TrashDir(path, '/')
for volume in self.volumes_listing.list_volumes(environ):
top_trash_dir_path = os.path.join(volume, '.Trash',
str(user_info.uid))
result = self.top_trash_dir_rules.valid_to_be_read(
top_trash_dir_path)
if result == top_trash_dir_valid:
yield trash_dir_found, TrashDir(top_trash_dir_path, volume)
elif result == top_trash_dir_invalid_because_not_sticky:
yield trash_dir_skipped_because_parent_not_sticky, (
top_trash_dir_path,)
elif result == top_trash_dir_invalid_because_parent_is_symlink:
yield trash_dir_skipped_because_parent_is_symlink, (
top_trash_dir_path,)
alt_top_trash_dir = os.path.join(volume,
'.Trash-%s' % user_info.uid)
if self.dir_checker.is_dir(alt_top_trash_dir):
yield trash_dir_found, TrashDir(alt_top_trash_dir, volume)
def only_found(events, # type: Iterable[TrashDir]
): # type: (...) -> Iterable[TrashDir]
for event, args in events:
if event == trash_dir_found:
yield args
| 4,006
|
Python
|
.py
| 84
| 37.27381
| 79
| 0.625833
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,821
|
shell_completion.py
|
andreafrancia_trash-cli/trashcli/shell_completion.py
|
import argparse
from copy import copy
from typing import Dict
try:
def convert_to_list(tuple):
return [item for item in tuple]
from shtab import add_argument_to, FILE, DIR # type: ignore
defaults = convert_to_list(add_argument_to.__defaults__)
defaults[-1] = {
"zsh": r"""
# https://github.com/zsh-users/zsh/blob/19390a1ba8dc983b0a1379058e90cd51ce156815/Completion/Unix/Command/_rm#L72-L74
_trash_files() {
(( CURRENT > 0 )) && line[CURRENT]=()
line=( ${line//(#m)[\[\]()\\*?#<>~\^\|]/\\$MATCH} )
_files -F line
}
""",
}
add_argument_to.__defaults__ = tuple(defaults)
TRASH_FILES = copy(FILE)
TRASH_DIRS = copy(DIR)
def complete_with(completion, # type: Dict[str, str]
action, # type: argparse.Action
):
action.complete = completion # type: ignore
except ImportError:
from argparse import Action
TRASH_FILES = TRASH_DIRS = {}
class PrintCompletionAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
print('Please install shtab firstly!')
parser.exit(0)
def add_argument_to(parser, *args, **kwargs): # type: ignore
Action.complete = None # type: ignore
parser.add_argument(
'--print-completion',
choices=['bash', 'zsh', 'tcsh'],
action=PrintCompletionAction,
help='print shell completion script',
)
return parser
def complete_with(completion, # type: Dict[str, str]
action, # type: argparse.Action
):
pass
TRASH_FILES.update({"zsh": "_trash_files"})
TRASH_DIRS.update({"zsh": "(\\${\\$(trash-list --trash-dirs)#parent_*})"})
| 1,775
|
Python
|
.py
| 47
| 30.12766
| 116
| 0.59883
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,822
|
file_system_reader.py
|
andreafrancia_trash-cli/trashcli/file_system_reader.py
|
from trashcli.fs import RealIsStickyDir, RealHasStickyBit, \
RealIsSymLink, RealContentsOf, RealEntriesIfDirExists, RealExists
from trashcli.list.fs import FileSystemReaderForListCmd
class FileSystemReader(FileSystemReaderForListCmd,
RealIsStickyDir,
RealHasStickyBit,
RealIsSymLink,
RealContentsOf,
RealEntriesIfDirExists,
RealExists
):
pass
| 514
|
Python
|
.py
| 12
| 27.583333
| 69
| 0.602
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,823
|
compat.py
|
andreafrancia_trash-cli/trashcli/compat.py
|
def protocol():
try:
from typing import Protocol
return Protocol
except ImportError as e:
from typing_extensions import Protocol
return Protocol
Protocol = protocol()
del protocol
| 223
|
Python
|
.py
| 9
| 19
| 46
| 0.696682
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,824
|
context.py
|
andreafrancia_trash-cli/trashcli/put/context.py
|
from typing import List
from typing import NamedTuple
from typing import Optional
from trashcli.compat import Protocol
from trashcli.lib.environ import Environ
from trashcli.put.core.logs import LogData
from trashcli.put.core.mode import Mode
from trashcli.put.core.trash_all_result import TrashAllResult
from trashcli.put.core.trash_result import TrashResult
class Context(NamedTuple('Context', [
('paths', List[str]),
('user_trash_dir', Optional[str]),
('mode', Mode),
('forced_volume', Optional[str]),
('home_fallback', bool),
('program_name', str),
('log_data', LogData),
('environ', Environ),
('uid', int),
])):
def trash_each(self, trasher, # type: SingleTrasher
): # type (...) -> TrashAllResult
failed_paths = []
for path in self.paths:
result = trasher.trash_single(path, self)
if result == TrashResult.Failure:
failed_paths.append(path)
return TrashAllResult(failed_paths)
class SingleTrasher(Protocol):
def trash_single(self,
path, # type: str
context, # type: 'Context'
):
raise NotImplementedError
| 1,219
|
Python
|
.py
| 34
| 28.852941
| 61
| 0.643766
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,825
|
suffix.py
|
andreafrancia_trash-cli/trashcli/put/suffix.py
|
from trashcli.put.core.int_generator import IntGenerator
class Suffix:
def __init__(self,
int_gen, # type: IntGenerator
):
self.int_gen = int_gen
def suffix_for_index(self, index):
if index == 0:
return ""
elif index < 100:
return "_%s" % index
else:
return "_%s" % self.int_gen.new_int(0, 65535)
| 411
|
Python
|
.py
| 13
| 21.923077
| 57
| 0.521519
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,826
|
dir_maker.py
|
andreafrancia_trash-cli/trashcli/put/dir_maker.py
|
from trashcli.put.fs.fs import Fs
class DirMaker:
def __init__(self, fs): # type: (Fs) -> None
self.fs = fs
def mkdir_p(self, path, mode):
try:
self.fs.makedirs(path, mode)
except OSError:
if not self.fs.isdir(path):
raise
| 298
|
Python
|
.py
| 10
| 21.3
| 48
| 0.54386
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,827
|
my_logger.py
|
andreafrancia_trash-cli/trashcli/put/my_logger.py
|
from typing import IO
from typing import List
from trashcli.compat import Protocol
from trashcli.put.core.logs import Level
from trashcli.put.core.logs import LogData
from trashcli.put.core.logs import LogEntry
class LoggerBackend(Protocol):
def write_message(self,
log_entry, # type: LogEntry
log_data, # type: LogData
):
raise NotImplementedError()
class StreamBackend(LoggerBackend):
def __init__(self,
stderr, # type: IO[str]
): # type: (...) -> None
self.stderr = stderr
def write_message(self,
log_entry, # type: LogEntry
log_data, # type: LogData
):
if is_right_for_level(log_data.verbose, log_entry.level):
for message in log_entry.resolve_messages():
self.stderr.write("%s: %s\n" % (log_data.program_name, message))
def is_right_for_level(verbose, # type: int
level, # type: Level
):
min_level = {
Level.WARNING: 0,
Level.INFO: 1,
Level.DEBUG: 2,
}
return verbose >= min_level[level]
class MyLogger:
def __init__(self,
backend, # type: LoggerBackend
): # type: (...) -> None
self.backend = backend
def log_put(self,
entry, # type: LogEntry
log_data, # type: LogData
):
self.backend.write_message(entry, log_data)
def log_multiple(self,
entries, # type: List[LogEntry]
log_data, # type: LogData
): # type: (...) -> None
for entry in entries:
self.log_put(entry, log_data)
| 1,812
|
Python
|
.py
| 49
| 25.428571
| 80
| 0.525985
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,828
|
user.py
|
andreafrancia_trash-cli/trashcli/put/user.py
|
from trashcli.lib.my_input import Input
from trashcli.put.describer import Describer
class User:
def __init__(self,
my_input, # type: Input
describer, # type: Describer
):
self.input = my_input
self.describer = describer
def ask_user_about_deleting_file(self, program_name, path):
reply = self.input.read_input(
"%s: trash %s '%s'? " % (program_name,
self.describer.describe(path), path))
return parse_user_reply(reply)
user_replied_no = "user_replied_no"
user_replied_yes = "user_replied_yes"
def parse_user_reply(reply):
return {False: user_replied_no,
True: user_replied_yes}[reply.lower().startswith("y")]
| 776
|
Python
|
.py
| 19
| 31.210526
| 74
| 0.599466
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,829
|
format_trash_info.py
|
andreafrancia_trash-cli/trashcli/put/format_trash_info.py
|
import datetime
from six.moves.urllib.parse import quote as url_quote
def format_trashinfo(original_location, # type: str
deletion_date, # type: datetime.datetime
):
content = ("[Trash Info]\n" +
"Path=%s\n" % format_original_location(original_location) +
"DeletionDate=%s\n" % format_date(deletion_date)).encode('utf-8')
return content
def format_date(deletion_date): # type: (datetime.datetime) -> str
return deletion_date.strftime("%Y-%m-%dT%H:%M:%S")
def format_original_location(original_location): # type: (str) -> str
return url_quote(original_location, '/')
| 665
|
Python
|
.py
| 13
| 42.846154
| 80
| 0.64031
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,830
|
trash_dir_volume_reader.py
|
andreafrancia_trash-cli/trashcli/put/trash_dir_volume_reader.py
|
import os
from trashcli.put.fs.fs import RealPathFs
class TrashDirVolumeReader:
def __init__(self,
fs, # type: RealPathFs
):
self.fs = fs
def volume_of_trash_dir(self, trash_dir_path):
norm_trash_dir_path = os.path.normpath(trash_dir_path)
return self.fs.volume_of(
self.fs.realpath(norm_trash_dir_path))
| 388
|
Python
|
.py
| 11
| 26.818182
| 62
| 0.616622
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,831
|
describer.py
|
andreafrancia_trash-cli/trashcli/put/describer.py
|
import os
class Describer:
def __init__(self, fs):
self.fs = fs
def describe(self, path):
"""
Return a textual description of the file pointed by this path.
Options:
- "symbolic link"
- "directory"
- "'.' directory"
- "'..' directory"
- "regular file"
- "regular empty file"
- "non existent"
- "entry"
"""
if self.fs.islink(path):
return 'symbolic link'
elif self.fs.isdir(path):
if path == '.':
return 'directory'
elif path == '..':
return 'directory'
else:
if os.path.basename(path) == '.':
return "'.' directory"
elif os.path.basename(path) == '..':
return "'..' directory"
else:
return 'directory'
elif self.fs.isfile(path):
if self.fs.getsize(path) == 0:
return 'regular empty file'
else:
return 'regular file'
elif not self.fs.exists(path):
return 'non existent'
else:
return 'entry'
| 1,221
|
Python
|
.py
| 40
| 18.75
| 70
| 0.453311
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,832
|
gate.py
|
andreafrancia_trash-cli/trashcli/put/gate.py
|
from enum import Enum
class Gate(Enum):
HomeFallback = "HomeFallbackGate"
SameVolume = "SameVolumeGate"
def __repr__(self):
return "%s.%s" % (type(self).__name__, self.name)
| 197
|
Python
|
.py
| 6
| 28
| 57
| 0.648936
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,833
|
clock.py
|
andreafrancia_trash-cli/trashcli/put/clock.py
|
import datetime
class PutClock:
def now(self): # type: () -> datetime.datetime
raise NotImplementedError()
class RealClock(PutClock):
def now(self): # type: () -> datetime.datetime
return datetime.datetime.now()
| 242
|
Python
|
.py
| 7
| 29.571429
| 51
| 0.683983
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,834
|
janitor.py
|
andreafrancia_trash-cli/trashcli/put/janitor.py
|
from typing import NamedTuple, TypeVar
from trashcli.put.suffix import Suffix
from trashcli.put.core.int_generator import IntGenerator
from trashcli.put.my_logger import LoggerBackend
from trashcli.put.clock import PutClock
from trashcli.lib.environ import Environ
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.either import Left
from trashcli.put.core.failure_reason import FailureReason, LogContext
from trashcli.put.core.trashee import Trashee
from trashcli.put.fs.fs import Fs
from trashcli.put.janitor_tools.info_creator import TrashInfoCreator
from trashcli.put.janitor_tools.info_file_persister import InfoFilePersister, \
TrashedFile
from trashcli.put.janitor_tools.put_trash_dir import PutTrashDir
from trashcli.put.janitor_tools.security_check import SecurityCheck
from trashcli.put.janitor_tools.trash_dir_checker import TrashDirChecker
from trashcli.put.janitor_tools.trash_dir_creator import TrashDirCreator
from trashcli.put.jobs import JobExecutor
from trashcli.put.my_logger import LogData
from trashcli.put.my_logger import MyLogger
class NoLog(FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return ""
class Janitor:
def __init__(self,
fs, # type: Fs
clock, # type: PutClock
backend, # type: LoggerBackend
randint, # type: IntGenerator
):
self.trash_dir = PutTrashDir(fs)
self.trashing_checker = TrashDirChecker(fs)
self.info_dir = TrashInfoCreator(fs, clock)
self.security_check = SecurityCheck(fs)
self.persister = InfoFilePersister(fs, MyLogger(backend), Suffix(randint))
self.dir_creator = TrashDirCreator(fs)
self.executor = JobExecutor(MyLogger(backend), TrashedFile)
class Result(NamedTuple('Result', [
('ok', bool),
('reason', FailureReason)
])):
def succeeded(self):
return self.ok
def trash_file_in(self,
candidate, # type: Candidate
log_data, # type: LogData
environ, # type: Environ
trashee, # type: Trashee
): # type: (...) -> Result
secure = self.security_check.check_trash_dir_is_secure(candidate)
if isinstance(secure, Left):
return make_error(secure)
can_be_used = self.trashing_checker.file_could_be_trashed_in(
trashee, candidate, environ)
if isinstance(can_be_used, Left):
return make_error(can_be_used)
dirs_creation = self.dir_creator.make_candidate_dirs(candidate)
if isinstance(dirs_creation, Left):
return make_error(dirs_creation)
trashinfo_data = self.info_dir.make_trashinfo_data(
trashee.path, candidate)
if isinstance(trashinfo_data, Left):
return make_error(trashinfo_data)
persisting_job = self.persister.try_persist(trashinfo_data.value())
trashed_file = self.executor.execute(persisting_job, log_data)
trashed = self.trash_dir.try_trash(trashee.path, trashed_file)
if isinstance(trashed, Left):
return make_error(trashed)
return make_ok()
S = TypeVar('S')
def make_error(reason): # type: (Left[S, FailureReason]) -> Janitor.Result
return Janitor.Result(False, reason.error())
def make_ok(): # type: () -> Janitor.Result
return Janitor.Result(True, NoLog())
| 3,514
|
Python
|
.py
| 75
| 38.68
| 82
| 0.683841
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,835
|
file_trasher.py
|
andreafrancia_trash-cli/trashcli/put/file_trasher.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from trashcli.put.fs.fs import Fs
from trashcli.put.context import Context
from trashcli.put.core.trash_result import TrashResult
from trashcli.put.core.trashee import Trashee
from trashcli.put.fs.parent_realpath import ParentRealpathFs
from trashcli.put.fs.volume_of_parent import VolumeOfParent
from trashcli.put.janitor import Janitor
from trashcli.put.my_logger import LoggerBackend
from trashcli.put.my_logger import MyLogger
from trashcli.put.reporting.trash_put_reporter import TrashPutReporter
from trashcli.put.trash_directories_finder import TrashDirectoriesFinder
class FileTrasher:
def __init__(self,
fs, # type: Fs
janitor, # type: Janitor
backend, # type: LoggerBackend
): # type: (...) -> None
self.trash_directories_finder = TrashDirectoriesFinder(fs)
self.parent_realpath_fs = ParentRealpathFs(fs)
self.logger = MyLogger(backend)
self.reporter = TrashPutReporter(fs)
self.janitor = janitor
self.volume_of_parent = VolumeOfParent(fs)
def trash_file(self,
path, # type: str
context, # type: Context
):
volume = self._figure_out_volume(path, context.forced_volume)
trashee = Trashee(path, volume)
candidates = self._select_candidates(volume, context.user_trash_dir,
context.environ,
context.uid, context.home_fallback)
failures = []
for candidate in candidates:
self.logger.log_put(self.reporter.trash_dir_with_volume(candidate),
context.log_data)
trashing = self.janitor.trash_file_in(
candidate, context.log_data, context.environ, trashee)
if trashing.succeeded():
self.logger.log_put(
self.reporter.file_has_been_trashed_in_as(path,
candidate,
context.environ),
context.log_data)
return TrashResult.Success
else:
failures.append((candidate, trashing.reason))
self.logger.log_put(self.reporter.unable_to_trash_file(
trashee, failures, context.environ), context.log_data)
return TrashResult.Failure
def _figure_out_volume(self, path, default_volume):
if default_volume:
return default_volume
else:
return self.volume_of_parent.volume_of_parent(path)
def _select_candidates(self, volume, user_trash_dir, environ, uid,
home_fallback):
return self.trash_directories_finder. \
possible_trash_directories_for(volume,
user_trash_dir, environ, uid,
home_fallback)
| 3,073
|
Python
|
.py
| 62
| 35.112903
| 80
| 0.591681
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,836
|
trash_directories_finder.py
|
andreafrancia_trash-cli/trashcli/put/trash_directories_finder.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from typing import List
from trashcli.fstab.volume_of import VolumeOf
from trashcli.lib.environ import Environ
from trashcli.lib.trash_dirs import (
volume_trash_dir1, volume_trash_dir2, home_trash_dir)
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.check_type import NoCheck, TopTrashDirCheck
from trashcli.put.core.path_maker_type import PathMakerType
from trashcli.put.gate import Gate
class TrashDirectoriesFinder:
def __init__(self,
fs, # type: VolumeOf
):
self.fs = fs
def possible_trash_directories_for(self,
volume, # type: str
specific_trash_dir, # type: str
environ, # type: Environ
uid, # type: int
home_fallback, # type: bool
): # type: (...) -> List[Candidate]
trash_dirs = []
def add_home_trash(path, volume, gate):
trash_dirs.append(
Candidate(trash_dir_path=path,
volume=volume,
path_maker_type=PathMakerType.AbsolutePaths,
check_type=NoCheck,
gate=gate))
def add_top_trash_dir(path, volume):
trash_dirs.append(
Candidate(trash_dir_path=path,
volume=volume,
path_maker_type=PathMakerType.RelativePaths,
check_type=TopTrashDirCheck,
gate=Gate.SameVolume))
def add_alt_top_trash_dir(path, volume):
trash_dirs.append(
Candidate(trash_dir_path=path,
volume=volume,
path_maker_type=PathMakerType.RelativePaths,
check_type=NoCheck,
gate=Gate.SameVolume))
if specific_trash_dir:
path = specific_trash_dir
volume = self.fs.volume_of(path)
trash_dirs.append(
Candidate(trash_dir_path=path,
volume=volume,
path_maker_type=PathMakerType.RelativePaths,
check_type=NoCheck,
gate=Gate.SameVolume))
else:
for path, dir_volume in home_trash_dir(environ, self.fs):
add_home_trash(path, dir_volume, Gate.SameVolume)
for path, dir_volume in volume_trash_dir1(volume, uid):
add_top_trash_dir(path, dir_volume)
for path, dir_volume in volume_trash_dir2(volume, uid):
add_alt_top_trash_dir(path, dir_volume)
if home_fallback:
for path, dir_volume in home_trash_dir(environ, self.fs):
add_home_trash(path, dir_volume, Gate.HomeFallback)
return trash_dirs
| 3,078
|
Python
|
.py
| 64
| 30.90625
| 75
| 0.526946
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,837
|
octal.py
|
andreafrancia_trash-cli/trashcli/put/octal.py
|
def octal(n): # type: (int) -> str
return "%s%s" % ("0o", _remove_octal_prefix(oct(n)))
def _remove_octal_prefix(o):
if o.startswith('0o'):
return o[2:]
elif o.startswith('0'):
return o[1:]
else:
ValueError('Invalid octal format: %s' % o)
| 282
|
Python
|
.py
| 9
| 25.666667
| 56
| 0.560886
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,838
|
original_location.py
|
andreafrancia_trash-cli/trashcli/put/original_location.py
|
import os
from trashcli.put.core.path_maker_type import PathMakerType
from trashcli.put.fs.fs import Fs
class OriginalLocation:
def __init__(self,
fs, # type: Fs
):
self.fs = fs
def for_file(self,
path,
path_maker_type, # type: PathMakerType
volume_top_dir,
): # type: (...) -> str
normalized_path = os.path.normpath(path)
basename = os.path.basename(normalized_path)
parent = self.fs.parent_realpath2(normalized_path)
parent = self._calc_parent_path(parent, volume_top_dir,
path_maker_type)
return os.path.join(parent, basename)
@staticmethod
def _calc_parent_path(parent, # type: str
volume_top_dir, # type: str
path_maker_type, # type: PathMakerType
):
if path_maker_type == PathMakerType.AbsolutePaths:
return parent
if path_maker_type == PathMakerType.RelativePaths:
if (parent == volume_top_dir) or parent.startswith(
volume_top_dir + os.path.sep):
parent = parent[len(volume_top_dir + os.path.sep):]
return parent
| 1,305
|
Python
|
.py
| 31
| 28.903226
| 67
| 0.541798
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,839
|
parser.py
|
andreafrancia_trash-cli/trashcli/put/parser.py
|
import os
import pprint
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
from argparse import SUPPRESS
from typing import Any
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Union
from trashcli.put.core.mode import Mode
from trashcli.shell_completion import TRASH_DIRS
from trashcli.shell_completion import TRASH_FILES
from trashcli.shell_completion import add_argument_to
from trashcli.trash import version
ExitWithCode = NamedTuple('ExitWithCode', [
('type', type),
('exit_code', int),
])
Trash = NamedTuple('Trash', [
('type', type),
('program_name', str),
('options', Any),
('files', List[str]),
('trash_dir', Optional[str]),
('mode', Mode),
('forced_volume', Optional[str]),
('verbose', int),
('home_fallback', bool),
])
class Parser:
def parse_args(self, argv): # type: (list) -> Union[ExitWithCode, Trash]
program_name = os.path.basename(argv[0])
arg_parser = make_parser(program_name)
try:
options = arg_parser.parse_args(argv[1:])
if len(options.files) <= 0:
arg_parser.error("Please specify the files to trash.")
except SystemExit as e:
return ExitWithCode(type=ExitWithCode, exit_code=ensure_int(e.code))
return Trash(type=Trash,
program_name=program_name,
options=options,
files=options.files,
trash_dir=options.trashdir,
mode=options.mode,
forced_volume=options.forced_volume,
verbose=options.verbose,
home_fallback=options.home_fallback)
def ensure_int(code):
if not isinstance(code, int):
raise ValueError("code must be an int, got %s" % pprint.pformat(code))
return code
def make_parser(program_name):
parser = ArgumentParser(prog=program_name,
usage="%(prog)s [OPTION]... FILE...",
description="Put files in trash",
formatter_class=RawDescriptionHelpFormatter,
epilog="""\
all trash-cli commands:
trash-put trash files and directories.
trash-empty empty the trashcan(s).
trash-list list trashed files.
trash-restore restore a trashed file.
trash-rm remove individual files from the trashcan
To remove a file whose name starts with a '-', for example '-foo',
use one of these commands:
trash -- -foo
trash ./-foo
Report bugs to https://github.com/andreafrancia/trash-cli/issues""")
add_argument_to(parser)
parser.add_argument("-d", "--directory",
action="store_true",
help="ignored (for GNU rm compatibility)")
parser.add_argument("-f", "--force",
action="store_const",
dest="mode",
const=Mode.mode_force,
default=Mode.mode_unspecified,
help="silently ignore nonexistent files")
parser.add_argument("-i", "--interactive",
action="store_const",
dest="mode",
const=Mode.mode_interactive,
default=Mode.mode_unspecified,
help="prompt before every removal")
parser.add_argument("-r", "-R", "--recursive",
action="store_true",
help="ignored (for GNU rm compatibility)")
parser.add_argument("--trash-dir",
type=str,
action="store", dest='trashdir',
help='use TRASHDIR as trash folder'
).complete = TRASH_DIRS
parser.add_argument("-v",
"--verbose",
default=0,
action="count",
dest="verbose",
help="explain what is being done")
parser.add_argument('--force-volume',
default=None,
action="store",
dest="forced_volume",
help=SUPPRESS)
parser.add_argument('--home-fallback',
default=False,
action="store_true",
dest="home_fallback",
help=SUPPRESS)
parser.add_argument("--version",
action="version",
version=version)
parser.add_argument('files',
nargs='*'
).complete = TRASH_FILES
return parser
| 4,803
|
Python
|
.py
| 117
| 28.418803
| 80
| 0.544209
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,840
|
main.py
|
andreafrancia_trash-cli/trashcli/put/main.py
|
import os
import random
import sys
from trashcli.lib.environ import cast_environ
from trashcli.lib.my_input import Input
from trashcli.lib.my_input import RealInput
from trashcli.put.clock import RealClock
from trashcli.put.core.int_generator import IntGenerator
from trashcli.put.describer import Describer
from trashcli.put.file_trasher import FileTrasher
from trashcli.put.fs.fs import Fs
from trashcli.put.fs.real_fs import RealFs
from trashcli.put.janitor import Janitor
from trashcli.put.my_logger import LoggerBackend
from trashcli.put.my_logger import StreamBackend
from trashcli.put.reporting.trash_put_reporter import TrashPutReporter
from trashcli.put.trash_put_cmd import TrashPutCmd
from trashcli.put.trasher import Trasher
from trashcli.put.user import User
def main():
cmd = make_cmd(clock=RealClock(),
fs=RealFs(),
user_input=RealInput(),
randint=RandomIntGenerator(),
backend=StreamBackend(sys.stderr))
try:
uid = int(os.environ["TRASH_PUT_FAKE_UID_FOR_TESTING"])
except KeyError:
uid = os.getuid()
return cmd.run_put(sys.argv, cast_environ(os.environ), uid)
def make_cmd(clock,
fs, # type: Fs
user_input, # type: Input
randint, # type: IntGenerator
backend, # type: LoggerBackend
): # type: (...) -> TrashPutCmd
reporter = TrashPutReporter(fs)
janitor = Janitor(fs, clock, backend, randint)
file_trasher = FileTrasher(fs, janitor, backend)
user = User(user_input, Describer(fs))
trasher = Trasher(file_trasher, user, fs, backend)
return TrashPutCmd(reporter, trasher)
class RandomIntGenerator(IntGenerator):
def new_int(self,
min, # type: int
max, # type: int
):
return random.randint(min, max)
| 1,884
|
Python
|
.py
| 48
| 32.75
| 70
| 0.694915
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,841
|
trash_put_cmd.py
|
andreafrancia_trash-cli/trashcli/put/trash_put_cmd.py
|
from typing import List
from trashcli.lib.environ import Environ
from trashcli.put.context import Context
from trashcli.put.my_logger import LogData
from trashcli.put.parser import ExitWithCode
from trashcli.put.parser import Parser
from trashcli.put.parser import Trash
from trashcli.put.reporting.trash_put_reporter import TrashPutReporter
from trashcli.put.trasher import Trasher
class TrashPutCmd:
def __init__(self,
reporter, # type: TrashPutReporter
trasher, # type: Trasher
):
self.reporter = reporter
self.trasher = trasher
def run_put(self,
argv, # type: List[str]
environ, # type: Environ
uid, # type: int
): # type: (...) -> int
parser = Parser()
parsed = parser.parse_args(argv)
if isinstance(parsed, ExitWithCode):
return parsed.exit_code
elif isinstance(parsed, Trash):
program_name = parsed.program_name
log_data = LogData(program_name, parsed.verbose)
context = Context(paths=parsed.files,
user_trash_dir=parsed.trash_dir,
mode=parsed.mode,
forced_volume=parsed.forced_volume,
home_fallback=parsed.home_fallback,
program_name=program_name,
log_data=log_data,
environ=environ,
uid=uid)
result = context.trash_each(self.trasher)
return self.reporter.exit_code(result)
| 1,676
|
Python
|
.py
| 39
| 29.461538
| 70
| 0.569853
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,842
|
trasher.py
|
andreafrancia_trash-cli/trashcli/put/trasher.py
|
from trashcli.put.my_logger import LoggerBackend
from trashcli.put.context import Context
from trashcli.put.context import SingleTrasher
from trashcli.put.core.trash_result import TrashResult
from trashcli.put.core.trashee import should_skipped_by_specs
from trashcli.put.file_trasher import FileTrasher
from trashcli.put.fs.fs import Fs
from trashcli.put.my_logger import MyLogger
from trashcli.put.reporting.trash_put_reporter import TrashPutReporter
from trashcli.put.user import User
from trashcli.put.user import user_replied_no
class Trasher(SingleTrasher):
def __init__(self,
file_trasher, # type: FileTrasher
user, # type: User
fs, # type: Fs
backend, # type: LoggerBackend
):
self.file_trasher = file_trasher
self.user = user
self.logger = MyLogger(backend)
self.reporter = TrashPutReporter(fs)
self.fs = fs
def trash_single(self,
path, # type: str
context, # type: Context
):
"""
Trash a file in the appropriate trash directory.
If the file belong to the same volume of the trash home directory it
will be trashed in the home trash directory.
Otherwise it will be trashed in one of the relevant volume trash
directories.
Each volume can have two trash directories, they are
- $volume/.Trash/$uid
- $volume/.Trash-$uid
Firstly the software attempt to trash the file in the first directory
then try to trash in the second trash directory.
"""
if should_skipped_by_specs(path):
self.logger.log_put(
self.reporter.unable_to_trash_dot_entries(path),
context.log_data)
return TrashResult.Failure
if not self.fs.lexists(path):
if context.mode.can_ignore_not_existent_path():
return TrashResult.Success
else:
self.logger.log_put(
self.reporter.unable_to_trash_file_non_existent(path),
context.log_data)
return TrashResult.Failure
if context.mode.should_we_ask_to_the_user(self.fs.is_accessible(path)):
reply = self.user.ask_user_about_deleting_file(context.program_name,
path)
if reply == user_replied_no:
return TrashResult.Success
return self.file_trasher.trash_file(path, context)
| 2,601
|
Python
|
.py
| 58
| 33.344828
| 80
| 0.621003
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,843
|
check_cast.py
|
andreafrancia_trash-cli/trashcli/put/check_cast.py
|
from typing import Any
from typing import Type
from typing import TypeVar
from typing import cast
T = TypeVar('T')
def check_cast(t, value): # type: (Type[T], Any) -> T
if isinstance(value, t):
return cast(t, value) # type: ignore
else:
raise TypeError("expected %s, got %s" % (t, type(value)))
| 324
|
Python
|
.py
| 10
| 28.7
| 65
| 0.665595
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,844
|
jobs.py
|
andreafrancia_trash-cli/trashcli/put/jobs.py
|
from typing import Generic
from typing import Iterator
from typing import Type
from typing import TypeVar
from trashcli.put.core.logs import Level
from trashcli.put.core.logs import LogData
from trashcli.put.core.logs import LogEntry
from trashcli.put.core.logs import LogTag
from trashcli.put.core.logs import MessageStr
from trashcli.put.my_logger import MyLogger
R = TypeVar('R')
class JobStatus(Generic[R]):
def __init__(self, message): # type: (str) -> None
self.log_entries = [LogEntry(Level.DEBUG,
LogTag.unspecified,
MessageStr.from_messages([message]))]
def has_succeeded(self):
return isinstance(self, Succeeded)
def result(self): # type: () -> R
raise NotImplementedError
def logs(self):
return self.log_entries
class NeedsMoreAttempts(JobStatus, Generic[R]):
def __init__(self,
trashinfo_path, # type: str
message, # type: str
):
super(NeedsMoreAttempts, self).__init__(message)
self.trashinfo_path = trashinfo_path
def result(self): # type: () -> R
raise ValueError("Result not available yet!")
class Succeeded(JobStatus, Generic[R]):
def __init__(self,
result, # type: R
message, # type: str
):
super(Succeeded, self).__init__(message)
self._result = result # type: R
def result(self): # type: () -> R
return self._result
def __repr__(self):
return "Succeeded(%s)" % repr(self.result)
class JobExecutor(Generic[R]):
def __init__(self,
logger, # type: MyLogger
_result_type, # type: Type[R]
):
self.logger = logger
def execute(self,
job, # type: Iterator[JobStatus[R]]
log_data, # type: LogData
): # type: (...) -> R
for status in job:
self.logger.log_multiple(status.logs(), log_data)
if status.has_succeeded():
return status.result()
raise ValueError("Should not happen!")
| 2,190
|
Python
|
.py
| 57
| 28.859649
| 74
| 0.583176
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,845
|
stats_reader.py
|
andreafrancia_trash-cli/trashcli/put/reporting/stats_reader.py
|
# Copyright (C) 2007-2024 Andrea Francia Trivolzio(PV) Italy
import os
from grp import getgrgid
from pwd import getpwuid
from typing import NamedTuple
import re
from trashcli.put.core.either import Either
from trashcli.put.core.either import Left
from trashcli.put.core.either import Right
def gentle_stat_read(path):
def stats_str(stats): # type: (Either[Stats, Exception]) -> str
if isinstance(result, Right):
value = result.value()
return "%s %s %s" % (value.octal_mode(), value.user, value.group)
elif isinstance(result, Left):
return str(result.error())
else:
raise ValueError()
result = StatReader().read_stats(path)
return stats_str(result)
class Stats(NamedTuple('Result', [
('user', str),
('group', str),
('mode', int),
])):
def octal_mode(self): # () -> str
return self._remove_octal_prefix(oct(self.mode & 0o777))
@staticmethod
def _remove_octal_prefix(mode): # type: (str) -> str
remove_new_octal_format = mode.replace('0o', '')
remove_old_octal_format = re.sub(r"^0", '', remove_new_octal_format)
return remove_old_octal_format
class StatReader:
@staticmethod
def read_stats(path, # type: str
): # type: (...) -> Either[Stats, Exception]
try:
stats = os.lstat(path)
user = getpwuid(stats.st_uid).pw_name
group = getgrgid(stats.st_gid).gr_name
mode = stats.st_mode
return Right(Stats(user, group, mode))
except (IOError, OSError) as e:
return Left(e)
| 1,634
|
Python
|
.py
| 44
| 30.090909
| 77
| 0.624446
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,846
|
trash_put_reporter.py
|
andreafrancia_trash-cli/trashcli/put/reporting/trash_put_reporter.py
|
# Copyright (C) 2007-2024 Andrea Francia Trivolzio(PV) Italy
import os
from typing import List
from typing import Tuple
from trashcli.put.fs.fs import Fs
from trashcli.lib.environ import Environ
from trashcli.lib.exit_codes import EX_IOERR
from trashcli.lib.exit_codes import EX_OK
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.failure_reason import FailureReason
from trashcli.put.core.failure_reason import LogContext
from trashcli.put.core.logs import Level
from trashcli.put.core.logs import LogEntry
from trashcli.put.core.logs import LogTag
from trashcli.put.core.logs import debug_str
from trashcli.put.core.logs import info_str
from trashcli.put.core.logs import log_str
from trashcli.put.core.trash_all_result import TrashAllResult
from trashcli.put.core.trashee import Trashee
from trashcli.put.describer import Describer
from trashcli.put.reporting.stats_reader import gentle_stat_read
class TrashPutReporter:
def __init__(self,
fs, # type: Fs
):
self.describer = Describer(fs)
def _describe(self, path):
return self.describer.describe(path)
def unable_to_trash_dot_entries(self, file
): # type: (...) -> LogEntry
return log_str(Level.WARNING, LogTag.trash_failed,
["cannot trash %s '%s'" % (self._describe(file), file)])
def unable_to_trash_file_non_existent(self,
path, # type: str
): # type: (...) -> LogEntry
return log_str(Level.WARNING, LogTag.trash_failed,
["cannot trash %s '%s'" % (self._describe(path), path)])
def unable_to_trash_file(
self,
trashee, # type: Trashee
failures, # type: List[Tuple[Candidate, FailureReason]]
environ, # type: Environ
): # (...) -> LogEntry
path = trashee.path
volume = trashee.volume
messages = []
messages.append("cannot trash %s '%s' (from volume '%s')" % (
self._describe(path), path, volume))
for candidate, reason in failures:
context = LogContext(path, candidate, environ)
message = " `- failed to trash %s in %s, because %s" % (
path,
candidate.norm_path(),
reason.log_entries(context))
messages.append(message)
return log_str(Level.WARNING, LogTag.trash_failed, messages)
@staticmethod
def file_has_been_trashed_in_as(trashed_file,
trash_dir, # type: Candidate
environ): # type: (...) -> LogEntry
return info_str("'%s' trashed in %s" % (trashed_file,
trash_dir.shrink_user(environ)))
@classmethod
def log_data_for_debugging(cls, error):
try:
filename = error.filename
except AttributeError:
pass
else:
if filename is not None:
for path in [filename, os.path.dirname(filename)]:
info = gentle_stat_read(path)
yield "stats for %s: %s" % (path, info)
@staticmethod
def trash_dir_with_volume(candidate, # type: Candidate
): # type: (...) -> LogEntry
return debug_str("trying trash dir: %s from volume: %s" % (
candidate.norm_path(), candidate.volume))
@staticmethod
def exit_code(result, # type: TrashAllResult
): # type: (...) -> int
if not result.any_failure():
return EX_OK
else:
return EX_IOERR
| 3,742
|
Python
|
.py
| 85
| 33.082353
| 80
| 0.589737
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,847
|
real_fs.py
|
andreafrancia_trash-cli/trashcli/put/fs/real_fs.py
|
import grp
import os
import pwd
import stat
from typing import NamedTuple
from typing import Optional
from trashcli import fs
from trashcli.fs import write_file
from trashcli.fstab.real_volume_of import RealVolumeOf
from trashcli.put.fs.fs import Fs
class Names:
def username(self, uid): # type: (int) -> Optional[str]
try:
return pwd.getpwuid(uid).pw_name
except KeyError as e:
return None
def groupname(self, gid):
try:
return grp.getgrgid(gid).gr_name
except KeyError as e:
return None
class Stat(NamedTuple('Stat', [
('mode', int),
('uid', int),
('gid', int),
])):
pass
class RealFs(RealVolumeOf, Fs):
def __init__(self):
super(RealFs, self).__init__()
def readlink(self, path):
return os.readlink(path)
def symlink(self, src, dest): # type: (str, str) -> None
os.symlink(src, dest)
def touch(self, path): # type: (str) -> None
with open(path, 'a'):
import os
os.utime(path, None)
def atomic_write(self, path, content):
fs.atomic_write(path, content)
def chmod(self, path, mode):
os.chmod(path, mode)
def isdir(self, path):
return os.path.isdir(path)
def isfile(self, path):
return os.path.isfile(path)
def getsize(self, path):
return os.path.getsize(path)
def walk_no_follow(self, path):
try:
import scandir # type: ignore
walk = scandir.walk
except ImportError:
walk = os.walk
return walk(path, followlinks=False)
def exists(self, path):
return os.path.exists(path)
def makedirs(self, path, mode):
os.makedirs(path, mode)
def lstat(self, path):
stat = os.lstat(path)
return Stat(mode=stat.st_mode, uid=stat.st_uid, gid=stat.st_gid)
def mkdir(self, path):
os.mkdir(path)
def mkdir_with_mode(self, path, mode):
os.mkdir(path, mode)
def move(self, path, dest):
return fs.move(path, dest)
def remove_file(self, path):
fs.remove_file(path)
def islink(self, path):
return os.path.islink(path)
def has_sticky_bit(self, path):
return (os.stat(path).st_mode & stat.S_ISVTX) == stat.S_ISVTX
def realpath(self, path):
return os.path.realpath(path)
def is_accessible(self, path):
return os.access(path, os.F_OK)
def make_file(self, path, content):
write_file(path, content)
def get_mod(self, path):
return stat.S_IMODE(os.lstat(path).st_mode)
def listdir(self, path):
return os.listdir(path)
def read(self, path):
return fs.read_file(path)
def write_file(self, path, content):
return fs.write_file(path, content)
def lexists(selfs, path):
return os.path.lexists(path)
| 2,914
|
Python
|
.py
| 90
| 25.288889
| 72
| 0.620158
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,848
|
fs.py
|
andreafrancia_trash-cli/trashcli/put/fs/fs.py
|
import os
from abc import abstractmethod
from typing import Iterable
from trashcli.compat import Protocol
class RealPathFs(Protocol):
@abstractmethod
def realpath(self, path):
raise NotImplementedError
class Fs(RealPathFs, Protocol):
@abstractmethod
def atomic_write(self, path, content):
raise NotImplementedError
@abstractmethod
def chmod(self, path, mode):
raise NotImplementedError
@abstractmethod
def isdir(self, path):
raise NotImplementedError
@abstractmethod
def isfile(self, path):
raise NotImplementedError
@abstractmethod
def getsize(self, path):
raise NotImplementedError
@abstractmethod
def exists(self, path):
raise NotImplementedError
@abstractmethod
def makedirs(self, path, mode):
raise NotImplementedError
@abstractmethod
def move(self, path, dest):
raise NotImplementedError
@abstractmethod
def remove_file(self, path):
raise NotImplementedError
@abstractmethod
def islink(self, path):
raise NotImplementedError
@abstractmethod
def has_sticky_bit(self, path):
raise NotImplementedError
@abstractmethod
def is_accessible(self, path):
raise NotImplementedError
@abstractmethod
def read(self, path):
raise NotImplementedError
@abstractmethod
def write_file(self, path, content):
raise NotImplementedError
@abstractmethod
def make_file(self, path, content):
raise NotImplementedError
@abstractmethod
def get_mod(self, path):
raise NotImplementedError
@abstractmethod
def lexists(self, path):
raise NotImplementedError
@abstractmethod
def walk_no_follow(self, top):
raise NotImplementedError
def parent_realpath2(self, path):
parent = os.path.dirname(path)
return self.realpath(parent)
def list_sorted(self, path):
return sorted(self.listdir(path))
def list_all(fs, path): # type: (Fs, str) -> Iterable[str]
result = fs.walk_no_follow(path)
for top, dirs, non_dirs in result:
for d in dirs:
yield os.path.join(top, d)
for f in non_dirs:
yield os.path.join(top, f)
| 2,290
|
Python
|
.py
| 75
| 24.053333
| 59
| 0.692413
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,849
|
volume_of_parent.py
|
andreafrancia_trash-cli/trashcli/put/fs/volume_of_parent.py
|
from trashcli.fstab.volume_of import VolumeOf
from trashcli.put.fs.parent_realpath import ParentRealpathFs
class VolumeOfParent:
def __init__(self,
fs, # type: VolumeOf
):
self.fs = fs
def volume_of_parent(self, path):
parent_realpath = ParentRealpathFs(self.fs).parent_realpath(path)
return self.fs.volume_of(parent_realpath)
| 397
|
Python
|
.py
| 10
| 31.8
| 73
| 0.669271
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,850
|
parent_realpath.py
|
andreafrancia_trash-cli/trashcli/put/fs/parent_realpath.py
|
import os
from trashcli.put.fs.fs import RealPathFs
class ParentRealpathFs:
def __init__(self, fs): # type: (RealPathFs) -> None
self.fs = fs
def parent_realpath(self, path):
parent = os.path.dirname(path)
return self.fs.realpath(parent)
| 275
|
Python
|
.py
| 8
| 28.875
| 57
| 0.673004
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,851
|
size_counter.py
|
andreafrancia_trash-cli/trashcli/put/fs/size_counter.py
|
import os
from six.moves import map as imap
from trashcli.put.fs.fs import Fs
class SizeCounter:
def __init__(self,
fs, # type: Fs
):
self.fs = fs
def get_size_recursive(self, path):
if self.fs.isfile(path):
return self.fs.getsize(path)
files = self.list_all_files(path)
files_sizes = imap(self.fs.getsize, files)
return sum(files_sizes, 0)
def list_all_files(self,
path, # type: str
):
for path, dirs, files in self.fs.walk_no_follow(path):
for f in files:
yield os.path.join(path, f)
| 675
|
Python
|
.py
| 20
| 23.4
| 62
| 0.541667
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,852
|
security_check.py
|
andreafrancia_trash-cli/trashcli/put/janitor_tools/security_check.py
|
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.check_type import NoCheck, TopTrashDirCheck
from trashcli.put.core.either import Either, Right, Left
from trashcli.put.core.failure_reason import FailureReason, LogContext
class SecurityCheck:
def __init__(self, fs):
self.fs = fs
def check_trash_dir_is_secure(self,
candidate, # type: Candidate
): # type: (...) -> Either[None, FailureReason]
if candidate.check_type == NoCheck:
return Right(None)
if candidate.check_type == TopTrashDirCheck:
parent = candidate.parent_dir()
if not self.fs.lexists(parent):
return Left(TrashDirDoesNotHaveParent())
if not self.fs.isdir(parent):
return Left(TrashDirCannotBeCreatedBecauseParentIsFile())
if self.fs.islink(parent):
return Left(TrashDirIsNotSecureBecauseSymLink())
if not self.fs.has_sticky_bit(parent):
return Left(TrashDirIsNotSecureBecauseNotSticky())
return Right(None)
raise Exception("Unknown check type: %s" % candidate.check_type)
class TrashDirDoesNotHaveParent(FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return trash_dir_parent_problem(context, (
"trash dir cannot be created because its parent does not exists"))
class TrashDirCannotBeCreatedBecauseParentIsFile(FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return trash_dir_parent_problem(context, (
"trash dir cannot be created as its parent is a file instead of being a directory"))
class TrashDirIsNotSecureBecauseSymLink(FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return trash_dir_parent_problem(context, (
"trash dir is insecure, its parent should not be a symlink"))
class TrashDirIsNotSecureBecauseNotSticky(FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return trash_dir_parent_problem(context, (
"trash dir is insecure, its parent should be sticky"))
def trash_dir_parent_problem(context, # type: LogContext
message, # type: str
): # type: (...) -> str
return "%s, trash-dir: %s, parent: %s" % (
message,
context.trash_dir_norm_path(),
context.candidate.parent_dir())
| 2,545
|
Python
|
.py
| 47
| 43.531915
| 96
| 0.649758
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,853
|
info_file_persister.py
|
andreafrancia_trash-cli/trashcli/put/janitor_tools/info_file_persister.py
|
import errno
import os
from typing import NamedTuple, Iterator
from trashcli.lib.path_of_backup_copy import path_of_backup_copy
from trashcli.put.fs.fs import Fs
from trashcli.put.jobs import JobStatus, NeedsMoreAttempts, Succeeded, \
JobExecutor
from trashcli.put.my_logger import LogData, MyLogger
from trashcli.put.suffix import Suffix
class TrashinfoData(NamedTuple('TrashinfoData', [
('basename', str),
('content', str),
('info_dir_path', str),
])):
pass
class TrashedFile(NamedTuple('TrashedFile', [
('trashinfo_path', str),
])):
@property
def backup_copy_path(self): # type: () -> str
return path_of_backup_copy(self.trashinfo_path)
class InfoFilePersister:
def __init__(self,
fs, # type: Fs
logger, # type: MyLogger
suffix, # type: Suffix
): # type: (...) -> None
self.fs = fs
self.logger = logger
self.suffix = suffix
def create_trashinfo_file(self,
trashinfo_data, # type: TrashinfoData
log_data, # type: LogData
): # type: (...) -> TrashedFile
return JobExecutor(self.logger, TrashedFile).execute(
self.try_persist(trashinfo_data), log_data)
Result = Iterator[JobStatus[TrashedFile]]
def try_persist(self,
data, # type: TrashinfoData
): # type: (...) -> Result
index = 0
name_too_long = False
while True:
suffix = self.suffix.suffix_for_index(index)
trashinfo_basename = create_trashinfo_basename(data.basename,
suffix,
name_too_long)
trashinfo_path = os.path.join(data.info_dir_path,
trashinfo_basename)
if os.path.exists(path_of_backup_copy(trashinfo_path)):
index += 1
continue
try:
self.fs.atomic_write(trashinfo_path, data.content)
yield Succeeded(TrashedFile(trashinfo_path),
".trashinfo created as %s." % trashinfo_path)
except OSError as e:
if e.errno == errno.ENAMETOOLONG:
name_too_long = True
yield NeedsMoreAttempts(trashinfo_path,
"attempt for creating %s failed." % trashinfo_path)
index += 1
def create_trashinfo_basename(basename, suffix, name_too_long):
after_basename = suffix + ".trashinfo"
if name_too_long:
truncated_basename = basename[0:len(basename) - len(after_basename)]
else:
truncated_basename = basename
return truncated_basename + after_basename
| 2,896
|
Python
|
.py
| 69
| 29.391304
| 91
| 0.557214
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,854
|
trash_dir_checker.py
|
andreafrancia_trash-cli/trashcli/put/janitor_tools/trash_dir_checker.py
|
from typing import NamedTuple
from trashcli.lib.environ import Environ
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.either import Either
from trashcli.put.core.either import Left
from trashcli.put.core.either import Right
from trashcli.put.core.failure_reason import FailureReason
from trashcli.put.core.failure_reason import LogContext
from trashcli.put.core.trashee import Trashee
from trashcli.put.fs.fs import Fs
from trashcli.put.gate import Gate
from trashcli.put.trash_dir_volume_reader import TrashDirVolumeReader
class DifferentVolumes(NamedTuple('DifferentVolumes', [
('trash_dir_volume', str),
('file_volume', str),
]), FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return (
"trash dir and file to be trashed are not in the same volume, trash-dir volume: %s, file volume: %s"
% (self.trash_dir_volume, self.file_volume))
class HomeFallBackNotEnabled(FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return "home fallback not enabled"
def __eq__(self, other):
return isinstance(other, HomeFallBackNotEnabled)
GateCheckResult = Either[None, FailureReason]
class TrashDirChecker:
def __init__(self,
fs, # type: Fs
): # type: (...) -> None
self.fs = fs
def file_could_be_trashed_in(self,
trashee, # type: Trashee
candidate, # type: Candidate
environ, # type: Environ
): # type: (...) -> GateCheckResult
if candidate.gate is Gate.HomeFallback:
return self._can_be_trashed_in_home_trash_dir(environ)
elif candidate.gate is Gate.SameVolume:
return SameVolumeGateImpl(self.fs).can_trash_in(
trashee, candidate)
else:
raise ValueError("Unknown gate: %s" % candidate.gate)
@staticmethod
def _can_be_trashed_in_home_trash_dir(environ, # type: Environ
):
if environ.get('TRASH_ENABLE_HOME_FALLBACK', None) == "1":
return make_ok()
return Left(HomeFallBackNotEnabled())
def make_ok():
return Right(None)
class SameVolumeGateImpl:
def __init__(self,
fs, # type: Fs
):
self.fs = fs
def can_trash_in(self,
trashee, # type: Trashee
candidate, # type: Candidate
):
trash_dir_volume = self._volume_of_trash_dir(candidate)
same_volume = trash_dir_volume == trashee.volume
if not same_volume:
return Left(DifferentVolumes(trash_dir_volume, trashee.volume))
return make_ok()
def _volume_of_trash_dir(self, candidate): # type: (Candidate) -> str
return (TrashDirVolumeReader(self.fs)
.volume_of_trash_dir(candidate.trash_dir_path))
| 3,039
|
Python
|
.py
| 68
| 34.558824
| 116
| 0.620807
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,855
|
put_trash_dir.py
|
andreafrancia_trash-cli/trashcli/put/janitor_tools/put_trash_dir.py
|
import os.path
from typing import NamedTuple
from trashcli.put.core.either import Either
from trashcli.put.core.either import Left
from trashcli.put.core.either import Right
from trashcli.put.core.failure_reason import FailureReason
from trashcli.put.core.failure_reason import LogContext
from trashcli.put.fs.fs import Fs
from trashcli.put.janitor_tools.info_file_persister import TrashedFile
class UnableToMoveFileToTrash(NamedTuple('UnableToMoveFileToTrash', [
('error', Exception),
]), FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return "failed to move %s in %s: %s" % (
context.trashee_path,
context.files_dir(),
self.error,
)
class PutTrashDir:
def __init__(self,
fs, # type: Fs
):
self.fs = fs
def try_trash(self,
path, # type: str
paths, # type: TrashedFile
): # type: (...) -> Either[None, Exception]
try:
move_file(self.fs, path, paths.backup_copy_path)
return Right(None)
except (IOError, OSError) as error:
self.fs.remove_file(paths.trashinfo_path)
return Left(UnableToMoveFileToTrash(error))
def move_file(fs, # type: Fs
src, # type: str
dest, # type: str
):
# Using nornpath allow to delete symlink to a dir even if the are
# specified with traling slash
fs.move(os.path.normpath(src), dest)
| 1,534
|
Python
|
.py
| 40
| 30.1
| 70
| 0.629879
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,856
|
trash_dir_creator.py
|
andreafrancia_trash-cli/trashcli/put/janitor_tools/trash_dir_creator.py
|
from typing import NamedTuple
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.either import Either, Right, Left
from trashcli.put.core.failure_reason import FailureReason, LogContext
from trashcli.put.dir_maker import DirMaker
from trashcli.put.fs.fs import Fs
class TrashDirCannotBeCreated(
NamedTuple('TrashDirCannotBeCreated', [
('error', Exception),
]), FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return "error during directory creation: %s" % (
self.error)
class TrashDirCreator:
def __init__(self, fs): # type: (Fs) -> None
self.dir_maker = DirMaker(fs)
def make_candidate_dirs(self,
candidate, # type: Candidate
): # type: (...) -> Either[None, TrashDirCannotBeCreated]
try:
self.dir_maker.mkdir_p(candidate.trash_dir_path, 0o700)
self.dir_maker.mkdir_p(candidate.files_dir(), 0o700)
self.dir_maker.mkdir_p(candidate.info_dir(), 0o700)
return Right(None)
except (IOError, OSError) as error:
return Left(TrashDirCannotBeCreated(error))
| 1,198
|
Python
|
.py
| 26
| 37.615385
| 86
| 0.657804
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,857
|
info_creator.py
|
andreafrancia_trash-cli/trashcli/put/janitor_tools/info_creator.py
|
import os
from typing import NamedTuple
from trashcli.put.clock import PutClock
from trashcli.put.core.candidate import Candidate
from trashcli.put.core.either import Either
from trashcli.put.core.either import Left
from trashcli.put.core.either import Right
from trashcli.put.core.failure_reason import FailureReason
from trashcli.put.core.failure_reason import LogContext
from trashcli.put.format_trash_info import format_trashinfo
from trashcli.put.fs.fs import Fs
from trashcli.put.janitor_tools.info_file_persister import TrashinfoData
from trashcli.put.original_location import OriginalLocation
class UnableToCreateTrashInfoContent(
NamedTuple('UnableToCreateTrashInfoContent', [
('error', Exception),
]), FailureReason):
def log_entries(self, context): # type: (LogContext) -> str
return "failed to generate trashinfo content: %s" % (
self.error)
class TrashInfoCreator:
def __init__(self,
fs, # type: Fs
clock, # type: PutClock
):
self.original_location = OriginalLocation(fs)
self.clock = clock
Result = Either[TrashinfoData, UnableToCreateTrashInfoContent]
def make_trashinfo_data(self,
path, # type: str
candidate, # type: Candidate
): # type: (...) -> Result
try:
original_location = self.original_location.for_file(path,
candidate.path_maker_type,
candidate.volume)
content = format_trashinfo(original_location, self.clock.now())
basename = os.path.basename(original_location)
trash_info_data = TrashinfoData(basename, content,
candidate.info_dir())
return Right(trash_info_data)
except (IOError, OSError) as error:
return Left(UnableToCreateTrashInfoContent(error))
| 2,058
|
Python
|
.py
| 43
| 35.906977
| 90
| 0.628799
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,858
|
trashee.py
|
andreafrancia_trash-cli/trashcli/put/core/trashee.py
|
import os
from typing import NamedTuple
class Trashee(NamedTuple('FileToBeTrashed', [
('path', str),
('volume', str)
])):
pass
def should_skipped_by_specs(path):
basename = os.path.basename(path)
return (basename == ".") or (basename == "..")
| 267
|
Python
|
.py
| 10
| 23.3
| 50
| 0.664032
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,859
|
failure_reason.py
|
andreafrancia_trash-cli/trashcli/put/core/failure_reason.py
|
from abc import abstractmethod
from typing import NamedTuple
from trashcli.compat import Protocol
from trashcli.lib.environ import Environ
from trashcli.put.core.candidate import Candidate
class LogContext(NamedTuple('LogContext', [
('trashee_path', str),
('candidate', Candidate),
('environ', Environ),
])):
def shrunk_candidate_path(self):
return self.candidate.shrink_user(self.environ)
def trash_dir_norm_path(self):
return self.candidate.norm_path()
def files_dir(self):
return self.candidate.files_dir()
class FailureReason(Protocol):
@abstractmethod
def log_entries(self, context): # type: (LogContext) -> str
raise NotImplementedError
| 715
|
Python
|
.py
| 20
| 31.2
| 64
| 0.736919
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,860
|
check_type.py
|
andreafrancia_trash-cli/trashcli/put/core/check_type.py
|
from enum import Enum
class CheckType(Enum):
NoCheck = 'NoCheck'
TopTrashDirCheck = 'TopTrashDirCheck'
NoCheck = CheckType.NoCheck
TopTrashDirCheck = CheckType.TopTrashDirCheck
| 189
|
Python
|
.py
| 6
| 28.5
| 45
| 0.815642
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,861
|
int_generator.py
|
andreafrancia_trash-cli/trashcli/put/core/int_generator.py
|
from trashcli.compat import Protocol
class IntGenerator(Protocol):
def new_int(self,
min, # type: int
max, # type: int
): # type: (...) -> int
raise NotImplementedError
| 237
|
Python
|
.py
| 7
| 23.571429
| 41
| 0.530702
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,862
|
logs.py
|
andreafrancia_trash-cli/trashcli/put/core/logs.py
|
from abc import abstractmethod
from enum import Enum
from typing import List
from typing import NamedTuple
from trashcli.compat import Protocol
class Level(Enum):
INFO = "INFO"
DEBUG = "DEBUG"
WARNING = "WARNING"
class LogTag(Enum):
"tags used only during testing"
unspecified = "unspecified"
trash_failed = "trash_failed"
class LogData:
def __init__(self, program_name, verbose):
self.program_name = program_name
self.verbose = verbose
class Message(Protocol):
@abstractmethod
def resolve(self):
raise NotImplementedError
class LogEntry(NamedTuple('LogEntry', [
('level', Level),
('tag', LogTag),
('messages', List[Message]),
])):
def resolve_messages(self):
for m in self.messages:
yield m.resolve()
class MessageStr(NamedTuple('Message', [
('message', str),
]), Message):
def resolve(self):
return self.message
@staticmethod
def from_messages(messages # type: List[str]
):
return [MessageStr(msg) for msg in messages]
def log_str(level, # type: Level
tag, # type: LogTag
messages, # type: List[str]
):
return LogEntry(level, tag, MessageStr.from_messages(messages))
def warning_str(message): # type: (str) -> LogEntry
return log_str(Level.WARNING, LogTag.unspecified, [message])
def info_str(message): # type: (str) -> LogEntry
return log_str(Level.INFO, LogTag.unspecified, [message])
def debug_str(message): # type: (str) -> LogEntry
return log_str(Level.DEBUG, LogTag.unspecified, [message])
| 1,628
|
Python
|
.py
| 49
| 27.673469
| 67
| 0.666881
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,863
|
either.py
|
andreafrancia_trash-cli/trashcli/put/core/either.py
|
from abc import abstractmethod
from typing import Callable, TypeVar, Generic
S = TypeVar("S")
R = TypeVar("R")
E = TypeVar("E")
class Either(Generic[S, E]):
@abstractmethod
def bind(self,
func): # type: (Callable[[S], Either[R, E]]) -> Either[R, E]
raise NotImplementedError
@abstractmethod
def __eq__(self, other): # type: (object) -> bool
raise NotImplementedError
def is_error(self): # type: () -> bool
return not self.is_valid()
def is_valid(self): # type: () -> bool
return {Left: False, Right: True}[type(self)]
def error(self): # type: () -> E
if isinstance(self, Left):
return self._error
else:
raise ValueError("Not an error: %s" % self)
def value(self):
if isinstance(self, Right):
return self._value
else:
raise ValueError("Not a value: %s" % self)
class Right(Either[S, E]):
def __init__(self, value): # type: (S) -> None
self._value = value
def bind(self,
func): # type: (Callable[[S], Either[R, E]]) -> Either[R, E]
return func(self._value)
def __eq__(self, other): # type: (object) -> bool
return isinstance(other, Right) and self._value == other._value
def __str__(self): # type: () -> str
return "Right %s" % self._value
class Left(Either[S, E]):
def __init__(self, error): # type: (E) -> None
self._error = error
def bind(self,
func): # type: (Callable[[S], Either[R, E]]) -> Either[R, E]
return Left(self._error)
def __eq__(self, other): # type: (object) -> bool
return isinstance(other, Left) and self._error == other._error
def __str__(self): # type: () -> str
return "Left: %s" % self._error
| 1,824
|
Python
|
.py
| 47
| 31.489362
| 74
| 0.561683
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,864
|
path_maker_type.py
|
andreafrancia_trash-cli/trashcli/put/core/path_maker_type.py
|
from enum import Enum
class PathMakerType(Enum):
AbsolutePaths = 'AbsolutePaths'
RelativePaths = 'RelativePaths'
| 123
|
Python
|
.py
| 4
| 27.25
| 35
| 0.786325
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,865
|
trash_result.py
|
andreafrancia_trash-cli/trashcli/put/core/trash_result.py
|
from enum import Enum
class TrashResult(Enum):
Failure = "Failure"
Success = "Success"
| 97
|
Python
|
.py
| 4
| 20.75
| 24
| 0.725275
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,866
|
candidate.py
|
andreafrancia_trash-cli/trashcli/put/core/candidate.py
|
import os
import posixpath
import re
from typing import NamedTuple
from trashcli.put.core.check_type import CheckType
from trashcli.put.core.path_maker_type import PathMakerType
from trashcli.put.gate import Gate
class Candidate(NamedTuple('Candidate', [
('trash_dir_path', str),
('volume', str),
('path_maker_type', PathMakerType),
('check_type', CheckType),
('gate', Gate),
])):
def parent_dir(self):
return os.path.dirname(self.trash_dir_path)
def info_dir(self):
return os.path.join(self.trash_dir_path, 'info')
def files_dir(self):
return os.path.join(self.trash_dir_path, 'files')
def norm_path(self):
return os.path.normpath(self.trash_dir_path)
def shrink_user(self, environ):
path = self.norm_path()
if environ.get('TRASH_PUT_DISABLE_SHRINK', '') == '1':
return path
home_dir = environ.get('HOME', '')
home_dir = posixpath.normpath(home_dir)
if home_dir != '':
path = re.sub('^' + re.escape(home_dir + os.path.sep),
'~' + os.path.sep, path)
return path
| 1,139
|
Python
|
.py
| 32
| 29.0625
| 66
| 0.630909
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,867
|
mode.py
|
andreafrancia_trash-cli/trashcli/put/core/mode.py
|
from enum import Enum
class Mode(Enum):
mode_unspecified = 'mode_unspecified'
mode_interactive = 'mode_interactive'
mode_force = 'mode_force'
def can_ignore_not_existent_path(self): # type: () -> bool
return self == Mode.mode_force
def should_we_ask_to_the_user(self, is_path_accessible): # type: (bool) -> bool
return self == Mode.mode_interactive and is_path_accessible
| 414
|
Python
|
.py
| 9
| 40.555556
| 84
| 0.683292
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,868
|
trash_all_result.py
|
andreafrancia_trash-cli/trashcli/put/core/trash_all_result.py
|
from typing import NamedTuple, List
class TrashAllResult(NamedTuple('TrashAllResult', [
('failed_paths', List[str]),
])):
def any_failure(self): # type: () -> bool
return len(self.failed_paths) > 0
| 217
|
Python
|
.py
| 6
| 32.166667
| 51
| 0.674641
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,869
|
fs.py
|
andreafrancia_trash-cli/trashcli/list/fs.py
|
import abc
from six import add_metaclass
from trashcli.fs import IsSymLink, ContentsOf, EntriesIfDirExists, PathExists, \
IsStickyDir, HasStickyBit
@add_metaclass(abc.ABCMeta)
class FileSystemReaderForListCmd(
IsStickyDir,
HasStickyBit,
IsSymLink,
ContentsOf,
EntriesIfDirExists,
PathExists,
):
pass
| 336
|
Python
|
.py
| 14
| 20.428571
| 80
| 0.789308
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,870
|
extractors.py
|
andreafrancia_trash-cli/trashcli/list/extractors.py
|
import os
from trashcli.fs import file_size
from trashcli.lib.path_of_backup_copy import path_of_backup_copy
from trashcli.parse_trashinfo.maybe_parse_deletion_date import \
maybe_parse_deletion_date
class DeletionDateExtractor:
def extract_attribute(self, _trashinfo_path, contents):
return maybe_parse_deletion_date(contents)
class SizeExtractor:
def extract_attribute(self, trashinfo_path, _contents):
backup_copy = path_of_backup_copy(trashinfo_path)
try:
return str(file_size(backup_copy))
except FileNotFoundError:
if os.path.islink(backup_copy):
return 0
else:
raise
| 691
|
Python
|
.py
| 18
| 30.888889
| 64
| 0.696108
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,871
|
list_trash_action.py
|
andreafrancia_trash-cli/trashcli/list/list_trash_action.py
|
from __future__ import print_function
import os
from typing import List
from typing import NamedTuple
from trashcli.lib.dir_reader import DirReader
from trashcli.lib.path_of_backup_copy import path_of_backup_copy
from trashcli.lib.trash_dir_reader import TrashDirReader
from trashcli.list.extractors import DeletionDateExtractor
from trashcli.list.extractors import SizeExtractor
from trashcli.parse_trashinfo.parse_path import parse_path
from trashcli.parse_trashinfo.parser_error import ParseError
from trashcli.trash_dirs_scanner import trash_dir_found
from trashcli.trash_dirs_scanner import \
trash_dir_skipped_because_parent_is_symlink
from trashcli.trash_dirs_scanner import \
trash_dir_skipped_because_parent_not_sticky
class ListTrashArgs(
NamedTuple('ListTrashArgs', [
('trash_dirs', List[str]),
('attribute_to_print', str),
('show_files', bool),
('all_users', bool),
])):
pass
class ListTrashAction:
def __init__(self,
environ,
uid,
selector,
out,
err,
dir_reader,
content_reader
):
self.environ = environ
self.uid = uid
self.selector = selector
self.out = out
self.err = err
self.dir_reader = dir_reader
self.content_reader = content_reader
def run_action(self,
args, # type: ListTrashArgs
):
for message in ListTrash(self.environ,
self.uid,
self.selector,
self.dir_reader,
self.content_reader).list_all_trash(args):
self.print_event(message)
def print_event(self, event):
if isinstance(event, Error):
print(event.error, file=self.err)
elif isinstance(event, Output):
print(event.message, file=self.out)
class ListTrash:
def __init__(self,
environ,
uid,
selector,
dir_reader, # type: DirReader
content_reader,
):
self.environ = environ
self.uid = uid
self.selector = selector
self.dir_reader = dir_reader
self.content_reader = content_reader
def list_all_trash(self,
args, # type: ListTrashArgs
):
extractors = {
'deletion_date': DeletionDateExtractor(),
'size': SizeExtractor(),
}
user_specified_trash_dirs = args.trash_dirs
extractor = extractors[args.attribute_to_print]
show_files = args.show_files
all_users = args.all_users
trash_dirs = self.selector.select(all_users,
user_specified_trash_dirs,
self.environ,
self.uid)
for event, event_args in trash_dirs:
if event == trash_dir_found:
path, volume = event_args
trash_dir = TrashDirReader(self.dir_reader)
for trash_info in trash_dir.list_trashinfo(path):
for msg in self._print_trashinfo(volume, trash_info,
extractor, show_files):
yield msg
elif event == trash_dir_skipped_because_parent_not_sticky:
path, = event_args
msg = Error(
self.top_trashdir_skipped_because_parent_not_sticky(path))
yield msg
elif event == trash_dir_skipped_because_parent_is_symlink:
path, = event_args
msg = Error(
self.top_trashdir_skipped_because_parent_is_symlink(path))
yield msg
def _print_trashinfo(self,
volume,
trashinfo_path,
extractor,
show_files):
try:
contents = self.content_reader.contents_of(trashinfo_path)
except IOError as e:
yield Error(str(e))
else:
try:
relative_location = parse_path(contents)
except ParseError:
yield Error(self.print_parse_path_error(trashinfo_path))
else:
attribute = extractor.extract_attribute(trashinfo_path,
contents)
original_location = os.path.join(volume, relative_location)
if show_files:
original_file = path_of_backup_copy(trashinfo_path)
line = format_line2(attribute, original_location,
original_file)
else:
line = format_line(attribute, original_location)
yield Output(line)
def top_trashdir_skipped_because_parent_is_symlink(self, trashdir):
return "TrashDir skipped because parent is symlink: %s" % trashdir
def top_trashdir_skipped_because_parent_not_sticky(self, trashdir):
return "TrashDir skipped because parent not sticky: %s" % trashdir
def print_parse_path_error(self, offending_file):
return "Parse Error: %s: Unable to parse Path." % offending_file
class Event:
pass
class Error(Event):
def __init__(self, error):
self.error = error
class Output(Event):
def __init__(self, message):
self.message = message
def format_line(attribute, original_location):
return "%s %s" % (attribute, original_location)
def format_line2(attribute, original_location, original_file):
return "%s %s -> %s" % (attribute, original_location, original_file)
| 5,915
|
Python
|
.py
| 144
| 27.805556
| 78
| 0.55805
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,872
|
trash_dir_selector.py
|
andreafrancia_trash-cli/trashcli/list/trash_dir_selector.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from typing import List, Dict, Iterator, Tuple
from trashcli.fstab.volume_of import VolumeOf
from trashcli.lib.dir_checker import DirChecker
from trashcli.lib.user_info import AllUsersInfoProvider, \
SingleUserInfoProvider
from trashcli.trash_dirs_scanner import trash_dir_found, TrashDir, \
TopTrashDirRules, TrashDirsScanner
class TrashDirsSelector:
def __init__(self,
current_user_dirs,
all_users_dirs,
volumes # type: VolumeOf
):
self.current_user_dirs = current_user_dirs
self.all_users_dirs = all_users_dirs
self.volumes = volumes
def select(self,
all_users_flag, # type: bool
user_specified_dirs, # type: List[str]
environ, # type: Dict[str, str]
uid, # type: int
): # type: (...) -> Iterator[Tuple[str, TrashDir]]
if all_users_flag:
for dir in self.all_users_dirs.scan_trash_dirs(environ, uid):
yield dir
else:
if not user_specified_dirs:
for dir in self.current_user_dirs.scan_trash_dirs(environ, uid):
yield dir
for dir in user_specified_dirs:
yield trash_dir_found, (
TrashDir(dir, self.volumes.volume_of(dir)))
@staticmethod
def make(volumes_listing,
reader, # type: TopTrashDirRules.Reader
volumes # type: VolumeOf
):
user_info_provider = SingleUserInfoProvider()
user_dir_scanner = TrashDirsScanner(user_info_provider,
volumes_listing,
TopTrashDirRules(reader),
DirChecker())
all_users_info_provider = AllUsersInfoProvider()
all_users_scanner = TrashDirsScanner(all_users_info_provider,
volumes_listing,
TopTrashDirRules(reader),
DirChecker())
return TrashDirsSelector(user_dir_scanner,
all_users_scanner,
volumes)
| 2,342
|
Python
|
.py
| 51
| 30.254902
| 80
| 0.542432
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,873
|
parser.py
|
andreafrancia_trash-cli/trashcli/list/parser.py
|
import argparse
from enum import Enum
from typing import List, Union
from trashcli.lib.print_version import PrintVersionArgs
from trashcli.list.list_trash_action import ListTrashArgs
from trashcli.list.minor_actions.debug_volumes import DebugVolumesArgs
from trashcli.list.minor_actions.list_trash_dirs import ListTrashDirsArgs
from trashcli.list.minor_actions.list_volumes import PrintVolumesArgs
from trashcli.list.minor_actions.print_python_executable import \
PrintPythonExecutableArgs
from trashcli.shell_completion import add_argument_to, TRASH_DIRS
Args = Union[
PrintVersionArgs,
PrintVolumesArgs,
DebugVolumesArgs,
ListTrashDirsArgs,
ListTrashArgs,
PrintPythonExecutableArgs
]
class Parser:
def __init__(self, prog):
self.parser = argparse.ArgumentParser(prog=prog,
description='List trashed files',
epilog='Report bugs to https://github.com/andreafrancia/trash-cli/issues')
add_argument_to(self.parser)
self.parser.add_argument('--version',
dest='action',
action='store_const',
const=ListAction.print_version,
default=ListAction.list_trash,
help="show program's version number and exit")
self.parser.add_argument('--debug-volumes',
dest='action',
action='store_const',
const=ListAction.debug_volumes,
help=argparse.SUPPRESS)
self.parser.add_argument('--volumes',
dest='action',
action='store_const',
const=ListAction.list_volumes,
help="list volumes")
self.parser.add_argument('--trash-dirs',
dest='action',
action='store_const',
const=ListAction.list_trash_dirs,
help="list trash dirs")
self.parser.add_argument('--trash-dir',
action='append',
default=[],
dest='trash_dirs',
help='specify the trash directory to use'
).complete = TRASH_DIRS
self.parser.add_argument('--size',
action='store_const',
default='deletion_date',
const='size',
dest='attribute_to_print',
help=argparse.SUPPRESS)
self.parser.add_argument('--files',
action='store_true',
default=False,
dest='show_files',
help=argparse.SUPPRESS)
self.parser.add_argument('--all-users',
action='store_true',
dest='all_users',
help='list trashcans of all the users')
self.parser.add_argument('--python',
dest='action',
action='store_const',
const=ListAction.print_python_executable,
help=argparse.SUPPRESS)
def parse_list_args(self,
args, # type: List[str]
argv0, # type: str
): # type: (...) -> Args
parsed = self.parser.parse_args(args)
if parsed.action == ListAction.print_version:
return PrintVersionArgs(argv0=argv0)
if parsed.action == ListAction.list_volumes:
return PrintVolumesArgs()
if parsed.action == ListAction.debug_volumes:
return DebugVolumesArgs()
if parsed.action == ListAction.list_trash_dirs:
return ListTrashDirsArgs(
trash_dirs=parsed.trash_dirs,
all_users=parsed.all_users
)
if parsed.action == ListAction.list_trash:
return ListTrashArgs(
trash_dirs=parsed.trash_dirs,
attribute_to_print=parsed.attribute_to_print,
show_files=parsed.show_files,
all_users=parsed.all_users
)
if parsed.action == ListAction.print_python_executable:
return PrintPythonExecutableArgs()
raise ValueError('Unknown action: {}'.format(parsed.action))
class ListAction(Enum):
debug_volumes = 'debug_volumes'
print_version = 'print_version'
list_trash = 'list_trash'
list_volumes = 'list_volumes'
list_trash_dirs = 'list_trash_dirs'
print_python_executable = 'print_python_executable'
| 5,083
|
Python
|
.py
| 105
| 29.961905
| 120
| 0.511473
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,874
|
main.py
|
andreafrancia_trash-cli/trashcli/list/main.py
|
# Copyright (C) 2011-2022 Andrea Francia Bereguardo(PV) Italy
import os
import sys
import trashcli.trash
from trashcli.empty.main import ContentReader
from trashcli.file_system_reader import FileSystemReader
from trashcli.fs import RealContentsOf
from trashcli.fstab.volume_listing import RealVolumesListing
from trashcli.fstab.real_volume_of import RealVolumeOf
from trashcli.fstab.volume_of import VolumeOf
from trashcli.lib.dir_reader import DirReader, RealDirReader
from trashcli.lib.print_version import PrintVersionArgs, \
PrintVersionAction
from trashcli.list.list_trash_action import ListTrashAction, ListTrashArgs
from trashcli.list.minor_actions.debug_volumes import DebugVolumes, \
DebugVolumesArgs
from trashcli.list.minor_actions.list_trash_dirs import ListTrashDirs, \
ListTrashDirsArgs
from trashcli.list.minor_actions.list_volumes import PrintVolumesList, \
PrintVolumesArgs
from trashcli.list.minor_actions.print_python_executable import \
PrintPythonExecutable, PrintPythonExecutableArgs
from trashcli.list.parser import Parser
from trashcli.list.trash_dir_selector import TrashDirsSelector
from trashcli.trash_dirs_scanner import TopTrashDirRules
def main():
ListCmd(
out=sys.stdout,
err=sys.stderr,
environ=os.environ,
volumes_listing=RealVolumesListing(),
uid=os.getuid(),
volumes=RealVolumeOf(),
dir_reader=RealDirReader(),
file_reader=FileSystemReader(),
content_reader=RealContentsOf(),
version=trashcli.trash.version
).run(sys.argv)
class ListCmd:
def __init__(self,
out,
err,
environ,
volumes_listing,
uid,
volumes, # type: VolumeOf
file_reader, # type: TopTrashDirRules.Reader
dir_reader, # type: DirReader
content_reader, # type: ContentReader
version,
):
self.out = out
self.err = err
self.version = version
self.dir_reader = dir_reader
self.content_reader = content_reader
self.environ = environ
self.uid = uid
self.volumes_listing = volumes_listing
self.selector = TrashDirsSelector.make(volumes_listing,
file_reader,
volumes)
self.actions = {PrintVersionArgs: PrintVersionAction(self.out,
self.version),
PrintVolumesArgs: PrintVolumesList(self.environ,
self.volumes_listing,
self.out),
DebugVolumesArgs: DebugVolumes(),
ListTrashDirsArgs: ListTrashDirs(self.environ,
self.uid,
self.selector),
ListTrashArgs: ListTrashAction(self.environ,
self.uid,
self.selector,
self.out,
self.err,
self.dir_reader,
self.content_reader),
PrintPythonExecutableArgs: PrintPythonExecutable()}
def run(self, argv):
parser = Parser(os.path.basename(argv[0]))
args = parser.parse_list_args(argv[1:], argv[0])
action = self.actions[type(args)]
action.run_action(args)
| 3,839
|
Python
|
.py
| 84
| 29.702381
| 80
| 0.559915
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,875
|
list_trash_dirs.py
|
andreafrancia_trash-cli/trashcli/list/minor_actions/list_trash_dirs.py
|
from typing import List, NamedTuple
from trashcli.trash_dirs_scanner import trash_dir_found, \
trash_dir_skipped_because_parent_not_sticky, \
trash_dir_skipped_because_parent_is_symlink
class ListTrashDirsArgs(
NamedTuple('ListTrashDirsArgs',
[('trash_dirs', List[str]),
('all_users', bool)])
):
pass
class ListTrashDirs:
def __init__(self, environ, uid, selector):
self.environ = environ
self.uid = uid
self.selector = selector
def run_action(self, args):
user_specified_trash_dirs = args.trash_dirs
all_users = args.all_users
trash_dirs = self.selector.select(all_users,
user_specified_trash_dirs,
self.environ,
self.uid)
for event, event_args in trash_dirs:
if event == trash_dir_found:
path, volume = event_args
print("%s" % path)
elif event == trash_dir_skipped_because_parent_not_sticky:
path = event_args
print("parent_not_sticky: %s" % (path))
elif event == trash_dir_skipped_because_parent_is_symlink:
path = event_args
print("parent_is_symlink: %s" % (path))
| 1,344
|
Python
|
.py
| 32
| 29.28125
| 70
| 0.552833
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,876
|
print_python_executable.py
|
andreafrancia_trash-cli/trashcli/list/minor_actions/print_python_executable.py
|
class PrintPythonExecutableArgs:
pass
class PrintPythonExecutable:
def run_action(self,
_args, # type: PrintPythonExecutableArgs
):
import sys
print(sys.executable)
| 230
|
Python
|
.py
| 8
| 19.75
| 60
| 0.618182
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,877
|
debug_volumes.py
|
andreafrancia_trash-cli/trashcli/list/minor_actions/debug_volumes.py
|
from pprint import pprint
class DebugVolumesArgs:
pass
class DebugVolumes(object):
def run_action(self,
_args, # type: DebugVolumesArgs
):
import psutil
import os
all = sorted([p for p in psutil.disk_partitions(all=True)],
key=lambda p: p.device)
physical = sorted([p for p in psutil.disk_partitions()],
key=lambda p: p.device)
virtual = [p for p in all if p not in physical]
print("physical ->")
pprint(physical)
print("virtual ->")
pprint(virtual)
os.system('df -P')
| 647
|
Python
|
.py
| 19
| 23.736842
| 67
| 0.551282
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,878
|
list_volumes.py
|
andreafrancia_trash-cli/trashcli/list/minor_actions/list_volumes.py
|
from __future__ import print_function
class PrintVolumesArgs(object):
pass
class PrintVolumesList(object):
def __init__(self, environ, volumes_listing, out):
self.environ = environ
self.volumes_listing = volumes_listing
self.out = out
def run_action(self,
args, # type: PrintVolumesArgs
):
for volume in self.volumes_listing.list_volumes(self.environ):
print(volume, file=self.out)
| 482
|
Python
|
.py
| 13
| 28.461538
| 70
| 0.635776
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,879
|
output_event.py
|
andreafrancia_trash-cli/trashcli/restore/output_event.py
|
from typing import NamedTuple, Union
Quit = NamedTuple('Quit', [])
Die = NamedTuple('Die', [('msg', Union[str, Exception])])
Println = NamedTuple('Println', [('msg', str)])
Exiting = NamedTuple('Exiting', [('msg', str)])
OutputEvent = Union[Quit, Die, Println, Exiting]
| 271
|
Python
|
.py
| 6
| 44
| 57
| 0.689394
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,880
|
trashed_files.py
|
andreafrancia_trash-cli/trashcli/restore/trashed_files.py
|
from typing import Iterable
from typing import NamedTuple
from typing import Optional
from typing import Union
from trashcli.lib.path_of_backup_copy import path_of_backup_copy
from trashcli.parse_trashinfo.parse_deletion_date import parse_deletion_date
from trashcli.parse_trashinfo.parse_original_location import \
parse_original_location
from trashcli.restore.file_system import FileReader
from trashcli.restore.info_dir_searcher import InfoDirSearcher
from trashcli.restore.restore_logger import RestoreLogger
from trashcli.restore.trashed_file import TrashedFile
class TrashedFiles:
def __init__(self,
logger, # type: RestoreLogger
file_reader, # type: FileReader
searcher, # type: InfoDirSearcher
):
self.logger = logger
self.file_reader = file_reader
self.searcher = searcher
def all_trashed_files(self,
trash_dir_from_cli, # type: Optional[str]
): # type: (...) -> Iterable[TrashedFile]
for event in self.all_trashed_files_internal(trash_dir_from_cli):
if type(event) is NonTrashinfoFileFound:
self.logger.warning("Non .trashinfo file in info dir")
elif type(event) is NonParsableTrashInfo:
self.logger.warning(
"Non parsable trashinfo file: %s, because %s" %
(event.path, event.reason))
elif type(event) is IOErrorReadingTrashInfo:
self.logger.warning(str(event))
elif type(event) is TrashedFileFound:
yield event.trashed_file
else:
raise RuntimeError()
def all_trashed_files_internal(self,
trash_dir_from_cli, # type: Optional[str]
): # type: (...) -> Iterable[Event]
for info_file in self.searcher.all_file_in_info_dir(trash_dir_from_cli):
if info_file.type == 'non_trashinfo':
yield NonTrashinfoFileFound(info_file.path)
elif info_file.type == 'trashinfo':
try:
contents = self.file_reader.contents_of(info_file.path)
original_location = parse_original_location(contents,
info_file.volume)
deletion_date = parse_deletion_date(contents)
backup_file_path = path_of_backup_copy(info_file.path)
trashedfile = TrashedFile(original_location,
deletion_date,
info_file.path,
backup_file_path)
yield TrashedFileFound(trashedfile)
except ValueError as e:
yield NonParsableTrashInfo(info_file.path, e)
except IOError as e:
yield IOErrorReadingTrashInfo(info_file.path, str(e))
else:
raise RuntimeError("Unexpected file type: %s: %s",
info_file.type, info_file.path)
class NonTrashinfoFileFound(
NamedTuple('NonTrashinfoFileFound', [
('path', str),
])): pass
class TrashedFileFound(
NamedTuple('TrashedFileFound', [
('trashed_file', TrashedFile),
])): pass
class NonParsableTrashInfo(
NamedTuple('NonParsableTrashInfo', [
('path', str),
('reason', Exception),
])): pass
class IOErrorReadingTrashInfo(
NamedTuple('IOErrorReadingTrashInfo', [
('path', str),
('error', str),
])): pass
Event = Union[
NonTrashinfoFileFound,
TrashedFileFound,
NonParsableTrashInfo,
IOErrorReadingTrashInfo]
| 3,841
|
Python
|
.py
| 85
| 31.835294
| 81
| 0.582999
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,881
|
trash_directories.py
|
andreafrancia_trash-cli/trashcli/restore/trash_directories.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from abc import abstractmethod, ABCMeta
import six
from typing import Optional
from trashcli.fstab.volume_of import VolumeOf
from trashcli.fstab.volumes import Volumes
from trashcli.lib.environ import Environ
from trashcli.lib.trash_dirs import (
volume_trash_dir1, volume_trash_dir2, home_trash_dir)
@six.add_metaclass(ABCMeta)
class TrashDirectories:
@abstractmethod
def list_trash_dirs(self, trash_dir_from_cli):
raise NotImplementedError()
class TrashDirectoriesImpl(TrashDirectories):
def __init__(self,
volumes, # type: Volumes
uid, # type: int
environ,
):
trash_directories1 = TrashDirectories1(volumes, uid, environ)
self.trash_directories2 = TrashDirectories2(volumes,
trash_directories1)
def list_trash_dirs(self,
trash_dir_from_cli, # type: Optional[str]
):
return self.trash_directories2.trash_directories_or_user(
trash_dir_from_cli)
class TrashDirectories2:
def __init__(self,
volume_of, # type: VolumeOf
trash_directories, # type: TrashDirectories1
):
self.volume_of = volume_of
self.trash_directories = trash_directories
def trash_directories_or_user(self,
trash_dir_from_cli, # type: Optional[str]
):
if trash_dir_from_cli:
return [(trash_dir_from_cli,
self.volume_of.volume_of(trash_dir_from_cli))]
return self.trash_directories.all_trash_directories()
class TrashDirectories1:
def __init__(self,
volumes, # type: Volumes
uid, # type: int
environ, # type: Environ
):
self.volumes = volumes
self.uid = uid
self.environ = environ
def all_trash_directories(self):
volumes_to_check = self.volumes.list_mount_points()
for path1, volume1 in home_trash_dir(self.environ, self.volumes):
yield path1, volume1
for volume in volumes_to_check:
for path1, volume1 in volume_trash_dir1(volume, self.uid):
yield path1, volume1
for path1, volume1 in volume_trash_dir2(volume, self.uid):
yield path1, volume1
| 2,510
|
Python
|
.py
| 60
| 30.333333
| 76
| 0.598522
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,882
|
run_restore_action.py
|
andreafrancia_trash-cli/trashcli/restore/run_restore_action.py
|
import os
from abc import ABCMeta, abstractmethod
import six
from typing import Optional, Iterable
from trashcli.restore.args import RunRestoreArgs
from trashcli.restore.sort_method import sort_files
from trashcli.restore.trashed_file import TrashedFile
from trashcli.restore.trashed_files import TrashedFiles
class RunRestoreAction:
def __init__(self,
handler, # type: 'Handler'
trashed_files, # type: TrashedFiles
):
self.handler = handler
self.trashed_files = trashed_files
def run_action(self, args, # type: RunRestoreArgs
): # type: (...) -> None
trashed_files = self.all_files_trashed_from_path(args.path,
args.trash_dir)
trashed_files = sort_files(args.sort, trashed_files)
self.handler.handle_trashed_files(trashed_files,
args.overwrite)
def all_files_trashed_from_path(self,
path, # type: str
trash_dir_from_cli, # type: Optional[str]
): # type: (...) -> Iterable[TrashedFile]
for trashed_file in self.trashed_files.all_trashed_files(
trash_dir_from_cli):
if trashed_file.original_location_matches_path(path):
yield trashed_file
@six.add_metaclass(ABCMeta)
class Handler:
@abstractmethod
def handle_trashed_files(self,
trashed_files,
overwrite, # type: bool
):
raise NotImplementedError()
def original_location_matches_path(trashed_file_original_location, path):
if path == os.path.sep:
return True
if trashed_file_original_location.startswith(path + os.path.sep):
return True
return trashed_file_original_location == path
| 1,964
|
Python
|
.py
| 44
| 31.727273
| 78
| 0.58543
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,883
|
range.py
|
andreafrancia_trash-cli/trashcli/restore/range.py
|
from six.moves import range
class Range:
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __eq__(self, other):
if type(other) != type(self):
return False
if self.start != other.start:
return False
if self.stop != other.stop:
return False
return True
def __iter__(self):
return iter(range(self.start, self.stop + 1))
def __repr__(self):
return "Range(%s, %s)" % (self.start, self.stop)
| 530
|
Python
|
.py
| 17
| 23.058824
| 56
| 0.551181
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,884
|
trashed_file.py
|
andreafrancia_trash-cli/trashcli/restore/trashed_file.py
|
import datetime
import os
from typing import NamedTuple, Optional
class TrashedFile(
NamedTuple('TrashedFile', [
('original_location', str),
('deletion_date', Optional[datetime.datetime]),
('info_file', str),
('original_file', str),
])):
"""
Represent a trashed file.
Each trashed file is persisted in two files:
- $trash_dir/info/$id.trashinfo
- $trash_dir/files/$id
Properties:
- path : the original path from where the file has been trashed
- deletion_date : the time when the file has been trashed (instance of
datetime)
- info_file : the file that contains information (instance of Path)
- original_file : the path where the trashed file has been placed after the
trash operation (instance of Path)
"""
def original_location_matches_path(self, path):
if path == os.path.sep:
return True
if self.original_location.startswith(path + os.path.sep):
return True
return self.original_location == path
| 1,092
|
Python
|
.py
| 29
| 30.034483
| 80
| 0.639282
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,885
|
output_recorder.py
|
andreafrancia_trash-cli/trashcli/restore/output_recorder.py
|
from typing import List
from trashcli.restore.output import Output
from trashcli.restore.output_event import Quit, Die, Println, OutputEvent
class OutputRecorder(Output):
def __init__(self): # type: (...) -> None
self.events = [] # type: List[OutputEvent]
def quit(self): # type: () -> None
self.append_event(Quit())
def die(self, msg): # type: (str) -> None
self.append_event(Die(msg))
def println(self, msg): # type: (str) -> None
self.append_event(Println(msg))
def append_event(self,
event, # type: OutputEvent
): # type: (...) -> None
self.events.append(event)
def apply_to(self, output, # type: Output
): # type: (...) -> None
for event in self.events:
output.append_event(event)
| 847
|
Python
|
.py
| 20
| 33.8
| 73
| 0.578755
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,886
|
real_restore_logger.py
|
andreafrancia_trash-cli/trashcli/restore/real_restore_logger.py
|
from logging import Logger
from trashcli.restore.restore_logger import RestoreLogger
class RealRestoreLogger(RestoreLogger):
def __init__(self,
logger, # type: Logger
):
self._logger = logger
def warning(self, message):
self._logger.warning(message)
| 313
|
Python
|
.py
| 9
| 26.888889
| 57
| 0.656667
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,887
|
sort_method.py
|
andreafrancia_trash-cli/trashcli/restore/sort_method.py
|
from abc import abstractmethod
from typing import Callable, Any, Iterable
from trashcli.compat import Protocol
from trashcli.restore.args import Sort
from trashcli.restore.trashed_file import TrashedFile
def sort_files(sort, # type: Sort
trashed_files, # type: Iterable[TrashedFile]
): # type: (...) -> Iterable[TrashedFile]
return sorter_for(sort).sort_files(trashed_files)
class Sorter(Protocol):
@abstractmethod
def sort_files(self, trashed_files, # type: Iterable[TrashedFile]
): # type: (...) -> Iterable[TrashedFile]
raise NotImplementedError()
class NoSorter(Sorter):
def sort_files(self, trashed_files, # type: Iterable[TrashedFile]
): # type: (...) -> Iterable[TrashedFile]
return trashed_files
class SortFunction(Sorter):
def __init__(self,
sort_func): # type: (Callable[[TrashedFile], Any]) -> None
self.sort_func = sort_func
def sort_files(self, trashed_files, # type: Iterable[TrashedFile]
): # type: (...) -> Iterable[TrashedFile]
return sorted(trashed_files, key=self.sort_func)
def sorter_for(sort, # type: Sort
): # type (...) -> Sorter
path_ranking = lambda x: x.original_location + str(x.deletion_date)
date_rankking = lambda x: x.deletion_date
return {
Sort.ByPath: SortFunction(path_ranking),
Sort.ByDate: SortFunction(date_rankking),
Sort.DoNot: NoSorter,
}[sort]
| 1,526
|
Python
|
.py
| 34
| 37.176471
| 76
| 0.64503
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,888
|
restorer.py
|
andreafrancia_trash-cli/trashcli/restore/restorer.py
|
import os
from trashcli.restore.file_system import RestoreWriteFileSystem, \
RestoreReadFileSystem
from trashcli.restore.trashed_file import TrashedFile
class Restorer:
def __init__(self,
read_fs, # type: RestoreReadFileSystem
write_fs, # type: RestoreWriteFileSystem
):
self.read_fs = read_fs
self.write_fs = write_fs
def restore_trashed_file(self,
trashed_file, # type: TrashedFile
overwrite, # type: bool
):
"""
If overwrite is enabled, then the restore functionality will overwrite an existing file
"""
if not overwrite and self.read_fs.path_exists(trashed_file.original_location):
raise IOError(
'Refusing to overwrite existing file "%s".' % os.path.basename(
trashed_file.original_location))
else:
parent = os.path.dirname(trashed_file.original_location)
self.write_fs.mkdirs(parent)
self.write_fs.move(trashed_file.original_file, trashed_file.original_location)
self.write_fs.remove_file(trashed_file.info_file)
| 1,218
|
Python
|
.py
| 27
| 33.037037
| 95
| 0.610455
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,889
|
restore_arg_parser.py
|
andreafrancia_trash-cli/trashcli/restore/restore_arg_parser.py
|
import os
from typing import Union, List, cast
from trashcli.lib.print_version import PrintVersionArgs
from trashcli.restore.args import RunRestoreArgs, Sort
from trashcli.shell_completion import add_argument_to, TRASH_FILES, TRASH_DIRS, \
complete_with
Command = Union[PrintVersionArgs, RunRestoreArgs]
class RestoreArgParser:
def parse_restore_args(self,
sys_argv, # type: List[str]
curdir, # type: str
): # type: (...) -> Command
import argparse
parser = argparse.ArgumentParser(
description='Restores from trash chosen file',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
add_argument_to(parser)
complete_with(
TRASH_FILES,
parser.add_argument('path',
default="", nargs='?',
help='Restore files from given path instead of current '
'directory'
)
)
parser.add_argument('--sort',
choices=['date', 'path', 'none'],
default='date',
help='Sort list of restore candidates by given field')
complete_with(
TRASH_DIRS,
parser.add_argument('--trash-dir',
action='store',
dest='trash_dir',
help=argparse.SUPPRESS
))
parser.add_argument('--version', action='store_true', default=False)
parser.add_argument('--overwrite',
action='store_true',
default=False,
help='Overwrite existing files with files coming out of the trash')
parsed = parser.parse_args(sys_argv[1:])
if parsed.version:
return PrintVersionArgs(argv0=sys_argv[0])
else:
path = os.path.normpath(
os.path.join(curdir + os.path.sep, parsed.path))
return RunRestoreArgs(path=path,
sort=cast(Sort, {
'path': Sort.ByPath,
'date': Sort.ByDate,
'none': Sort.DoNot
}[parsed.sort]),
trash_dir=parsed.trash_dir,
overwrite=parsed.overwrite)
| 2,595
|
Python
|
.py
| 55
| 28.054545
| 95
| 0.478467
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,890
|
sequences.py
|
andreafrancia_trash-cli/trashcli/restore/sequences.py
|
from typing import NamedTuple, List
from trashcli.restore.index import Sequence
class Sequences(NamedTuple('Sequences', [
('sequences', List[Sequence]),
])):
def all_indexes(self):
for sequence in self.sequences:
for index in sequence:
yield index
| 295
|
Python
|
.py
| 9
| 26.555556
| 43
| 0.681979
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,891
|
output.py
|
andreafrancia_trash-cli/trashcli/restore/output.py
|
from abc import ABCMeta, abstractmethod
import six
from trashcli.restore.output_event import OutputEvent
@six.add_metaclass(ABCMeta)
class Output:
@abstractmethod
def quit(self):
raise NotImplementedError
@abstractmethod
def die(self, msg):
raise NotImplementedError
@abstractmethod
def println(self, msg):
raise NotImplementedError
@abstractmethod
def append_event(self,
event, # type: OutputEvent
):
raise NotImplementedError
| 542
|
Python
|
.py
| 19
| 21.578947
| 53
| 0.686047
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,892
|
restore_cmd.py
|
andreafrancia_trash-cli/trashcli/restore/restore_cmd.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from typing import TextIO, Callable
from trashcli.lib.my_input import Input
from trashcli.lib.print_version import PrintVersionAction, PrintVersionArgs
from trashcli.restore.args import RunRestoreArgs
from trashcli.restore.file_system import RestoreReadFileSystem, \
RestoreWriteFileSystem, ReadCwd
from trashcli.restore.handler import HandlerImpl
from trashcli.restore.real_output import RealOutput
from trashcli.restore.restore_arg_parser import RestoreArgParser
from trashcli.restore.restorer import Restorer
from trashcli.restore.run_restore_action import RunRestoreAction, Handler
from trashcli.restore.trashed_files import TrashedFiles
class RestoreCmd(object):
@staticmethod
def make(stdout, # type: TextIO
stderr, # type: TextIO
exit, # type: Callable[[int], None]
input, # type: Input
version, # type: str
trashed_files, # type: TrashedFiles
read_fs, # type: RestoreReadFileSystem
write_fs, # type: RestoreWriteFileSystem
read_cwd, # type: ReadCwd
): # type: (...) -> RestoreCmd
restorer = Restorer(read_fs, write_fs)
output = RealOutput(stdout, stderr, exit)
handler = HandlerImpl(input, read_cwd, restorer, output)
return RestoreCmd(stdout, version, trashed_files, read_cwd, handler)
def __init__(self,
stdout, # type: TextIO
version, # type: str
trashed_files, # type: TrashedFiles
read_cwd, # type: ReadCwd
handler, # type: Handler
):
self.read_cwd = read_cwd
self.parser = RestoreArgParser()
self.run_restore_action = RunRestoreAction(handler,
trashed_files)
self.print_version_action = PrintVersionAction(stdout,
version)
def run(self, argv):
args = self.parser.parse_restore_args(argv,
self.read_cwd.getcwd_as_realpath())
if isinstance(args, RunRestoreArgs):
self.run_restore_action.run_action(args)
elif isinstance(args, PrintVersionArgs):
self.print_version_action.run_action(args)
| 2,385
|
Python
|
.py
| 49
| 37.285714
| 81
| 0.633047
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,893
|
info_dir_searcher.py
|
andreafrancia_trash-cli/trashcli/restore/info_dir_searcher.py
|
from typing import NamedTuple, Iterable, Optional
from trashcli.restore.info_files import InfoFiles
from trashcli.restore.trash_directories import TrashDirectories
class InfoDirSearcher:
def __init__(self,
trash_directories, # type: TrashDirectories
info_files, # type: InfoFiles
):
self.trash_directories = trash_directories
self.info_files = info_files
def all_file_in_info_dir(self,
trash_dir_from_cli, # type: Optional[str]
): # type: (...) -> Iterable[FileFound]
for trash_dir_path, volume in self.trash_directories.list_trash_dirs(
trash_dir_from_cli):
for type, path in self.info_files.all_info_files(trash_dir_path):
yield FileFound(type, path, volume)
class FileFound(NamedTuple('Info', [
('type', 'str'),
('path', 'str'),
('volume', 'str'),
])):
pass
| 970
|
Python
|
.py
| 23
| 32.173913
| 77
| 0.60255
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,894
|
index.py
|
andreafrancia_trash-cli/trashcli/restore/index.py
|
from typing import Union
from trashcli.restore.range import Range
from trashcli.restore.single import Single
Sequence = Union[Range, Single]
| 143
|
Python
|
.py
| 4
| 34.25
| 42
| 0.854015
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,895
|
restore_asking_the_user.py
|
andreafrancia_trash-cli/trashcli/restore/restore_asking_the_user.py
|
from typing import TypeVar, Generic, List, NamedTuple, Callable
from six.moves import range
from trashcli.lib.my_input import Input
from trashcli.restore.index import Sequence
from trashcli.restore.output import Output
from trashcli.restore.output_event import Die, OutputEvent, Quit
from trashcli.restore.output_event import Exiting
from trashcli.restore.range import Range
from trashcli.restore.sequences import Sequences
from trashcli.restore.single import Single
from trashcli.restore.trashed_file import TrashedFile
SelectedFiles = NamedTuple('SelectedFiles', [
('files_to_restore', List[TrashedFile]),
('overwrite', bool),
])
Context = NamedTuple('Context', [
('trashed_files', List[TrashedFile]),
('overwrite', bool),
])
InputRead = NamedTuple('InputRead', [
('user_input', str),
('trashed_files', List[TrashedFile]),
('overwrite', bool),
])
class RestoreAskingTheUser(object):
def __init__(self,
input, # type: Input
restorer,
output, # type: Output
):
self.input = input
self.restorer = restorer
self.output = output
def read_user_input(self,
args, # type: Context
): # type: (...) -> Either[OutputEvent, InputRead]
try:
user_input = self.input.read_input(
"What file to restore [0..%d]: " % (
len(args.trashed_files) - 1))
except KeyboardInterrupt:
return Left(Quit())
except EOFError:
return Left(Quit())
else:
if user_input == "":
return Left(Exiting("No files were restored"))
else:
return Right(
InputRead(user_input, args.trashed_files, args.overwrite))
def restore_asking_the_user(self, trashed_files, overwrite):
input = Right(Context(trashed_files, overwrite))
compose(input, [
self.read_user_input,
trashed_files_to_restore,
self.restore_selected_files,
]).on_error(
lambda error: self.output.append_event(error))
def restore_selected_files(self,
selected_files, # type: SelectedFiles
): # type: (...) -> Either[Die, None]
try:
for trashed_file in selected_files.files_to_restore:
self.restorer.restore_trashed_file(trashed_file,
selected_files.overwrite)
return Right(None)
except IOError as e:
return Left(Die(e))
Error = TypeVar('Error')
Value = TypeVar('Value')
def compose(input, funcs):
for f in funcs:
input = input.apply(f)
return input
class Either(Generic[Error, Value]):
def apply(self,
f): # type: (Callable[[Value], Either[Error, OutputValue]]) -> Either[Error, OutputValue]
raise NotImplementedError()
class Left(Either, Generic[Error, Value]):
def __init__(self,
error, # type: Error
):
self.error = error
def apply(self,
f): # type: (Callable[[Value], Either[Error, OutputValue]]) -> Either[Error, OutputValue]
return self
def on_error(self, f):
return f(self.error)
OutputValue = TypeVar('OutputValue')
class Right(Either[Error, Value]):
def __init__(self, value, # type: Value
):
self.value = value
def apply(self,
f): # type: (Callable[[Value], Either[Error, OutputValue]]) -> Either[Error, OutputValue]
return f(self.value)
def on_error(self, f):
return self
def trashed_files_to_restore(input_read, # type: InputRead
): # type: (...) -> Either[Die, SelectedFiles]
try:
sequences = parse_indexes(input_read.user_input,
len(input_read.trashed_files))
file_to_restore = [input_read.trashed_files[index] for index in
sequences.all_indexes()]
selected_files = SelectedFiles(file_to_restore, input_read.overwrite)
return Right(selected_files)
except InvalidEntry as e:
return Left(Die("Invalid entry: %s" % e))
class InvalidEntry(Exception):
pass
def parse_indexes(user_input, # type: str
len_trashed_files, # type: int
): # type: (...) -> Sequences
indexes = user_input.split(',')
sequences = [] # type: List[Sequence]
for index in indexes:
if "-" in index:
first, last = index.split("-", 2)
if first == "" or last == "":
raise InvalidEntry("open interval: %s" % index)
split = list(map(parse_int_index, (first, last)))
sequences.append(Range(split[0], split[1]))
else:
int_index = parse_int_index(index)
sequences.append(Single(int_index))
result = Sequences(sequences)
acceptable_values = range(0, len_trashed_files)
for index in result.all_indexes():
if not index in acceptable_values:
raise InvalidEntry(
"out of range %s..%s: %s" %
(acceptable_values[0], acceptable_values[-1], index))
return result
def parse_int_index(text): # type: (str) -> int
try:
return int(text)
except ValueError:
raise InvalidEntry("not an index: %s" % text)
| 5,528
|
Python
|
.py
| 139
| 29.884892
| 104
| 0.585917
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,896
|
single.py
|
andreafrancia_trash-cli/trashcli/restore/single.py
|
from typing import NamedTuple
class Single(NamedTuple('Single', [
('index', int),
])):
pass
| 102
|
Python
|
.py
| 5
| 17.4
| 35
| 0.684211
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,897
|
real_output.py
|
andreafrancia_trash-cli/trashcli/restore/real_output.py
|
from __future__ import print_function
import six
from trashcli.restore.output import Output
from trashcli.restore.output_event import Println, Die, Quit, Exiting, \
OutputEvent
class RealOutput(Output):
def __init__(self, stdout, stderr, exit):
self.stdout = stdout
self.stderr = stderr
self.exit = exit
def quit(self):
self.die('')
def printerr(self, msg):
print(six.text_type(msg), file=self.stderr)
def println(self, line):
print(six.text_type(line), file=self.stdout)
def die(self, error):
self.printerr(error)
self.exit(1)
def append_event(self,
event, # type: OutputEvent
):
if isinstance(event, Println):
self.println(event.msg)
elif isinstance(event, Die):
self.die(event.msg)
elif isinstance(event, Quit):
self.quit()
elif isinstance(event, Exiting):
self.println(event.msg)
else:
raise Exception("Unknown call %s" % event)
| 1,077
|
Python
|
.py
| 32
| 25.0625
| 72
| 0.604247
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,898
|
args.py
|
andreafrancia_trash-cli/trashcli/restore/args.py
|
from enum import Enum
from typing import NamedTuple, Optional
from trashcli.lib.enum_repr import repr_for_enum
class Sort(Enum):
ByDate = "ByDate"
ByPath = "ByPath"
DoNot = "DoNot"
def __repr__(self):
return repr_for_enum(self)
class RunRestoreArgs(
NamedTuple('RunRestoreArgs', [
('path', str),
('sort', Sort),
('trash_dir', Optional[str]),
('overwrite', bool),
])):
pass
| 447
|
Python
|
.py
| 17
| 20.941176
| 48
| 0.625
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,899
|
info_files.py
|
andreafrancia_trash-cli/trashcli/restore/info_files.py
|
import os
from trashcli.restore.file_system import ListingFileSystem
class InfoFiles:
def __init__(self,
fs, # type: ListingFileSystem
):
self.fs = fs
def all_info_files(self, path):
norm_path = os.path.normpath(path)
info_dir = os.path.join(norm_path, 'info')
try:
for info_file in self.fs.list_files_in_dir(info_dir):
if not os.path.basename(info_file).endswith('.trashinfo'):
yield ('non_trashinfo', info_file)
else:
yield ('trashinfo', info_file)
except OSError: # when directory does not exist
pass
| 688
|
Python
|
.py
| 18
| 27.111111
| 74
| 0.561562
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|