Skip to content

Commit

Permalink
updated css_check
Browse files Browse the repository at this point in the history
  • Loading branch information
IITI-tushar committed Jan 15, 2025
1 parent a16908f commit 0681a9a
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 41 deletions.
98 changes: 59 additions & 39 deletions .github/workflows/css_check.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
"""Check TypeScript files for CSS violations and embedded CSS."""

import argparse
import os
import re
import sys
from collections import namedtuple

# Define namedtuples for storing results
Violation = namedtuple('Violation', ['file_path', 'css_file', 'reason'])
CorrectImport = namedtuple('CorrectImport', ['file_path', 'css_file'])
EmbeddedViolation = namedtuple('EmbeddedViolation', ['file_path', 'css_codes'])
CSSCheckResult = namedtuple('CSSCheckResult', ['violations', 'correct_imports', 'embedded_violations'])

def check_embedded_css(content: str) -> list:
"""
Expand All @@ -19,12 +24,11 @@ def check_embedded_css(content: str) -> list:
embedded_css_pattern = r"#([0-9a-fA-F]{3}){1,2}" # Matches CSS color codes
return re.findall(embedded_css_pattern, content)


def check_files(
directory: str, exclude_files: list, exclude_directories: list, allowed_css_patterns: list
) -> tuple:
) -> CSSCheckResult:
"""
Check TypeScript files for CSS violations and print correct CSS imports.
Check TypeScript files for CSS violations and correct CSS imports.
Args:
directory: The directory to check.
Expand All @@ -33,7 +37,7 @@ def check_files(
allowed_css_patterns: List of allowed CSS file patterns.
Returns:
A tuple containing lists of violations, correct CSS imports, and embedded CSS violations.
A CSSCheckResult namedtuple containing lists of violations, correct CSS imports, and embedded CSS violations.
"""
violations = []
correct_css_imports = []
Expand Down Expand Up @@ -65,29 +69,30 @@ def check_files(
continue

# Check for CSS imports with an improved regex pattern
css_imports = re.findall(
r'import\s+.*?["\'](.*?\.css)["\'];', content
)
css_imports = re.findall(r'import\s+.*?["\'](.+?\.css)["\']', content)
for css_file in css_imports:
# Try to find the CSS file
css_file_path = os.path.join(os.path.dirname(file_path), css_file)
if not os.path.exists(css_file_path):
# If not found, try to find it relative to the src directory
src_dir = os.path.abspath(directory)
css_file_path = os.path.join(src_dir, css_file)

# Check if the CSS file exists
if not os.path.exists(css_file_path):
violations.append(Violation(file_path, css_file, "File not found"))
# Check if the CSS import matches the allowed patterns
if any(css_file.endswith(pattern) for pattern in allowed_css_patterns):
correct_css_imports.append(
f"Correct CSS import ({css_file}) in {file_path}"
)
elif any(css_file.endswith(pattern) for pattern in allowed_css_patterns):
correct_css_imports.append(CorrectImport(file_path, css_file))
else:
violations.append(
f"Invalid CSS import ({css_file}) in {file_path}"
)
violations.append(Violation(file_path, css_file, "Invalid import"))

# Check for embedded CSS
embedded_css = check_embedded_css(content)
if embedded_css:
embedded_css_violations.append(
f"Embedded CSS found in {file_path}: {', '.join(embedded_css)}"
)

return violations, correct_css_imports, embedded_css_violations
embedded_css_violations.append(EmbeddedViolation(file_path, embedded_css))

return CSSCheckResult(violations, correct_css_imports, embedded_css_violations)

def main():
"""Run the CSS check script."""
Expand All @@ -113,35 +118,50 @@ def main():
default=["app.module.css"],
help="Allowed CSS file patterns.",
)
parser.add_argument(
"--show_success",
action="store_true",
help="Show successful CSS imports.",
)
args = parser.parse_args()

violations, correct_css_imports, embedded_css_violations = check_files(
result = check_files(
directory=args.directory,
exclude_files=args.exclude_files,
exclude_directories=args.exclude_directories,
allowed_css_patterns=args.allowed_css_patterns,
)

if violations:
print("\nCSS Import Violations:")
print("\n".join(violations))

if embedded_css_violations:
print("\nEmbedded CSS Violations:")
print("\n".join(embedded_css_violations))

if correct_css_imports:
output = []
exit_code = 0
if result.violations:
output.append("CSS Import Violations:")
for violation in result.violations:
output.append(f"- {violation.file_path}: {violation.css_file} ({violation.reason})")
exit_code = 1

if result.embedded_violations:
output.append("\nEmbedded CSS Violations:")
for violation in result.embedded_violations:
output.append(f"- {violation.file_path}: {', '.join(violation.css_codes)}")
exit_code = 1

if output:
print("\n".join(output))
print("""
Please address the above CSS violations:
1. For invalid CSS imports, ensure you're using the correct import syntax and file paths.
2. For embedded CSS, move the CSS to appropriate stylesheet files and import them correctly.
3. Make sure to use only the allowed CSS patterns as specified in the script arguments.
4. Check that all imported CSS files exist in the specified locations.
""")
if args.show_success and result.correct_imports:
print("\nCorrect CSS Imports:")
print("\n".join(correct_css_imports))
else:
print("\nNo correct CSS imports found.")

if violations or embedded_css_violations:
sys.exit(1) # Exit with error code if violations found
else:
print("\nNo CSS violations found.")
sys.exit(0) # Exit with success code
for import_ in result.correct_imports:
print(f"- {import_.file_path}: {import_.css_file}")

sys.exit(exit_code)

if __name__ == "__main__":
main()

15 changes: 14 additions & 1 deletion .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,29 @@ jobs:
- name: Check for CSS violations and print correct imports
if: steps.changed-ts-files.outputs.any_changed == 'true'
run: |
if [ -z "${{ steps.changed-ts-files.outputs.modified_files }}" ]; then
echo "No TypeScript files were modified"
exit 0
fi
echo "${{ steps.changed-ts-files.outputs.modified_files }}" | tr ' ' '\n' | while read -r file; do
if [ ! -f "$file" ]; then
echo "Error: File not found: $file"
exit 1
fi
done
if [ ! -f ./.github/workflows/css_check.py ]; then
echo "Error: CSS check script not found"
exit 1
fi
chmod +x ./.github/workflows/css_check.py
./.github/workflows/css_check.py --files ${{ steps.changed-ts-files.outputs.modified_files }} || {
./.github/workflows/css_check.py --directory ./src --allowed_css_patterns app.module.css . || {
echo "Error: CSS check failed"
exit 1
}
- name: Get changed TypeScript files
id: changed-files
uses: tj-actions/changed-files@v45
Expand Down
2 changes: 1 addition & 1 deletion src/components/AddOn/core/AddOnEntry/AddOnEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { toast } from 'react-toastify';
import { Navigate, useParams } from 'react-router-dom';

/**
* Props for the `addOnEntry` component.
* Props for the `addOnEntry` component..
*/
interface InterfaceAddOnEntryProps {
id: string;
Expand Down

0 comments on commit 0681a9a

Please sign in to comment.