1 // Copyright 2014 The Chromium OS 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 
5 #include "chromeos-dbus-bindings/header_generator.h"
6 
7 #include <string>
8 
9 #include <base/files/file_path.h>
10 #include <base/files/file_util.h>
11 #include <base/strings/string_util.h>
12 #include <base/strings/stringprintf.h>
13 #include <brillo/strings/string_utils.h>
14 
15 #include "chromeos-dbus-bindings/indented_text.h"
16 
17 using std::string;
18 using std::vector;
19 
20 namespace chromeos_dbus_bindings {
21 
22 // static
GenerateHeaderGuard(const base::FilePath & output_file)23 string HeaderGenerator::GenerateHeaderGuard(
24     const base::FilePath& output_file) {
25   string guard = base::StringPrintf("____chromeos_dbus_binding__%s",
26                                     output_file.value().c_str());
27   for (auto& c : guard) {
28     if (base::IsAsciiAlpha(c)) {
29       c = base::ToUpperASCII(c);
30     } else if (!base::IsAsciiDigit(c)) {
31       c = '_';
32     }
33   }
34   return guard;
35 }
36 
37 // static
IsIntegralType(const string & type)38 bool HeaderGenerator::IsIntegralType(const string& type) {
39   return type.find("::") == std::string::npos;
40 }
41 
42 // static
MakeConstReferenceIfNeeded(std::string * type)43 void HeaderGenerator::MakeConstReferenceIfNeeded(std::string* type) {
44   if (!IsIntegralType(*type)) {
45     *type = base::StringPrintf("const %s&", type->c_str());
46   }
47 }
48 
49 // static
WriteTextToFile(const base::FilePath & output_file,const IndentedText & text)50 bool HeaderGenerator::WriteTextToFile(
51     const base::FilePath& output_file, const IndentedText &text) {
52   string contents = text.GetContents();
53   int expected_write_return = contents.size();
54   if (base::WriteFile(output_file, contents.c_str(), contents.size()) !=
55       expected_write_return) {
56     LOG(ERROR) << "Failed to write file " << output_file.value();
57     return false;
58   }
59   return true;
60 }
61 
62 // static
GetArgName(const char * prefix,const string & arg_name,int arg_index)63 string HeaderGenerator::GetArgName(const char* prefix,
64                                    const string& arg_name,
65                                    int arg_index) {
66   string name = arg_name.empty() ? std::to_string(arg_index) : arg_name;
67   return base::StringPrintf("%s_%s", prefix, name.c_str());
68 }
69 
70 }  // namespace chromeos_dbus_bindings
71