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
10 changes: 5 additions & 5 deletions src/filters/dates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,14 +477,14 @@ fn render_program(items: &[Piece], f: &Fields) -> String {
/// no key allocation on a hit.
struct Cache {
lang: String,
i18n: bool,
real: u8,
programs: HashMap<String, Vec<Piece>>,
}

thread_local! {
static CACHE: RefCell<Cache> = RefCell::new(Cache {
lang: String::new(),
i18n: false,
real: 0,
programs: HashMap::new(),
});
}
Expand Down Expand Up @@ -582,13 +582,13 @@ fn run_program(py: Python<'_>, fmt: &str, fields: &Fields) -> PyResult<Option<St
let Some(state) = trans_state(py) else {
return Ok(None);
};
let (lang, i18n) = (state.lang, state.i18n);
let (lang, real) = (state.lang, state.real);
// Cache hit fast path: rendering is pure Rust (no Python re-entry), so
// the borrow may be held.
let hit = CACHE.with(|c| {
let mut c = c.borrow_mut();
if c.i18n != i18n || c.lang != lang {
c.i18n = i18n;
if c.real != real || c.lang != lang {
c.real = real;
c.lang.clone_from(&lang);
c.programs.clear();
}
Expand Down
22 changes: 14 additions & 8 deletions src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,11 @@ pub(crate) fn is_err<T: PyTypeInfo>(py: Python<'_>, e: &PyErr) -> bool {
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct TransState {
pub lang: String,
pub i18n: bool,
/// Bit 0: `gettext` resolved to `trans_real`; bit 1: `pgettext` did.
/// `_trans` resolves each function independently (on first use, by the
/// `USE_I18N` of that moment), so they can disagree after
/// `override_settings(USE_I18N=...)`; month/weekday tables mix both.
pub real: u8,
}

/// Live `(language, USE_I18N)` snapshot.
Expand All @@ -184,14 +188,16 @@ pub(crate) struct TransState {
/// covers `trans_null`, which ignores `_active` entirely; see `trans_impl`).
/// Any unexpected shape → `None`; callers then fall back to the Python path.
pub(crate) fn trans_state(py: Python<'_>) -> Option<TransState> {
let i18n = match trans_impl(py, "gettext")? {
TransImpl::Real => true,
TransImpl::Null => false,
};
if !i18n {
let mut real = 0u8;
for (bit, name) in [(1u8, "gettext"), (2u8, "pgettext")] {
if let TransImpl::Real = trans_impl(py, name)? {
real |= bit;
}
}
if real == 0 {
return Some(TransState {
lang: String::new(),
i18n: false,
real,
});
}
// The catalog `trans_real.gettext` uses: the active translation, else
Expand All @@ -204,7 +210,7 @@ pub(crate) fn trans_state(py: Python<'_>) -> Option<TransState> {
CvarLang::Unset => setting(py, "LANGUAGE_CODE")?.extract().ok()?,
CvarLang::Unknown => return None,
};
Some(TransState { lang, i18n: true })
Some(TransState { lang, real })
}

/// Live `settings.<name>`.
Expand Down
20 changes: 20 additions & 0 deletions tests/test_realpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,23 @@ def test_dates_after_deactivate_all():
with translation.override(None, deactivate=True):
translation.deactivate_all()
assert_parity(src, {"d": AWARE})


def test_dates_mixed_trans_resolution():
"""`_trans` resolves each function once, by `USE_I18N` at first use, and
never re-resolves. With `gettext` pinned to `trans_null` but `pgettext`
still unresolved, a later `USE_I18N=True` run mixes both (`N` uses
`pgettext_lazy`); cached programs must not leak across languages."""
from django.utils.translation import _trans

saved = dict(_trans.__dict__)
try:
_trans.__dict__.clear()
with override_settings(USE_I18N=False):
translation.gettext("x") # pins gettext to trans_null
with override_settings(USE_I18N=True):
for lang in (None, "de", "ja", "de"):
assert_parity('{{ d|date:"N F" }}', {"d": AWARE}, lang=lang)
finally:
_trans.__dict__.clear()
_trans.__dict__.update(saved)
Loading