1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/common/variations/variations_util.h"
10 #include "base/metrics/field_trial.h"
11 #include "base/strings/string_split.h"
12 #include "chrome/common/variations/fieldtrial_testing_config.h"
13 #include "components/variations/variations_associated_data.h"
14 #include "net/base/escape.h"
16 namespace chrome_variations
{
20 std::string
EscapeValue(const std::string
& value
) {
21 return net::UnescapeURLComponent(value
, net::UnescapeRule::URL_SPECIAL_CHARS
);
26 bool AssociateParamsFromString(const std::string
& varations_string
) {
27 // Format: Trial1.Group1:k1/v1/k2/v2,Trial2.Group2:k1/v1/k2/v2
28 for (const base::StringPiece
& experiment_group
: base::SplitStringPiece(
29 varations_string
, ",",
30 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
)) {
31 std::vector
<base::StringPiece
> experiment
= base::SplitStringPiece(
32 experiment_group
, ":", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
33 if (experiment
.size() != 2) {
34 DLOG(ERROR
) << "Experiment and params should be separated by ':'";
38 std::vector
<std::string
> group_parts
= base::SplitString(
39 experiment
[0], ".", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
40 if (group_parts
.size() != 2) {
41 DLOG(ERROR
) << "Study and group name should be separated by '.'";
45 std::vector
<std::string
> key_values
= base::SplitString(
46 experiment
[1], "/", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
47 if (key_values
.size() % 2 != 0) {
48 DLOG(ERROR
) << "Param name and param value should be separated by '/'";
52 std::map
<std::string
, std::string
> params
;
53 for (size_t i
= 0; i
< key_values
.size(); i
+= 2) {
54 std::string key
= EscapeValue(key_values
[i
]);
55 std::string value
= EscapeValue(key_values
[i
+ 1]);
58 std::string trial
= EscapeValue(group_parts
[0]);
59 std::string group
= EscapeValue(group_parts
[1]);
60 variations::AssociateVariationParams(trial
, group
, params
);
65 void AssociateParamsFromFieldTrialConfig(
66 const FieldTrialTestingConfig
& config
) {
67 for (size_t i
= 0; i
< config
.groups_size
; ++i
) {
68 const FieldTrialTestingGroup
& group
= config
.groups
[i
];
69 if (group
.params_size
!= 0) {
70 std::map
<std::string
, std::string
> params
;
71 for (size_t j
= 0; j
< group
.params_size
; ++j
) {
72 const FieldTrialGroupParams
& param
= group
.params
[j
];
73 params
[param
.key
] = param
.value
;
75 variations::AssociateVariationParams(group
.study
, group
.group_name
,
78 base::FieldTrialList::CreateFieldTrial(group
.study
, group
.group_name
);
82 void AssociateDefaultFieldTrialConfig() {
83 AssociateParamsFromFieldTrialConfig(kFieldTrialConfig
);
86 } // namespace chrome_variations