Home | History | Annotate | Download | only in bots
      1 #!/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 
     12 import json
     13 import os
     14 import stat
     15 
     16 
     17 PLACEHOLDER = '<(TOOLCHAIN_BASE_DIR)'
     18 
     19 
     20 def _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 
     27 def _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 
     39 def _replace_in_file(filename, before, after):
     40   """Replace occurrences of one string with another within the file."""
     41   # Make the file writeable, or the below won't work.
     42   os.chmod(filename, stat.S_IWRITE)
     43 
     44   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 
     51 def 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 
     56 def 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)
     59