custom_device_config.dart 20 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:meta/meta.dart';

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
import '../base/platform.dart';
import '../build_info.dart';

/// Quiver has this, but unfortunately we can't depend on it bc flutter_tools
/// uses non-nullsafe quiver by default (because of dwds).
bool _listsEqual(List<dynamic>? a, List<dynamic>? b) {
  if (a == b) {
    return true;
  }
  if (a == null || b == null) {
    return false;
  }
  if (a.length != b.length) {
    return false;
  }

  return a.asMap().entries.every((MapEntry<int, dynamic> e) => e.value == b[e.key]);
}

/// The normal [RegExp.==] operator is inherited from [Object], so only
/// returns true when the regexes are the same instance.
///
/// This function instead _should_ return true when the regexes are
/// functionally the same, i.e. when they have the same matches & captures for
/// any given input. At least that's the goal, in reality this has lots of false
/// negatives (for example when the flags differ). Still better than [RegExp.==].
bool _regexesEqual(RegExp? a, RegExp? b) {
  if (a == b) {
    return true;
  }
  if (a == null || b == null) {
    return false;
  }

  return a.pattern == b.pattern
    && a.isMultiLine == b.isMultiLine
    && a.isCaseSensitive == b.isCaseSensitive
    && a.isUnicode == b.isUnicode
    && a.isDotAll == b.isDotAll;
}

/// Something went wrong while trying to load the custom devices config from the
/// JSON representation. Maybe some value is missing, maybe something has the
/// wrong type, etc.
@immutable
class CustomDeviceRevivalException implements Exception {
  const CustomDeviceRevivalException(this.message);

  const CustomDeviceRevivalException.fromDescriptions(
    String fieldDescription,
    String expectedValueDescription
  ) : message = 'Expected $fieldDescription to be $expectedValueDescription.';

  final String message;

  @override
  String toString() {
    return message;
  }

  @override
  bool operator ==(Object other) {
    return (other is CustomDeviceRevivalException) &&
        (other.message == message);
  }

  @override
  int get hashCode => message.hashCode;
}

77 78 79 80 81 82 83 84 85 86
/// A single configured custom device.
///
/// In the custom devices config file on disk, there may be multiple custom
/// devices configured.
@immutable
class CustomDeviceConfig {
  const CustomDeviceConfig({
    required this.id,
    required this.label,
    required this.sdkNameAndVersion,
87 88
    this.platform,
    required this.enabled,
89 90 91 92 93 94 95
    required this.pingCommand,
    this.pingSuccessRegex,
    required this.postBuildCommand,
    required this.installCommand,
    required this.uninstallCommand,
    required this.runDebugCommand,
    this.forwardPortCommand,
96 97
    this.forwardPortSuccessRegex,
    this.screenshotCommand
98 99 100 101 102 103
  }) : assert(forwardPortCommand == null || forwardPortSuccessRegex != null),
       assert(
         platform == null
         || platform == TargetPlatform.linux_x64
         || platform == TargetPlatform.linux_arm64
       );
104

105 106 107 108 109
  /// Create a CustomDeviceConfig from some JSON value.
  /// If anything fails internally (some value doesn't have the right type,
  /// some value is missing, etc) a [CustomDeviceRevivalException] with the description
  /// of the error is thrown. (No exceptions/errors other than JsonRevivalException
  /// should ever be thrown by this factory.)
110
  factory CustomDeviceConfig.fromJson(dynamic json) {
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    final Map<String, dynamic> typedMap = _castJsonObject(
      json,
      'device configuration',
      'a JSON object'
    );

    final List<String>? forwardPortCommand = _castStringListOrNull(
      typedMap[_kForwardPortCommand],
      _kForwardPortCommand,
      'null or array of strings with at least one element',
      minLength: 1
    );

    final RegExp? forwardPortSuccessRegex = _convertToRegexOrNull(
      typedMap[_kForwardPortSuccessRegex],
      _kForwardPortSuccessRegex,
      'null or string-ified regex'
    );

    final String? archString = _castStringOrNull(
      typedMap[_kPlatform],
      _kPlatform,
      'null or one of linux-arm64, linux-x64'
    );

    late TargetPlatform? platform;
    try {
      platform = archString == null
        ? null
        : getTargetPlatformForName(archString);
141
    } on UnsupportedError {
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
      throw const CustomDeviceRevivalException.fromDescriptions(
        _kPlatform,
        'null or one of linux-arm64, linux-x64'
      );
    }

    if (platform != null
        && platform != TargetPlatform.linux_arm64
        && platform != TargetPlatform.linux_x64
    ) {
      throw const CustomDeviceRevivalException.fromDescriptions(
        _kPlatform,
        'null or one of linux-arm64, linux-x64'
      );
    }

    if (forwardPortCommand != null && forwardPortSuccessRegex == null) {
      throw const CustomDeviceRevivalException('When forwardPort is given, forwardPortSuccessRegex must be specified too.');
    }
161 162

    return CustomDeviceConfig(
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
      id: _castString(typedMap[_kId], _kId, 'a string'),
      label: _castString(typedMap[_kLabel], _kLabel, 'a string'),
      sdkNameAndVersion: _castString(typedMap[_kSdkNameAndVersion], _kSdkNameAndVersion, 'a string'),
      platform: platform,
      enabled: _castBool(typedMap[_kEnabled], _kEnabled, 'a boolean'),
      pingCommand: _castStringList(
        typedMap[_kPingCommand],
        _kPingCommand,
        'array of strings with at least one element',
        minLength: 1
      ),
      pingSuccessRegex: _convertToRegexOrNull(typedMap[_kPingSuccessRegex], _kPingSuccessRegex, 'null or string-ified regex'),
      postBuildCommand: _castStringListOrNull(
        typedMap[_kPostBuildCommand],
        _kPostBuildCommand,
        'null or array of strings with at least one element',
        minLength: 1,
      ),
      installCommand: _castStringList(
        typedMap[_kInstallCommand],
        _kInstallCommand,
        'array of strings with at least one element',
        minLength: 1
      ),
      uninstallCommand: _castStringList(
        typedMap[_kUninstallCommand],
        _kUninstallCommand,
        'array of strings with at least one element',
        minLength: 1
      ),
      runDebugCommand: _castStringList(
        typedMap[_kRunDebugCommand],
        _kRunDebugCommand,
        'array of strings with at least one element',
        minLength: 1
      ),
      forwardPortCommand: forwardPortCommand,
      forwardPortSuccessRegex: forwardPortSuccessRegex,
      screenshotCommand: _castStringListOrNull(
        typedMap[_kScreenshotCommand],
        _kScreenshotCommand,
        'array of strings with at least one element',
        minLength: 1
      )
207 208 209 210 211 212
    );
  }

  static const String _kId = 'id';
  static const String _kLabel = 'label';
  static const String _kSdkNameAndVersion = 'sdkNameAndVersion';
213 214
  static const String _kPlatform = 'platform';
  static const String _kEnabled = 'enabled';
215 216 217 218 219 220 221 222
  static const String _kPingCommand = 'ping';
  static const String _kPingSuccessRegex = 'pingSuccessRegex';
  static const String _kPostBuildCommand = 'postBuild';
  static const String _kInstallCommand = 'install';
  static const String _kUninstallCommand = 'uninstall';
  static const String _kRunDebugCommand = 'runDebug';
  static const String _kForwardPortCommand = 'forwardPort';
  static const String _kForwardPortSuccessRegex = 'forwardPortSuccessRegex';
223
  static const String _kScreenshotCommand = 'screenshot';
224 225

  /// An example device config used for creating the default config file.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
  /// Uses windows-specific ping and pingSuccessRegex. For the linux and macOs
  /// example config, see [exampleUnix].
  static final CustomDeviceConfig exampleWindows = CustomDeviceConfig(
    id: 'pi',
    label: 'Raspberry Pi',
    sdkNameAndVersion: 'Raspberry Pi 4 Model B+',
    platform: TargetPlatform.linux_arm64,
    enabled: false,
    pingCommand: const <String>[
      'ping',
      '-w', '500',
      '-n', '1',
      'raspberrypi',
    ],
    pingSuccessRegex: RegExp(r'[<=]\d+ms'),
241
    postBuildCommand: null,
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    installCommand: const <String>[
      'scp',
      '-r',
      '-o', 'BatchMode=yes',
      r'${localPath}',
      r'pi@raspberrypi:/tmp/${appName}',
    ],
    uninstallCommand: const <String>[
      'ssh',
      '-o', 'BatchMode=yes',
      'pi@raspberrypi',
      r'rm -rf "/tmp/${appName}"',
    ],
    runDebugCommand: const <String>[
      'ssh',
      '-o', 'BatchMode=yes',
      'pi@raspberrypi',
      r'flutter-pi "/tmp/${appName}"',
    ],
    forwardPortCommand: const <String>[
      'ssh',
      '-o', 'BatchMode=yes',
      '-o', 'ExitOnForwardFailure=yes',
      '-L', r'127.0.0.1:${hostPort}:127.0.0.1:${devicePort}',
      'pi@raspberrypi',
267
      "echo 'Port forwarding success'; read",
268
    ],
269
    forwardPortSuccessRegex: RegExp('Port forwarding success'),
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    screenshotCommand: const <String>[
      'ssh',
      '-o', 'BatchMode=yes',
      'pi@raspberrypi',
      r"fbgrab /tmp/screenshot.png && cat /tmp/screenshot.png | base64 | tr -d ' \n\t'",
    ],
  );

  /// An example device config used for creating the default config file.
  /// Uses ping and pingSuccessRegex values that only work on linux or macOs.
  /// For the Windows example config, see [exampleWindows].
  static final CustomDeviceConfig exampleUnix = exampleWindows.copyWith(
    pingCommand: const <String>[
      'ping',
      '-w', '1',
      '-c', '1',
286
      'raspberrypi',
287
    ],
288
    explicitPingSuccessRegex: true
289 290
  );

291 292 293 294 295 296 297 298 299 300 301 302
  /// Returns an example custom device config that works on the given host platform.
  ///
  /// This is not the platform of the target device, it's the platform of the
  /// development machine. Examples for different platforms may be different
  /// because for example the ping command is different on Windows or Linux/macOS.
  static CustomDeviceConfig getExampleForPlatform(Platform platform) {
    if (platform.isWindows) {
      return exampleWindows;
    }
    if (platform.isLinux || platform.isMacOS) {
      return exampleUnix;
    }
303
    throw UnsupportedError('Unsupported operating system');
304 305
  }

306 307 308
  final String id;
  final String label;
  final String sdkNameAndVersion;
309 310
  final TargetPlatform? platform;
  final bool enabled;
311 312 313 314 315 316 317 318
  final List<String> pingCommand;
  final RegExp? pingSuccessRegex;
  final List<String>? postBuildCommand;
  final List<String> installCommand;
  final List<String> uninstallCommand;
  final List<String> runDebugCommand;
  final List<String>? forwardPortCommand;
  final RegExp? forwardPortSuccessRegex;
319
  final List<String>? screenshotCommand;
320

321 322
  /// Returns true when this custom device config uses port forwarding,
  /// which is the case when [forwardPortCommand] is not null.
323 324
  bool get usesPortForwarding => forwardPortCommand != null;

325 326
  /// Returns true when this custom device config supports screenshotting,
  /// which is the case when the [screenshotCommand] is not null.
327 328
  bool get supportsScreenshotting => screenshotCommand != null;

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
  /// Invokes and returns the result of [closure].
  ///
  /// If anything at all is thrown when executing the closure, a
  /// [CustomDeviceRevivalException] is thrown with the given [fieldDescription] and
  /// [expectedValueDescription].
  static T _maybeRethrowAsRevivalException<T>(T Function() closure, String fieldDescription, String expectedValueDescription) {
    try {
      return closure();
    } on Object {
      throw CustomDeviceRevivalException.fromDescriptions(fieldDescription, expectedValueDescription);
    }
  }

  /// Tries to make a string-keyed, non-null map from [value].
  ///
  /// If the value is null or not a valid string-keyed map, a [CustomDeviceRevivalException]
  /// with the given [fieldDescription] and [expectedValueDescription] is thrown.
  static Map<String, dynamic> _castJsonObject(dynamic value, String fieldDescription, String expectedValueDescription) {
    if (value == null) {
      throw CustomDeviceRevivalException.fromDescriptions(fieldDescription, expectedValueDescription);
    }

    return _maybeRethrowAsRevivalException(
      () => Map<String, dynamic>.from(value as Map<dynamic, dynamic>),
      fieldDescription,
      expectedValueDescription,
    );
  }

  /// Tries to cast [value] to a bool.
  ///
  /// If the value is null or not a bool, a [CustomDeviceRevivalException] with the given
  /// [fieldDescription] and [expectedValueDescription] is thrown.
  static bool _castBool(dynamic value, String fieldDescription, String expectedValueDescription) {
    if (value == null) {
      throw CustomDeviceRevivalException.fromDescriptions(fieldDescription, expectedValueDescription);
    }

    return _maybeRethrowAsRevivalException(
      () => value as bool,
      fieldDescription,
      expectedValueDescription,
    );
372 373
  }

374 375 376 377 378 379 380 381 382 383 384 385 386 387
  /// Tries to cast [value] to a String.
  ///
  /// If the value is null or not a String, a [CustomDeviceRevivalException] with the given
  /// [fieldDescription] and [expectedValueDescription] is thrown.
  static String _castString(dynamic value, String fieldDescription, String expectedValueDescription) {
    if (value == null) {
      throw CustomDeviceRevivalException.fromDescriptions(fieldDescription, expectedValueDescription);
    }

    return _maybeRethrowAsRevivalException(
      () => value as String,
      fieldDescription,
      expectedValueDescription,
    );
388 389
  }

390 391 392 393 394 395 396 397 398 399
  /// Tries to cast [value] to a nullable String.
  ///
  /// If the value not null and not a String, a [CustomDeviceRevivalException] with the given
  /// [fieldDescription] and [expectedValueDescription] is thrown.
  static String? _castStringOrNull(dynamic value, String fieldDescription, String expectedValueDescription) {
    if (value == null) {
      return null;
    }

    return _castString(value, fieldDescription, expectedValueDescription);
400 401
  }

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  /// Tries to make a list of strings from [value].
  ///
  /// If the value is null or not a list containing only string values,
  /// a [CustomDeviceRevivalException] with the given [fieldDescription] and
  /// [expectedValueDescription] is thrown.
  static List<String> _castStringList(
    dynamic value,
    String fieldDescription,
    String expectedValueDescription, {
    int minLength = 0,
  }) {
    if (value == null) {
      throw CustomDeviceRevivalException.fromDescriptions(fieldDescription, expectedValueDescription);
    }

    final List<String> list = _maybeRethrowAsRevivalException(
      () => List<String>.from(value as Iterable<dynamic>),
      fieldDescription,
      expectedValueDescription,
    );

    if (list.length < minLength) {
      throw CustomDeviceRevivalException.fromDescriptions(fieldDescription, expectedValueDescription);
    }

    return list;
  }

  /// Tries to make a list of strings from [value], or returns null if [value]
  /// is null.
  ///
  /// If the value is not null and not a list containing only string values,
  /// a [CustomDeviceRevivalException] with the given [fieldDescription] and
  /// [expectedValueDescription] is thrown.
  static List<String>? _castStringListOrNull(
    dynamic value,
    String fieldDescription,
    String expectedValueDescription, {
    int minLength = 0,
  }) {
    if (value == null) {
      return null;
    }

    return _castStringList(value, fieldDescription, expectedValueDescription, minLength: minLength);
  }

  /// Tries to construct a RegExp from [value], or returns null if [value]
  /// is null.
  ///
  /// If the value is not null and not a valid string-ified regex,
  /// a [CustomDeviceRevivalException] with the given [fieldDescription] and
  /// [expectedValueDescription] is thrown.
  static RegExp? _convertToRegexOrNull(dynamic value, String fieldDescription, String expectedValueDescription) {
    if (value == null) {
      return null;
    }

    return _maybeRethrowAsRevivalException(
      () => RegExp(value as String),
      fieldDescription,
      expectedValueDescription,
    );
  }

  Object toJson() {
468 469 470 471
    return <String, Object?>{
      _kId: id,
      _kLabel: label,
      _kSdkNameAndVersion: sdkNameAndVersion,
472 473
      _kPlatform: platform == null ? null : getNameForTargetPlatform(platform!),
      _kEnabled: enabled,
474 475
      _kPingCommand: pingCommand,
      _kPingSuccessRegex: pingSuccessRegex?.pattern,
476
      _kPostBuildCommand: (postBuildCommand?.length ?? 0) > 0 ? postBuildCommand : null,
477 478 479 480
      _kInstallCommand: installCommand,
      _kUninstallCommand: uninstallCommand,
      _kRunDebugCommand: runDebugCommand,
      _kForwardPortCommand: forwardPortCommand,
481 482
      _kForwardPortSuccessRegex: forwardPortSuccessRegex?.pattern,
      _kScreenshotCommand: screenshotCommand,
483 484 485 486 487 488 489
    };
  }

  CustomDeviceConfig copyWith({
    String? id,
    String? label,
    String? sdkNameAndVersion,
490 491 492
    bool explicitPlatform = false,
    TargetPlatform? platform,
    bool? enabled,
493 494 495 496 497 498 499 500 501 502 503
    List<String>? pingCommand,
    bool explicitPingSuccessRegex = false,
    RegExp? pingSuccessRegex,
    bool explicitPostBuildCommand = false,
    List<String>? postBuildCommand,
    List<String>? installCommand,
    List<String>? uninstallCommand,
    List<String>? runDebugCommand,
    bool explicitForwardPortCommand = false,
    List<String>? forwardPortCommand,
    bool explicitForwardPortSuccessRegex = false,
504 505 506
    RegExp? forwardPortSuccessRegex,
    bool explicitScreenshotCommand = false,
    List<String>? screenshotCommand
507 508 509 510 511
  }) {
    return CustomDeviceConfig(
      id: id ?? this.id,
      label: label ?? this.label,
      sdkNameAndVersion: sdkNameAndVersion ?? this.sdkNameAndVersion,
512 513
      platform: explicitPlatform ? platform : (platform ?? this.platform),
      enabled: enabled ?? this.enabled,
514 515 516 517 518 519 520
      pingCommand: pingCommand ?? this.pingCommand,
      pingSuccessRegex: explicitPingSuccessRegex ? pingSuccessRegex : (pingSuccessRegex ?? this.pingSuccessRegex),
      postBuildCommand: explicitPostBuildCommand ? postBuildCommand : (postBuildCommand ?? this.postBuildCommand),
      installCommand: installCommand ?? this.installCommand,
      uninstallCommand: uninstallCommand ?? this.uninstallCommand,
      runDebugCommand: runDebugCommand ?? this.runDebugCommand,
      forwardPortCommand: explicitForwardPortCommand ? forwardPortCommand : (forwardPortCommand ?? this.forwardPortCommand),
521 522
      forwardPortSuccessRegex: explicitForwardPortSuccessRegex ? forwardPortSuccessRegex : (forwardPortSuccessRegex ?? this.forwardPortSuccessRegex),
      screenshotCommand: explicitScreenshotCommand ? screenshotCommand : (screenshotCommand ?? this.screenshotCommand),
523 524
    );
  }
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

  @override
  bool operator ==(Object other) {
    return other is CustomDeviceConfig
      && other.id == id
      && other.label == label
      && other.sdkNameAndVersion == sdkNameAndVersion
      && other.platform == platform
      && other.enabled == enabled
      && _listsEqual(other.pingCommand, pingCommand)
      && _regexesEqual(other.pingSuccessRegex, pingSuccessRegex)
      && _listsEqual(other.postBuildCommand, postBuildCommand)
      && _listsEqual(other.installCommand, installCommand)
      && _listsEqual(other.uninstallCommand, uninstallCommand)
      && _listsEqual(other.runDebugCommand, runDebugCommand)
      && _listsEqual(other.forwardPortCommand, forwardPortCommand)
      && _regexesEqual(other.forwardPortSuccessRegex, forwardPortSuccessRegex)
      && _listsEqual(other.screenshotCommand, screenshotCommand);
  }

  @override
  int get hashCode {
    return id.hashCode
      ^ label.hashCode
      ^ sdkNameAndVersion.hashCode
      ^ platform.hashCode
      ^ enabled.hashCode
      ^ pingCommand.hashCode
      ^ (pingSuccessRegex?.pattern).hashCode
      ^ postBuildCommand.hashCode
      ^ installCommand.hashCode
      ^ uninstallCommand.hashCode
      ^ runDebugCommand.hashCode
      ^ forwardPortCommand.hashCode
      ^ (forwardPortSuccessRegex?.pattern).hashCode
      ^ screenshotCommand.hashCode;
  }

  @override
  String toString() {
    return 'CustomDeviceConfig('
      'id: $id, '
      'label: $label, '
      'sdkNameAndVersion: $sdkNameAndVersion, '
      'platform: $platform, '
      'enabled: $enabled, '
      'pingCommand: $pingCommand, '
      'pingSuccessRegex: $pingSuccessRegex, '
      'postBuildCommand: $postBuildCommand, '
      'installCommand: $installCommand, '
      'uninstallCommand: $uninstallCommand, '
      'runDebugCommand: $runDebugCommand, '
      'forwardPortCommand: $forwardPortCommand, '
      'forwardPortSuccessRegex: $forwardPortSuccessRegex, '
      'screenshotCommand: $screenshotCommand)';
  }
581
}