1# Copyright (c) 2012 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
5from base64 import b64encode
6from hashlib import sha1
7import os
8
9def FormatKey(key):
10  '''Normalize a key by making sure it has a .html extension, and convert any
11  '.'s to '_'s.
12  '''
13  if key.endswith('.html'):
14    key = key[:-len('.html')]
15  safe_key = key.replace('.', '_')
16  return '%s.html' % safe_key
17
18def SanitizeAPIName(name):
19  '''Sanitizes API filenames that are in subdirectories.
20  '''
21  filename = os.path.splitext(name)[0].replace(os.sep, '_')
22  if 'experimental' in filename:
23    filename = 'experimental_' + filename.replace('experimental_', '')
24  return filename
25
26def StringIdentity(first, *more):
27  '''Creates a small hash of a string.
28  '''
29  def encode(string):
30    return b64encode(sha1(string).digest())
31  identity = encode(first)
32  for m in more:
33    identity = encode(identity + m)
34  return identity[:8]
35
36def MarkFirst(dicts):
37  '''Adds a property 'first' == True to the first element in a list of dicts.
38  '''
39  if len(dicts) > 0:
40    dicts[0]['first'] = True
41
42def MarkLast(dicts):
43  '''Adds a property 'last' == True to the last element in a list of dicts.
44  '''
45  if len(dicts) > 0:
46    dicts[-1]['last'] = True
47
48def MarkFirstAndLast(dicts):
49  '''Marks the first and last element in a list of dicts.
50  '''
51  MarkFirst(dicts)
52  MarkLast(dicts)
53
54def ToUnicode(data):
55  '''Returns the str |data| as a unicode object. It's expected to be utf8, but
56  there are also latin-1 encodings in there for some reason. Fall back to that.
57  '''
58  try:
59    return unicode(data, 'utf-8')
60  except:
61    return unicode(data, 'latin-1')
62