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

feat: added Check for embedded CSS and the correct stylesheet in Typescript files #3261

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
147 changes: 147 additions & 0 deletions .github/workflows/css_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""Check TypeScript files for CSS violations and embedded CSS."""

Check warning on line 1 in .github/workflows/css_check.py

View workflow job for this annotation

GitHub Actions / Performs linting, formatting, type-checking, checking for different source and target branch

File ignored by default.

import argparse
import os
import re
import sys


def check_embedded_css(content: str) -> list:
"""
Check for embedded CSS in the content.

Args:
content: The content of the file to check.

Returns:
A list of embedded CSS violations found.
"""
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:
"""
Check TypeScript files for CSS violations and print correct CSS imports.

Args:
directory: The directory to check.
exclude_files: List of files to exclude from analysis.
exclude_directories: List of directories to exclude from analysis.
allowed_css_patterns: List of allowed CSS file patterns.

Returns:
A tuple containing lists of violations, correct CSS imports, and embedded CSS violations.
"""
violations = []
correct_css_imports = []
embedded_css_violations = []

# Normalize exclude paths
exclude_files = set(os.path.abspath(file) for file in exclude_files)
exclude_directories = set(os.path.abspath(dir) for dir in exclude_directories)

for root, _, files in os.walk(directory):
# Skip excluded directories
if any(root.startswith(exclude_dir) for exclude_dir in exclude_directories):
continue

for file in files:
file_path = os.path.abspath(os.path.join(root, file))

# Skip excluded files
if file_path in exclude_files:
continue

# Process TypeScript files
if file.endswith((".ts", ".tsx")) and "test" not in root:
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
except (IOError, UnicodeDecodeError) as e:
print(f"Error reading file {file_path}: {e}")
continue

# Check for CSS imports with an improved regex pattern
css_imports = re.findall(
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
r'import\s+.*?["\'](.*?\.css)["\'];', content
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
)
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
for css_file in css_imports:
# 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}"
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
)
else:
violations.append(
f"Invalid CSS import ({css_file}) in {file_path}"
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
)

# 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)}"
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
)

return violations, correct_css_imports, embedded_css_violations
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved


def main():
"""Run the CSS check script."""
parser = argparse.ArgumentParser(
description="Check for CSS violations in TypeScript files."
)
parser.add_argument("--directory", required=True, help="Directory to check.")
parser.add_argument(
"--exclude_files",
nargs="*",
default=[],
help="Specific files to exclude from analysis.",
)
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
parser.add_argument(
"--exclude_directories",
nargs="*",
default=[],
help="Directories to exclude from analysis.",
)
parser.add_argument(
"--allowed_css_patterns",
nargs="*",
default=["app.module.css"],
help="Allowed CSS file patterns.",
)
args = parser.parse_args()

violations, correct_css_imports, embedded_css_violations = 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:")
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
print("\n".join(violations))

if embedded_css_violations:
print("\nEmbedded CSS Violations:")
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
print("\n".join(embedded_css_violations))

if correct_css_imports:
print("\nCorrect CSS Imports:")
print("\n".join(correct_css_imports))
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
else:
print("\nNo correct CSS imports found.")
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved

if violations or embedded_css_violations:
sys.exit(1) # Exit with error code if violations found
else:
print("\nNo CSS violations found.")
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
sys.exit(0) # Exit with success code


if __name__ == "__main__":
main()
23 changes: 23 additions & 0 deletions .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
##############################################################################

Check warning on line 1 in .github/workflows/pull-request.yml

View workflow job for this annotation

GitHub Actions / Performs linting, formatting, type-checking, checking for different source and target branch

File ignored by default.
##############################################################################
#
# NOTE!
Expand Down Expand Up @@ -40,6 +40,29 @@
chmod +x ./.github/workflows/scripts/countline.py
./.github/workflows/scripts/countline.py --lines 600 --exclude_files src/screens/LoginPage/LoginPage.tsx src/GraphQl/Queries/Queries.ts src/screens/OrgList/OrgList.tsx src/GraphQl/Mutations/mutations.ts src/components/EventListCard/EventListCardModals.tsx src/components/TagActions/TagActionsMocks.ts src/utils/interfaces.ts src/screens/MemberDetail/MemberDetail.tsx

# Get Changed .ts and .tsx Files
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
- name: Get changed TypeScript files
id: changed-ts-files
uses: tj-actions/changed-files@v45
with:
files: |
**/*.ts
**/*.tsx

# Run the CSS import check script on changed .ts and .tsx files
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved
- name: Check for CSS violations and print correct imports
if: steps.changed-ts-files.outputs.any_changed == 'true'
run: |
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 }} || {
echo "Error: CSS check failed"
exit 1
}
IITI-tushar marked this conversation as resolved.
Show resolved Hide resolved

- name: Get changed TypeScript files
id: changed-files
uses: tj-actions/changed-files@v45
Expand Down
Loading