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.
13 from profile_chrome
import util
15 from pylib
import constants
17 sys
.path
.append(os
.path
.join(constants
.DIR_SOURCE_ROOT
,
21 # pylint: disable=F0401
22 from tracing_build
import trace2html
25 def _PackageTracesAsHtml(trace_files
, html_file
):
26 with codecs
.open(html_file
, mode
='w', encoding
='utf-8') as f
:
27 trace2html
.WriteHTMLForTracesToFile(trace_files
, f
)
28 for trace_file
in trace_files
:
32 def _CompressFile(host_file
, output
):
33 with gzip
.open(output
, 'wb') as out
, \
34 open(host_file
, 'rb') as input_file
:
35 out
.write(input_file
.read())
39 def _ArchiveFiles(host_files
, output
):
40 with zipfile
.ZipFile(output
, 'w', zipfile
.ZIP_DEFLATED
) as z
:
41 for host_file
in host_files
:
46 def _MergeTracesIfNeeded(trace_files
):
47 if len(trace_files
) <= 1:
50 for trace_file
in trace_files
:
51 with
open(trace_file
) as f
:
52 # Try to detect a JSON file cheaply since that's all we can merge.
57 json_data
= json
.load(f
)
60 merge_candidates
.append((trace_file
, json_data
))
61 if len(merge_candidates
) <= 1:
64 other_files
= [f
for f
in trace_files
65 if not f
in [c
[0] for c
in merge_candidates
]]
66 merged_file
, merged_data
= merge_candidates
[0]
67 for trace_file
, json_data
in merge_candidates
[1:]:
68 for key
, value
in json_data
.items():
69 if not merged_data
.get(key
) or json_data
[key
]:
70 merged_data
[key
] = value
73 with
open(merged_file
, 'w') as f
:
74 json
.dump(merged_data
, f
)
75 return [merged_file
] + other_files
78 def PackageTraces(trace_files
, output
=None, compress
=False, write_json
=False):
79 trace_files
= _MergeTracesIfNeeded(trace_files
)
81 html_file
= os
.path
.splitext(trace_files
[0])[0] + '.html'
82 _PackageTracesAsHtml(trace_files
, html_file
)
83 trace_files
= [html_file
]
85 if compress
and len(trace_files
) == 1:
86 result
= output
or trace_files
[0] + '.gz'
87 _CompressFile(trace_files
[0], result
)
88 elif len(trace_files
) > 1:
89 result
= output
or 'chrome-combined-trace-%s.zip' % util
.GetTraceTimestamp()
90 _ArchiveFiles(trace_files
, result
)
93 shutil
.move(trace_files
[0], result
)
95 result
= trace_files
[0]