• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright 2013 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import sys
7
8def main():
9  """Converts a vertical serialization into a compact, horizontal serialization.
10  """
11
12  COLUMNS = ['First name', 'Middle name', 'Last name', 'Email', 'Company name',
13             'Address line 1', 'Address line 2', 'City', 'State', 'ZIP code',
14             'Country', 'Phone']
15
16  if len(sys.argv) != 2:
17    print "Usage: python flatten.py <path/to/serialized_profiles>"
18    return
19
20  profiles = [COLUMNS]
21  with open(sys.argv[1], 'r') as serialized_profiles:
22    profile = []
23    previous_field_type = ''
24    for line in serialized_profiles:
25      # Trim the newline if present.
26      if line[-1] == '\n':
27        line = line[:-1]
28
29      if line == "---":
30        if len(profile):
31          # Reached the end of a profile.
32          # Save the current profile and prepare to build up the next one.
33          profiles.append(profile)
34          profile = []
35      else:
36        # Append the current field's value to the current profile.
37        line_parts = line.split(': ', 1)
38        field_type = line_parts[0]
39        field_value = line_parts[1]
40        if field_type != previous_field_type:
41          profile.append("'%s'" % field_value)
42        else:
43          # This is a non-primary value for a multi-valued field.
44          profile[-1] += ", '%s'" % field_value
45        previous_field_type = field_type
46
47    if len(profile):
48      profiles.append(profile)
49
50  # Prepare format strings so that we can align the contents of each column.
51  transposed = zip(*profiles)
52  column_widths = []
53  for column in transposed:
54    widths = [len(value) for value in column]
55    column_widths.append(max(widths))
56  column_formats = ["{0:<" + str(width) + "}" for width in column_widths]
57
58  for profile in profiles:
59    profile_format = zip(column_formats, profile)
60    profile = [format_.format(value) for (format_, value) in profile_format]
61    print " | ".join(profile)
62  return 0
63
64
65if __name__ == '__main__':
66  sys.exit(main())
67