aboutsummaryrefslogtreecommitdiffhomepage
path: root/infra/bots/win_toolchain_utils.py
blob: f8033e925bbdbd729199772d3adff95b38b35e05 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
#
# Copyright 2016 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


"""Utilities for manipulating the win_toolchain.json file."""


import json
import os
import stat


PLACEHOLDER = '<(TOOLCHAIN_BASE_DIR)'


def _replace_prefix(val, before, after):
  """Replace the given prefix with the given string."""
  if val.startswith(before):
    return val.replace(before, after, 1)
  return val


def _replace(val, before, after):
  """Replace occurrences of one string with another within the data."""
  if isinstance(val, basestring):
    return _replace_prefix(val, before, after)
  elif isinstance(val, (list, tuple)):
    return [_replace(elem, before, after) for elem in val]
  elif isinstance(val, dict):
    return {_replace(k, before, after):
            _replace(v, before, after) for k, v in val.iteritems()}
  raise Exception('Cannot replace variable: %s' % val)


def _replace_in_file(filename, before, after):
  """Replace occurrences of one string with another within the file."""
  # Make the file writeable, or the below won't work.
  os.chmod(filename, stat.S_IWRITE)

  with open(filename) as f:
    contents = json.load(f)
  new_contents = _replace(contents, before, after)
  with open(filename, 'w') as f:
    json.dump(new_contents, f)


def abstract(win_toolchain_json, old_path):
  """Replace absolute paths in win_toolchain.json with placeholders."""
  _replace_in_file(win_toolchain_json, old_path, PLACEHOLDER)


def resolve(win_toolchain_json, new_path):
  """Replace placeholders in win_toolchain.json with absolute paths."""
  _replace_in_file(win_toolchain_json, PLACEHOLDER, new_path)