unpack.dart 8.44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright 2019 The Chromium 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 '../artifacts.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../build_info.dart';
import '../cache.dart';
import '../globals.dart';
import '../runner/flutter_command.dart';

/// The directory in the Flutter cache for each platform's artifacts.
14
const Map<TargetPlatform, String> flutterArtifactPlatformDirectory = <TargetPlatform, String>{
15
  TargetPlatform.windows_x64: 'windows-x64',
16
  TargetPlatform.linux_x64: 'linux-x64',
17 18 19 20 21 22
};

// TODO(jonahwilliams): this should come from a configuration in each build
// directory.
const Map<TargetPlatform, List<String>> artifactFilesByPlatform = <TargetPlatform, List<String>>{
  TargetPlatform.windows_x64: <String>[
23 24 25 26
    'flutter_windows.dll',
    'flutter_windows.dll.exp',
    'flutter_windows.dll.lib',
    'flutter_windows.dll.pdb',
27 28 29
    'flutter_export.h',
    'flutter_messenger.h',
    'flutter_plugin_registrar.h',
30
    'flutter_windows.h',
31
    'icudtl.dat',
32
    'cpp_client_wrapper/',
33 34 35 36 37 38 39 40
  ],
};

/// Copies desktop artifacts to local cache directories.
class UnpackCommand extends FlutterCommand {
  UnpackCommand() {
    argParser.addOption(
      'target-platform',
41
      allowed: <String>['windows-x64', 'linux-x64'],
42 43 44 45 46 47
    );
    argParser.addOption('cache-dir',
        help: 'Location to output platform specific artifacts.');
  }

  @override
48
  String get description => '(DEPRECATED) unpack desktop artifacts';
49 50 51 52 53 54 55

  @override
  String get name => 'unpack';

  @override
  bool get hidden => true;

56 57 58 59 60 61 62 63 64 65
  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async {
    final Set<DevelopmentArtifact> result = <DevelopmentArtifact>{
      DevelopmentArtifact.universal,
    };
    final TargetPlatform targetPlatform = getTargetPlatformForName(argResults['target-platform']);
    switch (targetPlatform) {
      case TargetPlatform.windows_x64:
        result.add(DevelopmentArtifact.windows);
        break;
66 67 68
      case TargetPlatform.linux_x64:
        result.add(DevelopmentArtifact.linux);
        break;
69 70 71 72 73
      default:
    }
    return result;
  }

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  @override
  Future<FlutterCommandResult> runCommand() async {
    final String targetName = argResults['target-platform'];
    final String targetDirectory = argResults['cache-dir'];
    if (!fs.directory(targetDirectory).existsSync()) {
      fs.directory(targetDirectory).createSync(recursive: true);
    }
    final TargetPlatform targetPlatform = getTargetPlatformForName(targetName);
    final ArtifactUnpacker flutterArtifactFetcher = ArtifactUnpacker(targetPlatform);
    bool success = true;
    if (artifacts is LocalEngineArtifacts) {
      final LocalEngineArtifacts localEngineArtifacts = artifacts;
      success = flutterArtifactFetcher.copyLocalBuildArtifacts(
        localEngineArtifacts.engineOutPath,
        targetDirectory,
      );
    } else {
      success = flutterArtifactFetcher.copyCachedArtifacts(
        targetDirectory,
      );
    }
    if (!success) {
      throwToolExit('Failed to unpack desktop artifacts.');
    }
    return null;
  }
}

/// Manages the copying of cached or locally built Flutter artifacts, including
/// tracking the last-copied versions and updating only if necessary.
class ArtifactUnpacker {
  /// Creates a new fetcher for the given configuration.
  const ArtifactUnpacker(this.platform);

  /// The platform to copy artifacts for.
  final TargetPlatform platform;

  /// Checks [targetDirectory] to see if artifacts have already been copied for
  /// the current hash, and if not, copies the artifacts for [platform] from the
  /// Flutter cache (after ensuring that the cache is present).
  ///
  /// Returns true if the artifacts were successfully copied, or were already
  /// present with the correct hash.
  bool copyCachedArtifacts(String targetDirectory) {
    String cacheStamp;
    switch (platform) {
      case TargetPlatform.windows_x64:
        cacheStamp = 'windows-sdk';
        break;
123
      case TargetPlatform.linux_x64:
124
        return true;
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 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
      default:
        throwToolExit('Unsupported target platform: $platform');
    }
    final String targetHash =
        readHashFileIfPossible(Cache.instance.getStampFileFor(cacheStamp));
    if (targetHash == null) {
      printError('Failed to find engine stamp file');
      return false;
    }

    try {
      final String currentHash = _lastCopiedHash(targetDirectory);
      if (currentHash == null || targetHash != currentHash) {
        // Copy them to the target directory.
        final String flutterCacheDirectory = fs.path.join(
          Cache.flutterRoot,
          'bin',
          'cache',
          'artifacts',
          'engine',
          flutterArtifactPlatformDirectory[platform],
        );
        if (!_copyArtifactFiles(flutterCacheDirectory, targetDirectory)) {
          return false;
        }
        _setLastCopiedHash(targetDirectory, targetHash);
        printTrace('Copied artifacts for version $targetHash.');
      } else {
        printTrace('Artifacts for version $targetHash already present.');
      }
    } catch (error, stackTrace) {
      printError(stackTrace.toString());
      printError(error.toString());
      return false;
    }
    return true;
  }

  /// Acts like [copyCachedArtifacts], replacing the artifacts and updating
  /// the version stamp, except that it pulls the artifact from a local engine
  /// build with the given [buildConfiguration] (e.g., host_debug_unopt) whose
  /// checkout is rooted at [engineRoot].
  bool copyLocalBuildArtifacts(String buildOutput, String targetDirectory) {
    if (!_copyArtifactFiles(buildOutput, targetDirectory)) {
      return false;
    }

    // Update the hash file to indicate that it's a local build, so that it's
    // obvious where it came from.
    _setLastCopiedHash(targetDirectory, 'local build: $buildOutput');

    return true;
  }

  /// Copies the artifact files for [platform] from [sourceDirectory] to
  /// [targetDirectory].
  bool _copyArtifactFiles(String sourceDirectory, String targetDirectory) {
    final List<String> artifactFiles = artifactFilesByPlatform[platform];
    if (artifactFiles == null) {
      printError('Unsupported platform: $platform.');
      return false;
    }

    try {
      fs.directory(targetDirectory).createSync(recursive: true);
190 191 192 193 194 195 196 197 198 199 200
      for (final String entityName in artifactFiles) {
        final String sourcePath = fs.path.join(sourceDirectory, entityName);
        final String targetPath = fs.path.join(targetDirectory, entityName);
        if (entityName.endsWith('/')) {
          copyDirectorySync(
            fs.directory(sourcePath),
            fs.directory(targetPath),
          );
        } else {
          fs.file(sourcePath)
            .copySync(fs.path.join(targetDirectory, entityName));
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
        }
      }

      printTrace('Copied artifacts from $sourceDirectory.');
    } catch (e, stackTrace) {
      printError(stackTrace.toString());
      printError(e.message);
      return false;
    }
    return true;
  }

  /// Returns a File object for the file containing the last copied hash
  /// in [directory].
  File _lastCopiedHashFile(String directory) {
    return fs.file(fs.path.join(directory, '.last_artifact_version'));
  }

  /// Returns the hash of the artifacts last copied to [directory], or null if
  /// they haven't been copied.
  String _lastCopiedHash(String directory) {
    // Sanity check that at least one file is present; this won't catch every
    // case, but handles someone deleting all the non-hidden cached files to
    // force fresh copy.
    final String artifactFilePath = fs.path.join(
      directory,
      artifactFilesByPlatform[platform].first,
    );
    if (!fs.file(artifactFilePath).existsSync()) {
      return null;
    }
    final File hashFile = _lastCopiedHashFile(directory);
    return readHashFileIfPossible(hashFile);
  }

  /// Writes [hash] to the file that stores the last copied hash for
  /// in [directory].
  void _setLastCopiedHash(String directory, String hash) {
    _lastCopiedHashFile(directory).writeAsStringSync(hash);
  }

  /// Returns the engine hash from [file] as a String, or null.
  ///
  /// If the file is missing, or cannot be read, returns null.
  String readHashFileIfPossible(File file) {
    if (!file.existsSync()) {
      return null;
    }
    try {
      return file.readAsStringSync().trim();
    } on FileSystemException {
      // If the file can't be read for any reason, just treat it as missing.
      return null;
    }
  }
}