aboutsummaryrefslogtreecommitdiff
path: root/packages/finder/plugin/searcher/file/name.py
blob: b6319fe932311a5ed2ec4add90019fbde8d97016 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Finder searcher and browser REPL.
#
# Copyright (C) 2024 Silvio Rhatto <rhatto@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import re
import json
import asyncio

from platformdirs import user_cache_dir

class FinderPluginFileNameSearcher():
    def __init__(self, path):
        self.set_path(path)

    def set_path(self, path):
        # Initialize item list
        if 'items' not in dir(self):
            self.items = []

        # Reset item list when changing paths
        elif 'path' in dir(self) and self.path != path:
            self.items = []

        cache_dir  = user_cache_dir('finder', 'rhatto')
        self.path  = path
        self.cache = os.path.join(cache_dir, 'plugin', 'searcher', 'file', os.path.abspath(self.path).replace(os.sep, '_') + '.json')

    async def finder(self, force = False):
      # Check existing cache
      if not force and os.path.exists(self.cache) and os.path.isfile(self.cache):
          with open(self.cache, 'r') as f:
              self.items = json.load(f)

              # Then update the folder list in the background
              async with asyncio.TaskGroup() as tg:
                  walker = tg.create_task(self.walker())

              return self.items

      # Update the folder list
      await self.walker()

      # Update the cache
      os.makedirs(os.path.dirname(self.cache), exist_ok=True)
      with open(self.cache, 'w') as f:
          json.dump(self.items, f, sort_keys=True)

      return self.items

    def filter(self, text = ''):
        if text == '' or text is None:
            return self.items

        return filter(lambda s: re.search(re.escape(text), s, flags=re.IGNORECASE), self.items)

    async def walker(self):
      ignore_folders = [ '.git', '__pycache__' ]
      ignore_files   = [ '.gitignore', '.gitattributes', '.gitmodules' ]
      items          = []

      for parent, dirs, files in os.walk(self.path):
          # Do not traverse some folders
          for ignore_folder in ignore_folders:
             if ignore_folder in dirs:
                 dirs.remove(ignore_folder)

          # Do not traverse hidden folders
          for folder in dirs:
              if folder.startswith('.'):
                dirs.remove(folder)

          # Currently we're not listing folders
          #for folder in dirs:
          #    self.items.append(os.path.join(parent, folder))

          for file in files:
              # Ignore files
              for ignore_file in ignore_files:
                  if file == ignore_file:
                      continue

              # Ignore hidden files
              if file.startswith('.'):
                  continue

              items.append(os.path.join(parent, file))

      self.items = items