blob: f8033e925bbdbd729199772d3adff95b38b35e05 [file] [log] [blame]
borenet2f56b1a2016-03-11 04:54:42 -08001#!/usr/bin/env python
2#
3# Copyright 2016 Google Inc.
4#
5# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8
9"""Utilities for manipulating the win_toolchain.json file."""
10
11
12import json
borenet64e98162016-03-17 09:01:33 -070013import os
14import stat
borenet2f56b1a2016-03-11 04:54:42 -080015
16
17PLACEHOLDER = '<(TOOLCHAIN_BASE_DIR)'
18
19
20def _replace_prefix(val, before, after):
21 """Replace the given prefix with the given string."""
22 if val.startswith(before):
23 return val.replace(before, after, 1)
24 return val
25
26
27def _replace(val, before, after):
28 """Replace occurrences of one string with another within the data."""
29 if isinstance(val, basestring):
30 return _replace_prefix(val, before, after)
31 elif isinstance(val, (list, tuple)):
32 return [_replace(elem, before, after) for elem in val]
33 elif isinstance(val, dict):
34 return {_replace(k, before, after):
35 _replace(v, before, after) for k, v in val.iteritems()}
36 raise Exception('Cannot replace variable: %s' % val)
37
38
39def _replace_in_file(filename, before, after):
40 """Replace occurrences of one string with another within the file."""
borenet64e98162016-03-17 09:01:33 -070041 # Make the file writeable, or the below won't work.
42 os.chmod(filename, stat.S_IWRITE)
43
borenet2f56b1a2016-03-11 04:54:42 -080044 with open(filename) as f:
45 contents = json.load(f)
46 new_contents = _replace(contents, before, after)
47 with open(filename, 'w') as f:
48 json.dump(new_contents, f)
49
50
51def abstract(win_toolchain_json, old_path):
52 """Replace absolute paths in win_toolchain.json with placeholders."""
53 _replace_in_file(win_toolchain_json, old_path, PLACEHOLDER)
54
55
56def resolve(win_toolchain_json, new_path):
57 """Replace placeholders in win_toolchain.json with absolute paths."""
58 _replace_in_file(win_toolchain_json, PLACEHOLDER, new_path)