From 9ede898c3e7b893d69e9df5d74db9920c89b8bd4 Mon Sep 17 00:00:00 2001 From: "Matthew D. Scholefield" Date: Wed, 27 May 2020 06:52:00 -0500 Subject: [PATCH] Create __main__.py (Fixes #15) (#38) This adds a main method that mimics the behavior of `rm`. It can be called via `python -m send2trash somefile`. --- send2trash/__main__.py | 33 +++++++++++++++++++++++++++++++++ tests/test_script_main.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 send2trash/__main__.py create mode 100644 tests/test_script_main.py diff --git a/send2trash/__main__.py b/send2trash/__main__.py new file mode 100644 index 0000000..0f73a64 --- /dev/null +++ b/send2trash/__main__.py @@ -0,0 +1,33 @@ +# encoding: utf-8 +# Copyright 2017 Virgil Dupras + +# This software is licensed under the "BSD" License as described in the "LICENSE" file, +# which should be included with this package. The terms are also available at +# http://www.hardcoded.net/licenses/bsd_license + +from __future__ import print_function + +import sys + +from argparse import ArgumentParser +from send2trash import send2trash + + +def main(args=None): + parser = ArgumentParser(description='Tool to send files to trash') + parser.add_argument('files', nargs='+') + parser.add_argument('-v', '--verbose', action='store_true', help='Print deleted files') + args = parser.parse_args(args) + + for filename in args.files: + try: + send2trash(filename) + if args.verbose: + print('Trashed «' + filename + '»') + except OSError as e: + print(str(e), file=sys.stderr) + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/tests/test_script_main.py b/tests/test_script_main.py new file mode 100644 index 0000000..9fe1b1e --- /dev/null +++ b/tests/test_script_main.py @@ -0,0 +1,32 @@ +# encoding: utf-8 +import os +import unittest +from tempfile import NamedTemporaryFile +from os import path as op + +from send2trash.__main__ import main as trash_main +from tests.test_plat_other import HOMETRASH + + +class TestMainTrash(unittest.TestCase): + def setUp(self): + self.file = NamedTemporaryFile(dir=op.expanduser('~'), prefix='send2trash_test', delete=False) + + def test_trash(self): + trash_main(['-v', self.file.name]) + self.assertFalse(op.exists(self.file.name)) + + def test_no_args(self): + self.assertRaises(SystemExit, trash_main, []) + self.assertRaises(SystemExit, trash_main, ['-v']) + self.assertTrue(op.exists(self.file.name)) + trash_main([self.file.name]) # Trash the file so tearDown runs properly + + def tearDown(self): + name = op.basename(self.file.name) + os.remove(op.join(HOMETRASH, 'files', name)) + os.remove(op.join(HOMETRASH, 'info', name + '.trashinfo')) + + +if __name__ == '__main__': + unittest.main()