• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "codegen/code_generator.h"
17 #include <cstdlib>
18 #include <unistd.h>
19 #include <sys/stat.h>
20 #include "codegen/cpp_code_emitter.h"
21 #include "codegen/ts_code_emitter.h"
22 #include "util/logger.h"
23 
24 namespace OHOS {
25 namespace Idl {
26 const char* CodeGenerator::TAG = "CodeGenerator";
CodeGenerator(MetaComponent * mc,const String & language,const String & dir)27 CodeGenerator::CodeGenerator(MetaComponent* mc, const String& language, const String& dir)
28     : targetLanguage_(language),
29       targetDirectory_(dir),
30       metaComponent_(mc)
31 {
32     if (language.Equals("cpp")) {
33         emitter_ = new CppCodeEmitter(metaComponent_);
34     } else if (language.Equals("ts")) {
35         emitter_ = new TsCodeEmitter(metaComponent_);
36     }
37 }
38 
ResolveDirectory()39 bool CodeGenerator::ResolveDirectory()
40 {
41 #ifdef __MINGW32__
42     if (targetDirectory_.IndexOf(":\\") == -1) {
43         char* cmd = getcwd(nullptr, 0);
44         targetDirectory_ = String::Format("%s\\%s", cmd, targetDirectory_.string());
45         free(cmd);
46     }
47 #else
48     if (!targetDirectory_.StartsWith("/")) {
49         char* cwd = getcwd(nullptr, 0);
50         targetDirectory_ = String::Format("%s/%s", cwd, targetDirectory_.string());
51         free(cwd);
52     }
53 #endif
54 
55     if (!access(targetDirectory_.string(), R_OK | W_OK)) {
56         return true;
57     }
58 
59 #ifdef __MINGW32__
60     if (mkdir(targetDirectory_.string()) != 0) {
61 #else
62     if (mkdir(targetDirectory_.string(), S_IRWXU | S_IRWXG | S_IRWXO) != 0) {
63 #endif
64         Logger::E(TAG, "Create \"%s\" directory failed.", targetDirectory_.string());
65         return false;
66     }
67 
68     return true;
69 }
70 
71 bool CodeGenerator::Generate()
72 {
73     if (!ResolveDirectory()) {
74         return false;
75     }
76 
77     emitter_->SetDirectory(targetDirectory_);
78 
79     emitter_->EmitInterface();
80     emitter_->EmitInterfaceProxy();
81     emitter_->EmitInterfaceStub();
82 
83     return true;
84 }
85 } // namespace Idl
86 } // namespace OHOS