Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
furkanonder committed Sep 16, 2021
0 parents commit 4176e5d
Show file tree
Hide file tree
Showing 11 changed files with 505 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on: [push]

jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [3.6, 3.7, 3.8, 3.9]
steps:
- uses: actions/[email protected]

- name: Set up Python${{ matrix.python-version }}
uses: actions/[email protected]
with:
python-version: ${{ matrix.python-version }}
architecture: x64

- name: Test with unittest
run: |
python -m unittest discover
137 changes: 137 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
*.pyc
*.db
*.scssc
*.map
media

# Created by https://www.gitignore.io/api/python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

### Python Patch ###
.venv/

### Python.VirtualEnv Stack ###
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
pip-selfcheck.json


# End of https://www.gitignore.io/api/python
31 changes: 31 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
repos:

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files

- repo: https://github.com/psf/black
rev: 21.7b0
hooks:
- id: black

- repo: https://github.com/PyCQA/isort
rev: 5.9.2
hooks:
- id: isort

- repo: https://github.com/hakancelik96/unimport
rev: 0.8.4
hooks:
- id: unimport
args: [--remove, --include-star-import]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910
hooks:
- id: mypy
args: [--no-strict-optional, --ignore-missing-imports]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Furkan Taha ÖNDER

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
## Bor
User-friendly, tiny source code searcher written by pure Python.

## Example Usages

Cat is equivalent in the regular expression as '^Cat$'
```
bor class Cat
```
Output:
```
Cat at /home/arf/bor/examples/test.py : 18
```

***

.Cat is equivalent in the regular expression as 'Cat$'
```
bor class .Cat
```
Output:
```
Cat at /home/arf/bor/examples/test.py : 18
BlueCat at /home/arf/bor/examples/test.py : 26
```

***

get. is equivalent in the regular expression as '^get'
```
bor def get. examples/test.py
```
Output:
```
get_value at /home/arf/bor/examples/test.py : 5
get_blue_value at /home/arf/bor/examples/test.py : 11
get_purple_value at /home/arf/bor/examples/test.py : 14
get_meow at /home/arf/bor/examples/test.py : 22
```

***

.cat. is equivalent in the regular expression as 'cat+'
```
bor def .cat.
```
Output:
```
catch_me_if_you_can at /home/arf/bor/example/test.py : 8
am_i_blue_cat at /home/arf/bor/example/test.py : 30
where_is_the_cat at /home/arf/bor/example/test.py : 38
```
87 changes: 87 additions & 0 deletions bor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import argparse
import ast
import re
import sys
from contextlib import suppress
from pathlib import Path

var_types = {"def": ast.FunctionDef, "class": ast.ClassDef}


def analyzer(data, pattern):
nodes = data.get("nodes")
if nodes == {}:
return

path = data.get("path")
pattern = pattern.replace(".", "*")

if pattern.startswith("*") and pattern.endswith("*"):
regex = pattern.split("*")[1] + "+"
elif not pattern.startswith("*") and pattern.endswith("*"):
regex = "^" + pattern.split("*")[0]
elif pattern.startswith("*") and not pattern.endswith("*"):
regex = pattern.split("*")[1] + "$"
else:
regex = "^" + pattern + "$"

for key, value in nodes.items():
if re.search(regex, key):
print(key, "at", path, ":", value)


def searcher(source, file, var_type):
data = {"path": file.resolve().as_posix(), "nodes": {}}
node_type = var_types.get(var_type)

for node in ast.walk(source):
if isinstance(node, node_type):
node_data = {node.name: str(node.lineno)}
nodes = data.get("nodes")
if nodes.get(node.name):
old_key = nodes.get(node.name)
node_data = {node.name: str(node.lineno) + "," + old_key}
nodes.update(node_data)

return data


def file_parser(file):
try:
file = file.resolve().as_posix()
with open(file) as f:
source = ast.parse(f.read())
return source
except Exception as error:
print(error, " at " + file)
sys.exit(1)


def get_paths(path):
if path.is_dir():
return path.glob("**/*.py")
return [path]


def main(argv=None):
parser = argparse.ArgumentParser(
description="User friendly, tiny source code searcher written by pure Python."
)
parser.add_argument("-v", "--version", action="version", version="0.0.1")
_, args = parser.parse_known_args()

if len(args) < 2 or args[0] not in var_types:
print("Please, check your inputs.")
sys.exit(1)

var_type, pattern = args[0], args[1]
path = args[2] if len(args) > 2 else "."

for file in get_paths(Path(path)):
source = file_parser(file)
with suppress(KeyboardInterrupt):
analyzer(searcher(source, file, var_type), pattern)


if __name__ == "__main__":
main()
39 changes: 39 additions & 0 deletions examples/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Blue:
def __init__(self):
self.test = "test"

def get_value(self):
return 1

def catch_me_if_you_can(self):
return 0

def get_blue_value(self):
return "blue"

def get_purple_value(self):
return "purple"


class Cat:
def __init__(self):
self.test = "test"

def get_meow(self):
return "meow"


class BlueCat:
def __init__(self):
self.test = "test"

def am_i_blue_cat(self):
return "yes"


class BlueCatInZoo:
def __init__(self):
self.test = "test"

def where_is_the_cat(self):
return "?"
Loading

0 comments on commit 4176e5d

Please sign in to comment.