Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix override str util function to handle new lines and quotes correctly #2974

Merged
merged 1 commit into from
Oct 28, 2024
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
3 changes: 3 additions & 0 deletions hydra/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,7 @@ def to_hydra_override_value_str(obj: Any) -> str:
return (
"[" + ", ".join([to_hydra_override_value_str(value) for value in obj]) + "]"
)
elif isinstance(obj, str):
new_str = obj.replace('\\"', '\\\\"').replace('"', '\\"')
return f'"{new_str}"'
return json.dumps(obj)
30 changes: 20 additions & 10 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import io
import json
import os
import re
from pathlib import Path
Expand All @@ -15,6 +16,7 @@
from hydra._internal.utils import run_and_report
from hydra.conf import HydraConf, RuntimeConf
from hydra.core.hydra_config import HydraConfig
from hydra.core.override_parser.overrides_parser import OverridesParser
from hydra.errors import HydraDeprecationError
from hydra.test_utils.test_utils import (
assert_multiline_regex_search,
Expand Down Expand Up @@ -74,22 +76,30 @@ def test_to_absolute_path_without_hydra(


@mark.parametrize(
"obj, expected",
"obj",
[
("foo bar", '"foo bar"'),
(10, "10"),
({"foo": '\\"bar'}, '{foo: "\\\\\\"bar"}'),
([1, 2, "3", {"a": "xyz"}], '[1, 2, "3", {a: "xyz"}]'),
("foo bar"),
(10),
({"foo": '\\"bar\\\'"'}),
([1, 2, "3", {"a": "xyz"}]),
({"a": 10, "b": "c", "d": {"e": [1, 2, "3"], "f": ["g", {"h": {"i": "j"}}]}}),
(
{"a": 10, "b": "c", "d": {"e": [1, 2, "3"], "f": ["g", {"h": {"i": "j"}}]}},
'{a: 10, b: "c", d: {e: [1, 2, "3"], f: ["g", {h: {i: "j"}}]}}',
{
"a": 10,
"b": "c\nnl",
"d": {"e": [1, 2, "3"], "f": ["g", {"h": {"i": "j"}}]},
}
),
({"json_val": json.dumps({"a": 10, "b": "c\\\nnl"}, indent=4)}),
],
)
def test_to_hydra_override_value_str(
hydra_restore_singletons: Any, obj: Any, expected: str
def test_to_hydra_override_value_str_roundtrip(
hydra_restore_singletons: Any, obj: Any
) -> None:
assert utils.to_hydra_override_value_str(obj) == expected
override_str = utils.to_hydra_override_value_str(obj)
override_params = f"++ov={override_str}"
o = OverridesParser.create().parse_override(override_params)
assert o.value() == obj


@mark.parametrize(
Expand Down
Loading