os.dart 10 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 44 45 46 47
  File which(String execName) {
    final List<File> result = _which(execName);
    if (result == null || result.isEmpty)
      return null;
    return result.first;
  }
48

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

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

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

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

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

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

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

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

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

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

  /// 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;
  }
116 117
}

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

121
  @override
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  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');
    }
140
  }
141

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

155 156 157 158 159
  @override
  void zip(Directory data, File zipFile) {
    runSync(<String>['zip', '-r', '-q', zipFile.path, '.'], workingDirectory: data.path);
  }

160 161 162 163 164
  // unzip -o -q zipfile -d dest
  @override
  void unzip(File file, Directory targetDirectory) {
    runSync(<String>['unzip', '-o', '-q', file.path, '-d', targetDirectory.path]);
  }
165

166 167 168
  @override
  bool verifyZip(File zipFile) => exitsHappy(<String>['zip', '-T', zipFile.path]);

169 170 171 172 173 174
  // tar -xzf tarball -C dest
  @override
  void unpack(File gzippedTarFile, Directory targetDirectory) {
    runSync(<String>['tar', '-xzf', gzippedTarFile.path, '-C', targetDirectory.path]);
  }

175 176 177
  @override
  bool verifyGzip(File gzippedFile) => exitsHappy(<String>['gzip', '-t', gzippedFile.path]);

178 179 180
  @override
  File makePipe(String path) {
    runSync(<String>['mkfifo', path]);
181
    return fs.file(path);
182
  }
183 184 185 186 187 188 189 190

  String _name;

  @override
  String get name {
    if (_name == null) {
      if (platform.isMacOS) {
        final List<ProcessResult> results = <ProcessResult>[
191 192 193
          processManager.runSync(<String>['sw_vers', '-productName']),
          processManager.runSync(<String>['sw_vers', '-productVersion']),
          processManager.runSync(<String>['sw_vers', '-buildVersion']),
194 195
        ];
        if (results.every((ProcessResult result) => result.exitCode == 0)) {
196 197
          _name = '${results[0].stdout.trim()} ${results[1].stdout
              .trim()} ${results[2].stdout.trim()}';
198 199
        }
      }
200
      _name ??= super.name;
201 202 203
    }
    return _name;
  }
204 205 206

  @override
  String get pathVarSeparator => ':';
207 208
}

209 210 211
class _WindowsUtils extends OperatingSystemUtils {
  _WindowsUtils() : super._private();

212
  @override
213 214 215 216
  void makeExecutable(File file) {}

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

218
  @override
219
  List<File> _which(String execName, { bool all = false }) {
220
    // `where` always returns all matches, not just the first one.
221
    final ProcessResult result = processManager.runSync(<String>['where', execName]);
222
    if (result.exitCode != 0)
223 224 225
      return const <File>[];
    final List<String> lines = result.stdout.trim().split('\n');
    if (all)
226
      return lines.map<File>((String path) => fs.file(path.trim())).toList();
227
    return <File>[fs.file(lines.first.trim())];
228 229
  }

230 231
  @override
  void zip(Directory data, File zipFile) {
232
    final Archive archive = Archive();
233 234 235 236
    for (FileSystemEntity entity in data.listSync(recursive: true)) {
      if (entity is! File) {
        continue;
      }
237 238 239
      final File file = entity;
      final String path = file.fileSystem.path.relative(file.path, from: data.path);
      final List<int> bytes = file.readAsBytesSync();
240
      archive.addFile(ArchiveFile(path, bytes.length, bytes));
241
    }
242
    zipFile.writeAsBytesSync(ZipEncoder().encode(archive), flush: true);
243 244
  }

245 246
  @override
  void unzip(File file, Directory targetDirectory) {
247
    final Archive archive = ZipDecoder().decodeBytes(file.readAsBytesSync());
248 249 250
    _unpackArchive(archive, targetDirectory);
  }

251 252 253
  @override
  bool verifyZip(File zipFile) {
    try {
254
      ZipDecoder().decodeBytes(zipFile.readAsBytesSync(), verify: true);
255 256 257 258 259 260 261 262
    } on FileSystemException catch (_) {
      return false;
    } on ArchiveException catch (_) {
      return false;
    }
    return true;
  }

263 264
  @override
  void unpack(File gzippedTarFile, Directory targetDirectory) {
265 266
    final Archive archive = TarDecoder().decodeBytes(
      GZipDecoder().decodeBytes(gzippedTarFile.readAsBytesSync()),
267 268 269
    );
    _unpackArchive(archive, targetDirectory);
  }
270

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

283
  void _unpackArchive(Archive archive, Directory targetDirectory) {
284 285 286 287 288
    for (ArchiveFile archiveFile in archive.files) {
      // The archive package doesn't correctly set isFile.
      if (!archiveFile.isFile || archiveFile.name.endsWith('/'))
        continue;

289
      final File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name));
290 291 292 293
      if (!destFile.parent.existsSync())
        destFile.parent.createSync(recursive: true);
      destFile.writeAsBytesSync(archiveFile.content);
    }
294
  }
295 296 297

  @override
  File makePipe(String path) {
298
    throw UnsupportedError('makePipe is not implemented on Windows.');
299
  }
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

  String _name;

  @override
  String get name {
    if (_name == null) {
      final ProcessResult result = processManager.runSync(
          <String>['ver'], runInShell: true);
      if (result.exitCode == 0)
        _name = result.stdout.trim();
      else
        _name = super.name;
    }
    return _name;
  }
315 316 317

  @override
  String get pathVarSeparator => ';';
318
}
319

320 321
/// Find and return the project root directory relative to the specified
/// directory or the current working directory if none specified.
322
/// Return null if the project root could not be found
323
/// or if the project root is the flutter repository root.
324
String findProjectRoot([ String directory ]) {
325
  const String kProjectRootSentinel = 'pubspec.yaml';
326
  directory ??= fs.currentDirectory.path;
327
  while (true) {
328
    if (fs.isFileSync(fs.path.join(directory, kProjectRootSentinel)))
329
      return directory;
330
    final String parent = fs.path.dirname(directory);
331 332
    if (directory == parent)
      return null;
333 334 335
    directory = parent;
  }
}