def test_for_hidden(self):
        """Testing def main_flow.

        Equivalent to
        "count-files ~/.../tests/data_for_tests -nr -t .."
        and "count-files ~/.../tests/data_for_tests -nr -a -t .."
        :return:
        """
        current_os = get_current_os()
        if current_os.name == 'WinOS':
            self.assertEqual(
                main_flow([
                    self.get_locations('test_hidden_windows'), '-nr', '-t',
                    '..'
                ]), 1)
            self.assertEqual(
                main_flow([
                    self.get_locations('test_hidden_windows'), '-nr', '-t',
                    '..', '-a'
                ]), 2)
        elif current_os.name == 'UnixOS':
            self.assertEqual(
                main_flow([
                    self.get_locations('test_hidden_linux'), '-nr', '-t', '..'
                ]), 1)
            self.assertEqual(
                main_flow([
                    self.get_locations('test_hidden_linux'), '-nr', '-t', '..',
                    '-a'
                ]), 2)
        else:
            # raise unittest exception
            self.skipTest(
                'For BaseOS, hidden file detection is currently not available.'
            )
    def test_parser_exit_for_hidden(self):
        """Check if all checks are performed in CLI.

        If include_hidden=False and hidden folder in path:
        In this case, the hidden folder is skipped(default settings)
        and, accordingly, the files are not count at all.
        TODO: revise the check for cases when:
        count-files ~/Documents/not_hidden_subfolder/hidden_folder
        You can count files in Documents, not_hidden_subfolder and not count them in a hidden_folder.
        :return:
        """
        current_os = get_current_os()
        # if not include_hidden and current_os.is_hidden_file_or_dir(location)
        if current_os.name == 'WinOS':
            args_dict = {
                (self.get_locations('test_hidden_windows', 'folder_hidden_for_win'), ):
                1,
                (self.get_locations('test_hidden_windows', 'folder_hidden_for_win'), '-t', 'txt'):
                1,
                (self.get_locations('test_hidden_windows', 'folder_hidden_for_win'), '-fe', '..'):
                1
            }
        elif current_os.name == 'UnixOS':
            args_dict = {
                (self.get_locations('test_hidden_linux', '.ebookreader'), ):
                1,
                (self.get_locations('test_hidden_linux', '.ebookreader'), '-t', 'txt'):
                1,
                (self.get_locations('test_hidden_linux', '.ebookreader'), '-fe', '..'):
                1
            }
        else:
            # raise unittest exception
            self.skipTest(
                'For BaseOS, hidden file detection is currently not available.'
            )

        for k, v in args_dict.items():
            with self.subTest(k=k, v=v):
                try:
                    main_flow(k)
                # should return parser.exit(status=1)
                except SystemExit as se:
                    # main_flow return parser.exit(status=0) for count_group if check is not effected in CLI
                    self.assertEqual(se.code, v)
                except Exception as e:
                    self.fail(f'Unexpected exception raised: {e}')
                else:
                    # main_flow return total_result for --total if check is not effected in CLI
                    # main_flow return len(files) for -fe .. if check is not effected in CLI
                    self.fail('SystemExit not raised')
Exemplo n.º 3
0
    def setUp(self):
        # result of def show_result_for_search_files()/def show_result_for_total()
        self.test_file_total = self.get_locations(
            'compare_tables', 'test_show_result_total.txt')
        self.test_file = self.get_locations('compare_tables',
                                            'test_show_result_list.txt')
        self.test_file_groups = self.get_locations(
            'compare_tables', 'test_show_group_ext_and_freq.txt')
        self.test_file_groups_long = self.get_locations(
            'compare_tables', 'test_show_ext_grouped_by_type.txt')
        self.test_file_groups_alpha = self.get_locations(
            'compare_tables', 'test_show_ext_grouped_by_type_alpha.txt')
        self.test_file_groups_table = self.get_locations(
            'compare_tables', 'test_show_group_ext_and_freq_table.txt')
        self.standard_file_groups = self.get_locations(
            'compare_tables', 'show_group_ext_and_freq.txt')
        self.standard_file_groups_long = self.get_locations(
            'compare_tables', 'show_ext_grouped_by_type.txt')
        self.standard_file_groups_alpha = self.get_locations(
            'compare_tables', 'show_ext_grouped_by_type_alpha.txt')
        self.standard_file_groups_table = self.get_locations(
            'compare_tables', 'show_group_ext_and_freq_table.txt')

        # files generated in def generate_standard_file()/def generate_standard_file_for_total()
        if sys.platform.startswith('win'):
            self.standard_file = self.get_locations(
                'compare_tables', 'win_show_result_list.txt')
            self.standard_file_total = self.get_locations(
                'compare_tables', 'win_show_result_total.txt')
        elif sys.platform.startswith('linux') or sys.platform.startswith(
                'haiku'):
            self.standard_file = self.get_locations(
                'compare_tables', 'linux_show_result_list.txt')
            self.standard_file_total = self.get_locations(
                'compare_tables', 'linux_show_result_total.txt')
        elif sys.platform.startswith('darwin') or sys.platform.startswith(
                'ios'):
            self.standard_file = self.get_locations(
                'compare_tables', 'darwin_show_result_list.txt')
            self.standard_file_total = self.get_locations(
                'compare_tables', 'darwin_show_result_total.txt')
        else:
            self.standard_file = self.get_locations(
                'compare_tables', 'baseos_show_result_list.txt')
            self.standard_file_total = self.get_locations(
                'compare_tables', 'baseos_show_result_total.txt')
        self.current_os = get_current_os()
Exemplo n.º 4
0
 def setUp(self):
     self.test_file_total = self.get_locations(
         'compare_tables', 'test_show_result_total.txt')
     self.test_file = self.get_locations('compare_tables',
                                         'test_show_result_list.txt')
     if sys.platform.startswith('win'):
         self.standard_file = self.get_locations(
             'compare_tables', 'win_show_result_list.txt')
     elif sys.platform.startswith('linux') or sys.platform.startswith(
             'haiku'):
         self.standard_file = self.get_locations(
             'compare_tables', 'linux_show_result_list.txt')
     elif sys.platform.startswith('darwin') or sys.platform.startswith(
             'ios'):
         self.standard_file = self.get_locations(
             'compare_tables', 'darwin_show_result_list.txt')
     self.current_os = get_current_os()
Exemplo n.º 5
0
"""
import cProfile
import os
import sys

from count_files.utils.viewing_modes import show_result_for_search_files, show_2columns, show_result_for_total
from count_files.__main__ import main_flow
from count_files.platforms import get_current_os


def get_locations(*args):
    return os.path.normpath(os.path.join(os.path.expanduser('~/'), *args))


if __name__ == "__main__":
    current_os = get_current_os()
    if sys.platform.startswith('win'):
        location = get_locations('Count-files')
    elif sys.platform.startswith('darwin'):
        # specify folder
        pass
    elif sys.platform.startswith('linux'):
        # specify folder
        pass

    # Counter and count all files with all extensions, return table, feedback - file names
    """cProfile.run("data = current_os.count_files_by_extension("
                 "dirpath=location, no_feedback=False, recursive=True, include_hidden=False);"
                 "total_occurrences = sum(data.values());"
                 "max_word_width = max(map(len, data.keys()));"
                 "data = data.most_common();"
Exemplo n.º 6
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)