projectfluent / fluent-rs

Rust implementation of Project Fluent
https://projectfluent.org
Apache License 2.0
1.08k stars 97 forks source link

Inconsistent and misleading? behavior for FluentArgs::set #271

Closed MathieuTricoire closed 1 year ago

MathieuTricoire commented 2 years ago

Hi,

There is an inconsistent result when we set an argument that already exists, but I think the main issue is that when we set an argument that already exists it doesn't replace the argument in the underlying Vec but it is added.

There is an example that show the issue and my proposition to fix that.

use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};

fn main() {
    let res = FluentResource::try_new(
        r#"
hello = Hello, { $user }.
hello-with-email-count = Hello, { $user }. You have { $emailCount } messages.
"#
        .to_string(),
    )
    .expect("Failed to parse FTL.");
    let mut bundle = FluentBundle::default();
    bundle.set_use_isolating(false);
    bundle.add_resource(res).expect("Failed to add a resource.");

    // simple hello
    let msg = bundle
        .get_message("hello")
        .expect("Failed to retrieve a message.");
    let value = msg.value().expect("Failed to retrieve a value.");

    let mut args = FluentArgs::new();
    args.set("user", "John");
    args.set("user", "Alice");
    let mut err = vec![];

    // Returns "Hello, John."
    assert_eq!(
        bundle.format_pattern(value, Some(&args), &mut err),
        "Hello, Alice."
    );

    // hello with email count
    let msg = bundle
        .get_message("hello-with-email-count")
        .expect("Failed to retrieve a message.");
    let value = msg.value().expect("Failed to retrieve a value.");

    let mut args = FluentArgs::new();
    args.set("user", "John");
    args.set("emailCount", 5);
    args.set("user", "Alice");
    args.set("emailCount", 7);
    let mut err = vec![];

    // Returns "Hello, Alice. You have 5 messages."
    assert_eq!(
        bundle.format_pattern(value, Some(&args), &mut err),
        "Hello, Alice. You have 7 messages."
    );
}