Skip to content

Commit

Permalink
upload version 2.5
Browse files Browse the repository at this point in the history
  • Loading branch information
jdum committed Nov 25, 2023
1 parent 684b5f2 commit 14e82f0
Show file tree
Hide file tree
Showing 13 changed files with 2,330 additions and 1 deletion.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2023 Dumonteil
Copyright (c) 2018-2023 Jérôme Dumonteil

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
Empty file added grygry/__init__.py
Empty file.
39 changes: 39 additions & 0 deletions grygry/grycli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import json
from collections.abc import Callable
from importlib import resources as rso
from typing import Any

from .lib.grylib import Grygry


def read_parameters() -> dict[str, Any]:
path = rso.files("grygry.lib") / "parameters.json"
return json.loads(path.read_text(encoding="utf8"))


def gry_searcher(key: str) -> Callable:
def searcher():
parameters = read_parameters()
grygry = Grygry(parameters["_default_"] | parameters[key])
grygry.search()

return searcher


def functions_generator() -> None:
for key in read_parameters():
if key == "_default_":
continue
globals()[f"gry{key}"] = gry_searcher(key)


def _list_functions() -> None:
lines = []
for key in read_parameters():
if key.startswith("_"):
continue
lines.append(f'gry{key} = "grygry.grycli:gry{key}"')
print("\n".join(sorted(lines)))


functions_generator()
Empty file added grygry/lib/__init__.py
Empty file.
126 changes: 126 additions & 0 deletions grygry/lib/grylib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import contextlib
import sys
from pathlib import Path


class NoPatternError(ValueError):
pass


class Grygry:
def __init__(self, config: dict):
self.show_unicode_error = config.get("show_unicode_error", False)
self.sort_files = config.get("sort_files", False)
self.context_lines = config.get("context_lines", 0)
self.with_suffix = set(config.get("with_suffix", []))
self.no_suffix = set(config.get("no_suffix", []))
self.no_start_dir = config.get("no_start_dir", ["."])
self.no_start_file = config.get("no_start_file", [".", "~"])
self.pattern = ""
self.path = Path()
self.found = {}

def search(self) -> None:
if len(sys.argv) < 2:
raise NoPatternError
self.pattern = " ".join(sys.argv[1:])
self.grep_pattern()

def grep_pattern(self) -> None:
if not self.pattern:
raise NoPatternError
self.grep_folder(Path.cwd())

def grep_folder(self, path: Path) -> None:
self.path = path
for no_start in self.no_start_dir:
if self.path.name.startswith(no_start):
return
sub_dirs = []
files = []
for path in self.path.glob("*"):
self._list_files(path, files, sub_dirs)
if self.sort_files:
self._sorted_show_found_words(files)
for path in sorted(sub_dirs):
self.grep_folder(path)
else:
self._show_found_words(files)
for path in sub_dirs:
self.grep_folder(path)

def _list_files(self, path: Path, files: list, sub_dirs: list) -> None:
if path.is_dir():
sub_dirs.append(path)
return
if (self.with_suffix and path.suffix not in self.with_suffix) or (
self.no_suffix and path.suffix in self.no_suffix
):
return
for no_start in self.no_start_file:
if path.name.startswith(no_start):
return
files.append(path)

def _show_found_words(self, files: list) -> None:
for path in files:
self.show_find_word(path)

def _sorted_show_found_words(self, files: list) -> None:
for path in sorted(files):
self.show_find_word(path)

def show_find_word(self, path: Path) -> None:
self.find_word(path)
if not self.found:
return
self.show_found(path)

def show_found(self, path: Path) -> None:
print(path)
sorted_dict = dict(sorted(self.found.items()))
if self.context_lines:
self._show_found_context(sorted_dict)
else:
self._show_found_no_context(sorted_dict)
print()

def _show_found_context(self, sorted_dict: dict[int, str]) -> None:
previous = 0
for idx, line in sorted_dict.items():
if previous and idx > previous + 1:
print()
previous = idx
print(f" {idx:4d}: {line.rstrip()}")

def _show_found_no_context(self, sorted_dict: dict[int, str]) -> None:
for idx, line in sorted_dict.items():
print(f" {idx:4d}: {line.rstrip()}")

def find_word(self, path: Path) -> None:
# assuming reading the full file
self.found = {}
pattern = self.pattern
try:
with path.open() as file:
content = file.readlines()
for index, line in enumerate(content):
if pattern not in line:
continue
self.found[index + 1] = line
if not self.context_lines:
continue
for step in range(1, self.context_lines + 1):
with contextlib.suppress(IndexError):
self.found[index + 1 + step] = content[index + step]
with contextlib.suppress(IndexError):
self.found[index + 1 - step] = content[index - step]

except UnicodeDecodeError:
if self.show_unicode_error:
print("Unicode error for", path)
self.found = {}
except OSError as e:
print(e)
print(path)
self.found = {}
73 changes: 73 additions & 0 deletions grygry/lib/parameters.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{
"_default_": {
"show_unicode_error": false,
"sort_files": false,
"context_lines": 0,
"with_suffix": [],
"no_suffix": [
".png",
".jpg",
".bmp",
".ttf",
".svg",
".ico",
".lock",
".orig"
],
"no_start_dir": [".", "__pycache__"],
"no_start_file": [".", "~"]
},
"all": {},
"py": {
"with_suffix": [".py"],
"sort_files": true,
"context_lines": 1
},
"py2": {
"with_suffix": [".py"],
"sort_files": true,
"context_lines": 2
},
"py0": {
"with_suffix": [".py"],
"sort_files": true,
"context_lines": 0
},
"nopy": {
"no_suffix": [
".py",
".png",
".jpg",
".bmp",
".ttf",
".svg",
".ico",
".orig"
]
},
"md": { "with_suffix": [".md", ".MD"] },
"txt": { "with_suffix": [".txt", ".TXT"] },
"cfg": { "with_suffix": [".cfg", ".ini", ".INI", ".CFG"] },
"rb": { "with_suffix": [".rb"] },
"js": { "with_suffix": [".js", ".JS", ".ts", ".vue"] },
"css": { "with_suffix": [".css", ".CSS"] },
"json": { "with_suffix": [".json", ".JSON"] },
"toml": { "with_suffix": [".toml", ".TOML"] },
"html": { "with_suffix": [".html", ".htm", ".HTML", ".HTM"] },
"htmlall": {
"with_suffix": [
".html",
".htm",
".js",
".ts",
".vue",
".css",
".HTML",
".HTM",
".JS",
".CSS"
]
},
"yml": { "with_suffix": [".yml", ".yaml", ".YML", ".YAML"] },
"sh": { "with_suffix": [".sh"] }
}
Loading

0 comments on commit 14e82f0

Please sign in to comment.