Skip to content

Commit

Permalink
Make flags_into_string deterministic.
Browse files Browse the repository at this point in the history
This is (1) to match the c++ behavior and (2) so that build based upon the flag
values are also deterministic.

PiperOrigin-RevId: 222884822
  • Loading branch information
rickeylev authored and Copybara-Service committed Nov 26, 2018
1 parent 1193ccf commit 910aa92
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
10 changes: 7 additions & 3 deletions absl/flags/_flagvalues.py
Original file line number Diff line number Diff line change
Expand Up @@ -1178,11 +1178,15 @@ def flags_into_string(self):
Returns:
str, the string with the flags assignments from this FlagValues object.
The flags are ordered by (module_name, flag_name).
"""
module_flags = sorted(self.flags_by_module_dict().items())
s = ''
for flag in self._flags().values():
if flag.value is not None:
s += flag.serialize() + '\n'
for unused_module_name, flags in module_flags:
flags = sorted(flags, key=lambda f: f.name)
for flag in flags:
if flag.value is not None:
s += flag.serialize() + '\n'
return s

def append_flags_into_file(self, filename):
Expand Down
28 changes: 28 additions & 0 deletions absl/flags/tests/_flagvalues_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from __future__ import division
from __future__ import print_function

import collections
import copy
import pickle
import types
Expand Down Expand Up @@ -526,6 +527,33 @@ def test_flags_dir(self):
self.assertEqual(
sorted([flag_name1, flag_name2, flag_name3]), dir(flag_values))

def test_flags_into_string_deterministic(self):
flag_values = _flagvalues.FlagValues()
_defines.DEFINE_string(
'fa', 'x', '', flag_values=flag_values, module_name='mb')
_defines.DEFINE_string(
'fb', 'x', '', flag_values=flag_values, module_name='mb')
_defines.DEFINE_string(
'fc', 'x', '', flag_values=flag_values, module_name='ma')
_defines.DEFINE_string(
'fd', 'x', '', flag_values=flag_values, module_name='ma')

expected = ('--fc=x\n'
'--fd=x\n'
'--fa=x\n'
'--fb=x\n')

flags_by_module_items = sorted(
flag_values.flags_by_module_dict().items(), reverse=True)
for _, module_flags in flags_by_module_items:
module_flags.sort(reverse=True)

flag_values.__dict__['__flags_by_module'] = collections.OrderedDict(
flags_by_module_items)

actual = flag_values.flags_into_string()
self.assertEqual(expected, actual)


class FlagValuesLoggingTest(absltest.TestCase):
"""Test to make sure logging.* functions won't recurse.
Expand Down

0 comments on commit 910aa92

Please sign in to comment.