تُعد متغيرات البيئة المضبوطة بشكل خاطئ سببًا رئيسيًا لأعطال "يعمل على جهازي" وعمليات النشر المعطّلة. يتحقق هذا السكربت من ملف .env مقابل مخطط JSON صغير يحدد المتغيرات المطلوبة وأنواعها المتوقعة (int أو bool أو url أو string) وقيمة افتراضية اختيارية وحدًا أدنى للطول. يحلل الملف بأمان متجاهلًا التعليقات والأسطر الفارغة، ويزيل علامات الاقتباس المحيطة، وينبّه على الأسطر المشوّهة. ثم تُطبّق كل قاعدة: المفاتيح المطلوبة المفقودة، والأنواع الخاطئة، والقيم الأقصر من الحد الأدنى، وكلها تنتج رسائل خطأ واضحة ومفصّلة. أما المتغيرات الموجودة وغير الموصوفة في المخطط فتولّد ملاحظة لطيفة تساعدك على رصد الإعدادات الزائدة أو المهملة. يخرج السكربت برمز حالة غير صفري عند فشل التحقق، فتستطيع ربطه مباشرة بخط CI أو بنقطة دخول حاوية كبوابة تحقق مسبقة. يعتمد على المكتبة القياسية فقط.
التحقق من ملف .env مقابل مخطط
التأكد من أن ملف .env يحتوي على كل المتغيرات المطلوبة بالأنواع الصحيحة قبل بدء تشغيل التطبيق.
16 مشاهدة
مشاركة
السكربت
تحميل .pypython
#!/usr/bin/env python3
"""Validate a .env file against a JSON schema of expected variables.
Schema example (schema.json):
{
"DATABASE_URL": {"required": true, "type": "url"},
"PORT": {"required": true, "type": "int"},
"DEBUG": {"required": false, "type": "bool", "default": "false"},
"API_KEY": {"required": true, "type": "string", "min_length": 10}
}
Pure standard library; no external dependencies.
"""
import argparse
import json
import re
import sys
URL_RE = re.compile(r"^https?://|^[a-z][a-z0-9+.-]*://", re.IGNORECASE)
BOOL_VALUES = {"true", "false", "1", "0", "yes", "no"}
def parse_env(path):
"""Parse a .env file into a dict, ignoring blanks and comments."""
values = {}
with open(path, encoding="utf-8") as f:
for lineno, raw in enumerate(f, start=1):
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
print(f" warning: line {lineno} has no '=' -> ignored")
continue
key, _, val = line.partition("=")
key = key.strip()
val = val.strip().strip('"').strip("'")
values[key] = val
return values
def check_type(value, expected):
"""Return an error string if value does not match expected type."""
if expected == "int":
if not re.fullmatch(r"-?\d+", value):
return "expected an integer"
elif expected == "bool":
if value.lower() not in BOOL_VALUES:
return "expected a boolean (true/false)"
elif expected == "url":
if not URL_RE.match(value):
return "expected a URL"
elif expected == "string":
return None
return None
def validate(env, schema):
"""Return a list of error messages (empty list means valid)."""
errors = []
for name, rules in schema.items():
present = name in env and env[name] != ""
if not present:
if rules.get("required", False):
errors.append(f"{name}: missing required variable")
continue
value = env[name]
type_err = check_type(value, rules.get("type", "string"))
if type_err:
errors.append(f"{name}: {type_err} (got '{value}')")
min_len = rules.get("min_length")
if min_len is not None and len(value) < min_len:
errors.append(f"{name}: shorter than min_length {min_len}")
# Warn about unknown variables not described in the schema.
for name in env:
if name not in schema:
print(f" note: '{name}' is set but not in schema")
return errors
def main():
parser = argparse.ArgumentParser(description="Validate a .env file.")
parser.add_argument("env_file", help="Path to the .env file.")
parser.add_argument("schema_file", help="Path to the JSON schema file.")
args = parser.parse_args()
with open(args.schema_file, encoding="utf-8") as f:
schema = json.load(f)
env = parse_env(args.env_file)
errors = validate(env, schema)
if errors:
print(f"\nVALIDATION FAILED ({len(errors)} error(s)):")
for err in errors:
print(f" - {err}")
sys.exit(1)
print("\nVALIDATION PASSED: .env matches the schema.")
if __name__ == "__main__":
main()كيفية التشغيل
راجع السكربت أولاً، ثم حمّله أو انسخه وشغّله في بيئتك.
قد يعجبك أيضاً
pythoncross-platformمتوسط
حاسبة موعد التشغيل التالي لتعبير cron
عند إعطاء تعبير cron يطبع المواعيد التالية لتشغيله مع العد التنازلي لكل منها.
bashlinuxمتوسط
نسخ احتياطي لكل قواعد بيانات PostgreSQL باستخدام pg_dumpall
يُفرغ عنقود PostgreSQL كاملاً، مع الأدوار، في ملف مضغوط واحد.
bashlinuxمتقدم
تنظيف صور AMI واللقطات القديمة
إلغاء تسجيل صور AMI القديمة بعد فترة الاحتفاظ وحذف لقطات EBS الداعمة لها.