Пример #1
0
    def test_show_start_message(self):
        """Testing def show_start_message. Count, search, total group.

        :return:
        """
        count = show_start_message(value=None,
                                   case_sensitive=False,
                                   recursive=True,
                                   include_hidden=False,
                                   location='/some/path',
                                   group=None)
        search = show_start_message(value='.',
                                    case_sensitive=False,
                                    recursive=False,
                                    include_hidden=False,
                                    location='/some/path',
                                    group=None)
        total = show_start_message(value='TXT',
                                   case_sensitive=True,
                                   recursive=True,
                                   include_hidden=True,
                                   location='/some/path',
                                   group='total')
        self.assertEqual(
            count, 'Recursively counting all files, '
            'ignoring hidden files and directories, in /some/path')
        self.assertEqual(
            search, 'Searching files without any extension, '
            'ignoring hidden files and directories, in /some/path')
        self.assertEqual(
            total,
            'Recursively counting total number of files with (case-sensitive) extension .TXT, '
            'including hidden files and directories, in /some/path')
Пример #2
0
def main_flow(*args: [argparse_namespace_object, Union[bytes, str]]):
    """Main application function.

    :param args: object <class 'argparse.Namespace'>,
    for tests param args - list with objects of <class 'str'>
    :return:
    Returns the processed data as text to the screen.
    Total number of files, table or list with file paths.
    Returns parser.exit(status=1):
    if path does not exist or there may be a typo in it,
    if the path has hidden folders and the argument --all is not specified,
    if the preview is not available for the specified file type.
    """
    args = parser.parse_args(*args)
    recursive = not args.no_recursion
    include_hidden = args.all
    sort_alpha = args.sort_alpha
    extension = args.file_extension
    current_os = get_current_os()
    if current_os.name == 'BaseOS':
        # the default option to exclude hidden files and folders is not implemented for undefined OS,
        # no need to call self.is_hidden_file_or_dir()
        include_hidden = True

    if args.supported_types:
        parser.exit(status=0, message=SUPPORTED_TYPE_INFO_MESSAGE)

    if args.topic:
        search_in_help(args.topic)
        parser.exit(status=0)

    if os.path.abspath(args.path) == os.getcwd():
        location = os.getcwd()
        loc_text = ' the current directory'
    else:
        location = os.path.expanduser(args.path)
        loc_text = ':\n' + os.path.normpath(location)

    if not os.path.exists(location):
        parser.exit(status=1, message=f'The path {location} '
                                      f'does not exist, or there may be a typo in it.')

    if not include_hidden and current_os.is_hidden_file_or_dir(location):
        # skip check if path is a local drive
        if platform.startswith('win') and len(Path(location).parents) == 0:
            pass
        else:
            parser.exit(status=1, message=f'\nNot counting any files, because {loc_text[2:]}'
                                          f' has hidden folders.\n'
                                          f'Use the --all argument to include hidden files and folders.')

    # Parser total_group
    # getting the total number of files for -t .. (all extensions), -t . and -t extension_name
    print("")
    if args.extension:
        print(fill(show_start_message(args.extension, args.case_sensitive, recursive,
                                      include_hidden, location, 'total'),
                   width=START_TEXT_WIDTH),
              end="\n\n")

        data = current_os.search_files(dirpath=location,
                                       extension=args.extension,
                                       include_hidden=include_hidden,
                                       recursive=recursive,
                                       case_sensitive=args.case_sensitive)
        total_result = show_result_for_total(data, args.no_feedback)
        return total_result

    # Parser search_group
    # search and list files by extension
    if extension:
        print(fill(show_start_message(extension, args.case_sensitive, recursive, include_hidden, location),
                   width=START_TEXT_WIDTH),
              end="\n\n")

        # list of all found file paths - enabled by default,
        # optional: information about file sizes, file preview, size specification for file preview
        if args.preview:
            if extension == '.' or not is_supported_filetype(extension.lower()):
                parser.exit(status=1, message=NOT_SUPPORTED_TYPE_MESSAGE)

        # getting data list for -fe .. (all extensions), -fe . and -fe extension_name
        data = (f for f in current_os.search_files(dirpath=location,
                                                   extension=extension,
                                                   include_hidden=include_hidden,
                                                   recursive=recursive,
                                                   case_sensitive=args.case_sensitive))

        # display the result as a list
        len_files = show_result_for_search_files(files=data,
                                                 file_sizes=args.file_sizes,
                                                 preview=args.preview,
                                                 preview_size=args.preview_size)

        return len_files

    # Parser count_group
    # counting all files by extension
    print(fill(show_start_message(None, args.case_sensitive, recursive, include_hidden, location),
               width=START_TEXT_WIDTH),
          end="\n\n"
          )
    data = current_os.count_files_by_extension(dirpath=location,
                                               no_feedback=args.no_feedback,
                                               include_hidden=include_hidden,
                                               recursive=recursive,
                                               case_sensitive=args.case_sensitive)

    # display the result as a table
    
    # if empty sequence
    if not data:
        print("Oops! We have no data to show...\n")
        parser.exit(status=0)
        
    total_occurrences = sum(data.values())
    max_word_width = max(map(len, data.keys()))

    if sort_alpha:
        # sort extensions alphabetically, with uppercase versions on top
        sort_key = lambda data: (data[0].casefold(), data[0])
        data = sorted(data.items(), key=sort_key)
    else:
        # sort extensions by frequency for each file extension
        data = data.most_common()
    show_2columns(data, max_word_width, total_occurrences)
    parser.exit(status=0)