mdrs-client-python/mdrsclient/commands/rm.py

47 lines
1.9 KiB
Python
Raw Permalink Normal View History

2023-05-10 18:17:35 +09:00
import os
from argparse import Namespace
from typing import Any
2023-05-10 18:17:35 +09:00
2023-12-12 20:05:46 +09:00
from mdrsclient.api import FilesApi, FoldersApi
2023-05-10 18:17:35 +09:00
from mdrsclient.commands.base import BaseCommand
from mdrsclient.exceptions import IllegalArgumentException
class RmCommand(BaseCommand):
@classmethod
def register(cls, parsers: Any) -> None:
2023-05-10 18:17:35 +09:00
rm_parser = parsers.add_parser("rm", help="remove the file or folder")
rm_parser.add_argument(
"-r", "--recursive", help="remove folders and their contents recursive", action="store_true"
)
rm_parser.add_argument("remote_path", help="remote file path (remote:/lab/path/file)")
rm_parser.set_defaults(func=cls.func)
2023-05-10 18:17:35 +09:00
@classmethod
def func(cls, args: Namespace) -> None:
remote_path = str(args.remote_path)
is_recursive = bool(args.recursive)
cls.rm(remote_path, is_recursive)
@classmethod
def rm(cls, remote_path: str, is_recursive: bool) -> None:
(remote, laboratory_name, r_path) = cls._parse_remote_host_with_path(remote_path)
2023-05-10 18:17:35 +09:00
r_path = r_path.rstrip("/")
r_dirname = os.path.dirname(r_path)
r_basename = os.path.basename(r_path)
connection = cls._create_connection(remote)
laboratory = cls._find_laboratory(connection, laboratory_name)
parent_folder = cls._find_folder(connection, laboratory, r_dirname)
2023-05-10 18:17:35 +09:00
file = parent_folder.find_file(r_basename)
if file is not None:
2023-12-12 20:05:46 +09:00
file_api = FilesApi(connection)
2023-05-10 18:17:35 +09:00
file_api.destroy(file)
else:
folder = parent_folder.find_sub_folder(r_basename)
if folder is None:
raise IllegalArgumentException(f"Cannot remove `{r_path}`: No such file or folder.")
if not is_recursive:
2023-05-10 18:17:35 +09:00
raise IllegalArgumentException(f"Cannot remove `{r_path}`: Is a folder.")
2023-12-12 20:05:46 +09:00
folder_api = FoldersApi(connection)
folder_api.destroy(folder.id, True)