1#!/usr/bin/env python 2# Copyright 2020 The Chromium Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5""" 6Converts a data file, e.g. a JSON file, into a C++ raw string that 7can be #included. 8""" 9 10import argparse 11import os 12import sys 13 14FORMAT_STRING = """#pragma once 15 16namespace openscreen {{ 17namespace {0} {{ 18 19constexpr char {1}[] = R"( 20 {2} 21)"; 22 23}} // namspace {0} 24}} // namespace openscreen 25""" 26 27 28def ToCamelCase(snake_case): 29 """Converts snake_case to TitleCamelCase.""" 30 return ''.join(x.title() for x in snake_case.split('_')) 31 32 33def GetVariableName(path): 34 """Converts a snake case file name into a kCamelCase variable name.""" 35 file_name = os.path.splitext(os.path.split(path)[1])[0] 36 return 'k' + ToCamelCase(file_name) 37 38 39def Convert(namespace, input_path, output_path): 40 """Takes an input file, such as a JSON file, and converts it into a C++ 41 data file, in the form of a character array constant in a header.""" 42 if not os.path.exists(input_path): 43 print('\tERROR: failed to generate, invalid path supplied: ' + 44 input_path) 45 return 1 46 47 content = False 48 with open(input_path, 'r') as f: 49 content = f.read() 50 51 with open(output_path, 'w') as f: 52 f.write( 53 FORMAT_STRING.format(namespace, GetVariableName(input_path), 54 content)) 55 56 57def main(): 58 parser = argparse.ArgumentParser( 59 description='Convert a file to a C++ data file') 60 parser.add_argument( 61 'namespace', 62 help='Namespace to scope data variable (nested under openscreen)') 63 parser.add_argument('input_path', help='Path to file to convert') 64 parser.add_argument('output_path', help='Output path of converted file') 65 args = parser.parse_args() 66 67 input_path = os.path.abspath(args.input_path) 68 output_path = os.path.abspath(args.output_path) 69 Convert(args.namespace, input_path, output_path) 70 71 72if __name__ == '__main__': 73 sys.exit(main()) 74