11cb0ef41Sopenharmony_ci#!/usr/bin/env python
21cb0ef41Sopenharmony_ci# Copyright 2021 the V8 project authors. All rights reserved.
31cb0ef41Sopenharmony_ci# Use of this source code is governed by a BSD-style license that can be
41cb0ef41Sopenharmony_ci# found in the LICENSE file.
51cb0ef41Sopenharmony_ci"""Script to wrap protoc execution.
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciThis script exists to work-around the bad depfile generation by protoc when
81cb0ef41Sopenharmony_cigenerating descriptors."""
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_cifrom __future__ import print_function
111cb0ef41Sopenharmony_ciimport argparse
121cb0ef41Sopenharmony_ciimport os
131cb0ef41Sopenharmony_ciimport sys
141cb0ef41Sopenharmony_ciimport subprocess
151cb0ef41Sopenharmony_ciimport tempfile
161cb0ef41Sopenharmony_ciimport uuid
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_cifrom codecs import open
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_cidef main():
221cb0ef41Sopenharmony_ci  parser = argparse.ArgumentParser()
231cb0ef41Sopenharmony_ci  parser.add_argument('--descriptor_set_out', default=None)
241cb0ef41Sopenharmony_ci  parser.add_argument('--dependency_out', default=None)
251cb0ef41Sopenharmony_ci  parser.add_argument('protoc')
261cb0ef41Sopenharmony_ci  args, remaining = parser.parse_known_args()
271cb0ef41Sopenharmony_ci
281cb0ef41Sopenharmony_ci  if args.dependency_out and args.descriptor_set_out:
291cb0ef41Sopenharmony_ci    tmp_path = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))
301cb0ef41Sopenharmony_ci    custom = [
311cb0ef41Sopenharmony_ci        '--descriptor_set_out', args.descriptor_set_out, '--dependency_out',
321cb0ef41Sopenharmony_ci        tmp_path
331cb0ef41Sopenharmony_ci    ]
341cb0ef41Sopenharmony_ci    try:
351cb0ef41Sopenharmony_ci      cmd = [args.protoc] + custom + remaining
361cb0ef41Sopenharmony_ci      subprocess.check_call(cmd)
371cb0ef41Sopenharmony_ci      with open(tmp_path, 'rb') as tmp_rd:
381cb0ef41Sopenharmony_ci        dependency_data = tmp_rd.read().decode('utf-8')
391cb0ef41Sopenharmony_ci    finally:
401cb0ef41Sopenharmony_ci      if os.path.exists(tmp_path):
411cb0ef41Sopenharmony_ci        os.unlink(tmp_path)
421cb0ef41Sopenharmony_ci
431cb0ef41Sopenharmony_ci    with open(args.dependency_out, 'w', encoding='utf-8') as f:
441cb0ef41Sopenharmony_ci      f.write(args.descriptor_set_out + ":")
451cb0ef41Sopenharmony_ci      f.write(dependency_data)
461cb0ef41Sopenharmony_ci  else:
471cb0ef41Sopenharmony_ci    subprocess.check_call(sys.argv[1:])
481cb0ef41Sopenharmony_ci
491cb0ef41Sopenharmony_ci
501cb0ef41Sopenharmony_ciif __name__ == '__main__':
511cb0ef41Sopenharmony_ci  sys.exit(main())
52