1# Copyright 2016 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.
4
5import json
6import logging
7
8from telemetry.internal.results import output_formatter
9
10
11class HistogramSetJsonOutputFormatter(output_formatter.OutputFormatter):
12  def __init__(self, output_stream, metadata, reset_results):
13    super(HistogramSetJsonOutputFormatter, self).__init__(output_stream)
14    self._metadata = metadata
15    self._reset_results = reset_results
16
17  def Format(self, page_test_results):
18    histograms = page_test_results.AsHistogramDicts(self._metadata)
19    self._output_stream.seek(0)
20    if not self._reset_results:
21      existing = self._output_stream.read()
22      self._output_stream.seek(0)
23      if existing:
24        try:
25          histograms += json.loads(existing)
26        except ValueError:
27          logging.warn('Found existing histograms json but failed to parse it.')
28    json.dump(histograms, self._output_stream)
29