Automatically generate an OpenHarmony system code framework based on the design document, including directory structure, IDL interfaces, header files, source files, build configuration, etc.
Quick Start
Provide the design document path:
基于 {功能设计文档} 生成代码框架
Specify the module name:
为 {模块名} 生成完整代码,基于 {功能设计文档}
OpenHarmony Code Analysis
Before generating code, it is necessary to analyze existing OpenHarmony code to ensure that the generated code conforms to the existing code style and architecture specifications.
Analysis Steps
1. Discover Directory Structure
Use the Glob tool to discover the organizational structure of existing modules:
# 查找相似模块的目录结构
foundation/{subsystem}/*/services/
foundation/{subsystem}/*/interfaces/
foundation/{subsystem}/*/tests/
2. Search Code Patterns
Use the Grep tool to search code patterns:
| Search Target | Search Keyword | Extract Information |
|---|---|---|
| Class Naming | class.*Service |
Service Class Naming |
| Namespace | namespace.* |
Namespace Organization |
| Log Tag | HiLogLabel |
Log Usage Method |
| Error Code | ERROR_.*=.*[0-9] |
Error Code Allocation |
| Macro Definition | #define.*_ENABLE |
Conditional Compilation Switch |
| Initialization Function | bool Init\(\) |
Initialization Pattern |
| Cleanup Function | void.*Release\(\) |
Resource Cleanup Pattern |
3. Read Reference Implementation
Use the Read tool to read the implementation of similar modules:
- Service Implementation:
*_service.cpp - Provider Implementation:
*_provider.cpp - IDL Definition:
I*.idl - Build Configuration:
BUILD.gn
4. Intelligent Exploration
Use the Task tool to start the Explore agent:
- Find best practices for reference implementations
- Extract common code templates
- Discover dependent public libraries and utility classes
Reference Directory Patterns
OpenHarmony standard directory structure:
foundation/{subsystem}/{part}/
├── bundle.json # 部件配置
├── BUILD.gn # 主构建文件
├── {part}.gni # 模块配置
├── services/
│ └── native/
│ ├── {sa_id}.json # SA 配置
│ ├── include/ # 对外头文件
│ └── src/ # 实现文件
├── interfaces/
│ ├── idl/ # IDL 接口
│ ├── innerkits/ # 内部 Kit
│ └── kits/ # 对外 Kit
└── tests/ # 测试代码
Code Style Reference
| Code Element | Style Rule | Example |
|---|---|---|
| Class Name | UpperCamelCase + suffix | DiskInfoService |
| Method Name | UpperCamelCase | GetDiskList() |
| Member Variable | lowerCamelCase + underscore suffix | mutex_, inited_ |
| Namespace | lowercase separated by double colons | OHOS::DiskManagement |
| File Name | lowercase with underscores | disk_info_service.cpp |
| Macro Definition | uppercase with underscores | DISK_MANAGEMENT_FORMAT_ENABLE |
Commonly Used Dependency Libraries
| Dependency | external_deps Format | Purpose |
|---|---|---|
| HiLog | hilog:libhilog |
Log Output |
| c_utils | c_utils:utils |
C Utility Functions |
| ipc_core | ipc_core:ipc_core |
IPC Communication |
| AccessToken | access_token:libaccesstoken |
Permission Management |
| HiSysEvent | hisysevent:libhisysevent |
Event Reporting |
| HiTrace | hitrace_native:hitrace_meter |
Link Tracing |
Generated Content
1. Directory Structure
Automatically create a directory structure that conforms to OpenHarmony specifications:
disk_management/
├── bundle.json # 部件配置
├── BUILD.gn # 主构建配置
├── disk_management.gni # 模块配置
├── services/
│ ├── native/
│ │ ├── 5001.json # SA 配置文件
│ │ ├── disk_management.cfg # Init 配置文件
│ │ ├── include/ # 头文件目录
│ │ └── src/ # 源文件目录
│ └── disk_info_service/ # 各服务目录
│ ├── include/
│ └── src/
├── interfaces/
│ ├── idl/OHOS/DiskManagement/ # IDL 接口定义
│ ├── innerkits/native/ # Native Kit
│ └── kits/js/ # JS Kit
└── tests/ # 测试目录
2. IDL Interface File
Generate an IDL interface definition file, format:
/* Copyright (c) 2026 Huawei Device Co., Ltd. */
package OHOS.DiskManagement;
import "DiskInfoTypes.idl";
interface IDiskInfoService {
/// 获取系统所有磁盘列表
GetDiskList(): DiskInfo[];
/// 获取指定磁盘的详细信息
GetDiskInfo([in] string diskId): DiskInfo;
/// 注册磁盘变化监听器
RegisterChangeListener([in] IDiskChangeListener listener): void;
};
3. Header file template
Generate a header file that conforms to the OpenHarmony coding specification:
/* Copyright (c) 2026 Huawei Device Co., Ltd. */
#ifndef DISK_INFO_SERVICE_H
#define DISK_INFO_SERVICE_H
#include <string>
#include <vector>
#include <mutex>
namespace OHOS {
namespace DiskManagement {
class DiskInfoService {
public:
DiskInfoService();
~DiskInfoService();
bool Init();
void Release();
std::vector<DiskInfo> GetDiskList();
DiskInfo GetDiskInfo(const std::string& diskId);
private:
std::mutex mutex_;
bool inited_;
};
} // namespace DiskManagement
} // namespace OHOS
#endif // DISK_INFO_SERVICE_H
4. Source file template
Generate the basic implementation framework:
/* Copyright (c) 2026 Huawei Device Co., Ltd. */
#include "disk_info_service.h"
#include "hilog/log.h"
namespace OHOS {
namespace DiskManagement {
static constexpr HiLogLabel LABEL = { LOG_CORE, 0xD00430D, "DiskInfoService" };
DiskInfoService::DiskInfoService() : inited_(false)
{
HiLog::Info(LABEL, "DiskInfoService constructed");
}
DiskInfoService::~DiskInfoService()
{
Release();
}
bool DiskInfoService::Init()
{
std::lock_guard<std::mutex> lock(mutex_);
if (inited_) {
HiLog::Warn(LABEL, "Already initialized");
return true;
}
// TODO: 初始化逻辑
inited_ = true;
return true;
}
void DiskInfoService::Release()
{
std::lock_guard<std::mutex> lock(mutex_);
if (!inited_) {
return;
}
// TODO: 清理资源
inited_ = false;
}
} // namespace DiskManagement
} // namespace OHOS
5. BUILD.gn configuration
Generate the build configuration file:
import("//build/ohos.gni")
import("//build/test.gni")
import("//foundation/filemanagement/disk_management/disk_management.gni")
ohos_shared_library("disk_management_sa") {
subsystem_name = "filemanagement"
part_name = "disk_management"
sources = [
"src/disk_management_service.cpp",
"src/main.cpp",
]
include_dirs = [
"include",
"${disk_management_path}/include",
"//utils/native/base/include",
]
deps = [
":disk_management_idl",
"//foundation/hiviewdfx/hilog/native/framework:libhilog",
]
external_deps = [
"c_utils:c_utils",
]
branch_protector_ret = "pac_ret"
sanitize = {
integer_overflow = true
cfi = true
debug = false
}
}
ohos_unittest("disk_management_unittest") {
subsystem_name = "filemanagement"
part_name = "disk_management"
test_type = "unittest"
test_time_out = 300
sources = [
"test/disk_management_test.cpp",
]
deps = [
":disk_management_sa",
]
external_deps = [
"googletest:gmock_main",
"googletest:gtest_main",
]
cflags_cc = [ "--coverage" ]
ldflags = [ "--coverage" ]
}
6. SA configuration file (5001.json)
{
"sa-id": 5001,
"sa-name": "disk_management",
"run-on-create": true,
"auto-start": true,
"start-mode": "boot",
"process": "disk_management_service",
"dump-level": "control",
"critical": [1, 4, 240],
"libpath": "libdisk_management_sa.z.so"
}
7. bundle.json
{
"name": "disk_management",
"description": "HM Desktop Disk Management Service",
"version": "1.0.0",
"component": {
"name": "disk_management",
"subsystem": "filemanagement",
"syscap": [
"SystemCapability.DiskManagement.DiskInfo",
"SystemCapability.DiskManagement.Format"
]
}
}
Reference documents
- IDL Writing Guide: references/idl_guide.md
- BUILD.gn Specification: references/build_gn_guide.md
- SA Configuration Specification: references/sa_profile_guide.md
- Coding Specification: references/coding_style.md
Naming convention mapping
| Design document term | Code term | Rule |
|---|---|---|
| Service name | Class name | UpperCamelCase + Service suffix |
| Module name | Namespace | Lowercase with underscore separators |
| Interface name | IDL interface | I + UpperCamelCase |
| Data structure | struct | UpperCamelCase |
| Method name | Function name | UpperCamelCase |
| Member variable | Member variable | LowerCamelCase + underscore suffix |
Module types and generation strategies
Information service (InfoService)
Generated content:
- GetList() method
- Get() method
- RegisterListener() method
Example: DiskInfoService
Management service (ManagerService)
Generated content:
- Execute() method
- Cancel() method
- RegisterProgressListener() method
Example: FormatManagerService, RepairManagerService
Listener
Generated content:
- OnChanged() callback method
- OnCompleted() callback method
Example: DiskChangeListener, FormatProgressListener
Usage example
Generate a complete code framework:
基于 {功能设计文档} 为 {模块名} 模块生成完整代码
Generate only the IDL interface:
只生成 IDL 接口文件,基于 {功能设计文档}
Specify SA ID:
生成代码,SA ID 使用 {SA_ID},基于 {功能设计文档}
Preview mode:
预览将要生成的文件,不实际创建,基于 {功能设计文档}
Specify output directory:
生成代码到 ./code_output 目录,基于 {功能设计文档}
Conditional compilation support
The generated code supports feature conditional compilation:
# 在 .gni 文件中定义
declare_args() {
disk_management_enable_format = true
disk_management_enable_repair = true
}
# 在 BUILD.gn 中使用
if (disk_management_enable_format) {
sources += [ "src/format_service.cpp" ]
defines += [ "DISK_MANAGEMENT_FORMAT_ENABLE" ]
}
Test code generation
Generate the unit test framework at the same time:
/* Copyright (c) 2026 Huawei Device Co., Ltd. */
#include <gtest/gtest.h>
#include "disk_info_service.h"
namespace OHOS {
namespace DiskManagement {
class DiskInfoServiceTest : public testing::Test {
protected:
void SetUp() override {
service_ = std::make_unique<DiskInfoService>();
ASSERT_TRUE(service_->Init());
}
void TearDown() override {
service_->Release();
}
std::unique_ptr<DiskInfoService> service_;
};
TEST_F(DiskInfoServiceTest, GetDiskList) {
auto disks = service_->GetDiskList();
EXPECT_GE(disks.size(), 0u);
}
} // namespace DiskManagement
} // namespace OHOS
Error handling
| Error type | Handling method |
|---|---|
| Design document format error | Indicate the specific missing section |
| IDL syntax error | Mark the error line number and provide the correct format |
| Directory creation failed | Check permissions and prompt the user to create manually |
| File already exists | Use --force to overwrite or skip |
List of generated files
After generation is complete, output the file list:
[INFO] 代码框架生成完成!
[INFO]
[INFO] 生成的文件:
[INFO] 目录: disk_management/
[INFO] 配置: bundle.json, BUILD.gn, disk_management.gni
[INFO] SA配置: services/native/5001.json, disk_management.cfg
[INFO] IDL: interfaces/idl/OHOS/DiskManagement/*.idl
[INFO] 头文件: services/native/include/*.h
[INFO] 源文件: services/native/src/*.cpp
[INFO] 测试: test/unittest/*_test.cpp
[INFO]
[INFO] 总计: 15 个文件, 5 个目录