os.dart 13.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:archive/archive.dart';
6 7 8
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
9

10
import '../build_info.dart';
11
import '../globals.dart' as globals;
12
import 'common.dart';
13
import 'file_system.dart';
14
import 'io.dart';
15
import 'logger.dart';
16
import 'platform.dart';
17
import 'process.dart';
18

19
abstract class OperatingSystemUtils {
20 21 22 23 24 25 26 27 28 29 30 31 32
  factory OperatingSystemUtils({
    @required FileSystem fileSystem,
    @required Logger logger,
    @required Platform platform,
    @required ProcessManager processManager,
  }) {
    if (platform.isWindows) {
      return _WindowsUtils(
        fileSystem: fileSystem,
        logger: logger,
        platform: platform,
        processManager: processManager,
      );
33 34 35 36 37 38 39
    } else if (platform.isMacOS) {
      return _MacOSUtils(
        fileSystem: fileSystem,
        logger: logger,
        platform: platform,
        processManager: processManager,
      );
40
    } else {
41 42 43 44 45 46
      return _PosixUtils(
        fileSystem: fileSystem,
        logger: logger,
        platform: platform,
        processManager: processManager,
      );
47 48 49
    }
  }

50 51 52 53 54 55 56 57 58 59 60 61 62 63
  OperatingSystemUtils._private({
    @required FileSystem fileSystem,
    @required Logger logger,
    @required Platform platform,
    @required ProcessManager processManager,
  }) : _fileSystem = fileSystem,
       _logger = logger,
       _platform = platform,
       _processManager = processManager,
       _processUtils = ProcessUtils(
        logger: logger,
        processManager: processManager,
      );

64 65 66
  @visibleForTesting
  static final GZipCodec gzipLevel1 = GZipCodec(level: 1);

67 68 69 70 71
  final FileSystem _fileSystem;
  final Logger _logger;
  final Platform _platform;
  final ProcessManager _processManager;
  final ProcessUtils _processUtils;
72

73
  /// Make the given file executable. This may be a no-op on some platforms.
74 75 76 77 78 79 80 81 82
  void makeExecutable(File file);

  /// Updates the specified file system [entity] to have the file mode
  /// bits set to the value defined by [mode], which can be specified in octal
  /// (e.g. `644`) or symbolically (e.g. `u+x`).
  ///
  /// On operating systems that do not support file mode bits, this will be a
  /// no-op.
  void chmod(FileSystemEntity entity, String mode);
83

84
  /// Return the path (with symlinks resolved) to the given executable, or null
85
  /// if `which` was not able to locate the binary.
86 87
  File which(String execName) {
    final List<File> result = _which(execName);
88
    if (result == null || result.isEmpty) {
89
      return null;
90
    }
91 92
    return result.first;
  }
93

94 95
  /// Return a list of all paths to `execName` found on the system. Uses the
  /// PATH environment variable.
96
  List<File> whichAll(String execName) => _which(execName, all: true);
97

98 99 100
  /// Return the File representing a new pipe.
  File makePipe(String path);

101
  void unzip(File file, Directory targetDirectory);
102

103 104
  void unpack(File gzippedTarFile, Directory targetDirectory);

105 106 107 108 109
  /// Compresses a stream using gzip level 1 (faster but larger).
  Stream<List<int>> gzipLevel1Stream(Stream<List<int>> stream) {
    return stream.cast<List<int>>().transform<List<int>>(gzipLevel1.encoder);
  }

110 111 112 113
  /// Returns a pretty name string for the current operating system.
  ///
  /// If available, the detailed version of the OS is included.
  String get name {
114
    const Map<String, String> osNames = <String, String>{
115 116
      'macos': 'Mac OS',
      'linux': 'Linux',
117
      'windows': 'Windows',
118
    };
119
    final String osName = _platform.operatingSystem;
120 121 122
    return osNames.containsKey(osName) ? osNames[osName] : osName;
  }

123 124
  HostPlatform get hostPlatform;

125
  List<File> _which(String execName, { bool all = false });
126 127 128

  /// Returns the separator between items in the PATH environment variable.
  String get pathVarSeparator;
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

  /// Returns an unused network port.
  ///
  /// Returns 0 if an unused port cannot be found.
  ///
  /// The port returned by this function may become used before it is bound by
  /// its intended user.
  Future<int> findFreePort({bool ipv6 = false}) async {
    int port = 0;
    ServerSocket serverSocket;
    final InternetAddress loopback =
        ipv6 ? InternetAddress.loopbackIPv6 : InternetAddress.loopbackIPv4;
    try {
      serverSocket = await ServerSocket.bind(loopback, 0);
      port = serverSocket.port;
    } on SocketException catch (e) {
      // If ipv4 loopback bind fails, try ipv6.
      if (!ipv6) {
        return findFreePort(ipv6: true);
      }
149
      _logger.printTrace('findFreePort failed: $e');
150
    } on Exception catch (e) {
151
      // Failures are signaled by a return value of 0 from this function.
152
      _logger.printTrace('findFreePort failed: $e');
153 154 155 156 157 158 159
    } finally {
      if (serverSocket != null) {
        await serverSocket.close();
      }
    }
    return port;
  }
160 161
}

162
class _PosixUtils extends OperatingSystemUtils {
163 164 165 166 167 168 169 170 171 172 173
  _PosixUtils({
    @required FileSystem fileSystem,
    @required Logger logger,
    @required Platform platform,
    @required ProcessManager processManager,
  }) : super._private(
    fileSystem: fileSystem,
    logger: logger,
    platform: platform,
    processManager: processManager,
  );
174

175
  @override
176 177 178 179 180 181 182
  void makeExecutable(File file) {
    chmod(file, 'a+x');
  }

  @override
  void chmod(FileSystemEntity entity, String mode) {
    try {
183 184 185
      final ProcessResult result = _processManager.runSync(
        <String>['chmod', mode, entity.path],
      );
186
      if (result.exitCode != 0) {
187
        _logger.printTrace(
188 189 190 191 192 193
          'Error trying to run chmod on ${entity.absolute.path}'
          '\nstdout: ${result.stdout}'
          '\nstderr: ${result.stderr}',
        );
      }
    } on ProcessException catch (error) {
194 195 196
      _logger.printTrace(
        'Error trying to run chmod on ${entity.absolute.path}: $error',
      );
197
    }
198
  }
199

200
  @override
201
  List<File> _which(String execName, { bool all = false }) {
202 203 204 205 206
    final List<String> command = <String>[
      'which',
      if (all) '-a',
      execName,
    ];
207
    final ProcessResult result = _processManager.runSync(command);
208
    if (result.exitCode != 0) {
209
      return const <File>[];
210
    }
211
    final String stdout = result.stdout as String;
212 213 214
    return stdout.trim().split('\n').map<File>(
      (String path) => _fileSystem.file(path.trim()),
    ).toList();
215
  }
216 217 218 219

  // unzip -o -q zipfile -d dest
  @override
  void unzip(File file, Directory targetDirectory) {
220 221 222 223 224 225
    try {
      _processUtils.runSync(
        <String>['unzip', '-o', '-q', file.path, '-d', targetDirectory.path],
        throwOnError: true,
        verboseExceptions: true,
      );
226
    } on ArgumentError {
227 228 229 230 231 232 233 234 235 236 237 238
      // unzip is not available. this error message is modeled after the download
      // error in bin/internal/update_dart_sdk.sh
      String message = 'Please install unzip.';
      if (_platform.isMacOS) {
        message = 'Consider running "brew install unzip".';
      } else if (_platform.isLinux) {
        message = 'Consider running "sudo apt-get install unzip".';
      }
      throwToolExit(
        'Missing "unzip" tool. Unable to extract ${file.path}.\n$message'
      );
    }
239
  }
240

241 242 243
  // tar -xzf tarball -C dest
  @override
  void unpack(File gzippedTarFile, Directory targetDirectory) {
244
    _processUtils.runSync(
245 246 247
      <String>['tar', '-xzf', gzippedTarFile.path, '-C', targetDirectory.path],
      throwOnError: true,
    );
248 249
  }

250 251
  @override
  File makePipe(String path) {
252
    _processUtils.runSync(
253 254 255
      <String>['mkfifo', path],
      throwOnError: true,
    );
256
    return _fileSystem.file(path);
257
  }
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  @override
  String get pathVarSeparator => ':';

  @override
  HostPlatform hostPlatform = HostPlatform.linux_x64;
}

class _MacOSUtils extends _PosixUtils {
  _MacOSUtils({
    @required FileSystem fileSystem,
    @required Logger logger,
    @required Platform platform,
    @required ProcessManager processManager,
  }) : super(
          fileSystem: fileSystem,
          logger: logger,
          platform: platform,
          processManager: processManager,
        );

279 280 281 282
  String _name;

  @override
  String get name {
283
    if (_name == null) {
284 285 286 287 288 289 290 291
      final List<RunResult> results = <RunResult>[
        _processUtils.runSync(<String>['sw_vers', '-productName']),
        _processUtils.runSync(<String>['sw_vers', '-productVersion']),
        _processUtils.runSync(<String>['sw_vers', '-buildVersion']),
      ];
      if (results.every((RunResult result) => result.exitCode == 0)) {
        _name =
            '${results[0].stdout.trim()} ${results[1].stdout.trim()} ${results[2].stdout.trim()} ${getNameForHostPlatform(hostPlatform)}';
292 293
      }
      _name ??= super.name;
294
    }
295
    return _name;
296
  }
297

298 299 300
  HostPlatform _hostPlatform;

  // On ARM returns arm64, even when this process is running in Rosetta.
301
  @override
302 303
  HostPlatform get hostPlatform {
    if (_hostPlatform == null) {
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
      String sysctlPath;
      if (which('sysctl') == null) {
        // Fallback to known install locations.
        for (final String path in <String>[
          '/usr/sbin/sysctl',
          '/sbin/sysctl',
        ]) {
          if (_fileSystem.isFileSync(path)) {
            sysctlPath = path;
          }
        }
      } else {
        sysctlPath = 'sysctl';
      }

      if (sysctlPath == null) {
        throwToolExit('sysctl not found. Try adding it to your PATH environment variable.');
      }
322
      final RunResult arm64Check =
323
          _processUtils.runSync(<String>[sysctlPath, 'hw.optional.arm64']);
324
      // On arm64 stdout is "sysctl hw.optional.arm64: 1"
325
      // On x86 hw.optional.arm64 is unavailable and exits with 1.
326 327 328 329 330 331 332 333
      if (arm64Check.exitCode == 0 && arm64Check.stdout.trim().endsWith('1')) {
        _hostPlatform = HostPlatform.darwin_arm;
      } else {
        _hostPlatform = HostPlatform.darwin_x64;
      }
    }
    return _hostPlatform;
  }
334 335
}

336
class _WindowsUtils extends OperatingSystemUtils {
337 338 339 340 341 342 343 344 345 346
  _WindowsUtils({
    @required FileSystem fileSystem,
    @required Logger logger,
    @required Platform platform,
    @required ProcessManager processManager,
  }) : super._private(
    fileSystem: fileSystem,
    logger: logger,
    platform: platform,
    processManager: processManager,
347
  );
348

349 350 351
  @override
  HostPlatform hostPlatform = HostPlatform.windows_x64;

352
  @override
353 354 355 356
  void makeExecutable(File file) {}

  @override
  void chmod(FileSystemEntity entity, String mode) {}
357

358
  @override
359
  List<File> _which(String execName, { bool all = false }) {
360
    // `where` always returns all matches, not just the first one.
361 362 363
    ProcessResult result;
    try {
      result = _processManager.runSync(<String>['where', execName]);
364
    } on ArgumentError {
365 366 367
      // `where` could be missing if system32 is not on the PATH.
      throwToolExit(
        'Cannot find the executable for `where`. This can happen if the System32 '
368
        r'folder (e.g. C:\Windows\System32 ) is removed from the PATH environment '
369 370 371 372
        'variable. Ensure that this is present and then try again after restarting '
        'the terminal and/or IDE.'
      );
    }
373
    if (result.exitCode != 0) {
374
      return const <File>[];
375
    }
376
    final List<String> lines = (result.stdout as String).trim().split('\n');
377
    if (all) {
378
      return lines.map<File>((String path) => _fileSystem.file(path.trim())).toList();
379
    }
380
    return <File>[_fileSystem.file(lines.first.trim())];
381 382 383 384
  }

  @override
  void unzip(File file, Directory targetDirectory) {
385 386
    final Archive archive = ZipDecoder().decodeBytes(file.readAsBytesSync());
    _unpackArchive(archive, targetDirectory);
387 388 389 390
  }

  @override
  void unpack(File gzippedTarFile, Directory targetDirectory) {
391 392
    final Archive archive = TarDecoder().decodeBytes(
      GZipDecoder().decodeBytes(gzippedTarFile.readAsBytesSync()),
393 394 395
    );
    _unpackArchive(archive, targetDirectory);
  }
396

397
  void _unpackArchive(Archive archive, Directory targetDirectory) {
398
    for (final ArchiveFile archiveFile in archive.files) {
399
      // The archive package doesn't correctly set isFile.
400
      if (!archiveFile.isFile || archiveFile.name.endsWith('/')) {
401
        continue;
402
      }
403

404 405 406 407
      final File destFile = _fileSystem.file(_fileSystem.path.join(
        targetDirectory.path,
        archiveFile.name,
      ));
408
      if (!destFile.parent.existsSync()) {
409
        destFile.parent.createSync(recursive: true);
410
      }
411
      destFile.writeAsBytesSync(archiveFile.content as List<int>);
412
    }
413
  }
414 415 416

  @override
  File makePipe(String path) {
417
    throw UnsupportedError('makePipe is not implemented on Windows.');
418
  }
419 420 421 422 423 424

  String _name;

  @override
  String get name {
    if (_name == null) {
425
      final ProcessResult result = _processManager.runSync(
426
          <String>['ver'], runInShell: true);
427
      if (result.exitCode == 0) {
428
        _name = (result.stdout as String).trim();
429
      } else {
430
        _name = super.name;
431
      }
432 433 434
    }
    return _name;
  }
435 436 437

  @override
  String get pathVarSeparator => ';';
438
}
439

440 441
/// Find and return the project root directory relative to the specified
/// directory or the current working directory if none specified.
442
/// Return null if the project root could not be found
443
/// or if the project root is the flutter repository root.
444
String findProjectRoot([ String directory ]) {
445
  const String kProjectRootSentinel = 'pubspec.yaml';
446
  directory ??= globals.fs.currentDirectory.path;
447
  while (true) {
448
    if (globals.fs.isFileSync(globals.fs.path.join(directory, kProjectRootSentinel))) {
449
      return directory;
450
    }
451
    final String parent = globals.fs.path.dirname(directory);
452
    if (directory == parent) {
453
      return null;
454
    }
455 456 457
    directory = parent;
  }
}