Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def generate_attestation_from_results(
# Save the attestation
try:
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
with open(output_path, 'w') as f:
with open(output_path, 'w', encoding="utf-8") as f:
f.write(output)
logger.info(f"Attestation saved to: {output_path}")
except OSError as e:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def _parse_go_mod(repo_path: str, declared: set[str]) -> None:


def _read_file(path: str) -> str:
with open(path, errors="ignore") as f:
with open(path, errors="ignore", encoding="utf-8") as f:
return f.read()


Expand Down
2 changes: 1 addition & 1 deletion packages/darnit-baseline/src/darnit_baseline/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1089,7 +1089,7 @@ def generate_threat_model(

target = repo_path / output_path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
target.write_text(content, encoding="utf-8")
return (
f"Threat model written to {output_path} ({len(content)} bytes, "
f"{len(emitted)} findings, {overflow.total} trimmed)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def check_pattern_not_found(
for file_path in repo.glob(file_pattern):
if file_path.is_file():
try:
content = file_path.read_text(errors="ignore")
content = file_path.read_text(errors="ignore", encoding="utf-8")
for pattern_name, regex in regex_patterns.items():
matches = re.findall(regex, content, re.MULTILINE)
if matches:
Expand Down Expand Up @@ -134,7 +134,7 @@ def check_pattern_found(
for file_path in repo.glob(file_pattern):
if file_path.is_file():
try:
content = file_path.read_text(errors="ignore")
content = file_path.read_text(errors="ignore", encoding="utf-8")
for pattern_name, regex in regex_patterns.items():
if re.search(regex, content, re.MULTILINE):
found[pattern_name] = True
Expand Down Expand Up @@ -589,7 +589,7 @@ def _create_readme(
source="testchecks",
)

readme_path.write_text(content)
readme_path.write_text(content, encoding="utf-8")
return RemediationResult(
control_id="TEST-DOC-01",
success=True,
Expand Down Expand Up @@ -641,7 +641,7 @@ def _create_gitignore(self, local_path: str, dry_run: bool) -> RemediationResult
source="testchecks",
)

gitignore_path.write_text(content)
gitignore_path.write_text(content, encoding="utf-8")
return RemediationResult(
control_id="TEST-IGN-01",
success=True,
Expand Down
8 changes: 4 additions & 4 deletions packages/darnit/src/darnit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ def cmd_init(args: argparse.Namespace) -> int:
# check = {{ adapter = "kusari" }}
'''

baseline_path.write_text(template)
baseline_path.write_text(template, encoding="utf-8")
logger.info(f"✓ Created {baseline_path}")
return 0

Expand Down Expand Up @@ -570,7 +570,7 @@ def cmd_install(args: argparse.Namespace) -> int:
config = {}
if settings_path.exists():
try:
config = json.loads(settings_path.read_text())
config = json.loads(settings_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in settings file: {settings_path}: {e}")
return 1
Expand All @@ -594,7 +594,7 @@ def cmd_install(args: argparse.Namespace) -> int:

try:
json.dumps(config) # validate before write
settings_path.write_text(json.dumps(config, indent=2) + "\n")
settings_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
except Exception as e:
logger.error(f"Failed to write settings file: {e}")
return 1
Expand Down Expand Up @@ -765,7 +765,7 @@ def cmd_harness(args: argparse.Namespace) -> int:
)
return int(HarnessExitCode.SETUP_ERROR)
try:
_tty_probe = open("/dev/tty", "r+", buffering=1) # noqa: SIM115
_tty_probe = open("/dev/tty", "r+", buffering=1, encoding="utf-8") # noqa: SIM115
_tty_probe.close()
except OSError as exc:
_emit_exit_summary(
Expand Down
4 changes: 2 additions & 2 deletions packages/darnit/src/darnit/config/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def discover_project_name(local_path: str) -> str | None:
try:
pkg_path = os.path.join(local_path, "package.json")
if os.path.exists(pkg_path):
with open(pkg_path) as f:
with open(pkg_path, encoding="utf-8") as f:
data = json.load(f)
if "name" in data:
return data["name"]
Expand Down Expand Up @@ -176,7 +176,7 @@ def discover_project_name(local_path: str) -> str | None:
try:
go_mod_path = os.path.join(local_path, "go.mod")
if os.path.exists(go_mod_path):
with open(go_mod_path) as f:
with open(go_mod_path, encoding="utf-8") as f:
first_line = f.readline().strip()
if first_line.startswith("module "):
module_path = first_line[7:].strip()
Expand Down
8 changes: 4 additions & 4 deletions packages/darnit/src/darnit/context/dot_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ def read(self) -> ProjectConfig:
yaml = YAML()
yaml.preserve_quotes = True

with open(self.project_yaml) as f:
with open(self.project_yaml, encoding="utf-8") as f:
data = yaml.load(f)

if data is None:
Expand Down Expand Up @@ -405,7 +405,7 @@ def _read_maintainers_into(self, config: ProjectConfig) -> None:
from ruamel.yaml import YAML

yaml = YAML()
with open(self.maintainers_yaml) as f:
with open(self.maintainers_yaml, encoding="utf-8") as f:
data = yaml.load(f)

if data is None:
Expand Down Expand Up @@ -905,7 +905,7 @@ def update(self, updates: dict[str, Any]) -> None:

# Read existing content or create new
if self.project_yaml.exists():
with open(self.project_yaml) as f:
with open(self.project_yaml, encoding="utf-8") as f:
data = yaml.load(f)
if data is None:
data = {}
Expand All @@ -918,7 +918,7 @@ def update(self, updates: dict[str, Any]) -> None:
self._deep_update(data, updates)

# Write back
with open(self.project_yaml, "w") as f:
with open(self.project_yaml, "w", encoding="utf-8") as f:
yaml.dump(data, f)

logger.info("Updated .project/project.yaml")
Expand Down
4 changes: 2 additions & 2 deletions packages/darnit/src/darnit/context/dot_project_org.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def _fetch_org_project(self, owner: str) -> ProjectConfig | None:
)

if project_content:
(project_dir / "project.yaml").write_text(project_content)
(project_dir / "project.yaml").write_text(project_content, encoding="utf-8")
else:
logger.debug("No project.yaml found in %s/.project", owner)
return None
Expand All @@ -182,7 +182,7 @@ def _fetch_org_project(self, owner: str) -> ProjectConfig | None:
owner, ".project/maintainers.yaml"
)
if maintainers_content:
(project_dir / "maintainers.yaml").write_text(maintainers_content)
(project_dir / "maintainers.yaml").write_text(maintainers_content, encoding="utf-8")

# Parse using existing reader
reader = DotProjectReader(tmpdir)
Expand Down
14 changes: 7 additions & 7 deletions packages/darnit/src/darnit/context/sieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def _detect_maintainers_deterministic(self, local_path: str) -> list[ContextSign
filepath = path / filename
if filepath.exists():
try:
content = filepath.read_text()
content = filepath.read_text(encoding="utf-8")
maintainers = self._parse_maintainers_file(content)
if maintainers:
signals.append(ContextSignal(
Expand All @@ -251,7 +251,7 @@ def _detect_maintainers_deterministic(self, local_path: str) -> list[ContextSign
filepath = path / codeowners_path
if filepath.exists():
try:
content = filepath.read_text()
content = filepath.read_text(encoding="utf-8")
owners = self._parse_codeowners(content)
if owners:
signals.append(ContextSignal(
Expand Down Expand Up @@ -282,7 +282,7 @@ def _detect_maintainers_heuristic(self, local_path: str) -> list[ContextSignal]:
package_json = path / "package.json"
if package_json.exists():
try:
data = json.loads(package_json.read_text())
data = json.loads(package_json.read_text(encoding="utf-8"))
authors = []

# Get author
Expand Down Expand Up @@ -332,7 +332,7 @@ def _detect_maintainers_heuristic(self, local_path: str) -> list[ContextSignal]:

if tomllib:
try:
data = tomllib.loads(pyproject.read_text())
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
authors = []

# Get authors from [project] section
Expand Down Expand Up @@ -437,7 +437,7 @@ def _detect_security_contact_deterministic(self, local_path: str) -> list[Contex
filepath = path / filename
if filepath.exists():
try:
content = filepath.read_text()
content = filepath.read_text(encoding="utf-8")
contact = self._parse_security_contact(content)
if contact:
signals.append(ContextSignal(
Expand All @@ -462,7 +462,7 @@ def _detect_security_contact_heuristic(self, local_path: str) -> list[ContextSig
filepath = path / filename
if filepath.exists():
try:
content = filepath.read_text()
content = filepath.read_text(encoding="utf-8")
# Look for security section
security_section = re.search(
r"(?:^|\n)#+\s*Security[^\n]*\n([\s\S]*?)(?=\n#+|\Z)",
Expand Down Expand Up @@ -498,7 +498,7 @@ def _detect_governance_deterministic(self, local_path: str) -> list[ContextSigna
filepath = path / filename
if filepath.exists():
try:
content = filepath.read_text()
content = filepath.read_text(encoding="utf-8")
model = self._parse_governance_model(content)
if model:
signals.append(ContextSignal(
Expand Down
4 changes: 2 additions & 2 deletions packages/darnit/src/darnit/core/audit_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def write_audit_cache(
# Atomic write: write to temp file in same directory, then rename.
fd, tmp_path = tempfile.mkstemp(dir=str(cache_dir), suffix=".tmp", prefix="audit-cache-")
try:
with os.fdopen(fd, "w") as f:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(envelope, f, indent=2)
os.replace(tmp_path, str(cache_path))
logger.debug("Wrote audit cache to %s", cache_path)
Expand Down Expand Up @@ -167,7 +167,7 @@ def read_audit_cache(local_path: str, ttl_seconds: int = 3600) -> dict[str, Any]

# Parse JSON
try:
with open(cache_path) as f:
with open(cache_path, encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, OSError) as exc:
logger.debug("Corrupt or unreadable audit cache: %s", exc)
Expand Down
2 changes: 1 addition & 1 deletion packages/darnit/src/darnit/core/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ class TemplateInfo:
def load_content(self) -> str:
"""Load template content from file."""
if self.content is None:
self.content = self.path.read_text()
self.content = self.path.read_text(encoding="utf-8")
return self.content


Expand Down
4 changes: 2 additions & 2 deletions packages/darnit/src/darnit/core/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def get(self, package_name: str, version: str) -> VerificationResult | None:
return None

try:
with open(cache_path) as f:
with open(cache_path, encoding="utf-8") as f:
data = json.load(f)

# Check expiration
Expand Down Expand Up @@ -298,7 +298,7 @@ def set(
"version": version,
}

with open(cache_path, "w") as f:
with open(cache_path, "w", encoding="utf-8") as f:
json.dump(data, f)

logger.debug(f"Cached verification result for {package_name}:{version}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def _ensure_streams(self) -> tuple[TextIO, TextIO]:
from darnit.harness.driver import HarnessSetupError

try:
self._tty = open("/dev/tty", "r+", buffering=1) # noqa: SIM115
self._tty = open("/dev/tty", "r+", buffering=1, encoding="utf-8") # noqa: SIM115
except OSError as exc:
raise HarnessSetupError(
"interactive channel unavailable (/dev/tty not openable): "
Expand Down
2 changes: 1 addition & 1 deletion packages/darnit/src/darnit/remediation/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ def _get_template_content(self, template_name: str) -> str | None:
) from err

try:
with open(resolved) as f:
with open(resolved, encoding="utf-8") as f:
return f.read()
except OSError as e:
logger.warning(f"Failed to read template file {resolved}: {e}")
Expand Down
2 changes: 1 addition & 1 deletion packages/darnit/src/darnit/remediation/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def write_file_safe(path: str, content: str) -> tuple[bool, str]:
Tuple of (success: bool, message: str)
"""
try:
with open(path, 'w') as f:
with open(path, 'w', encoding="utf-8") as f:
f.write(content)
return True, f"Successfully wrote {path}"
except OSError as e:
Expand Down
6 changes: 3 additions & 3 deletions packages/darnit/src/darnit/server/tools/test_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def create_test_repository_impl(
}
}
"""
with open(os.path.join(repo_path, "package.json"), "w") as f:
with open(os.path.join(repo_path, "package.json"), "w", encoding="utf-8") as f:
f.write(package_json)

# Create src/index.js
Expand All @@ -67,15 +67,15 @@ def create_test_repository_impl(
console.log('Run an OpenSSF Baseline audit to see what is missing:');
console.log(chalk.cyan(' audit_openssf_baseline(local_path=".")'));
"""
with open(os.path.join(repo_path, "src", "index.js"), "w") as f:
with open(os.path.join(repo_path, "src", "index.js"), "w", encoding="utf-8") as f:
f.write(index_js)

# Create minimal .gitignore (intentionally missing security exclusions)
gitignore = """# Intentionally minimal .gitignore for testing
# This is MISSING important security exclusions!
node_modules/
"""
with open(os.path.join(repo_path, ".gitignore"), "w") as f:
with open(os.path.join(repo_path, ".gitignore"), "w", encoding="utf-8") as f:
f.write(gitignore)

# Initialize git
Expand Down
Loading
Loading