os.dart 2.23 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 'dart:async';
6 7
import 'dart:io';

8 9 10 11
import 'context.dart';

/// Returns [OperatingSystemUtils] active in the current app context (i.e. zone).
OperatingSystemUtils get os => context[OperatingSystemUtils] ?? (context[OperatingSystemUtils] = new OperatingSystemUtils._());
12 13 14 15 16 17

abstract class OperatingSystemUtils {
  factory OperatingSystemUtils._() {
    if (Platform.isWindows) {
      return new _WindowsUtils();
    } else {
Adam Barth's avatar
Adam Barth committed
18
      return new _PosixUtils();
19 20 21
    }
  }

22 23 24 25 26 27 28 29
  OperatingSystemUtils._private();

  String get operatingSystem => Platform.operatingSystem;

  bool get isMacOS => operatingSystem == 'macos';
  bool get isWindows => operatingSystem == 'windows';
  bool get isLinux => operatingSystem == 'linux';

30 31
  /// Make the given file executable. This may be a no-op on some platforms.
  ProcessResult makeExecutable(File file);
32 33 34 35

  /// Return the path (with symlinks resolved) to the given executable, or `null`
  /// if `which` was not able to locate the binary.
  File which(String execName);
36 37
}

38 39 40
class _PosixUtils extends OperatingSystemUtils {
  _PosixUtils() : super._private();

41 42 43
  ProcessResult makeExecutable(File file) {
    return Process.runSync('chmod', ['u+x', file.path]);
  }
44 45 46 47 48 49 50 51 52 53

  /// Return the path (with symlinks resolved) to the given executable, or `null`
  /// if `which` was not able to locate the binary.
  File which(String execName) {
    ProcessResult result = Process.runSync('which', <String>[execName]);
    if (result.exitCode != 0)
      return null;
    String path = result.stdout.trim().split('\n').first.trim();
    return new File(new File(path).resolveSymbolicLinksSync());
  }
54 55
}

56 57 58
class _WindowsUtils extends OperatingSystemUtils {
  _WindowsUtils() : super._private();

59 60 61 62
  // This is a no-op.
  ProcessResult makeExecutable(File file) {
    return new ProcessResult(0, 0, null, null);
  }
63 64 65 66

  File which(String execName) {
    throw new UnimplementedError('_WindowsUtils.which');
  }
67
}
68 69 70 71 72 73 74

Future<int> findAvailablePort() async {
  ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0);
  int port = socket.port;
  await socket.close();
  return port;
}