Add detectors module
This commit is contained in:
77
i18n_guardian/detectors/react_intl.py
Normal file
77
i18n_guardian/detectors/react_intl.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""React Intl detector."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from i18n_guardian.detectors.base import Detector
|
||||
|
||||
|
||||
class ReactIntlDetector(Detector):
|
||||
"""Detect React Intl (react-intl) library usage."""
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "react-intl"
|
||||
|
||||
@property
|
||||
def patterns(self) -> list:
|
||||
return ["package.json", "webpack.config.js", ".babelrc", ".babelrc.js"]
|
||||
|
||||
def detect(self, path: Path) -> Optional[str]:
|
||||
"""Check for React Intl usage."""
|
||||
package_json = path / "package.json"
|
||||
if package_json.exists():
|
||||
try:
|
||||
with open(package_json, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
dependencies = data.get("dependencies", {})
|
||||
dev_dependencies = data.get("devDependencies", {})
|
||||
all_deps = {**dependencies, **dev_dependencies}
|
||||
if "react-intl" in all_deps or "格式化消息" in str(all_deps):
|
||||
return self.name
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
|
||||
webpack_config = path / "webpack.config.js"
|
||||
if webpack_config.exists():
|
||||
try:
|
||||
content = webpack_config.read_text(encoding="utf-8")
|
||||
if "react-intl" in content or "FormattedMessage" in content:
|
||||
return self.name
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
babelrc = path / ".babelrc"
|
||||
if babelrc.exists():
|
||||
try:
|
||||
with open(babelrc, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
if "react-intl" in content:
|
||||
return self.name
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
|
||||
for js_file in path.rglob("*.js"):
|
||||
try:
|
||||
content = js_file.read_text(encoding="utf-8")
|
||||
if "import { defineMessages } from 'react-intl'" in content or "import { FormattedMessage } from 'react-intl'" in content:
|
||||
return self.name
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
return None
|
||||
|
||||
def get_i18n_functions(self) -> list:
|
||||
"""Get React Intl function names."""
|
||||
return [
|
||||
"formatMessage",
|
||||
"defineMessages",
|
||||
"FormattedMessage",
|
||||
"FormattedDate",
|
||||
"FormattedTime",
|
||||
"FormattedRelativeTime",
|
||||
"FormattedNumber",
|
||||
"FormattedPlural",
|
||||
"FormattedHTMLMessage",
|
||||
]
|
||||
Reference in New Issue
Block a user