DevEco 5.0管理同时支持HarmonyOS 4和5的代码分支策略

133 阅读2分钟

以下为 ​​DevEco 5.0同时支持HarmonyOS 4和5的代码分支管理方案​​,包含多版本兼容、条件编译和自动化检测的完整代码实现:


1. 多版本兼容基础框架

1.1 版本检测工具

// version-detector.ets
import deviceInfo from '@ohos.deviceInfo';

class HarmonyVersion {
  static getCurrent(): number {
    const version = deviceInfo.osFullName.match(/HarmonyOS (\d+)/)?.[1];
    return version ? parseInt(version) : 4; // 默认返回4
  }

  static isHarmonyOS5(): boolean {
    return this.getCurrent() >= 5;
  }
}

1.2 API兼容层

// api-compat.ets
class CompatAPI {
  static getDistributedStorage() {
    return HarmonyVersion.isHarmonyOS5() ? 
      distributedStorage : // HarmonyOS 5专用API
      legacyStorage;       // HarmonyOS 4备用实现
  }

  static requestPermission(permission: string): Promise<boolean> {
    if (HarmonyVersion.isHarmonyOS5()) {
      return permission.requestSystemGrant();
    } else {
      return new Promise(resolve => {
        legacyPermission.request(resolve);
      });
    }
  }
}

2. 条件编译系统

2.1 编译指令标记

// build-flags.ets
class BuildFlags {
  static readonly HOS4 = !HarmonyVersion.isHarmonyOS5();
  static readonly HOS5 = HarmonyVersion.isHarmonyOS5();
}

2.2 条件代码块

// conditional-render.ets
@Component
struct VersionAwareComponent {
  build() {
    Column() {
      // 公共部分
      Text('通用功能').fontSize(20)

      // HarmonyOS 5专属功能
      if (BuildFlags.HOS5) {
        Text('5.0特效').fontColor('#FF0000')
        ParticleEffect()
      }

      // HarmonyOS 4备用实现
      if (BuildFlags.HOS4) {
        Image($r('app.media.fallback'))
      }
    }
  }
}

3. 分支管理策略

3.1 Git分支模型

# 仓库结构示例
main         # 稳定版主干
├── hos4     # HarmonyOS 4维护分支
├── hos5     # HarmonyOS 5开发分支
└── feature  # 功能开发分支

3.2 自动化合并脚本

// merge-helper.ets
class BranchMerger {
  static async syncFeatures(source: string, targets: string[]): Promise<void> {
    const changes = await git.getDiff(source);
    await Promise.all(targets.map(branch => 
      git.applyPatch(branch, changes)
    ));
  }

  static async checkConflicts(base: string, feature: string): Promise<string[]> {
    const diff = await git.getConflictFiles(base, feature);
    return diff.filter(file => 
      file.includes('.ets') || file.includes('.json')
    );
  }
}

4. 版本特性隔离

4.1 平台适配层

// platform-adapter.ets
class PlatformAdapter {
  private static impl: PlatformInterface = 
    BuildFlags.HOS5 ? new HarmonyOS5Impl() : new HarmonyOS4Impl();

  static callFeature(feature: string, ...args: any[]): any {
    return this.impl[feature]?.(...args);
  }
}

4.2 组件版本封装

// versioned-component.ets
@Component
struct SafeArea {
  build() {
    // 根据版本选择不同实现
    (BuildFlags.HOS5 ? SafeAreaV5 : SafeAreaV4)()
  }
}

5. 自动化检测工具

5.1 API兼容性检查

// api-checker.ets
class ApiCompatibility {
  static check(code: string): CompatibilityReport {
    const hos4Apis = code.match(/legacy.\w+/g) || [];
    const hos5Apis = code.match(/distributed.\w+/g) || [];
    
    return {
      hos4: hos4Apis,
      hos5: hos5Apis,
      crossPlatform: hos4Apis.length === 0 && hos5Apis.length === 0
    };
  }
}

5.2 构建配置生成

// build-config-generator.ets
class BuildConfigGenerator {
  static generate(target: 'hos4' | 'hos5'): BuildConfig {
    return {
      define: {
        HOS_VERSION: target === 'hos5' ? 5 : 4
      },
      resources: this._getResources(target),
      dependencies: this._getDependencies(target)
    };
  }
}

6. 多版本测试方案

6.1 版本模拟器

// version-simulator.ets
class VersionSimulator {
  static setMockVersion(version: number): void {
    deviceInfo.mock({
      osFullName: `HarmonyOS ${version}`
    });
  }
}

// 测试用例示例
describe('API兼容性测试', () => {
  it('在HarmonyOS 4上应使用备用存储', () => {
    VersionSimulator.setMockVersion(4);
    expect(CompatAPI.getDistributedStorage()).toBe(legacyStorage);
  });
});

6.2 自动化测试分发

// test-distributor.ets
class TestDistributor {
  static async runMultiVersionTests(): Promise<void> {
    await this._runOnVersion(4);
    await this._runOnVersion(5);
  }

  private static async _runOnVersion(version: number): Promise<void> {
    VersionSimulator.setMockVersion(version);
    await testRunner.run();
  }
}

7. 生产环境配置

7.1 版本化构建配置

// hos4-build.json
{
  "compilerOptions": {
    "defines": ["HOS_VERSION=4"]
  },
  "exclude": ["src/hos5/**"]
}

// hos5-build.json
{
  "compilerOptions": {
    "defines": ["HOS_VERSION=5"]
  },
  "include": ["src/hos5/**"]
}

7.2 发布流水线

// release-pipeline.ets
class ReleasePipeline {
  static async buildAll(): Promise<void> {
    await this._buildVersion('hos4');
    await this._buildVersion('hos5');
    await this._generateUniversalAPK();
  }

  private static async _buildVersion(target: string): Promise<void> {
    exec(`ohpm build --config=${target}-build.json`);
  }
}

8. 代码合并策略

8.1 公共代码提取

// common-code.ets
class CommonUtils {
  static formatDate(date: Date): string {
    // 跨版本通用实现
    return `${date.getFullYear()}-${date.getMonth() + 1}`;
  }
}

8.2 差异代码隔离

# 项目目录结构
src/
├── common/      # 公共代码
├── hos4/        # HarmonyOS 4实现
├── hos5/        # HarmonyOS 5实现
└── entry.ets    # 入口文件

9. 关键版本差异处理

功能模块HarmonyOS 4方案HarmonyOS 5方案兼容策略
分布式能力自定义RPC实现原生distributedKit接口统一封装
动画引擎基础动画API全新动画系统条件编译
安全机制传统权限管理动态权限申请运行时检测
线程模型Worker线程TaskPool工厂模式选择实现

10. 完整工作流示例

10.1 开发新功能

// feature.ets
class NewFeature {
  static enable() {
    if (BuildFlags.HOS5) {
      // 使用HarmonyOS 5专属API
      distributedAbility.execute();
    } else {
      // HarmonyOS 4兼容实现
      legacyBridge.sendCommand();
    }
  }
}

10.2 自动化版本发布

# 构建命令示例
ohpm build --target=hos4 --output=build/hos4
ohpm build --target=hos5 --output=build/hos5

# 合并产物
zip -j release.zip build/hos4/* build/hos5/*

通过本方案可实现:

  1. ​单代码库​​ 维护双版本
  2. ​自动化​​ 版本适配检测
  3. ​零冲突​​ 分支合并
  4. ​灵活切换​​ 构建目标