os.dart 10.3 KB
Newer Older
1 2 3 4
// Copyright 2015 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.

5
import 'package:archive/archive.dart';
6 7

import '../globals.dart';
8
import 'context.dart';
9
import 'file_system.dart';
10
import 'io.dart';
11
import 'platform.dart';
12
import 'process.dart';
13
import 'process_manager.dart';
14 15

/// Returns [OperatingSystemUtils] active in the current app context (i.e. zone).
16
OperatingSystemUtils get os => context.get<OperatingSystemUtils>();
17 18

abstract class OperatingSystemUtils {
19
  factory OperatingSystemUtils() {
20
    if (platform.isWindows) {
21
      return _WindowsUtils();
22
    } else {
23
      return _PosixUtils();
24 25 26
    }
  }

27 28
  OperatingSystemUtils._private();

29
  /// Make the given file executable. This may be a no-op on some platforms.
30 31 32 33 34 35 36 37 38
  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);
39

40
  /// Return the path (with symlinks resolved) to the given executable, or null
41
  /// if `which` was not able to locate the binary.
42 43
  File which(String execName) {
    final List<File> result = _which(execName);
44
    if (result == null || result.isEmpty) {
45
      return null;
46
    }
47 48
    return result.first;
  }
49

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

54 55 56
  /// Return the File representing a new pipe.
  File makePipe(String path);

57 58
  void zip(Directory data, File zipFile);

59
  void unzip(File file, Directory targetDirectory);
60

61 62 63
  /// Returns true if the ZIP is not corrupt.
  bool verifyZip(File file);

64 65
  void unpack(File gzippedTarFile, Directory targetDirectory);

66 67 68
  /// Returns true if the gzip is not corrupt (does not check tar).
  bool verifyGzip(File gzippedFile);

69 70 71 72
  /// Returns a pretty name string for the current operating system.
  ///
  /// If available, the detailed version of the OS is included.
  String get name {
73
    const Map<String, String> osNames = <String, String>{
74 75
      'macos': 'Mac OS',
      'linux': 'Linux',
76
      'windows': 'Windows',
77 78 79 80 81
    };
    final String osName = platform.operatingSystem;
    return osNames.containsKey(osName) ? osNames[osName] : osName;
  }

82
  List<File> _which(String execName, { bool all = false });
83 84 85

  /// Returns the separator between items in the PATH environment variable.
  String get pathVarSeparator;
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

  /// 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);
      }
      printTrace('findFreePort failed: $e');
    } catch (e) {
      // Failures are signaled by a return value of 0 from this function.
      printTrace('findFreePort failed: $e');
    } finally {
      if (serverSocket != null) {
        await serverSocket.close();
      }
    }
    return port;
  }
117 118
}

119 120 121
class _PosixUtils extends OperatingSystemUtils {
  _PosixUtils() : super._private();

122
  @override
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  void makeExecutable(File file) {
    chmod(file, 'a+x');
  }

  @override
  void chmod(FileSystemEntity entity, String mode) {
    try {
      final ProcessResult result = processManager.runSync(<String>['chmod', mode, entity.path]);
      if (result.exitCode != 0) {
        printTrace(
          'Error trying to run chmod on ${entity.absolute.path}'
          '\nstdout: ${result.stdout}'
          '\nstderr: ${result.stderr}',
        );
      }
    } on ProcessException catch (error) {
      printTrace('Error trying to run chmod on ${entity.absolute.path}: $error');
    }
141
  }
142

143
  @override
144
  List<File> _which(String execName, { bool all = false }) {
145 146 147 148 149
    final List<String> command = <String>[
      'which',
      if (all) '-a',
      execName,
    ];
150
    final ProcessResult result = processManager.runSync(command);
151
    if (result.exitCode != 0) {
152
      return const <File>[];
153
    }
154
    final String stdout = result.stdout;
155
    return stdout.trim().split('\n').map<File>((String path) => fs.file(path.trim())).toList();
156
  }
157

158 159
  @override
  void zip(Directory data, File zipFile) {
160 161 162 163 164
    processUtils.runSync(
      <String>['zip', '-r', '-q', zipFile.path, '.'],
      workingDirectory: data.path,
      throwOnError: true,
    );
165 166
  }

167 168 169
  // unzip -o -q zipfile -d dest
  @override
  void unzip(File file, Directory targetDirectory) {
170 171 172 173
    processUtils.runSync(
      <String>['unzip', '-o', '-q', file.path, '-d', targetDirectory.path],
      throwOnError: true,
    );
174
  }
175

176
  @override
177 178
  bool verifyZip(File zipFile) =>
      processUtils.exitsHappySync(<String>['zip', '-T', zipFile.path]);
179

180 181 182
  // tar -xzf tarball -C dest
  @override
  void unpack(File gzippedTarFile, Directory targetDirectory) {
183 184 185 186
    processUtils.runSync(
      <String>['tar', '-xzf', gzippedTarFile.path, '-C', targetDirectory.path],
      throwOnError: true,
    );
187 188
  }

189
  @override
190 191
  bool verifyGzip(File gzippedFile) =>
      processUtils.exitsHappySync(<String>['gzip', '-t', gzippedFile.path]);
192

193 194
  @override
  File makePipe(String path) {
195 196 197 198
    processUtils.runSync(
      <String>['mkfifo', path],
      throwOnError: true,
    );
199
    return fs.file(path);
200
  }
201 202 203 204 205 206 207

  String _name;

  @override
  String get name {
    if (_name == null) {
      if (platform.isMacOS) {
208 209 210 211
        final List<RunResult> results = <RunResult>[
          processUtils.runSync(<String>['sw_vers', '-productName']),
          processUtils.runSync(<String>['sw_vers', '-productVersion']),
          processUtils.runSync(<String>['sw_vers', '-buildVersion']),
212
        ];
213
        if (results.every((RunResult result) => result.exitCode == 0)) {
214 215
          _name = '${results[0].stdout.trim()} ${results[1].stdout
              .trim()} ${results[2].stdout.trim()}';
216 217
        }
      }
218
      _name ??= super.name;
219 220 221
    }
    return _name;
  }
222 223 224

  @override
  String get pathVarSeparator => ':';
225 226
}

227 228 229
class _WindowsUtils extends OperatingSystemUtils {
  _WindowsUtils() : super._private();

230
  @override
231 232 233 234
  void makeExecutable(File file) {}

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

236
  @override
237
  List<File> _which(String execName, { bool all = false }) {
238
    // `where` always returns all matches, not just the first one.
239
    final ProcessResult result = processManager.runSync(<String>['where', execName]);
240
    if (result.exitCode != 0) {
241
      return const <File>[];
242
    }
243
    final List<String> lines = result.stdout.trim().split('\n');
244
    if (all) {
245
      return lines.map<File>((String path) => fs.file(path.trim())).toList();
246
    }
247
    return <File>[fs.file(lines.first.trim())];
248 249
  }

250 251
  @override
  void zip(Directory data, File zipFile) {
252
    final Archive archive = Archive();
253 254 255 256
    for (FileSystemEntity entity in data.listSync(recursive: true)) {
      if (entity is! File) {
        continue;
      }
257 258 259
      final File file = entity;
      final String path = file.fileSystem.path.relative(file.path, from: data.path);
      final List<int> bytes = file.readAsBytesSync();
260
      archive.addFile(ArchiveFile(path, bytes.length, bytes));
261
    }
262
    zipFile.writeAsBytesSync(ZipEncoder().encode(archive), flush: true);
263 264
  }

265 266
  @override
  void unzip(File file, Directory targetDirectory) {
267
    final Archive archive = ZipDecoder().decodeBytes(file.readAsBytesSync());
268 269 270
    _unpackArchive(archive, targetDirectory);
  }

271 272 273
  @override
  bool verifyZip(File zipFile) {
    try {
274
      ZipDecoder().decodeBytes(zipFile.readAsBytesSync(), verify: true);
275 276 277 278 279 280 281 282
    } on FileSystemException catch (_) {
      return false;
    } on ArchiveException catch (_) {
      return false;
    }
    return true;
  }

283 284
  @override
  void unpack(File gzippedTarFile, Directory targetDirectory) {
285 286
    final Archive archive = TarDecoder().decodeBytes(
      GZipDecoder().decodeBytes(gzippedTarFile.readAsBytesSync()),
287 288 289
    );
    _unpackArchive(archive, targetDirectory);
  }
290

291 292 293
  @override
  bool verifyGzip(File gzipFile) {
    try {
294
      GZipDecoder().decodeBytes(gzipFile.readAsBytesSync(), verify: true);
295 296 297 298 299 300 301 302
    } on FileSystemException catch (_) {
      return false;
    } on ArchiveException catch (_) {
      return false;
    }
    return true;
  }

303
  void _unpackArchive(Archive archive, Directory targetDirectory) {
304 305
    for (ArchiveFile archiveFile in archive.files) {
      // The archive package doesn't correctly set isFile.
306
      if (!archiveFile.isFile || archiveFile.name.endsWith('/')) {
307
        continue;
308
      }
309

310
      final File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name));
311
      if (!destFile.parent.existsSync()) {
312
        destFile.parent.createSync(recursive: true);
313
      }
314 315
      destFile.writeAsBytesSync(archiveFile.content);
    }
316
  }
317 318 319

  @override
  File makePipe(String path) {
320
    throw UnsupportedError('makePipe is not implemented on Windows.');
321
  }
322 323 324 325 326 327 328 329

  String _name;

  @override
  String get name {
    if (_name == null) {
      final ProcessResult result = processManager.runSync(
          <String>['ver'], runInShell: true);
330
      if (result.exitCode == 0) {
331
        _name = result.stdout.trim();
332
      } else {
333
        _name = super.name;
334
      }
335 336 337
    }
    return _name;
  }
338 339 340

  @override
  String get pathVarSeparator => ';';
341
}
342

343 344
/// Find and return the project root directory relative to the specified
/// directory or the current working directory if none specified.
345
/// Return null if the project root could not be found
346
/// or if the project root is the flutter repository root.
347
String findProjectRoot([ String directory ]) {
348
  const String kProjectRootSentinel = 'pubspec.yaml';
349
  directory ??= fs.currentDirectory.path;
350
  while (true) {
351
    if (fs.isFileSync(fs.path.join(directory, kProjectRootSentinel))) {
352
      return directory;
353
    }
354
    final String parent = fs.path.dirname(directory);
355
    if (directory == parent) {
356
      return null;
357
    }
358 359 360
    directory = parent;
  }
}