Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add new feature to auto copy function protoype from c file from spec… #14

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions alxcheck/checks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
from .general import *
from .python import *
from .javascript import *
from .autoprototype import *
81 changes: 81 additions & 0 deletions alxcheck/checks/autoprototype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import argparse
import subprocess
import os
import re
from ..utils.error_logging import print_check_betty_first, print_dir_header_error
def check_ctags():
try:
subprocess.run(['ctags', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
return True, None
except subprocess.CalledProcessError:
msg = "ctags is not installed. Please install ctags before running this script."
return False, msg

def generate_tags(directory):
try:
subprocess.run(['ctags', '-R', '--c-kinds=+p', '--fields=+S', '--extra=+q', '--languages=c', f'--langmap=c:.c', directory], check=True)
return True
except subprocess.CalledProcessError as e:
print_dir_header_error(f"Error generating ctags: {e}")
return False
def filter_tags(directory,tags_file):
temp_tags_path = os.path.join(directory,'temp_tags')
tags_path = os.path.join(directory,tags_file)

sed_command = r"cat {0} | sed -n 's/^.*\/^\(.*\)/\1/p' | sed 's/\(.*\)\$.*/\1/' | sed 's/;$//' | uniq | sed '/int main(/d' | sed '/.*:/d' | sed 's/$/;/g' > {1}".format(tags_path, temp_tags_path)

# Run the sed_command using subprocess
subprocess.run(sed_command, shell=True, check=True)

# Check if the file exists before trying to open it
if os.path.exists(temp_tags_path):
with open(temp_tags_path, 'r') as temp_tags_file:
filtered_tags = temp_tags_file.read()
return filtered_tags
else:
# Handle the case where the file doesn't exist
msg =f"Error: File {temp_tags_path} does not exist."
print_dir_header_error(msg)
return None

def create_header(header_file, filtered_tags):
header_name = header_file.split('/')[-1]
header_name =header_name.split('.')
header_name= '_'.join(header_name)
with open(header_file, 'w') as header:
header.write(f'#ifndef {header_name.upper()}\n')
header.write(f'#define {header_name.upper()}\n\n')
header.write(filtered_tags)
header.write('\n#endif\n')
def delete_files(tags, temp_tags):
command = "rm {0} {1}".format(tags, temp_tags)
subprocess.run(command, shell=True, check=True)
def check_directory(directory):
if not os.path.exists(directory):
msg = f"Error: Directory '{directory}' does not exist."
return False , msg
return True, None

def check_header_file(header_file):
if not header_file.endswith('.h'):

msg = "Error: Invalid header file. It should have a '.h' extension."
return False , msg
return True, None
def autoproto(directory, header):
check0, msg0=check_directory(directory)
check1, msg1=check_header_file(header)
check2, msg2=check_ctags()
if (not check0):
print_dir_header_error(msg0)
elif (not check1):
print_dir_header_error(msg1)

elif (not check2):
print_dir_header_error(msg2)

if generate_tags(directory) != False:
filtered_tags = filter_tags(directory, 'tags')
if filtered_tags != None:
create_header(header, filtered_tags)
delete_files('tags', 'temp_tags')
11 changes: 10 additions & 1 deletion alxcheck/checks/c.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import subprocess
from ..utils.error_logging import print_please_install_betty


def betty_check(file_path):
try:
result = subprocess.run(["betty", file_path])
except Exception:
print_please_install_betty()
return False
# because it have different ouput meaning looking for errors
try:
result1 = subprocess.run(["betty", file_path], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
except subprocess.CalledProcessError as e:
return False

if "ERROR:" in result1.stdout or "ERROR:" in result1.stderr:
return False

return result.returncode == 0

100 changes: 52 additions & 48 deletions alxcheck/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,59 +3,63 @@
from .utils.helpers import *
from .utils.error_logging import *


def main():
try:
if not check_file_present("README.md"):
print_file_not_present("README.md")
sys.exit(1)
if not check_file_not_empty("README.md"):
print_file_empty("README.md")
for root, dirs, files in os.walk("."):
# exclude virtual environment folders
for dir in dirs:
if is_python_virtual_env_folder(dir):
dirs.remove(dir)
break
# exclude .git folder
if ".git" in dirs:
dirs.remove(".git")
for file in files:
file_path = os.path.join(root, file)
if file_path.endswith(
(".c", ".py", ".js", ".m", ".h", ".mjs", ".jsx", ".json")

if not check_file_present("README.md"):
print_file_not_present("README.md")
sys.exit(1)
if not check_file_not_empty("README.md"):
print_file_empty("README.md")
for root, dirs, files in os.walk("."):
# exclude virtual environment folders
for dir in dirs:
if is_python_virtual_env_folder(dir):
dirs.remove(dir)
break
# exclude .git folder
if ".git" in dirs:
dirs.remove(".git")
for file in files:
file_path = os.path.join(root, file)
if file_path.endswith(
(".c", ".py", ".js", ".m", ".h", ".mjs", ".jsx", ".json")
):
if not check_file_ends_with_new_line(file_path):
if not is_empty_init_py(file_path):
print_no_ending_new_line(file_path)
# c and c header files
if file.endswith((".c", ".h")):
v=betty_check(file_path)
if "-D" in sys.argv and "-H" in sys.argv:
if (v == False):
print_check_betty_first()
else:
directory = sys.argv[sys.argv.index("-D") + 1]
header = sys.argv[sys.argv.index("-H") + 1]
autoproto(directory, header)
elif ("-D" in sys.argv or "-H" in sys.argv):
print_dir_header_error("Usage: -D/-H Together");
# python checks
if file_path.endswith(".py") and not is_empty_init_py(file_path):
if not check_file_is_executable(file_path):
print_file_not_executable(file_path)
if not is_empty_init_py(file_path) and not check_python_shebang(
file_path
):
if not check_file_ends_with_new_line(file_path):
if not is_empty_init_py(file_path):
print_no_ending_new_line(file_path)
# c and c header files
if file.endswith((".c", ".h")):
betty_check(file_path)
# python checks
if file_path.endswith(".py") and not is_empty_init_py(file_path):
print_no_shebang(file_path)
check_module_function_class_documentation(file_path)
pycodestyle_check(file_path)
# javascript checks
if file.endswith(".js"):
if is_nodejs_project():
if not check_file_is_executable(file_path):
print_file_not_executable(file_path)
if not is_empty_init_py(file_path) and not check_python_shebang(
file_path
):
if not check_javascript_shebang(file_path):
print_no_shebang(file_path)
check_module_function_class_documentation(file_path)
pycodestyle_check(file_path)
# javascript checks
if file.endswith(".js"):
if is_nodejs_project():
if not check_file_is_executable(file_path):
print_file_not_executable(file_path)
if not check_javascript_shebang(file_path):
print_no_shebang(file_path)
if not check_no_var(file_path):
print_var_was_used(file_path)
semistandard_check(file_path)
except Exception as e:
print_uncaught_exception()
sys.stderr = open("./error.txt", "w")
raise
if not check_no_var(file_path):
print_var_was_used(file_path)
semistandard_check(file_path)


if __name__ == "__main__":
main()
main()
96 changes: 96 additions & 0 deletions alxcheck/tests/test_autoprototype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import unittest
from unittest.mock import patch
import os, shutil
import subprocess
from alxcheck.checks.autoprototype import (
check_ctags,
generate_tags,
filter_tags,
create_header,
delete_files,
check_directory,
check_header_file,
)
class TestYourFunctions(unittest.TestCase):

def setUp(self):
# Create a temporary directory for testing
self.test_dir = 'test_directory_1'
if not os.path.exists(self.test_dir):
os.makedirs(self.test_dir)

def tearDown(self):
try:
if os.path.exists(self.test_dir):
shutil.rmtree(self.test_dir)
except Exception as e:
print(f"Error during cleanup: {e}")

def test_check_ctags(self):
# Mock the subprocess.run to simulate a successful run
with patch('subprocess.run') as mock_run:
mock_run.return_value.returncode = 0

self.assertTrue(check_ctags())

# Mock the subprocess.run to simulate a failed run
with patch('subprocess.run') as mock_run:
mock_run.side_effect = subprocess.CalledProcessError(returncode=1, cmd='')
self.assertFalse(check_ctags())

def test_generate_tags(self):
# Mock the subprocess.run to simulate a successful run
with patch('subprocess.run') as mock_run:
mock_run.return_value.returncode = 0
generate_tags(self.test_dir)
mock_run.assert_called_once_with(['ctags', '-R', '--c-kinds=+p', '--fields=+S', '--extra=+q', self.test_dir], check=True)
def test_create_header(self):
# Test the create_header function

# Create a sample filtered_tags content
filtered_tags_content = "int func1();\nchar *func2();\n"

# Define the header file path
header_file_path = os.path.join(self.test_dir, 'test_header.h')

# Call the create_header function
create_header(header_file_path, filtered_tags_content)

# Assert that the header file is created with the expected content
expected_content = (
'#ifndef TEST_HEADER_H\n'
'#define TEST_HEADER_H\n\n'
'int func1();\n'
'char *func2();\n\n'
'#endif\n'
)

with open(header_file_path, 'r') as header_file:
actual_content = header_file.read()

self.assertEqual(expected_content, actual_content)

def test_check_directory(self):
# Test when the directory exists
self.assertTrue(check_directory(self.test_dir))


# Test when the directory does not exist
with patch('builtins.print') as mock_print:
self.assertFalse(check_directory('/path/to/nonexistent/directory'))
mock_print.assert_called_with("Error: Directory '/path/to/nonexistent/directory' does not exist.")

def test_check_header_file(self):
# Test a valid header file
self.assertTrue(check_header_file('valid_header.h'))

# Test an invalid header file
with patch('builtins.print') as mock_print:
self.assertFalse(check_header_file('invalid_header.txt'))
mock_print.assert_called_with("Error: Invalid header file. It should have a '.h' extension.")


# Additional test cases for different scenarios can be added as needed...

if __name__ == '__main__':
unittest.main()
7 changes: 7 additions & 0 deletions alxcheck/utils/error_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,10 @@ def print_uncaught_exception():
+ "Uncaught Exception: Please raise an issue here with the contents of './error.txt'\n\thttps://github.com/Emmo00/alxcheck/issues"
+ Fore.RESET
)
## auto checks errors
def print_check_betty_first():
print(Fore.YELLOW + "+++++++++++++++++++++++++++++++++++++++++++++++" + Fore.RESET)
print(Fore.RED + "You should check betty first before using -D/-H" + Fore.RESET)
def print_dir_header_error(msg):
print(Fore.YELLOW + "+++++++++++++++++++++++++++++++++++++++++++++++" + Fore.RESET)
print(Fore.RED + msg + Fore.RESET)
Loading