mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-29 14:12:54 +08:00
Merge pull request #6 from LongSimple/fix-download-error
Fix for file download failures in cursor-rules-cli
This commit is contained in:
@@ -16,6 +16,7 @@ A simple tool that helps you find and install the right Cursor rules for your pr
|
|||||||
- 🎨 Provides a colorful, user-friendly interface
|
- 🎨 Provides a colorful, user-friendly interface
|
||||||
- 🔀 Works with custom rule repositories
|
- 🔀 Works with custom rule repositories
|
||||||
- 🔒 100% privacy-focused (all scanning happens locally)
|
- 🔒 100% privacy-focused (all scanning happens locally)
|
||||||
|
- 🔄 GitHub API integration for reliable downloads
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -46,14 +47,29 @@ cursor-rules -d /path/to/my/project
|
|||||||
| `--quick-scan` | Faster scan (checks package files only) |
|
| `--quick-scan` | Faster scan (checks package files only) |
|
||||||
| `--max-results N` | Show top N results (default: 20) |
|
| `--max-results N` | Show top N results (default: 20) |
|
||||||
|
|
||||||
## Custom Repositories (not tested yet)
|
## Custom Repositories
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Use rules from your own repository
|
# Use rules from your own GitHub repository
|
||||||
cursor-rules --custom-repo your-username/your-repo
|
cursor-rules --source https://github.com/your-username/your-repo
|
||||||
|
|
||||||
# Save repository setting for future use
|
# Save repository setting for future use
|
||||||
cursor-rules --custom-repo your-username/your-repo --save-config
|
cursor-rules --source https://github.com/your-username/your-repo --save-config
|
||||||
|
```
|
||||||
|
|
||||||
|
## Repository URL Format
|
||||||
|
|
||||||
|
The tool now uses the GitHub API to reliably download rules. You can specify the repository URL in several formats:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Standard GitHub repository URL (recommended)
|
||||||
|
cursor-rules --source https://github.com/username/repo
|
||||||
|
|
||||||
|
# With a specific branch
|
||||||
|
cursor-rules --source https://github.com/username/repo/tree/branch-name
|
||||||
|
|
||||||
|
# Legacy raw content URL will also work
|
||||||
|
cursor-rules --source https://raw.githubusercontent.com/username/repo/branch
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|||||||
@@ -2,4 +2,4 @@
|
|||||||
Cursor Rules CLI - A tool to scan projects and suggest relevant Cursor rules
|
Cursor Rules CLI - A tool to scan projects and suggest relevant Cursor rules
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = "0.5.1"
|
__version__ = "0.5.2"
|
||||||
@@ -8,6 +8,8 @@ import os
|
|||||||
import time
|
import time
|
||||||
import logging
|
import logging
|
||||||
import requests
|
import requests
|
||||||
|
import re
|
||||||
|
import base64
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List, Any, Optional, Tuple
|
from typing import Dict, List, Any, Optional, Tuple
|
||||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||||
@@ -31,6 +33,36 @@ class ValidationError(Exception):
|
|||||||
"""Custom exception for validation errors."""
|
"""Custom exception for validation errors."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def extract_repo_info(source_url: str) -> Tuple[str, str, str]:
|
||||||
|
"""
|
||||||
|
Extract owner and repo name from GitHub URL.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_url: GitHub URL
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (owner, repo, branch)
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If URL is not a valid GitHub repository URL
|
||||||
|
"""
|
||||||
|
# Handle various GitHub URL formats
|
||||||
|
github_patterns = [
|
||||||
|
r"https?://github\.com/([^/]+)/([^/]+)(?:/tree/([^/]+))?", # github.com URLs
|
||||||
|
r"https?://raw\.githubusercontent\.com/([^/]+)/([^/]+)/([^/]+)" # raw.githubusercontent.com URLs
|
||||||
|
]
|
||||||
|
|
||||||
|
for pattern in github_patterns:
|
||||||
|
match = re.match(pattern, source_url)
|
||||||
|
if match:
|
||||||
|
groups = match.groups()
|
||||||
|
owner = groups[0]
|
||||||
|
repo = groups[1]
|
||||||
|
branch = groups[2] if len(groups) > 2 and groups[2] else "main"
|
||||||
|
return owner, repo, branch
|
||||||
|
|
||||||
|
raise ValueError(f"Invalid GitHub URL format: {source_url}")
|
||||||
|
|
||||||
def create_session() -> requests.Session:
|
def create_session() -> requests.Session:
|
||||||
"""
|
"""
|
||||||
Create a requests session with retry configuration.
|
Create a requests session with retry configuration.
|
||||||
@@ -54,6 +86,53 @@ def create_session() -> requests.Session:
|
|||||||
|
|
||||||
return session
|
return session
|
||||||
|
|
||||||
|
def verify_source_url(source_url: str, session: requests.Session = None) -> Tuple[bool, str]:
|
||||||
|
"""
|
||||||
|
Verify that the source URL is a valid GitHub repository.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_url: GitHub repository URL
|
||||||
|
session: Optional requests session to use
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (is_accessible: bool, error_message: str)
|
||||||
|
"""
|
||||||
|
if not session:
|
||||||
|
session = create_session()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Extract repo information
|
||||||
|
owner, repo, branch = extract_repo_info(source_url)
|
||||||
|
|
||||||
|
# Check if the repository exists using GitHub API
|
||||||
|
api_url = f"https://api.github.com/repos/{owner}/{repo}"
|
||||||
|
response = session.get(api_url, timeout=DEFAULT_TIMEOUT)
|
||||||
|
|
||||||
|
if response.status_code >= 400:
|
||||||
|
return False, f"GitHub repository not found: {owner}/{repo} (Status code: {response.status_code})"
|
||||||
|
|
||||||
|
# Check if the branch exists
|
||||||
|
branches_url = f"{api_url}/branches/{branch}"
|
||||||
|
response = session.get(branches_url, timeout=DEFAULT_TIMEOUT)
|
||||||
|
|
||||||
|
if response.status_code >= 400:
|
||||||
|
return False, f"Branch not found: {branch} (Status code: {response.status_code})"
|
||||||
|
|
||||||
|
# Check if the rules-mdc directory exists
|
||||||
|
contents_url = f"{api_url}/contents/rules-mdc?ref={branch}"
|
||||||
|
response = session.get(contents_url, timeout=DEFAULT_TIMEOUT)
|
||||||
|
|
||||||
|
if response.status_code >= 400:
|
||||||
|
return False, f"Rules directory not found: rules-mdc (Status code: {response.status_code})"
|
||||||
|
|
||||||
|
return True, ""
|
||||||
|
except ValueError as e:
|
||||||
|
return False, str(e)
|
||||||
|
except requests.RequestException as e:
|
||||||
|
return False, f"Failed to connect to GitHub: {e}"
|
||||||
|
except Exception as e:
|
||||||
|
return False, f"Unexpected error verifying source URL: {e}"
|
||||||
|
|
||||||
def download_rules(
|
def download_rules(
|
||||||
rules: List[Dict[str, Any]],
|
rules: List[Dict[str, Any]],
|
||||||
source_url: str,
|
source_url: str,
|
||||||
@@ -63,11 +142,11 @@ def download_rules(
|
|||||||
max_workers: int = 4,
|
max_workers: int = 4,
|
||||||
) -> List[Dict[str, Any]]:
|
) -> List[Dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
Download selected MDC rule files.
|
Download selected MDC rule files from GitHub.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
rules: List of rule metadata to download
|
rules: List of rule metadata to download
|
||||||
source_url: Base URL for the repository
|
source_url: GitHub repository URL
|
||||||
temp_dir: Temporary directory to store downloaded files
|
temp_dir: Temporary directory to store downloaded files
|
||||||
rate_limit: Maximum requests per second
|
rate_limit: Maximum requests per second
|
||||||
max_retries: Maximum number of retries for failed downloads
|
max_retries: Maximum number of retries for failed downloads
|
||||||
@@ -94,6 +173,21 @@ def download_rules(
|
|||||||
rate_limiter = utils.RateLimiter(rate_limit)
|
rate_limiter = utils.RateLimiter(rate_limit)
|
||||||
session = create_session()
|
session = create_session()
|
||||||
|
|
||||||
|
# Verify source URL is accessible
|
||||||
|
is_accessible, error_msg = verify_source_url(source_url, session)
|
||||||
|
if not is_accessible:
|
||||||
|
logger.error(f"Source URL verification failed: {error_msg}")
|
||||||
|
logger.error(f"Please check if the source URL is correct: {source_url}")
|
||||||
|
raise DownloadError(f"Source URL is not accessible: {error_msg}")
|
||||||
|
|
||||||
|
# Get repository information
|
||||||
|
try:
|
||||||
|
owner, repo, branch = extract_repo_info(source_url)
|
||||||
|
logger.info(f"Using GitHub repository: {owner}/{repo}, branch: {branch}")
|
||||||
|
except ValueError as e:
|
||||||
|
logger.error(f"Invalid GitHub URL: {str(e)}")
|
||||||
|
raise DownloadError(f"Invalid GitHub URL: {str(e)}")
|
||||||
|
|
||||||
# Download rules in parallel
|
# Download rules in parallel
|
||||||
downloaded_rules = []
|
downloaded_rules = []
|
||||||
failed_downloads = []
|
failed_downloads = []
|
||||||
@@ -102,8 +196,11 @@ def download_rules(
|
|||||||
# Submit download tasks
|
# Submit download tasks
|
||||||
future_to_rule = {
|
future_to_rule = {
|
||||||
executor.submit(
|
executor.submit(
|
||||||
download_rule,
|
download_rule_from_github,
|
||||||
rule,
|
rule,
|
||||||
|
owner,
|
||||||
|
repo,
|
||||||
|
branch,
|
||||||
temp_dir,
|
temp_dir,
|
||||||
rate_limiter,
|
rate_limiter,
|
||||||
session,
|
session,
|
||||||
@@ -124,7 +221,7 @@ def download_rules(
|
|||||||
logger.error(f"Failed to download {rule['name']}")
|
logger.error(f"Failed to download {rule['name']}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
failed_downloads.append(rule)
|
failed_downloads.append(rule)
|
||||||
logger.error(f"Error downloading {rule['name']}: {e}")
|
logger.error(f"Error downloading {rule['name']}: {str(e)}")
|
||||||
|
|
||||||
# Close the session
|
# Close the session
|
||||||
session.close()
|
session.close()
|
||||||
@@ -135,29 +232,38 @@ def download_rules(
|
|||||||
failed_count = len(failed_downloads)
|
failed_count = len(failed_downloads)
|
||||||
|
|
||||||
if failed_count > 0:
|
if failed_count > 0:
|
||||||
|
failed_names = [rule['name'] for rule in failed_downloads]
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Downloaded {success_count}/{total_rules} rules. "
|
f"Downloaded {success_count}/{total_rules} rules. "
|
||||||
f"Failed to download {failed_count} rules."
|
f"Failed to download {failed_count} rules: {', '.join(failed_names)}"
|
||||||
)
|
)
|
||||||
if failed_count == total_rules:
|
if failed_count == total_rules:
|
||||||
raise DownloadError("All downloads failed")
|
logger.error("All downloads failed. Please check your internet connection and the source URL.")
|
||||||
|
logger.error(f"Source URL: {source_url}")
|
||||||
|
raise DownloadError("All downloads failed. Check internet connection and source URL.")
|
||||||
else:
|
else:
|
||||||
logger.info(f"Successfully downloaded all {success_count} rules")
|
logger.info(f"Successfully downloaded all {success_count} rules")
|
||||||
|
|
||||||
return downloaded_rules
|
return downloaded_rules
|
||||||
|
|
||||||
def download_rule(
|
def download_rule_from_github(
|
||||||
rule: Dict[str, Any],
|
rule: Dict[str, Any],
|
||||||
|
owner: str,
|
||||||
|
repo: str,
|
||||||
|
branch: str,
|
||||||
temp_dir: Path,
|
temp_dir: Path,
|
||||||
rate_limiter: utils.RateLimiter,
|
rate_limiter: utils.RateLimiter,
|
||||||
session: requests.Session,
|
session: requests.Session,
|
||||||
max_retries: int,
|
max_retries: int,
|
||||||
) -> Optional[Dict[str, Any]]:
|
) -> Optional[Dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
Download a single MDC rule file with validation.
|
Download a single MDC rule file from GitHub with validation.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
rule: Rule metadata
|
rule: Rule metadata
|
||||||
|
owner: GitHub repository owner
|
||||||
|
repo: GitHub repository name
|
||||||
|
branch: GitHub repository branch
|
||||||
temp_dir: Temporary directory to store downloaded file
|
temp_dir: Temporary directory to store downloaded file
|
||||||
rate_limiter: Rate limiter instance
|
rate_limiter: Rate limiter instance
|
||||||
session: Requests session
|
session: Requests session
|
||||||
@@ -169,13 +275,11 @@ def download_rule(
|
|||||||
Raises:
|
Raises:
|
||||||
ValidationError: If the downloaded content fails validation
|
ValidationError: If the downloaded content fails validation
|
||||||
"""
|
"""
|
||||||
url = rule["url"]
|
|
||||||
name = rule["name"]
|
name = rule["name"]
|
||||||
|
file_path = f"rules-mdc/{name}.mdc"
|
||||||
|
|
||||||
# Validate URL
|
# Create the GitHub API URL for the file
|
||||||
is_trusted, error_msg = utils.is_url_trusted(url)
|
api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{file_path}?ref={branch}"
|
||||||
if not is_trusted:
|
|
||||||
raise ValidationError(f"URL validation failed for {name}: {error_msg}")
|
|
||||||
|
|
||||||
# Create local file path
|
# Create local file path
|
||||||
local_path = temp_dir / f"{name}.mdc"
|
local_path = temp_dir / f"{name}.mdc"
|
||||||
@@ -186,18 +290,27 @@ def download_rule(
|
|||||||
# Respect rate limit
|
# Respect rate limit
|
||||||
rate_limiter.wait()
|
rate_limiter.wait()
|
||||||
|
|
||||||
# Download the file
|
# Download the file using GitHub API
|
||||||
response = session.get(url, timeout=DEFAULT_TIMEOUT)
|
response = session.get(api_url, timeout=DEFAULT_TIMEOUT)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
content = response.text
|
|
||||||
|
# Extract content from GitHub API response
|
||||||
|
data = response.json()
|
||||||
|
if "content" not in data:
|
||||||
|
raise ValidationError(f"GitHub API response doesn't contain file content for {name}")
|
||||||
|
|
||||||
|
# Decode base64 content
|
||||||
|
content = base64.b64decode(data["content"].replace("\n", "")).decode("utf-8")
|
||||||
|
|
||||||
# Validate content
|
# Validate content
|
||||||
is_valid, error_msg = utils.validate_mdc_content(content)
|
is_valid, error_msg = utils.validate_mdc_content(content)
|
||||||
if not is_valid:
|
if not is_valid:
|
||||||
|
logger.error(f"Content validation failed for {name}: {error_msg}")
|
||||||
raise ValidationError(f"Content validation failed: {error_msg}")
|
raise ValidationError(f"Content validation failed: {error_msg}")
|
||||||
|
|
||||||
# Calculate content hash before saving
|
# Calculate content hash before saving
|
||||||
content_hash = utils.calculate_content_hash(content)
|
content_hash = utils.calculate_content_hash(content)
|
||||||
|
logger.debug(f"Content hash for {name}: {content_hash}")
|
||||||
|
|
||||||
# Save the file
|
# Save the file
|
||||||
with open(local_path, "w", encoding="utf-8") as f:
|
with open(local_path, "w", encoding="utf-8") as f:
|
||||||
@@ -205,8 +318,23 @@ def download_rule(
|
|||||||
|
|
||||||
# Verify the saved file
|
# Verify the saved file
|
||||||
saved_hash = utils.calculate_file_hash(local_path)
|
saved_hash = utils.calculate_file_hash(local_path)
|
||||||
|
logger.debug(f"Saved file hash for {name}: {saved_hash}")
|
||||||
|
|
||||||
if saved_hash != content_hash:
|
if saved_hash != content_hash:
|
||||||
raise ValidationError("File integrity check failed")
|
logger.error(f"File integrity check failed for {name}. Content hash: {content_hash}, File hash: {saved_hash}")
|
||||||
|
# Fix: Read the file back and compare the content
|
||||||
|
with open(local_path, "r", encoding="utf-8") as f:
|
||||||
|
saved_content = f.read()
|
||||||
|
if content == saved_content:
|
||||||
|
logger.info(f"Content matches but hashes differ for {name}. This may be due to line ending differences. Proceeding anyway.")
|
||||||
|
# Update rule metadata and continue
|
||||||
|
rule["local_path"] = str(local_path)
|
||||||
|
rule["content"] = content
|
||||||
|
rule["hash"] = saved_hash # Use the file hash since that's what we'll verify against later
|
||||||
|
return rule
|
||||||
|
else:
|
||||||
|
logger.error(f"Content mismatch for {name}")
|
||||||
|
raise ValidationError("File integrity check failed")
|
||||||
|
|
||||||
# Update rule metadata
|
# Update rule metadata
|
||||||
rule["local_path"] = str(local_path)
|
rule["local_path"] = str(local_path)
|
||||||
@@ -249,18 +377,12 @@ def preview_rule_content(rule: Dict[str, Any], max_lines: int = 10) -> str:
|
|||||||
if "content" not in rule:
|
if "content" not in rule:
|
||||||
return "Content not available"
|
return "Content not available"
|
||||||
|
|
||||||
content = rule["content"]
|
lines = rule["content"].splitlines()
|
||||||
lines = content.split("\n")
|
|
||||||
|
|
||||||
if len(lines) <= max_lines:
|
if len(lines) <= max_lines:
|
||||||
return content
|
return rule["content"]
|
||||||
|
|
||||||
# Show first few lines and indicate there's more
|
# Show first few lines
|
||||||
preview_lines = lines[:max_lines]
|
return "\n".join(lines[:max_lines]) + f"\n... (and {len(lines) - max_lines} more lines)"
|
||||||
preview = "\n".join(preview_lines)
|
|
||||||
preview += f"\n... ({len(lines) - max_lines} more lines)"
|
|
||||||
|
|
||||||
return preview
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# For testing
|
# For testing
|
||||||
|
|||||||
@@ -83,8 +83,8 @@ def parse_args():
|
|||||||
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--source",
|
"--source",
|
||||||
default="https://raw.githubusercontent.com/sanjeed5/awesome-cursor-rules-mdc/main",
|
default="https://github.com/sanjeed5/awesome-cursor-rules-mdc",
|
||||||
help="Base URL for downloading rules"
|
help="GitHub repository URL for downloading rules"
|
||||||
)
|
)
|
||||||
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
@@ -271,18 +271,29 @@ def main():
|
|||||||
for rule in selected_rules:
|
for rule in selected_rules:
|
||||||
logger.info(f" - {Fore.CYAN}{rule}{Style.RESET_ALL}")
|
logger.info(f" - {Fore.CYAN}{rule}{Style.RESET_ALL}")
|
||||||
else:
|
else:
|
||||||
downloaded_rules = download_rules(selected_rules, config["source"])
|
try:
|
||||||
|
# Normalize source URL if needed (remove trailing slashes)
|
||||||
|
source_url = config["source"].rstrip('/')
|
||||||
|
|
||||||
# Install downloaded rules
|
# Log source information
|
||||||
result = install_rules(downloaded_rules, force=args.force)
|
logger.info(f"Using source URL: {source_url}")
|
||||||
|
|
||||||
if result["installed"]:
|
# Download selected rules
|
||||||
logger.info(f"{Fore.GREEN}✅ Successfully installed {len(result['installed'])} rules!{Style.RESET_ALL}")
|
downloaded_rules = download_rules(selected_rules, source_url)
|
||||||
|
|
||||||
if result["failed"]:
|
# Install downloaded rules
|
||||||
logger.warning(f"{Fore.YELLOW}⚠️ Failed to install {len(result['failed'])} rules:{Style.RESET_ALL}")
|
result = install_rules(downloaded_rules, force=args.force)
|
||||||
|
|
||||||
return 0
|
if result["installed"]:
|
||||||
|
logger.info(f"{Fore.GREEN}✅ Successfully installed {len(result['installed'])} rules!{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
if result["failed"]:
|
||||||
|
logger.warning(f"{Fore.YELLOW}⚠️ Failed to install {len(result['failed'])} rules:{Style.RESET_ALL}")
|
||||||
|
for rule in result["failed"]:
|
||||||
|
logger.warning(f" - {Fore.CYAN}{rule}{Style.RESET_ALL}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"An error occurred: {str(e)}")
|
||||||
|
return 1
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
logger.info(f"\n{Fore.YELLOW}Operation cancelled by user.{Style.RESET_ALL}")
|
logger.info(f"\n{Fore.YELLOW}Operation cancelled by user.{Style.RESET_ALL}")
|
||||||
@@ -432,7 +443,8 @@ def main():
|
|||||||
|
|
||||||
if result["failed"]:
|
if result["failed"]:
|
||||||
logger.warning(f"{Fore.YELLOW}⚠️ Failed to install {len(result['failed'])} rules:{Style.RESET_ALL}")
|
logger.warning(f"{Fore.YELLOW}⚠️ Failed to install {len(result['failed'])} rules:{Style.RESET_ALL}")
|
||||||
|
for rule in result["failed"]:
|
||||||
|
logger.warning(f" - {Fore.CYAN}{rule}{Style.RESET_ALL}")
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ def match_libraries(
|
|||||||
for rule in matched_rules:
|
for rule in matched_rules:
|
||||||
rule_name = rule.get("rule")
|
rule_name = rule.get("rule")
|
||||||
rule["name"] = rule_name
|
rule["name"] = rule_name
|
||||||
rule["url"] = f"{source_url}/rules-mdc/{rule_name}.mdc"
|
# We don't construct a URL here anymore - the downloader will handle this using GitHub API
|
||||||
|
|
||||||
# Mark direct matches
|
# Mark direct matches
|
||||||
if direct_match_libraries and rule_name.lower() in (lib.lower() for lib in direct_match_libraries):
|
if direct_match_libraries and rule_name.lower() in (lib.lower() for lib in direct_match_libraries):
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ def calculate_content_hash(content: str) -> str:
|
|||||||
Returns:
|
Returns:
|
||||||
SHA-256 hash as hex string
|
SHA-256 hash as hex string
|
||||||
"""
|
"""
|
||||||
|
# Normalize line endings to '\n'
|
||||||
|
content = content.replace('\r\n', '\n').replace('\r', '\n')
|
||||||
return hashlib.sha256(content.encode('utf-8')).hexdigest()
|
return hashlib.sha256(content.encode('utf-8')).hexdigest()
|
||||||
|
|
||||||
def get_cursor_dir() -> Path:
|
def get_cursor_dir() -> Path:
|
||||||
@@ -289,12 +291,15 @@ def calculate_file_hash(file_path: Path) -> Optional[str]:
|
|||||||
SHA-256 hash as a hex string, or None if failed
|
SHA-256 hash as a hex string, or None if failed
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
with open(file_path, "rb") as f:
|
# Read the file as text and normalize line endings
|
||||||
file_hash = hashlib.sha256()
|
with open(file_path, "r", encoding="utf-8") as f:
|
||||||
# Read in chunks to handle large files
|
content = f.read()
|
||||||
for chunk in iter(lambda: f.read(4096), b""):
|
|
||||||
file_hash.update(chunk)
|
# Normalize line endings to '\n'
|
||||||
return file_hash.hexdigest()
|
content = content.replace('\r\n', '\n').replace('\r', '\n')
|
||||||
|
|
||||||
|
# Calculate hash from normalized content
|
||||||
|
return hashlib.sha256(content.encode('utf-8')).hexdigest()
|
||||||
except IOError as e:
|
except IOError as e:
|
||||||
logger.error(f"Failed to calculate hash for {file_path}: {e}")
|
logger.error(f"Failed to calculate hash for {file_path}: {e}")
|
||||||
return None
|
return None
|
||||||
|
|||||||
Reference in New Issue
Block a user