rewrite_imports.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Copyright 2022 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. import argparse
  5. import os
  6. import re
  7. import sys
  8. _CWD = os.getcwd()
  9. # TODO(crbug.com/1320176): Consider either integrating this functionality into
  10. # ts_library.py or replacing the regex if only "tslib" is ever rewritten.
  11. def main(argv):
  12. parser = argparse.ArgumentParser()
  13. parser.add_argument('--import_mappings', nargs='*')
  14. parser.add_argument('--out_dir', required=True)
  15. parser.add_argument('--in_files', nargs='*')
  16. args = parser.parse_args(argv)
  17. import_mappings = dict()
  18. for mapping in args.import_mappings:
  19. (src, dst) = mapping.split('|')
  20. import_mappings[src] = dst
  21. for f in args.in_files:
  22. filename = os.path.basename(f)
  23. output = []
  24. for line in open(f, 'r').readlines():
  25. # Investigate JS parsing if this is insufficient.
  26. match = re.match(r'^(import .*["\'])(.*)(["\'];)$', line)
  27. if match:
  28. import_src = match.group(2)
  29. if import_src in import_mappings:
  30. line = (match.group(1) + import_mappings[import_src] +
  31. match.group(3) + '\n')
  32. output.append(line)
  33. with open(os.path.join(args.out_dir, filename), 'w') as out_file:
  34. out_file.write(''.join(output))
  35. if __name__ == '__main__':
  36. main(sys.argv[1:])