Advertisement
DeaD_EyE

something like locate db

Jun 25th, 2022
1,156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. import shelve
  2. from os import access, X_OK
  3. from pathlib import Path
  4. from collections import UserDict
  5. from functools import reduce
  6. from operator import or_
  7.  
  8.  
  9. class DictSetMerge(UserDict):
  10.     def __or__(self, other):
  11.         results = self.copy()
  12.         for key, paths in other.items():
  13.             if key in results:
  14.                 results[key] |= paths
  15.             else:
  16.                 results[key] = paths
  17.                
  18.         return results
  19.                
  20.     def __getitem__(self, key):
  21.         if key not in self:
  22.             paths = set()
  23.             self[key] = paths
  24.             return paths
  25.         else:    
  26.             return super().__getitem__(key)
  27.            
  28.     def add(self, key: str | Path, paths: set[Path] | None = None):
  29.         """
  30.        Add a single Path if key is a Path object.
  31.        Otherwise add values to the set.
  32.        """
  33.         if not isinstance(key, Path) and paths is None:
  34.             raise ValueError("Values allowed only to be None, if key is a Path")
  35.            
  36.         if not paths:
  37.             paths = [key]
  38.             key = key.name
  39.            
  40.         if key in self:
  41.             self[key] |= set(paths)
  42.         else:
  43.             self[key] = set(paths)
  44.  
  45.  
  46. def make_db(root) -> DictListMerge:
  47.    
  48.     results = DictSetMerge()
  49.    
  50.     for file in Path(root).rglob("*"):
  51.        
  52.         if file.is_file() and access(file, X_OK):
  53.             results.add(file)
  54.        
  55.     return results
  56.  
  57. db_file = Path("db.shelve")
  58. if db_file.exists():
  59.     with shelve.open(db_file) as sh:
  60.         db = DictListMerge(sh)
  61. else:
  62.     paths = ["/bin","/sbin","/usr/sbin","/usr/lib","/home/deadeye/.local/"]
  63.     db = reduce(or_, map(make_db, paths))
  64.     with shelve.open(db_file) as sh:
  65.         sh.update(db)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement