以下为 CodeGenie理解HarmonyOS 5项目结构的完整机制解析,包含项目扫描、依赖分析和上下文感知的代码实现:
1. 项目解析架构
2. 核心解析模块
2.1 目录扫描引擎
// project-scanner.ets
class ProjectScanner {
static scan(root: string): ProjectStructure {
const files = this.walkDirectory(root);
return {
modules: this.detectModules(files),
configs: this.parseConfigs(files),
dependencies: this.buildDependencyGraph(files)
};
}
private static detectModules(files: FileEntry[]): Module[] {
return files
.filter(f => f.path.match(//pages/|/components//))
.map(f => ({
name: f.path.split('/').pop()?.replace('.ets', '') || '',
type: f.path.includes('/pages/') ? 'page' : 'component',
path: f.path
}));
}
}
2.2 依赖关系分析
// dependency-analyzer.ets
class DependencyAnalyzer {
static buildGraph(files: FileEntry[]): DependencyGraph {
const graph = new Map<string, string[]>();
files.forEach(file => {
if (file.path.endsWith('.ets')) {
const imports = this.extractImports(file.content);
graph.set(file.path, imports);
}
});
return graph;
}
private static extractImports(code: string): string[] {
return code.match(/import .* from ['"](.*)['"]/g)?.map(i => {
return i.replace(/import .* from ['"](.*)['"]/, '$1');
}) || [];
}
}
3. 配置智能解析
3.1 模块配置解析
// config-parser.ets
function parseModuleConfig(config: string): ModuleConfig {
const json = JSON.parse(config);
return {
name: json.name,
type: json.type || 'feature',
capabilities: json.capabilities || [],
dependencies: json.dependencies || []
};
}
3.2 资源映射分析
// resource-mapper.ets
class ResourceMapper {
static analyze(resDir: string): ResourceMap {
const resources = {
images: this.walkFiles(`${resDir}/media`),
strings: this.parseStringTable(`${resDir}/string.json`),
layouts: this.walkFiles(`${resDir}/layout`)
};
return {
...resources,
totalSize: this.calculateTotalSize(resources)
};
}
}
4. 上下文感知模型
4.1 项目特征提取
// feature-extractor.ets
class ProjectFeatureExtractor {
static extract(structure: ProjectStructure): ProjectFeatures {
return {
hasNetwork: this.checkFeature(structure, /@ohos.net.http/),
hasDatabase: this.checkFeature(structure, /@ohos.data.relationalStore/),
uiFramework: this.detectUIFramework(structure)
};
}
private static checkFeature(structure: ProjectStructure, pattern: RegExp): boolean {
return structure.dependencies.some(dep => pattern.test(dep));
}
}
4.2 架构模式识别
// architecture-detector.ets
function detectArchitecture(structure: ProjectStructure): 'mvvm' | 'mvc' | 'clean' {
const hasViewModel = structure.files.some(f =>
f.path.includes('/viewmodel/') && f.path.endsWith('.ets')
);
return hasViewModel ? 'mvvm' :
structure.files.some(f => f.path.includes('/controller/')) ? 'mvc' : 'clean';
}
5. 智能建议生成
5.1 依赖推荐引擎
// dependency-suggester.ets
class DependencySuggester {
static suggest(structure: ProjectStructure): Suggestion[] {
const missingDeps = [];
if (structure.features.hasNetwork && !this.hasDependency('@ohos.security')) {
missingDeps.push({
type: 'security',
suggestion: '添加网络安全模块',
package: '@ohos.security'
});
}
return missingDeps;
}
}
5.2 代码组织建议
// structure-optimizer.ets
function suggestStructure(structure: ProjectStructure): StructureSuggestion {
const suggestions = [];
if (structure.modules.length > 10 && !structure.hasLayers) {
suggestions.push({
level: 'high',
message: '建议按功能分层组织代码',
example: `src/
├── features/
│ ├── home/
│ ├── settings/
├── core/
│ ├── network/
│ ├── database/`
});
}
return suggestions;
}
6. 实时项目监控
6.1 文件变更监听
// file-watcher.ets
class ProjectWatcher {
private static watchers = new Map<string, FSWatcher>();
static watch(root: string, callback: (event: FileEvent) => void) {
const watcher = fs.watch(root, { recursive: true });
watcher.on('change', (path, event) => {
callback({ path, event });
});
this.watchers.set(root, watcher);
}
}
6.2 增量分析
// incremental-analyzer.ets
function analyzeChanges(base: ProjectStructure, changes: FileEvent[]): Delta {
return changes.reduce((delta, change) => {
if (change.path.endsWith('.ets')) {
delta.modules = this.updateModules(base.modules, change);
}
return delta;
}, { modules: [], dependencies: [] });
}
7. 完整工作流示例
7.1 项目初始化扫描
// init-scan.ets
const projectRoot = '/path/to/project';
const structure = ProjectScanner.scan(projectRoot);
const features = ProjectFeatureExtractor.extract(structure);
console.log('项目特征:', features);
7.2 持续分析服务
// analysis-service.ets
class AnalysisService {
private currentStructure: ProjectStructure;
constructor(root: string) {
this.currentStructure = ProjectScanner.scan(root);
ProjectWatcher.watch(root, this.handleChange.bind(this));
}
private handleChange(event: FileEvent) {
const delta = IncrementalAnalyzer.analyze(this.currentStructure, [event]);
this.currentStructure = mergeStructure(this.currentStructure, delta);
this.emitSuggestions();
}
}
8. 调试与验证工具
8.1 结构可视化
// structure-visualizer.ets
function visualize(structure: ProjectStructure) {
const nodes = structure.modules.map(m => ({
id: m.name,
label: `${m.name} (${m.type})`,
group: m.type
}));
const edges = structure.dependencies.map(d => ({
from: d.source,
to: d.target
}));
renderGraph({ nodes, edges });
}
8.2 依赖冲突检测
// conflict-detector.ets
function detectConflicts(structure: ProjectStructure): Conflict[] {
return structure.dependencies.filter(dep => {
return dep.versions.some(v => v !== dep.versions[0]);
}).map(dep => ({
package: dep.name,
versions: dep.versions,
suggestion: `统一版本到 ${dep.versions[0]}`
}));
}
9. 性能优化策略
9.1 缓存机制
// analysis-cache.ets
class AnalysisCache {
private static cache = new LRU<string, ProjectStructure>(100);
static get(key: string): ProjectStructure | null {
return this.cache.get(key) || null;
}
static set(key: string, structure: ProjectStructure) {
this.cache.set(key, structure);
}
}
9.2 并行分析
// parallel-analyzer.ets
async function parallelAnalyze(files: FileEntry[]) {
const batches = chunk(files, 100);
const results = await Promise.all(
batches.map(batch =>
workerPool.run(() => analyzeBatch(batch))
)
);
return mergeResults(results);
}
10. 扩展API接口
10.1 自定义规则注册
// custom-rules.ets
interface AnalysisRule {
name: string;
check: (structure: ProjectStructure) => boolean;
suggestion: string;
}
class RuleEngine {
private static rules: AnalysisRule[] = [];
static register(rule: AnalysisRule) {
this.rules.push(rule);
}
static applyAll(structure: ProjectStructure) {
return this.rules.map(rule => ({
rule: rule.name,
triggered: rule.check(structure),
suggestion: rule.suggestion
}));
}
}
10.2 插件系统
// plugin-system.ets
interface ProjectAnalyzerPlugin {
onProjectScan?: (structure: ProjectStructure) => void;
onFileChange?: (event: FileEvent) => void;
}
function registerPlugin(plugin: ProjectAnalyzerPlugin) {
ProjectAnalyzer.addListener(plugin);
}
11. 关键数据结构
11.1 项目结构表示
interface ProjectStructure {
modules: Module[];
dependencies: Dependency[];
resources: ResourceMap;
configs: {
module: ModuleConfig[];
build: BuildConfig;
};
}
interface Module {
name: string;
type: 'page' | 'component' | 'service';
path: string;
size: number;
}
interface Dependency {
source: string;
target: string;
versions?: string[];
}
11.2 变更事件定义
interface FileEvent {
path: string;
event: 'create' | 'delete' | 'modify';
content?: string;
}
12. 完整示例输出
12.1 扫描结果示例
{
"modules": [
{
"name": "HomePage",
"type": "page",
"path": "src/main/pages/HomePage.ets",
"size": 2451
}
],
"dependencies": [
{
"source": "HomePage",
"target": "@ohos.net.http"
}
],
"suggestions": [
{
"type": "dependency",
"message": "建议添加安全模块",
"package": "@ohos.security"
}
]
}
通过本方案可实现:
- 秒级 项目结构解析
- 智能 架构建议
- 实时 变更追踪
- 可扩展 的分析规则