feat: Add safe_read_json and safe_write_json functions to aider/utils.py

This commit is contained in:
Paul Gauthier (aider) 2024-08-25 07:55:02 -07:00
parent fb812acfe1
commit 7f1f2cb7ba
2 changed files with 20 additions and 0 deletions

View file

@ -5,7 +5,9 @@ import math
import os import os
import platform import platform
import sys import sys
import time
from dataclasses import dataclass, fields from dataclasses import dataclass, fields
from pathlib import Path
from typing import Optional from typing import Optional
import yaml import yaml
@ -14,6 +16,7 @@ from PIL import Image
from aider import urls from aider import urls
from aider.dump import dump # noqa: F401 from aider.dump import dump # noqa: F401
from aider.llm import AIDER_APP_NAME, AIDER_SITE_URL, litellm from aider.llm import AIDER_APP_NAME, AIDER_SITE_URL, litellm
from aider.utils import safe_read_json, safe_write_json
DEFAULT_MODEL_NAME = "gpt-4o" DEFAULT_MODEL_NAME = "gpt-4o"
ANTHROPIC_BETA_HEADER = "max-tokens-3-5-sonnet-2024-07-15,prompt-caching-2024-07-31" ANTHROPIC_BETA_HEADER = "max-tokens-3-5-sonnet-2024-07-15,prompt-caching-2024-07-31"

View file

@ -80,6 +80,8 @@ def make_repo(path=None):
return repo return repo
import json
def is_image_file(file_name): def is_image_file(file_name):
""" """
Check if the given file name has an image file extension. Check if the given file name has an image file extension.
@ -90,6 +92,21 @@ def is_image_file(file_name):
file_name = str(file_name) # Convert file_name to string file_name = str(file_name) # Convert file_name to string
return any(file_name.endswith(ext) for ext in IMAGE_EXTENSIONS) return any(file_name.endswith(ext) for ext in IMAGE_EXTENSIONS)
def safe_read_json(file_path):
try:
with open(file_path, 'r') as f:
return json.load(f)
except Exception:
return None
def safe_write_json(file_path, data):
try:
with open(file_path, 'w') as f:
json.dump(data, f)
return True
except Exception:
return False
def safe_abs_path(res): def safe_abs_path(res):
"Gives an abs path, which safely returns a full (not 8.3) windows path" "Gives an abs path, which safely returns a full (not 8.3) windows path"