From a16908fc1731fc4401b5504ce20d77fc355018d7 Mon Sep 17 00:00:00 2001 From: IITI-tushar <019saxenatushar@gmail.com> Date: Sun, 12 Jan 2025 16:36:58 +0530 Subject: [PATCH 01/23] update --- .github/workflows/css_check.py | 147 +++++++++++++++++++++++++++++ .github/workflows/pull-request.yml | 23 +++++ 2 files changed, 170 insertions(+) create mode 100644 .github/workflows/css_check.py diff --git a/.github/workflows/css_check.py b/.github/workflows/css_check.py new file mode 100644 index 0000000000..81f9f9c658 --- /dev/null +++ b/.github/workflows/css_check.py @@ -0,0 +1,147 @@ +"""Check TypeScript files for CSS violations and embedded CSS.""" + +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( + r'import\s+.*?["\'](.*?\.css)["\'];', content + ) + 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}" + ) + else: + violations.append( + f"Invalid CSS import ({css_file}) in {file_path}" + ) + + # 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 + + +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.", + ) + 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:") + print("\n".join(violations)) + + if embedded_css_violations: + print("\nEmbedded CSS Violations:") + print("\n".join(embedded_css_violations)) + + if correct_css_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 + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index f387698bce..6caf41e09a 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -40,6 +40,29 @@ jobs: 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 + - 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 + - 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 + } + - name: Get changed TypeScript files id: changed-files uses: tj-actions/changed-files@v45 From 0681a9a7057b5949e256de99a8b864ff85de2e4b Mon Sep 17 00:00:00 2001 From: IITI-tushar <019saxenatushar@gmail.com> Date: Wed, 15 Jan 2025 21:42:27 +0530 Subject: [PATCH 02/23] updated css_check --- .github/workflows/css_check.py | 98 +++++++++++-------- .github/workflows/pull-request.yml | 15 ++- .../AddOn/core/AddOnEntry/AddOnEntry.tsx | 2 +- 3 files changed, 74 insertions(+), 41 deletions(-) diff --git a/.github/workflows/css_check.py b/.github/workflows/css_check.py index 81f9f9c658..5641cba670 100644 --- a/.github/workflows/css_check.py +++ b/.github/workflows/css_check.py @@ -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: """ @@ -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. @@ -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 = [] @@ -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.""" @@ -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() + diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 6caf41e09a..97d362fd40 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -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 diff --git a/src/components/AddOn/core/AddOnEntry/AddOnEntry.tsx b/src/components/AddOn/core/AddOnEntry/AddOnEntry.tsx index 0d317266d9..ef02f65629 100644 --- a/src/components/AddOn/core/AddOnEntry/AddOnEntry.tsx +++ b/src/components/AddOn/core/AddOnEntry/AddOnEntry.tsx @@ -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; From 1e5934ba3d2e919149fe8a4b93b0ae876c990f9b Mon Sep 17 00:00:00 2001 From: IITI-tushar <019saxenatushar@gmail.com> Date: Thu, 16 Jan 2025 00:24:51 +0530 Subject: [PATCH 03/23] moved csscheck to script folder --- .github/workflows/pull-request.yml | 2 +- .github/workflows/{ => scripts}/css_check.py | 53 ++++++++++++++------ 2 files changed, 39 insertions(+), 16 deletions(-) rename .github/workflows/{ => scripts}/css_check.py (79%) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 97d362fd40..03575f0d37 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -70,7 +70,7 @@ jobs: exit 1 fi chmod +x ./.github/workflows/css_check.py - ./.github/workflows/css_check.py --directory ./src --allowed_css_patterns app.module.css . || { + ./.github/workflows/css_check.py --directory --allowed_css_patterns app.module.cs . || { echo "Error: CSS check failed" exit 1 } diff --git a/.github/workflows/css_check.py b/.github/workflows/scripts/css_check.py similarity index 79% rename from .github/workflows/css_check.py rename to .github/workflows/scripts/css_check.py index 5641cba670..00697e30ff 100644 --- a/.github/workflows/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 +# -*- coding: UTF-8 -*- """Check TypeScript files for CSS violations and embedded CSS.""" import argparse import os @@ -6,10 +8,13 @@ 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']) +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: """ @@ -24,8 +29,12 @@ 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 + directory: str, + exclude_files: list, + exclude_directories: list, + allowed_css_patterns: list, ) -> CSSCheckResult: """ Check TypeScript files for CSS violations and correct CSS imports. @@ -72,7 +81,8 @@ def check_files( 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) + base_path = os.path.dirname(file_path) + css_file_path = os.path.normpath(os.path.join(base_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) @@ -80,20 +90,29 @@ def check_files( # Check if the CSS file exists if not os.path.exists(css_file_path): - violations.append(Violation(file_path, css_file, "File not found")) + violations.append( + Violation(file_path, css_file, "File not found") + ) # Check if the CSS import matches the allowed patterns - elif any(css_file.endswith(pattern) for pattern in allowed_css_patterns): + elif any( + css_file.endswith(pattern) for pattern in allowed_css_patterns + ): correct_css_imports.append(CorrectImport(file_path, css_file)) else: - violations.append(Violation(file_path, css_file, "Invalid import")) + 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(EmbeddedViolation(file_path, embedded_css)) + 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.""" parser = argparse.ArgumentParser( @@ -137,24 +156,28 @@ def main(): if result.violations: output.append("CSS Import Violations:") for violation in result.violations: - output.append(f"- {violation.file_path}: {violation.css_file} ({violation.reason})") + 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 + exit_code = 1 if output: print("\n".join(output)) - print(""" + 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:") for import_ in result.correct_imports: @@ -162,6 +185,6 @@ def main(): sys.exit(exit_code) + if __name__ == "__main__": main() - From 46ae791dfd2def8131989160ae2b9cd48abcfb5e Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Thu, 16 Jan 2025 00:31:40 +0530 Subject: [PATCH 04/23] Update pull-request.yml --- .github/workflows/pull-request.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 03575f0d37..7243ca6311 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -65,12 +65,12 @@ jobs: fi done - if [ ! -f ./.github/workflows/css_check.py ]; then + if [ ! -f ./.github/workflows/scripts/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 --directory --allowed_css_patterns app.module.cs . || { + chmod +x ./.github/workflows/scripts/css_check.py + ./.github/workflows/scripts/css_check.py --directory "$(dirname "$file")" --allowed_css_patterns app.module.css || { echo "Error: CSS check failed" exit 1 } From f62a543e1379ed193dd744be736dd6dc0ff8f725 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Thu, 16 Jan 2025 01:03:55 +0530 Subject: [PATCH 05/23] Update pull-request.yml Hoping it will run ..... --- .github/workflows/pull-request.yml | 25 ++----------------------- 1 file changed, 2 insertions(+), 23 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 7243ca6311..8f174bf580 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -51,30 +51,9 @@ jobs: # Run the CSS import check script on changed .ts and .tsx files - name: Check for CSS violations and print correct imports - if: steps.changed-ts-files.outputs.any_changed == 'true' + 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/scripts/css_check.py ]; then - echo "Error: CSS check script not found" - exit 1 - fi - chmod +x ./.github/workflows/scripts/css_check.py - ./.github/workflows/scripts/css_check.py --directory "$(dirname "$file")" --allowed_css_patterns app.module.css || { - echo "Error: CSS check failed" - exit 1 - } - + echo "${{ steps.changed-ts-files.outputs.modified_files }}" | tr ' ' '\n' | xargs -I {} python3 ./.github/workflows/scripts/css_check.py --directory "$(dirname "{}")" --allowed_css_patterns app.module.css - name: Get changed TypeScript files id: changed-files From d6d51c47c4ec797dec06c4b74f0b1776109443c0 Mon Sep 17 00:00:00 2001 From: IITI-tushar <019saxenatushar@gmail.com> Date: Thu, 16 Jan 2025 19:16:36 +0530 Subject: [PATCH 06/23] updated code hope it will fix the issue --- .github/workflows/pull-request.yml | 5 +- .github/workflows/scripts/css_check.py | 115 ++++++++++++++----------- 2 files changed, 69 insertions(+), 51 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 8f174bf580..76ee98528d 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -53,7 +53,10 @@ jobs: - name: Check for CSS violations and print correct imports if: ${{ steps.changed-ts-files.outputs.any_changed == 'true' }} run: | - echo "${{ steps.changed-ts-files.outputs.modified_files }}" | tr ' ' '\n' | xargs -I {} python3 ./.github/workflows/scripts/css_check.py --directory "$(dirname "{}")" --allowed_css_patterns app.module.css + # Pass all modified files as arguments to the script + python3 ./.github/workflows/scripts/css_check.py \ + --directories ${{ steps.changed-ts-files.outputs.modified_files }} \ + --allowed_css_patterns app.module.css - name: Get changed TypeScript files id: changed-files diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 00697e30ff..ed211d28b8 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -31,7 +31,7 @@ def check_embedded_css(content: str) -> list: def check_files( - directory: str, + directories: list, exclude_files: list, exclude_directories: list, allowed_css_patterns: list, @@ -40,7 +40,7 @@ def check_files( Check TypeScript files for CSS violations and correct CSS imports. Args: - directory: The directory to check. + directories: List of directories or files 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. @@ -56,60 +56,70 @@ def check_files( 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 directory in directories: + directory = os.path.abspath(directory) - for file in files: - file_path = os.path.abspath(os.path.join(root, file)) - - # Skip excluded files - if file_path in exclude_files: + for root, _, files in os.walk(directory): + # Skip excluded directories + if any(root.startswith(exclude_dir) for exclude_dir in exclude_directories): 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}") + for file in files: + file_path = os.path.abspath(os.path.join(root, file)) + + # Skip excluded files + if file_path in exclude_files: continue - # Check for CSS imports with an improved regex pattern - css_imports = re.findall(r'import\s+.*?["\'](.+?\.css)["\']', content) - for css_file in css_imports: - # Try to find the CSS file - base_path = os.path.dirname(file_path) - css_file_path = os.path.normpath(os.path.join(base_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") + # 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( + r'import\s+.*?["\'](.+?\.css)["\']', content + ) + for css_file in css_imports: + # Try to find the CSS file + base_path = os.path.dirname(file_path) + css_file_path = os.path.normpath( + os.path.join(base_path, css_file) ) - # Check if the CSS import matches the allowed patterns - elif any( - css_file.endswith(pattern) for pattern in allowed_css_patterns - ): - correct_css_imports.append(CorrectImport(file_path, css_file)) - else: - violations.append( - Violation(file_path, css_file, "Invalid import") + 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 + elif any( + css_file.endswith(pattern) + for pattern in allowed_css_patterns + ): + correct_css_imports.append( + CorrectImport(file_path, css_file) + ) + else: + 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( + EmbeddedViolation(file_path, embedded_css) ) - # Check for embedded CSS - embedded_css = check_embedded_css(content) - if embedded_css: - embedded_css_violations.append( - EmbeddedViolation(file_path, embedded_css) - ) - return CSSCheckResult(violations, correct_css_imports, embedded_css_violations) @@ -118,7 +128,12 @@ def main(): parser = argparse.ArgumentParser( description="Check for CSS violations in TypeScript files." ) - parser.add_argument("--directory", required=True, help="Directory to check.") + parser.add_argument( + "--directories", + nargs="+", + required=True, + help="List of directories or files to check for CSS violations.", + ) parser.add_argument( "--exclude_files", nargs="*", @@ -145,7 +160,7 @@ def main(): args = parser.parse_args() result = check_files( - directory=args.directory, + directories=args.directories, exclude_files=args.exclude_files, exclude_directories=args.exclude_directories, allowed_css_patterns=args.allowed_css_patterns, From 0cce49a279d183144bb0388fb4efc5a1cb792359 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Thu, 16 Jan 2025 19:35:22 +0530 Subject: [PATCH 07/23] Update css_check.py may pass black code formatter From 73e930dd768f6360998e0b7969e64c174e7cc295 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Fri, 17 Jan 2025 14:59:47 +0530 Subject: [PATCH 08/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index ed211d28b8..27367aeee8 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -186,12 +186,12 @@ def main(): 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. -""" + 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:") From e4e0c494624f1ea257a85d1aca22126870ff3883 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sun, 19 Jan 2025 19:58:22 +0530 Subject: [PATCH 09/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 140 +++++++++++++------------ 1 file changed, 73 insertions(+), 67 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 27367aeee8..3fad48b31f 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -30,97 +30,101 @@ def check_embedded_css(content: str) -> list: return re.findall(embedded_css_pattern, content) +def process_typescript_file( + file_path, + directory, + allowed_css_patterns, + violations, + correct_css_imports, + embedded_css_violations, +): + """ + Process a TypeScript file for CSS violations and correct CSS imports. + + Args: + file_path: Path to the TypeScript file to process. + directory: Base directory being scanned. + allowed_css_patterns: List of allowed CSS file patterns. + violations: List to store CSS violations. + correct_css_imports: List to store correct CSS imports. + embedded_css_violations: List to store embedded CSS violations. + """ + 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}") + return + + # Check for CSS imports with an improved regex pattern + css_imports = re.findall(r'import\s+.*?["\'](.+?\.css)["\']', content) + for css_file in css_imports: + base_path = os.path.dirname(file_path) + css_file_path = os.path.normpath(os.path.join(base_path, css_file)) + if not os.path.exists(css_file_path): + src_dir = os.path.abspath(directory) + css_file_path = os.path.join(src_dir, css_file) + + if not os.path.exists(css_file_path): + violations.append(Violation(file_path, css_file, "File not found")) + elif any( + css_file.endswith(pattern) for pattern in allowed_css_patterns + ): + correct_css_imports.append(CorrectImport(file_path, css_file)) + else: + 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( + EmbeddedViolation(file_path, embedded_css) + ) + + def check_files( directories: list, exclude_files: list, exclude_directories: list, allowed_css_patterns: list, ) -> CSSCheckResult: - """ - Check TypeScript files for CSS violations and correct CSS imports. - - Args: - directories: List of directories or files 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 CSSCheckResult namedtuple 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) + exclude_directories = set( + os.path.abspath(dir) for dir in exclude_directories + ) for directory in directories: directory = os.path.abspath(directory) for root, _, files in os.walk(directory): - # Skip excluded directories - if any(root.startswith(exclude_dir) for exclude_dir in exclude_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( - r'import\s+.*?["\'](.+?\.css)["\']', content + process_typescript_file( + file_path, + directory, + allowed_css_patterns, + violations, + correct_css_imports, + embedded_css_violations, ) - for css_file in css_imports: - # Try to find the CSS file - base_path = os.path.dirname(file_path) - css_file_path = os.path.normpath( - os.path.join(base_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 - elif any( - css_file.endswith(pattern) - for pattern in allowed_css_patterns - ): - correct_css_imports.append( - CorrectImport(file_path, css_file) - ) - else: - 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( - EmbeddedViolation(file_path, embedded_css) - ) - - return CSSCheckResult(violations, correct_css_imports, embedded_css_violations) + + return CSSCheckResult( + violations, correct_css_imports, embedded_css_violations + ) def main(): @@ -179,7 +183,9 @@ def main(): 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)}") + output.append( + f"- {violation.file_path}: {', '.join(violation.css_codes)}" + ) exit_code = 1 if output: From cc9fe6fa00addc570559832ceacfe313e521c8a5 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sun, 19 Jan 2025 20:29:19 +0530 Subject: [PATCH 10/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 38 ++++++++++++++++++-------- 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 3fad48b31f..264f244238 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -17,8 +17,7 @@ def check_embedded_css(content: str) -> list: - """ - Check for embedded CSS in the content. + """Check for embedded CSS in the content. Args: content: The content of the file to check. @@ -38,8 +37,7 @@ def process_typescript_file( correct_css_imports, embedded_css_violations, ): - """ - Process a TypeScript file for CSS violations and correct CSS imports. + """Process a TypeScript file for CSS violations and correct CSS imports. Args: file_path: Path to the TypeScript file to process. @@ -88,6 +86,17 @@ def check_files( exclude_directories: list, allowed_css_patterns: list, ) -> CSSCheckResult: + """Scan directories for TypeScript files and check for CSS violations. + + This function checks TypeScriptfiles in given directories for violations. + + Args: + directories: List of directories to scan for TypeScript files. + exclude_files: List of file paths to exclude from the scan. + exclude_directories: List of directories to exclude from the scan. + allowed_css_patterns: List of allowed CSS patterns for validation. + + """ violations = [] correct_css_imports = [] embedded_css_violations = [] @@ -176,7 +185,8 @@ def main(): output.append("CSS Import Violations:") for violation in result.violations: output.append( - f"- {violation.file_path}: {violation.css_file} ({violation.reason})" + f"- {violation.file_path}: " + f"{violation.css_file} ({violation.reason})" ) exit_code = 1 @@ -191,14 +201,18 @@ def main(): 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. - """ + "Please address the above CSS violations:\n" + "1. For invalid CSS imports,\n" + " ensure you're using the correct import syntax and file paths.\n" + "2. For embedded CSS,\n" + " move the CSS to appropriate stylesheet\n" + " files and import them correctly.\n" + "3. Make sure to use only the allowed CSS patterns\n" + " as specified in the script arguments.\n" + "4. Check that all imported CSS files\n" + " exist in the specified locations." ) + if args.show_success and result.correct_imports: print("\nCorrect CSS Imports:") for import_ in result.correct_imports: From ba04cba5c5d77925185f78faa83d3a132e148140 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sun, 19 Jan 2025 23:08:38 +0530 Subject: [PATCH 11/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 264f244238..d6e514ed8d 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -23,7 +23,7 @@ def check_embedded_css(content: str) -> list: content: The content of the file to check. Returns: - A list of embedded CSS violations found. + list: 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) @@ -46,6 +46,9 @@ def process_typescript_file( violations: List to store CSS violations. correct_css_imports: List to store correct CSS imports. embedded_css_violations: List to store embedded CSS violations. + + Returns: + None: This function modifies provided lists & does not return any value. """ try: with open(file_path, "r", encoding="utf-8") as f: @@ -96,6 +99,11 @@ def check_files( exclude_directories: List of directories to exclude from the scan. allowed_css_patterns: List of allowed CSS patterns for validation. + Returns: + CSSCheckResult: A result object containing: + - violations: List of CSS violations found. + - correct_css_imports: List of correct CSS imports. + - embedded_css_violations: List of embedded CSS violations. """ violations = [] correct_css_imports = [] @@ -137,7 +145,17 @@ def check_files( def main(): - """Run the CSS check script.""" + """Main function to run the CSS check. + + This function serves as the entry point to run the CSS check, processing the + necessary files and directories, and printing the violations found. + + Args: + None: This function does not take any arguments. + + Returns: + None: This function does not return any value but prints the violations. + """ parser = argparse.ArgumentParser( description="Check for CSS violations in TypeScript files." ) From 55320e2651c4a1747a1972fc5af72850e744c99a Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sun, 19 Jan 2025 23:17:55 +0530 Subject: [PATCH 12/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index d6e514ed8d..12bc9780d4 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -100,10 +100,10 @@ def check_files( allowed_css_patterns: List of allowed CSS patterns for validation. Returns: - CSSCheckResult: A result object containing: - - violations: List of CSS violations found. - - correct_css_imports: List of correct CSS imports. - - embedded_css_violations: List of embedded CSS violations. + CSSCheckResult: A result object containing: + - violations: List of CSS violations found. + - correct_css_imports: List of correct CSS imports. + - embedded_css_violations: List of embedded CSS violations. """ violations = [] correct_css_imports = [] @@ -152,6 +152,7 @@ def main(): Args: None: This function does not take any arguments. + It uses argparse to handle command-line arguments. Returns: None: This function does not return any value but prints the violations. From 1704f44e413727b4727878ec874daa059301701e Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Mon, 20 Jan 2025 08:33:31 +0530 Subject: [PATCH 13/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 12bc9780d4..2314da090a 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -151,8 +151,8 @@ def main(): necessary files and directories, and printing the violations found. Args: - None: This function does not take any arguments. - It uses argparse to handle command-line arguments. + None: This function does not take any arguments.It uses + argparse to handle command-line arguments. Returns: None: This function does not return any value but prints the violations. From 01472728779bf1cc993d916c1b94a88e3fb7063c Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Mon, 20 Jan 2025 08:38:20 +0530 Subject: [PATCH 14/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 2314da090a..77c9f5cb29 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -151,8 +151,7 @@ def main(): necessary files and directories, and printing the violations found. Args: - None: This function does not take any arguments.It uses - argparse to handle command-line arguments. + None: This function does not take any arguments. Returns: None: This function does not return any value but prints the violations. From 1f1bf1c8a11ee2fbe35f843f45ec3ead115ab432 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Mon, 20 Jan 2025 09:00:17 +0530 Subject: [PATCH 15/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 77c9f5cb29..62d05a50ac 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -147,14 +147,23 @@ def check_files( def main(): """Main function to run the CSS check. - This function serves as the entry point to run the CSS check, processing the - necessary files and directories, and printing the violations found. + This function serves as the entry point to run the CSS check. It processes + directories and files, checks for CSS violations, and prints the results. Args: - None: This function does not take any arguments. + None: This function does not directly accept arguments but uses argparse + to handle command-line inputs. + + Command-line Arguments: + --directories: List of directories or files to check for CSS violations. + --exclude_files: Specific files to exclude from analysis. + --exclude_directories: Directories to exclude from analysis. + --allowed_css_patterns: Allowed CSS file patterns. + --show_success: Flag to show successful CSS imports. Returns: - None: This function does not return any value but prints the violations. + None: This function does not return any value. It prints the results + and exits with a code indicating success (0) or failure (1). """ parser = argparse.ArgumentParser( description="Check for CSS violations in TypeScript files." From 2c8c740372c7e005d70d23cb7c0d985d1def4513 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sat, 25 Jan 2025 12:12:52 +0530 Subject: [PATCH 16/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 106 ++++++++++++++++++++----- 1 file changed, 87 insertions(+), 19 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 62d05a50ac..5c1113f265 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -25,8 +25,8 @@ def check_embedded_css(content: str) -> list: Returns: list: 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) + embedded_css_pattern = r"\{[^{}]*#[0-9a-fA-F]{3,6}\b.*?}" + return re.findall(embedded_css_pattern, content, re.DOTALL) def process_typescript_file( @@ -59,6 +59,7 @@ def process_typescript_file( # Check for CSS imports with an improved regex pattern css_imports = re.findall(r'import\s+.*?["\'](.+?\.css)["\']', content) + found_correct_import = False for css_file in css_imports: base_path = os.path.dirname(file_path) css_file_path = os.path.normpath(os.path.join(base_path, css_file)) @@ -72,9 +73,16 @@ def process_typescript_file( css_file.endswith(pattern) for pattern in allowed_css_patterns ): correct_css_imports.append(CorrectImport(file_path, css_file)) + found_correct_import = True else: violations.append(Violation(file_path, css_file, "Invalid import")) + # Fail if no correct import of app.module.css is found + if not found_correct_import: + violations.append( + Violation(file_path, "app.module.css", "Missing required import") + ) + # Check for embedded CSS embedded_css = check_embedded_css(content) if embedded_css: @@ -85,16 +93,18 @@ def process_typescript_file( def check_files( directories: list, + files: list, exclude_files: list, exclude_directories: list, allowed_css_patterns: list, ) -> CSSCheckResult: - """Scan directories for TypeScript files and check for CSS violations. + """Scan directories and specific files for TS files and their violations. - This function checks TypeScriptfiles in given directories for violations. + This function checks TypeScript files in given directories for violations. Args: directories: List of directories to scan for TypeScript files. + files: List of specific files to check. exclude_files: List of file paths to exclude from the scan. exclude_directories: List of directories to exclude from the scan. allowed_css_patterns: List of allowed CSS patterns for validation. @@ -117,14 +127,14 @@ def check_files( for directory in directories: directory = os.path.abspath(directory) - for root, _, files in os.walk(directory): + for root, _, files_in_dir in os.walk(directory): if any( root.startswith(exclude_dir) for exclude_dir in exclude_directories ): continue - for file in files: + for file in files_in_dir: file_path = os.path.abspath(os.path.join(root, file)) if file_path in exclude_files: continue @@ -139,11 +149,51 @@ def check_files( embedded_css_violations, ) + # Fail if CSS file exists in the same directory + if file.endswith(".css") and root == os.path.dirname( + file_path + ): + violations.append( + Violation( + file_path, file, "CSS file in same directory" + ) + ) + + # Process individual files explicitly listed + for file_path in files: + file_path = os.path.abspath(file_path) + if file_path not in exclude_files and file_path.endswith( + (".ts", ".tsx") + ): + process_typescript_file( + file_path, + os.path.dirname(file_path), + allowed_css_patterns, + violations, + correct_css_imports, + embedded_css_violations, + ) + return CSSCheckResult( violations, correct_css_imports, embedded_css_violations ) +def validate_directories_input(input_directories): + """Validate that the --directories input is correctly formatted.""" + validated_dirs = [] + for path in input_directories: + if os.path.isdir(path): + validated_dirs.append(path) + elif os.path.isfile(path): + validated_dirs.append(os.path.dirname(path)) + else: + raise ValueError( + f"Invalid path: {path}. Must be an existing file or directory." + ) + return validated_dirs + + def main(): """Main function to run the CSS check. @@ -151,15 +201,7 @@ def main(): directories and files, checks for CSS violations, and prints the results. Args: - None: This function does not directly accept arguments but uses argparse - to handle command-line inputs. - - Command-line Arguments: - --directories: List of directories or files to check for CSS violations. - --exclude_files: Specific files to exclude from analysis. - --exclude_directories: Directories to exclude from analysis. - --allowed_css_patterns: Allowed CSS file patterns. - --show_success: Flag to show successful CSS imports. + None Returns: None: This function does not return any value. It prints the results @@ -171,8 +213,14 @@ def main(): parser.add_argument( "--directories", nargs="+", - required=True, - help="List of directories or files to check for CSS violations.", + required=False, + help="List of directories to check for CSS violations.", + ) + parser.add_argument( + "--files", + nargs="*", + default=[], + help="Specific files to check for CSS violations.", ) parser.add_argument( "--exclude_files", @@ -199,8 +247,24 @@ def main(): ) args = parser.parse_args() + if not args.directories and not args.files: + parser.error( + "At least one of --directories or --files must be provided." + ) + + try: + directories = ( + validate_directories_input(args.directories) + if args.directories + else [] + ) + except ValueError as e: + print(f"Error: {e}") + sys.exit(1) + result = check_files( - directories=args.directories, + directories=directories, + files=args.files, exclude_files=args.exclude_files, exclude_directories=args.exclude_directories, allowed_css_patterns=args.allowed_css_patterns, @@ -237,7 +301,11 @@ def main(): "3. Make sure to use only the allowed CSS patterns\n" " as specified in the script arguments.\n" "4. Check that all imported CSS files\n" - " exist in the specified locations." + " exist in the specified locations.\n" + "5. Ensure each TypeScript file has exactly\n" + " one import of the allowed CSS file.\n" + "6. Remove any CSS files from the same\n" + " directory as TypeScript files." ) if args.show_success and result.correct_imports: From 8df379600ce8cb3446ca7092adea58c7d85dca97 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sat, 25 Jan 2025 12:13:31 +0530 Subject: [PATCH 17/23] Update pull-request.yml --- .github/workflows/pull-request.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 76ee98528d..e4908e3fed 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -55,7 +55,7 @@ jobs: run: | # Pass all modified files as arguments to the script python3 ./.github/workflows/scripts/css_check.py \ - --directories ${{ steps.changed-ts-files.outputs.modified_files }} \ + --files ${{ steps.changed-ts-files.outputs.modified_files }} \ --allowed_css_patterns app.module.css - name: Get changed TypeScript files From 8d57c397d23294506b81b36ae0c2ba44c40f2ba8 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sat, 25 Jan 2025 12:22:31 +0530 Subject: [PATCH 18/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 5c1113f265..c042688439 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -180,7 +180,18 @@ def check_files( def validate_directories_input(input_directories): - """Validate that the --directories input is correctly formatted.""" + """Validate that the --directories input is correctly formatted. + + Args: + input_directories: A list of file or directory paths to validate. + + Returns: + validated_dirs: A list containing validated directory paths. + If the input is a file, its parent directory is added to the list. + + Raises: + ValueError: If a path is neither a valid file nor a directory. + """ validated_dirs = [] for path in input_directories: if os.path.isdir(path): From 0e8c706e5f69bfb2a6efc84b5b35762459c8e66e Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sat, 25 Jan 2025 13:54:07 +0530 Subject: [PATCH 19/23] Update css_check.py added code rabbit suggestion --- .github/workflows/scripts/css_check.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index c042688439..8308bc82bb 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -139,7 +139,16 @@ def check_files( if file_path in exclude_files: continue - if file.endswith((".ts", ".tsx")) and "test" not in root: + if file.endswith((".ts", ".tsx")) and not any( + pattern in root + for pattern in [ + "__tests__", + ".test.", + ".spec.", + "test/", + "tests/", + ] + ): process_typescript_file( file_path, directory, From 7e8afba04274add28c2aeb67c9811d383283d728 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sat, 25 Jan 2025 18:15:42 +0530 Subject: [PATCH 20/23] Update pull-request.yml --- .github/workflows/pull-request.yml | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index e4908e3fed..3e93871fae 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -40,27 +40,19 @@ jobs: 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 - name: Get changed TypeScript files - id: changed-ts-files + id: changed-files uses: tj-actions/changed-files@v45 - with: - files: | - **/*.ts - **/*.tsx - - # Run the CSS import check script on changed .ts and .tsx files + + # Run the CSS import check script on changed .ts and .tsx files - name: Check for CSS violations and print correct imports - if: ${{ steps.changed-ts-files.outputs.any_changed == 'true' }} + if: ${{ steps.changed-files.outputs.any_changed == 'true' }} run: | # Pass all modified files as arguments to the script python3 ./.github/workflows/scripts/css_check.py \ - --files ${{ steps.changed-ts-files.outputs.modified_files }} \ + --files ${{ steps.changed-files.outputs.modified_files }} \ --allowed_css_patterns app.module.css - - name: Get changed TypeScript files - id: changed-files - uses: tj-actions/changed-files@v45 - name: Check formatting if: steps.changed-files.outputs.only_changed != 'true' run: npm run format:check From 5400027abb29948bcac8513a74774c391b214769 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Sat, 25 Jan 2025 18:42:29 +0530 Subject: [PATCH 21/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 8308bc82bb..89dbbf52dd 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -25,8 +25,15 @@ def check_embedded_css(content: str) -> list: Returns: list: A list of embedded CSS violations found. """ - embedded_css_pattern = r"\{[^{}]*#[0-9a-fA-F]{3,6}\b.*?}" - return re.findall(embedded_css_pattern, content, re.DOTALL) + color_code_pattern = r"#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b" + violations = [] + + for line_number, line in enumerate(content.splitlines(), start=1): + matches = re.findall(color_code_pattern, line) + for match in matches: + violations.append((line_number, match)) + + return violations def process_typescript_file( @@ -304,9 +311,12 @@ def main(): 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)}" - ) + for css_code in violation.css_codes: + output.append( + f"- {violation.file_path}: " + f"has embedded color code `{css_code}`. use CSS variable " + f"in src/style/app.module.css." + ) exit_code = 1 if output: From 5511fe7d8df7ea64809c412dd9504f206a500d33 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Tue, 4 Feb 2025 11:16:53 +0530 Subject: [PATCH 22/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 44 ++++++++++++++------------ 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 89dbbf52dd..7d5e72c268 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -146,15 +146,15 @@ def check_files( if file_path in exclude_files: continue - if file.endswith((".ts", ".tsx")) and not any( - pattern in root - for pattern in [ - "__tests__", - ".test.", - ".spec.", - "test/", - "tests/", - ] + if ( + file.endswith((".ts", ".tsx")) + and not file.endswith( + (".test.tsx", ".spec.tsx", ".test.ts", ".spec.ts") + ) # Ensure test files are excluded + and not any( + pattern in root + for pattern in ["__tests__", "test/", "tests/"] + ) ): process_typescript_file( file_path, @@ -178,8 +178,10 @@ def check_files( # Process individual files explicitly listed for file_path in files: file_path = os.path.abspath(file_path) - if file_path not in exclude_files and file_path.endswith( - (".ts", ".tsx") + if ( + file_path not in exclude_files + and file_path.endswith((".ts", ".tsx")) + and not file_path.endswith((".test.tsx", ".spec.tsx")) ): process_typescript_file( file_path, @@ -306,7 +308,7 @@ def main(): f"- {violation.file_path}: " f"{violation.css_file} ({violation.reason})" ) - exit_code = 1 + exit_code = 0 if result.embedded_violations: output.append("\nEmbedded CSS Violations:") @@ -323,19 +325,21 @@ def main(): print("\n".join(output)) print( "Please address the above CSS violations:\n" - "1. For invalid CSS imports,\n" + "1. For invalid CSS imports," " ensure you're using the correct import syntax and file paths.\n" - "2. For embedded CSS,\n" - " move the CSS to appropriate stylesheet\n" + "2. For embedded CSS," + " move the CSS to appropriate stylesheet" " files and import them correctly.\n" - "3. Make sure to use only the allowed CSS patterns\n" + "3. Make sure to use only the allowed CSS patterns" " as specified in the script arguments.\n" - "4. Check that all imported CSS files\n" + "4. Check that all imported CSS files" " exist in the specified locations.\n" - "5. Ensure each TypeScript file has exactly\n" + "5. Ensure each TypeScript file has exactly" " one import of the allowed CSS file.\n" - "6. Remove any CSS files from the same\n" - " directory as TypeScript files." + "6. Remove any CSS files from the same" + " directory as TypeScript files.\n" + "Note: for now the script fails only" + " because of embedded CSS violations." ) if args.show_success and result.correct_imports: From d0c2737cb68713f4151b83be730162f9ddbb1372 Mon Sep 17 00:00:00 2001 From: Tushar Saxena <165766280+IITI-tushar@users.noreply.github.com> Date: Tue, 4 Feb 2025 11:37:10 +0530 Subject: [PATCH 23/23] Update css_check.py --- .github/workflows/scripts/css_check.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/.github/workflows/scripts/css_check.py b/.github/workflows/scripts/css_check.py index 7d5e72c268..21ca08e7ad 100644 --- a/.github/workflows/scripts/css_check.py +++ b/.github/workflows/scripts/css_check.py @@ -10,7 +10,9 @@ # 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"]) +EmbeddedViolation = namedtuple( + "EmbeddedViolation", ["file_path", "css_codes", "line_numbers"] +) CSSCheckResult = namedtuple( "CSSCheckResult", ["violations", "correct_imports", "embedded_violations"] ) @@ -93,8 +95,10 @@ def process_typescript_file( # Check for embedded CSS embedded_css = check_embedded_css(content) if embedded_css: + line_numbers = [violation[0] for violation in embedded_css] + css_codes = [violation[1] for violation in embedded_css] embedded_css_violations.append( - EmbeddedViolation(file_path, embedded_css) + EmbeddedViolation(file_path, css_codes, line_numbers) ) @@ -313,11 +317,15 @@ def main(): if result.embedded_violations: output.append("\nEmbedded CSS Violations:") for violation in result.embedded_violations: + for line_number, css_code in zip( + violation.line_numbers, violation.css_codes + ): + relative_file_path = os.path.relpath(violation.file_path) for css_code in violation.css_codes: output.append( - f"- {violation.file_path}: " - f"has embedded color code `{css_code}`. use CSS variable " - f"in src/style/app.module.css." + f"- File: {relative_file_path}, Line: {line_number}: " + f"Embedded color code `{css_code}` detected.Please replace" + f" it with a CSS variable in `src/style/app.module.css`." ) exit_code = 1