Slight adjustment to above script so that all files in project directory are found. Note: requires hard-coding the directory that holds project directories. Standard Pythonista projects sit in the Documents directory. Working Copy projects sit in a directory called Repositories. Etc. Etc.
import console
import editor
import os
import pathlib
import ui
# "parent" directories that contain project roots
ROOTS = ['Documents', 'Repositories']
def get_project_root(path):
'''Determines the root of the project, returns PosixPath()
'''
if path.parent.name in ROOTS:
return path
else:
return get_project_root(path.parent)
def find_files(path):
'''Recurses through project tree, returns PosixPath() list of all files
'''
file_paths = []
for item in os.listdir(path):
item_path = pathlib.Path(os.path.join(path, item))
if item_path.is_file():
file_paths.append(item_path)
elif item_path.is_dir() and '.git' not in item_path.name:
file_paths.extend(find_files(item_path))
return file_paths
def main():
t = console.input_alert('text to search',hide_cancel_button=True)
if t == '':
return
t = t.lower()
path = pathlib.Path(editor.get_path())
project_root = get_project_root(path)
files_list = find_files(project_root)
for file in files_list:
if os.path.splitext(file)[-1].lower() in (".py", ".txt"):
with open(os.path.join(path, file), mode='rt', encoding='utf-8') as fil:
content = fil.read().lower()
lines = content.split('\n')
first = True
for i, line in enumerate(lines, 1):
if line.find(t) >= 0:
if first:
first = False
print(
'\n%%%Found in ' +
file.as_posix().split(
project_root.parent.as_posix() + '/'
)[-1] +':'
)
print('l.'+str(i)+':',line.strip())
if __name__ == '__main__':
main()