<commit_before>#!/usr/bin/python3

"""
Black-Arrow file keyword searcher
"""

import argparse
import sys
import os
import re
import multiprocessing as mp
import time
import subprocess
from typing import Optional
import fabulous.color as color


RETYPE = type(re.compile('a'))  # since re module apparently doesn't have good compiled types
EDITOR = os.environ.get('EDITOR', 'vim')  # Default editor


def main():
    args = get_args()
    print_process, final_queue = start_search(args)
    print_process.join()    # Wait main thread until printer is done


def start_search(args:argparse.Namespace):
    """
    This function is separated out in order to use code as module
    """
    start_time = time.time()

    # compile for performance reasons
    try:
        ignore_re = re.compile('a^')
        if args.ignore:
            ignore_re = re.compile('|'.join(args.ignore))
        filename_re = re.compile('.*')
        if args.filename:
            filename_re = re.compile('|'.join(args.filename))
        search_re = re.compile(args.regex)
    except re.error as e:
        print(color.red('Error, bad regular expression:'))
        raise
    input = mp.Queue()
    output = mp.Queue()
    final_queue = mp.Queue()  # Use final queue for external output

    indexer = mp.Process(name='indexer',
                         target=index_worker,
                         args=(args.directories,
                               ignore_re,
                               args.workers,
                               input, output))
    indexer.start()

    for i in range(args.workers):
        worker = mp.Process(name='worker-{}'.format(i + 1),
                            target=file_searching_worker,
                            args=(search_re, ignore_re, filename_re,
                                  input, output))
        worker.start()
    printer = mp.Process(name='printer',
                         target=print_worker,
                         args=(start_time, args.workers,
                               output, final_queue, args.pipe, args.edit))
    printer.start()
    return printer, final_queue


def index_worker(directories: str, ignore_re: RETYPE, workers: int, input: mp.Queue, output: mp.Queue) -> None:
    for dir in list(set(directories)):  # no duplicates
        for subdir, _, files in os.walk(dir):
            for question_file in files:
                # we don't want to block, this process should be fastest
                input.put(subdir + '/' + question_file, block=False, timeout=10)  # faster than os.path.join
    for i in range(workers):
        input.put('EXIT')  # poison pill workers


def file_searching_worker(regex: RETYPE, ignore_re: RETYPE, filename_re: RETYPE, input: mp.Queue, output: mp.Queue) -> None:
    line_count = 0
    file_count = 0
    found_count = 0
    # https://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
    rows, columns = os.popen('stty size', 'r').read().split()
    # Max width of printed line is 3/4 column count
    maxwidth = int(3 * int(columns) / 4)
    while True:
        # we want to block this thread until we get input
        name = input.get()
        if name == 'EXIT':
            output.put(('EXIT', line_count, file_count, found_count))
            break
        if ignore_re.search(name) is None and filename_re.search(name) is not None:
            file_count += 1
            try:
                with open(name, 'r') as ofile:
                    flag = []<commit_msg>#1 -> fixed using process.terminate()<commit_after>#!/usr/bin/env python3

"""
Black-Arrow file keyword searcher
"""

import argparse
import sys
import os
import re
import multiprocessing as mp
import time
import subprocess
from typing import Optional
import fabulous.color as color


RETYPE = type(re.compile('a'))  # since re module apparently doesn't have good compiled types
EDITOR = os.environ.get('EDITOR', 'nvim')  # Default editor


def main():
    args = get_args()
    processes, final_queue = start_search(args)
    print_process = processes[-1]
    try:
        print_process.join()    # Wait main thread until printer is done
    except (KeyboardInterrupt, EOFError):
        [p.terminate() for p in processes]



def start_search(args:argparse.Namespace):
    """
    This function is separated out in order to use code as module
    """
    start_time = time.time()

    # compile for performance reasons
    try:
        ignore_re = re.compile('a^')
        if args.ignore:
            ignore_re = re.compile('|'.join(args.ignore))
        filename_re = re.compile('.*')
        if args.filename:
            filename_re = re.compile('|'.join(args.filename))
        search_re = re.compile(args.regex)
    except re.error as e:
        print(color.red('Error, bad regular expression:'))
        raise
    input = mp.Queue()
    output = mp.Queue()
    final_queue = mp.Queue()  # Use final queue for external output
    processes = []

    indexer = mp.Process(name='indexer',
                         target=index_worker,
                         args=(args.directories,
                               ignore_re,
                               args.workers,
                               input, output))
    indexer.start()
    processes.append(indexer)

    for i in range(args.workers):
        worker = mp.Process(name='worker-{}'.format(i + 1),
                            target=file_searching_worker,
                            args=(search_re, ignore_re, filename_re,
                                  input, output))
        worker.start()
        processes.append(worker)
    printer = mp.Process(name='printer',
                         target=print_worker,
                         args=(start_time, args.workers,
                               output, final_queue, args.pipe, args.edit))
    printer.start()
    processes.append(printer)

    return processes, final_queue


def index_worker(directories: str, ignore_re: RETYPE, workers: int, input: mp.Queue, output: mp.Queue) -> None:
    for dir in list(set(directories)):  # no duplicates
        for subdir, _, files in os.walk(dir):
            for question_file in files:
                # we don't want to block, this process should be fastest
                input.put(subdir + '/' + question_file, block=False, timeout=10)  # faster than os.path.join
    for i in range(workers):
        input.put('EXIT')  # poison pill workers


def file_searching_worker(regex: RETYPE, ignore_re: RETYPE, filename_re: RETYPE, input: mp.Queue, output: mp.Queue) -> None:
    line_count = 0
    file_count = 0
    found_count = 0
    # https://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
    rows, columns = os.popen('stty size', 'r').read().split()
    # Max width of printed line is 3/4 column count
    maxwidth = int(3 * int(columns) / 4)
    while True:
        # we want to block this thread until we get input
        name = input.get()
        if name == 'EXIT':
            output.put(('EXIT', line_count, file_count, found_count))
            break
        if ignore_re.search(name) is None and filename_re.search(name) is not None:
            file_count += 1
            try:
                with open(name, 'r') as ofile:
                    flag = []
{'fraction_non_alphanumeric': 0.10645028194196121, 'fraction_numerical': 0.00522624123229267, 'mean_word_length': 2.1010660980810236, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 8, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3779363', 'n_tokens_mistral': 2097, 'n_tokens_neox': 2045, 'n_words': 581}