Skip to content

Commit

Permalink
♻️ :spakles: pref: refactor counter.py
Browse files Browse the repository at this point in the history
  • Loading branch information
InnoFang committed Nov 8, 2023
1 parent 3f79bbb commit 6e89820
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 20 deletions.
2 changes: 1 addition & 1 deletion code_counter/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def main():
else:
raise Exception('wrong command')

code_counter.setArgs(args)
code_counter.set_args(args)

time_start = time.time()
code_counter.search()
Expand Down
68 changes: 49 additions & 19 deletions code_counter/core/counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,38 @@
# -*- coding: utf-8 -*-

import os
import argparse
import asyncio
from collections import defaultdict
from typing import List, Optional, Dict

from code_counter.conf.config import Config
from code_counter.core.visualization import GraphVisualization
from code_counter.core.countable.file import CountableFile
from code_counter.core.countable.iterators import LocalFileIterator, RemoteFileIterator
from code_counter.tools.progress import SearchingProgressBar


class CodeCounter:
def __init__(self):
self.config = Config()
self.config: Config = Config()

self.total_file_lines = 0
self.total_code_lines = 0
self.total_blank_lines = 0
self.total_comment_lines = 0
self.files_of_language = defaultdict(int)
self.lines_of_language = defaultdict(int)
self.files_of_language: Dict[str, int] = defaultdict(int)
self.lines_of_language: Dict[str, int] = defaultdict(int)

self.args: Optional = None

self.args = None
def set_args(self, args: argparse.Namespace) -> None:
"""
Set command line arguments to configure the code counter.
def setArgs(self, args):
Args:
args: Parsed command line arguments.
"""
self.args = args
if args.suffix:
self.config.suffix = set(args.suffix)
Expand All @@ -32,16 +42,19 @@ def setArgs(self, args):
if args.ignore:
self.config.ignore = set(args.ignore)

def search(self):
def search(self) -> None:
"""
Search for code files in the specified input path and perform code counting.
"""
if self.args is None:
raise Exception('search_args is None, please invoke the `setArgs` function first.')

input_path = self.args.input_path
input_path: str = self.args.input_path
if not input_path:
print('{} is not a validate path.'.format(input_path))
return

output_path = self.args.output_path
output_path: str = self.args.output_path
output_file = open(output_path, 'w') if output_path else None

if self.args.verbose:
Expand All @@ -56,8 +69,15 @@ def search(self):
if output_file:
output_file.close()

async def __search(self, input_path, output_file):
tasks = []
async def __search(self, input_path: str, output_file: Optional) -> None:
"""
Asynchronously search for code files in the specified input path and perform code counting.
Args:
input_path: Input path where code files are searched.
output_file: Optional output file to write verbose results.
"""
tasks: List[asyncio.Task] = []
if isinstance(input_path, list):
for path in input_path:
if os.path.exists(path):
Expand All @@ -68,7 +88,14 @@ async def __search(self, input_path, output_file):
tasks.append(asyncio.create_task(self.__resolve_counting_file(cf, output_file)))
await asyncio.gather(*tasks)

async def __resolve_counting_file(self, cf, output_file=None):
async def __resolve_counting_file(self, cf: CountableFile, output_file: Optional[str] = None) -> None:
"""
Asynchronously resolve and count a code file.
Args:
cf: CountableFile object.
output_file: Optional output file to write verbose results.
"""
await cf.count()
if self.args.verbose:
print(cf, file=output_file)
Expand All @@ -79,16 +106,16 @@ async def __resolve_counting_file(self, cf, output_file=None):
self.total_comment_lines += cf.comment_lines
self.lines_of_language[cf.file_type] += cf.code_lines

def __print_searching_verbose_title(self, output_file=None):
print('\n\t{}'.format("SEARCHING"), file=output_file)
print("\t{}".format('=' * 20), file=output_file)
def __print_searching_verbose_title(self, output_file: Optional[str] = None):
print('\n\tSEARCHING', file=output_file)
print("\t" + ("=" * 20), file=output_file)
print('\t{:>10} |{:>10} |{:>10} |{:>10} |{:>10} | {}'
.format("File Type", "Lines", "Code", "Blank", "Comment", "File Path"), file=output_file)
print("\t{}".format('-' * 90), file=output_file)
print("\t" + ("-" * 90), file=output_file)

def __print_result_info(self, output_file=None):
print('\n\t{}'.format("RESULT"), file=output_file)
print("\t{}".format('=' * 20), file=output_file)
def __print_result_info(self, output_file: Optional[str] = None):
print('\n\tRESULT', file=output_file)
print("\t" + ("=" * 20), file=output_file)
print("\t{:<20}:{:>8} ({:>7})"
.format("Total file lines", self.total_file_lines, '100.00%'), file=output_file)

Expand Down Expand Up @@ -125,7 +152,10 @@ def __print_result_info(self, output_file=None):
tp, file_count, '%.2f%%' % (file_count / total_files * 100),
code_count, '%.2f%%' % (code_count / self.total_code_lines * 100)), file=output_file)

def visualize(self):
def visualize(self) -> None:
"""
Visualize the code counting results and display graphical information.
"""
gv = GraphVisualization(
total_code_lines=self.total_code_lines,
total_blank_lines=self.total_blank_lines,
Expand Down

0 comments on commit 6e89820

Please sign in to comment.