Flutter 命令本質之 Flutter tools 機制原始碼深入分析

工匠若水發表於2021-07-25

背景

上一篇《Flutter Android 工程結構及應用層編譯原始碼深入分析》我們分析了 Flutter Android 相關的應用層主要編譯流程,其中分析到底層本質命令工具【Flutter SDK 下bin/flutter編譯命令分析】小節時只提到,我們執行任何 flutter 命令的本質都是把引數傳遞到了FLUTTER_SDK_DIR/packages/flutter_tools/bin/flutter_tools.dart原始碼的 main 方法中,沒有對這裡面進行深入分析。本文要做的事就是層層遞進揭開這裡的本質,並與上篇呼應解釋編譯產物的由來。

flutter_tools 介紹

通過flutter -h命令我們可以直觀全域性感受都支援哪些引數,有些引數還有子引數。我們所執行的所有引數本質都走進了下面模組的原始碼入口中。 在這裡插入圖片描述 因此我們如果直接想從原始碼方式使用 flutter tools,則可以直接當前目錄中如下命令:

# ARGS 就是一堆引數,譬如我們上篇的 build apk
dart bin/flutter_tools.dart ARGS
複製程式碼

如果想重新生成 Flutter Tools snapshot,可以直接當前目錄中執行如下命令:

rm ../../bin/cache/flutter_tools.stamp ../../bin/cache/flutter_tools.snapshot
複製程式碼

這樣就成功刪除了上篇中 shell 指令碼呼叫的 Flutter Tools snapshot,然後在執行時會自動重新生成一個。

原始碼分析

上面既然交代了整個背景,那麼我們接下來就基於 Flutter SDK 入口packages/flutter_tools/bin/flutter_tools.dart開始分析,整個分析繼續承接上篇flutter build apk命令,如下:

//1、匯入packages/flutter_tools/lib/executable.dart檔案
import 'package:flutter_tools/executable.dart' as executable;
//2、入口重點,執行executable.main方法,並將我們`build apk`引數傳入
void main(List<String> args) {
  executable.main(args);
}
複製程式碼

接下來我們去packages/flutter_tools/lib/executable.dart看看他的 main 方法,如下:

Future<void> main(List<String> args) async {
  //一堆引數解析判斷啥的,譬如解析flutter doctor的doctor引數啥的
  ......
  //1、重點!runner的本質是import 'runner.dart' as runner;
  // 本質就是呼叫run方法的各種引數傳遞,重點關注第一個和第二個引數即可
  await runner.run(
    args,
    () => generateCommands(
      verboseHelp: verboseHelp,
      verbose: verbose,
    ),
    ......,
  );
}
//2、步驟1中runner.run的第二個核心引數方法定義
//FlutterCommand為packages/flutter_tools/lib/src/runner/flutter_command.dart中定義的抽象類
//這個方法本質就是把flutter執行的命令引數列表全部加入列表,類似命令模式
List<FlutterCommand> generateCommands({
  @required bool verboseHelp,
  @required bool verbose,
}) => <FlutterCommand>[
  AnalyzeCommand(
    ......
  ),
  AssembleCommand(verboseHelp: verboseHelp, buildSystem: globals.buildSystem),
  AttachCommand(verboseHelp: verboseHelp),
  BuildCommand(verboseHelp: verboseHelp),
  ChannelCommand(verboseHelp: verboseHelp),
  CleanCommand(verbose: verbose),
  ConfigCommand(verboseHelp: verboseHelp),
  CreateCommand(verboseHelp: verboseHelp),
  DaemonCommand(hidden: !verboseHelp),
  DevicesCommand(verboseHelp: verboseHelp),
  DoctorCommand(verbose: verbose),
  DowngradeCommand(verboseHelp: verboseHelp),
  DriveCommand(verboseHelp: verboseHelp,
    ......
  ),
  EmulatorsCommand(),
  FormatCommand(),
  GenerateCommand(),
  GenerateLocalizationsCommand(
    ......
  ),
  InstallCommand(),
  LogsCommand(),
  MakeHostAppEditableCommand(),
  PackagesCommand(),
  PrecacheCommand(
    ......
  ),
  RunCommand(verboseHelp: verboseHelp),
  ScreenshotCommand(),
  ShellCompletionCommand(),
  TestCommand(verboseHelp: verboseHelp),
  UpgradeCommand(verboseHelp: verboseHelp),
  SymbolizeCommand(
    ......
  ),
  // Development-only commands. These are always hidden,
  IdeConfigCommand(),
  UpdatePackagesCommand(),
];
......
複製程式碼

讓我們把目光先移動到runner.dart檔案的 run 方法,然後回過頭來看上面程式碼中的步驟1如何呼叫步驟2,如下:

Future<int> run(
  List<String> args,
  List<FlutterCommand> Function() commands, {
    bool muteCommandLogging = false,
    bool verbose = false,
    bool verboseHelp = false,
    bool reportCrashes,
    String flutterVersion,
    Map<Type, Generator> overrides,
  }) async {
  ......
  //1、FlutterCommandRunner位於packages/flutter_tools/lib/src/runner/flutter_command_runner.dart
  return runInContext<int>(() async {
    reportCrashes ??= !await globals.isRunningOnBot;
    //2、建立runner物件例項,並把上一片段程式碼中步驟2方法返回的FlutterCommand列表追加進runner中
    final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: verboseHelp);
    commands().forEach(runner.addCommand);
    ......
    return runZoned<Future<int>>(() async {
      try {
      	//3、依據args引數執行runner例項的run方法
        await runner.run(args);
		......
      } catch (error, stackTrace) {  // ignore: avoid_catches_without_on_clauses
        ......
      }
    }, onError: (Object error, StackTrace stackTrace) async { // ignore: deprecated_member_use
      ......
    });
  }, overrides: overrides);
}
複製程式碼

可以看到,首先例項化了一個 FlutterCommandRunner 物件,接著把所有支援的 FlutterCommand 列表加入 runner 物件中,然後呼叫了 runner 的 run 方法,所以我們現在檢視packages/flutter_tools/lib/src/runner/flutter_command_runner.dart檔案的 run 方法,如下:

......
@override
Future<void> run(Iterable<String> args) {
  ......
  //本質呼叫了父類CommandRunner的run方法,run方法呼叫了子類FlutterCommandRunner的runCommand方法
  //子類FlutterCommandRunner的runCommand最終又呼叫了父類CommandRunner的runCommand方法
  return super.run(args);
}
......
複製程式碼

所以我們接下來看父類 CommandRunner 的 runCommand 方法,如下:

  Future<T?> runCommand(ArgResults topLevelResults) async {
  	//1、flutter命令後面傳遞進來引數,譬如build apk
    var argResults = topLevelResults;
    //2、前面分析過的,runner中新增的支援命令列表
    var commands = _commands;
    //3、定義一個Command變數,用來最終依據引數賦值為對應的Command物件例項
    Command? command;
    var commandString = executableName;
	//4、while條件為真,因為commands為支援的引數列表
    while (commands.isNotEmpty) {
      ......
      //5、填充指令
      argResults = argResults.command!;
      command = commands[argResults.name]!;
      command._globalResults = topLevelResults;
      command._argResults = argResults;
      commands = command._subcommands as Map<String, Command<T>>;
      commandString += ' ${argResults.name}';
	  ......
    }
    ......
    //6、執行對應命令的run方法
    return (await command.run()) as T?;
  }
  ......
}
複製程式碼

可以看到,這就是一個標準的命令模式設計,先把支援的命令新增到列表,然後依據引數遍歷匹配對應命令進行執行。下面我們以flutter build apk命令為例來看其對應的 BuildCommand 命令(packages/flutter_tools/lib/src/commands/build.dart)實現,如下:

class BuildCommand extends FlutterCommand {
  BuildCommand({ bool verboseHelp = false }) {
    addSubcommand(BuildAarCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildApkCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildAppBundleCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildIOSCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildIOSFrameworkCommand(
      buildSystem: globals.buildSystem,
      verboseHelp: verboseHelp,
    ));
    addSubcommand(BuildIOSArchiveCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildBundleCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildWebCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildMacosCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildLinuxCommand(
      operatingSystemUtils: globals.os,
      verboseHelp: verboseHelp
    ));
    addSubcommand(BuildWindowsCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildWindowsUwpCommand(verboseHelp: verboseHelp));
    addSubcommand(BuildFuchsiaCommand(verboseHelp: verboseHelp));
  }
  //上一小段程式碼中command = commands[argResults.name]就是這麼得到的
  //name=build就是執行flutter build apk中的build字串
  @override
  final String name = 'build';

  @override
  final String description = 'Build an executable app or install bundle.';

  @override
  Future<FlutterCommandResult> runCommand() async => null;
}
複製程式碼

可以看到,任意一個命令基本都繼承自 FlutterCommand 實現,命令的執行都是呼叫了 FlutterCommand 的 run 方法,如下:

abstract class FlutterCommand extends Command<void> {
  ......
  //runner物件中最終執行呼叫的方法是這個
  @override
  Future<void> run() {
    ......
    return context.run<void>(
      name: 'command',
      overrides: <Type, Generator>{FlutterCommand: () => this},
      body: () async {
        ......
        try {
          //見名知意,先校驗再執行命令
          commandResult = await verifyThenRunCommand(commandPath);
        } finally {
          ......
        }
      },
    );
  }
  ......
    @mustCallSuper
  Future<FlutterCommandResult> verifyThenRunCommand(String commandPath) async {
    //1、如果需要更新快取就先更新快取
    if (shouldUpdateCache) {
      await globals.cache.updateAll(<DevelopmentArtifact>{DevelopmentArtifact.universal});
      await globals.cache.updateAll(await requiredArtifacts);
    }
    globals.cache.releaseLock();
	//2、校驗命令
    await validateCommand();
	//3、如果需要先執行pub就先執行,譬如pub get下載依賴
    if (shouldRunPub) {
      ......
	  //4、執行pub get下載依賴,即下載pubspec.yaml裡配置的依賴
      await pub.get(
        context: PubContext.getVerifyContext(name),
        generateSyntheticPackage: project.manifest.generateSyntheticPackage,
        checkUpToDate: cachePubGet,
      );
      await project.regeneratePlatformSpecificTooling();
      if (reportNullSafety) {
        await _sendNullSafetyAnalyticsEvents(project);
      }
    }

    setupApplicationPackages();
	......
	//5、真正開始執行命令
    return runCommand();
  }
}
複製程式碼

繞一圈最終我們又回到 BuildCommand 類,可以發現其 runCommand 方法重寫為空實現,而其構造時通過 addSubcommand 方法追加了很多子命令,譬如執行flutter build aar編譯 aar 的 BuildAarCommand 命令、執行flutter build apk編譯 apk 的 BuildApkCommand 命令。整個 sub command 與其宿主又算是一個責任鏈,所以上面同樣的套路順序對於 sub command 同樣適用,因此我們去看下編譯 apk 產物的 BuildApkCommand 原始碼(packages/flutter_tools/lib/src/commands/build_apk.dart),如下:

class BuildApkCommand extends BuildSubCommand {
  BuildApkCommand({bool verboseHelp = false}) {
    ......
    //一堆引數的確認
  }
  //對應flutter build apk裡面子命令字串apk
  @override
  final String name = 'apk';
  ......
  //本質命令執行方法
  @override
  Future<FlutterCommandResult> runCommand() async {
    ......
    //呼叫androidBuilder的buildApk方法進行真正的編譯,目測裡面的產物也就是上一篇文章分析的那些
    //androidBuilder位於packages/flutter_tools/lib/src/android/android_builder.dart
    await androidBuilder.buildApk(
      project: FlutterProject.current(),
      target: targetFile,
      androidBuildInfo: androidBuildInfo,
    );
    return FlutterCommandResult.success();
  }
}
複製程式碼

順著這條路我們繼續跟進位於packages/flutter_tools/lib/src/android/android_builder.dart的 androidBuilder 屬性的 buildApk 方法,如下:

//本質是packages/flutter_tools/lib/src/context_runner.dart中context.run方法中的AndroidGradleBuilder例項
AndroidBuilder get androidBuilder {
  return context.get<AndroidBuilder>();
}
//抽象類定義,AndroidBuilder
abstract class AndroidBuilder {
  const AndroidBuilder();
  // 定義編譯aar的方法
  Future<void> buildAar({
    @required FlutterProject project,
    @required Set<AndroidBuildInfo> androidBuildInfo,
    @required String target,
    @required String outputDirectoryPath,
    @required String buildNumber,
  });

  // 定義編譯apk的方法
  Future<void> buildApk({
    @required FlutterProject project,
    @required AndroidBuildInfo androidBuildInfo,
    @required String target,
  });

  // 定義編譯aab的方法
  Future<void> buildAab({
    @required FlutterProject project,
    @required AndroidBuildInfo androidBuildInfo,
    @required String target,
    bool validateDeferredComponents = true,
    bool deferredComponentsEnabled = false,
  });
}
複製程式碼

所以我們繼續去看 AndroidGradleBuilder 實現類(packages/flutter_tools/lib/src/android/gradle.dart)的 buildApk 方法,如下:

class AndroidGradleBuilder implements AndroidBuilder {
  AndroidGradleBuilder({
    ......
  }) : ......;
  ......
  //1、編譯 apk 的方法
  @override
  Future<void> buildApk({
    @required FlutterProject project,
    @required AndroidBuildInfo androidBuildInfo,
    @required String target,
  }) async {
  	//2、呼叫
    await buildGradleApp(
      project: project,
      androidBuildInfo: androidBuildInfo,
      target: target,
      isBuildingBundle: false,
      localGradleErrors: gradleErrors,
    );
  }
  ......
  //3、真的編譯
  Future<void> buildGradleApp({
    @required FlutterProject project, //FlutterProject.current()
    @required AndroidBuildInfo androidBuildInfo, //build configuration
    @required String target, //dart程式碼入口,預設lib/main.dart
    @required bool isBuildingBundle, //是aab還是apk,預設false則apk
    @required List<GradleHandledError> localGradleErrors,
    bool shouldBuildPluginAsAar = false, //是不是將外掛編譯為aar
    bool validateDeferredComponents = true,
    bool deferredComponentsEnabled = false,
    int retries = 1,
  }) async {
    //4、檢查支援的android版本,獲取android編譯產物目錄,即gradle中配置的build產物目錄,預設為專案根目錄下的build目錄
    if (!project.android.isSupportedVersion) {
      _exitWithUnsupportedProjectMessage(_usage, _logger.terminal);
    }
    final Directory buildDirectory = project.android.buildDirectory;
	//5、讀取安卓相關屬性檔案判斷是否使用androidx,然後傳送編譯事件引數
    final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot);
    if (usesAndroidX) {
      BuildEvent('app-using-android-x', flutterUsage: _usage).send();
    } else if (!usesAndroidX) {
      BuildEvent('app-not-using-android-x', flutterUsage: _usage).send();
      ......
    }
    //6、更新安卓專案中local.properties中的versionName和versionCode值,值來自於public.yaml檔案配置
    updateLocalProperties(project: project, buildInfo: androidBuildInfo.buildInfo);
	//7、編譯aar的話就走buildPluginsAsAar方法進行
    if (shouldBuildPluginAsAar) {
      // Create a settings.gradle that doesn't import the plugins as subprojects.
      createSettingsAarGradle(project.android.hostAppGradleRoot, _logger);
      await buildPluginsAsAar(
        project,
        androidBuildInfo,
        buildDirectory: buildDirectory.childDirectory('app'),
      );
    }
	//8、獲取編譯apk或者aab對應的標準安卓task name,構建引數等資訊,也就是gradle命令後面一堆的引數構造
    final BuildInfo buildInfo = androidBuildInfo.buildInfo;
    final String assembleTask = isBuildingBundle
        ? getBundleTaskFor(buildInfo)
        : getAssembleTaskFor(buildInfo);
	......
    final List<String> command = <String>[
      _gradleUtils.getExecutable(project),
    ];
    ......
    //9、依據條件追加command的一堆引數,譬如-Psplit-per-abi=true、-Pverbose=true、--no-daemon等
    ......
    try {
      exitCode = await _processUtils.stream(
        command,
        workingDirectory: project.android.hostAppGradleRoot.path,
        allowReentrantFlutter: true,
        environment: <String, String>{
          if (javaPath != null)
            'JAVA_HOME': javaPath,
        },
        mapFunction: consumeLog,
      );
    } on ProcessException catch (exception) {
      ......
    } finally {
      status.stop();
    }
    ......
  }
  ......
}
複製程式碼

哈哈,真相了,這下配合《Flutter Android 工程結構及應用層編譯原始碼深入分析》一文首尾呼應後你應該徹底明白 Flutter android apk 是怎麼編譯的流程!

總結

現在我們結合《Flutter Android 工程結構及應用層編譯原始碼深入分析》和這篇進行關聯總結,可以總結出執行flutter build apk命令背後的大致主流程如下: 在這裡插入圖片描述 既然執行flutter build apk命令你都搞明白了,那麼其他 flutter 相關的任何命令你是否也可以自己舉一反三進行分析學習,本質都一樣哈。由於我這裡時間有限,所以對於flutter pub getflutter doctor等其他命令不再做詳細分析。

相關文章