Esempio n. 1
0
    def push(self, path):
        """
        Created trashinfo element. Return filename in trashinfo.
        """
        deletion_date = datetime.datetime.now()
        old_path = get_full_path(path)

        filename = os.path.basename(old_path)
        index = 0

        unique_name = "{filename}.{index}".format(filename=filename,
                                                  index=index)
        trashinfo_list = os.listdir(self.trashinfo_path)

        while unique_name in trashinfo_list:
            index += 1
            unique_name = "{filename}.{index}".format(filename=filename,
                                                      index=index)

        trashinfo = {
            "old path": old_path,
            "deletion date": deletion_date.strftime("%Y-%m-%dT%H:%M:%S")
        }
        trashinfo_filename = os.path.join(self.trashinfo_path, unique_name)

        with open(trashinfo_filename, 'w') as trashinfo_file:
            json.dump(trashinfo, trashinfo_file)

        return unique_name
Esempio n. 2
0
def load_config(path):
    """
     Load config file and return configuration parameters dict.
     """
    path = get_full_path(path)
    file_extension = os.path.splitext(path)[-1]
    config = DEFAULT_CONFIG

    if not os.path.exists(path):
        warning_message = """The "{file}" does not exist!
The default config will be used.""".format(file=path)

        logging.warning(warning_message)
        return config

    with open(path, 'r') as config_file:
        if file_extension == ".json":
            config = json.load(config_file)
        elif file_extension == ".toml":
            config = pytoml.load(config_file)
        else:
            warning_message = """The "{file}" does not match the format of toml in json!
The default config will be used.""".format(file=path)
            logging.warning(warning_message)

    return config
Esempio n. 3
0
    def remove(self, *paths):
        """
        Remove directories and files in WasteBasket.

        Returns a list of successfully moved files. The list item contains a
        tuple from the old and new paths.

        If path doesn't exist, OSError will be raised.
        """
        success_moved_files = []
        for path in paths:
            path = get_full_path(path)
            filename = self.trashinfo.push(path)

            try:
                if os.path.isdir(path) and not self.rmdir:
                    raise OSError(13, "Rmdir mode in not active")

                src_dst = move(path, os.path.join(self.file_dir, filename), dry_run=self.dry_run)
                success_moved_files.append(src_dst)

                if self.dry_run:
                    self.trashinfo.pop(filename) 

            except OSError as exception:
                self.trashinfo.pop(filename)
                if not self.force:
                    raise MoveError(message=exception.strerror,
                                    raised_path=path,
                                    success=success_moved_files)
        
        return success_moved_files
Esempio n. 4
0
    def remove_regex(self, pattern, search_dirs=False):
        """
        Removes files by regex. Using breadth-first search.
        """
        full_pattern_path = get_full_path(pattern)
        pattern = os.path.basename(pattern)

        success_moved_files = []

        queue, visited_dirs = [], []
        queue.append(os.path.dirname(full_pattern_path))
        while queue:
            current_dir = queue.pop()
            visited_dirs.append(current_dir)

            for path in os.listdir(current_dir):
                if re.match(pattern, path):
                    path = os.path.join(current_dir, path)
                    src_dst = self.remove(path)
                    success_moved_files.extend(src_dst)

                    if os.path.isdir(path):
                        visited_dirs.append(path)

            if os.path.exists(current_dir):
                for path in os.listdir(current_dir):
                    full_path = os.path.join(current_dir, path)
                    if search_dirs and os.path.isdir(full_path) and full_path not in visited_dirs:
                        queue.insert(0, full_path)

        return success_moved_files
Esempio n. 5
0
 def create_wastebasket(self, path):
     """
     Creates wastebasket by the specified path.
     """
     self.wastebasket_path = get_full_path(path)
     
     if not os.path.exists(self.wastebasket_path):
         create_path(self.wastebasket_path)
     if not os.path.exists(self.file_dir):
         create_path(self.file_dir)
     if not os.path.exists(self.trashinfo_dir):
         create_path(self.trashinfo_dir)
Esempio n. 6
0
def setup_file_logger(filename="",
                      str_format="%(levelname)s: %(message)s",
                      level=logging.INFO):
    """Setup file logger"""
    root_logger = logging.getLogger()
    formatter = logging.Formatter(str_format)

    fhandler = logging.FileHandler(get_full_path(filename))
    fhandler.setLevel(level)
    fhandler.setFormatter(formatter)

    root_logger.addHandler(fhandler)
    root_logger.setLevel(level)
Esempio n. 7
0
def cat_config(path):
    """
    Shows config file content
    """
    path = get_full_path(path)

    with open(path, "r") as config_file:
        config_file_lines = config_file.readlines()

    config_string_representation = '"{file}":\n'.format(file=path)
    for line in config_file_lines:
        config_string_representation += "\t{line}".format(line=line)

    logging.info(config_string_representation)
Esempio n. 8
0
class WasteBasket(models.Model):
    name = models.CharField(max_length=50, default="WasteBasket")

    rmdir = models.BooleanField(default=False)
    force = models.BooleanField(default=False)
    dry_run = models.BooleanField(default=False)

    max_size = models.PositiveIntegerField(default=32)
    storage_time = models.DurationField(default=datetime.timedelta(days=30))
    wastebasket_path = models.FilePathField(path=get_full_path('~/'), allow_files=False, allow_folders=True)
    wastebasket_path = models.TextField(default='~/Trash', unique=True)

    def __unicode__(self):
        return self.name
Esempio n. 9
0
def create_config(path, config_dict=None):
    """
    Create config file.
    """
    if config_dict is None:
        config_dict = {}

    file_extension = os.path.splitext(path)[-1]
    path = get_full_path(path)

    if not os.path.exists(path):
        create_path(path, is_file=True)

    with open(path, 'w') as config_file:
        if file_extension == ".json":
            json.dump(config_dict, config_file, indent=4, sort_keys=True)
        elif file_extension == ".toml":
            pytoml.dump(config_dict, config_file, sort_keys=True)
        else:
            warning_message = """"{file}" has not been created!
It has a format different from json and toml.""".format(file=path)
            logging.warning(warning_message)
Esempio n. 10
0
def update_config(path="", config_dict=None):
    """
    Update current config file
    """
    if config_dict is None:
        config_dict = {}

    path = get_full_path(path)
    file_extension = os.path.splitext(path)[-1]

    if not os.path.exists(path):
        warning_message = """The "{file}" does not exist!""".format(file=path)
        logging.warning(warning_message)
        return

    with open(path, 'w') as config_file:
        if file_extension == ".json":
            json.dump(config_dict, config_file, indent=4, sort_keys=True)
        elif file_extension == ".toml":
            pytoml.dump(config_dict, config_file, sort_keys=True)
        else:
            warning_message = """"{file}" has not been updated!
It has a format different from json and toml.""".format(file=path)
            logging.warning(warning_message)
Esempio n. 11
0
 def __init__(self, trashinfo_path=TRASHINFO_PATH):
     self.trashinfo_path = get_full_path(trashinfo_path)