sapling/eden/cli/configinterpolator.py
Michael Bolin bfb89289b2 Upgrade tests to use Python 3.
Summary:
Presumably for historical reasons, we still had some tests hanging around with
`from __future__ import absolute_import` in the header even though all of our
tests should be Python 3. I converted these stragglers and added a smattering of
type annotations to enforce their Python 3-ness.

(Note: this ignores all push blocking failures!)

Reviewed By: simpkins

Differential Revision: D6464805

fbshipit-source-id: 6177d7663ab428a0dbbecb287f340d770679551d
2017-12-01 17:21:35 -08:00

45 lines
1.7 KiB
Python

#!/usr/bin/env python3
#
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
import configparser
from typing import Dict
class EdenConfigInterpolator(configparser.Interpolation):
''' Python provides a couple of interpolation options but neither
of them quite match the simplicity that we want. This class
will interpolate the keys of the provided map and replace
those tokens with the values from the map. There is no
recursion or referencing of values from other sections of
the config.
Limiting the scope interpolation makes it easier to replicate
this approach in the C++ implementation of the parser.
'''
def __init__(self, defaults) -> None:
self._defaults: Dict[str, str] = {}
''' pre-construct the token name that we're going to substitute.
eg: {"foo": "bar"} is stored as {"${foo}": "bar"} internally
'''
for k, v in defaults.items():
self._defaults['${' + k + '}'] = v
def _interpolate(self, value: str) -> str:
''' simple brute force replacement using the defaults that were
provided to us during construction '''
for k, v in self._defaults.items():
value = value.replace(k, v)
return value
def before_get(self, parser, section, option, value, defaults) -> str:
return self._interpolate(value)
def before_read(self, parser, section, option, value) -> str:
return self._interpolate(value)