1// Copyright 2015 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5import 'package:archive/archive.dart'; 6 7import '../globals.dart'; 8import 'context.dart'; 9import 'file_system.dart'; 10import 'io.dart'; 11import 'platform.dart'; 12import 'process.dart'; 13import 'process_manager.dart'; 14 15/// Returns [OperatingSystemUtils] active in the current app context (i.e. zone). 16OperatingSystemUtils get os => context.get<OperatingSystemUtils>(); 17 18abstract class OperatingSystemUtils { 19 factory OperatingSystemUtils() { 20 if (platform.isWindows) { 21 return _WindowsUtils(); 22 } else { 23 return _PosixUtils(); 24 } 25 } 26 27 OperatingSystemUtils._private(); 28 29 /// Make the given file executable. This may be a no-op on some platforms. 30 void makeExecutable(File file); 31 32 /// Updates the specified file system [entity] to have the file mode 33 /// bits set to the value defined by [mode], which can be specified in octal 34 /// (e.g. `644`) or symbolically (e.g. `u+x`). 35 /// 36 /// On operating systems that do not support file mode bits, this will be a 37 /// no-op. 38 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 File which(String execName) { 43 final List<File> result = _which(execName); 44 if (result == null || result.isEmpty) 45 return null; 46 return result.first; 47 } 48 49 /// Return a list of all paths to `execName` found on the system. Uses the 50 /// PATH environment variable. 51 List<File> whichAll(String execName) => _which(execName, all: true); 52 53 /// Return the File representing a new pipe. 54 File makePipe(String path); 55 56 void zip(Directory data, File zipFile); 57 58 void unzip(File file, Directory targetDirectory); 59 60 /// Returns true if the ZIP is not corrupt. 61 bool verifyZip(File file); 62 63 void unpack(File gzippedTarFile, Directory targetDirectory); 64 65 /// Returns true if the gzip is not corrupt (does not check tar). 66 bool verifyGzip(File gzippedFile); 67 68 /// Returns a pretty name string for the current operating system. 69 /// 70 /// If available, the detailed version of the OS is included. 71 String get name { 72 const Map<String, String> osNames = <String, String>{ 73 'macos': 'Mac OS', 74 'linux': 'Linux', 75 'windows': 'Windows', 76 }; 77 final String osName = platform.operatingSystem; 78 return osNames.containsKey(osName) ? osNames[osName] : osName; 79 } 80 81 List<File> _which(String execName, { bool all = false }); 82 83 /// Returns the separator between items in the PATH environment variable. 84 String get pathVarSeparator; 85 86 /// Returns an unused network port. 87 /// 88 /// Returns 0 if an unused port cannot be found. 89 /// 90 /// The port returned by this function may become used before it is bound by 91 /// its intended user. 92 Future<int> findFreePort({bool ipv6 = false}) async { 93 int port = 0; 94 ServerSocket serverSocket; 95 final InternetAddress loopback = 96 ipv6 ? InternetAddress.loopbackIPv6 : InternetAddress.loopbackIPv4; 97 try { 98 serverSocket = await ServerSocket.bind(loopback, 0); 99 port = serverSocket.port; 100 } on SocketException catch (e) { 101 // If ipv4 loopback bind fails, try ipv6. 102 if (!ipv6) { 103 return findFreePort(ipv6: true); 104 } 105 printTrace('findFreePort failed: $e'); 106 } catch (e) { 107 // Failures are signaled by a return value of 0 from this function. 108 printTrace('findFreePort failed: $e'); 109 } finally { 110 if (serverSocket != null) { 111 await serverSocket.close(); 112 } 113 } 114 return port; 115 } 116} 117 118class _PosixUtils extends OperatingSystemUtils { 119 _PosixUtils() : super._private(); 120 121 @override 122 void makeExecutable(File file) { 123 chmod(file, 'a+x'); 124 } 125 126 @override 127 void chmod(FileSystemEntity entity, String mode) { 128 try { 129 final ProcessResult result = processManager.runSync(<String>['chmod', mode, entity.path]); 130 if (result.exitCode != 0) { 131 printTrace( 132 'Error trying to run chmod on ${entity.absolute.path}' 133 '\nstdout: ${result.stdout}' 134 '\nstderr: ${result.stderr}', 135 ); 136 } 137 } on ProcessException catch (error) { 138 printTrace('Error trying to run chmod on ${entity.absolute.path}: $error'); 139 } 140 } 141 142 @override 143 List<File> _which(String execName, { bool all = false }) { 144 final List<String> command = <String>['which']; 145 if (all) 146 command.add('-a'); 147 command.add(execName); 148 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 @override 156 void zip(Directory data, File zipFile) { 157 runSync(<String>['zip', '-r', '-q', zipFile.path, '.'], workingDirectory: data.path); 158 } 159 160 // unzip -o -q zipfile -d dest 161 @override 162 void unzip(File file, Directory targetDirectory) { 163 runSync(<String>['unzip', '-o', '-q', file.path, '-d', targetDirectory.path]); 164 } 165 166 @override 167 bool verifyZip(File zipFile) => exitsHappy(<String>['zip', '-T', zipFile.path]); 168 169 // tar -xzf tarball -C dest 170 @override 171 void unpack(File gzippedTarFile, Directory targetDirectory) { 172 runSync(<String>['tar', '-xzf', gzippedTarFile.path, '-C', targetDirectory.path]); 173 } 174 175 @override 176 bool verifyGzip(File gzippedFile) => exitsHappy(<String>['gzip', '-t', gzippedFile.path]); 177 178 @override 179 File makePipe(String path) { 180 runSync(<String>['mkfifo', path]); 181 return fs.file(path); 182 } 183 184 String _name; 185 186 @override 187 String get name { 188 if (_name == null) { 189 if (platform.isMacOS) { 190 final List<ProcessResult> results = <ProcessResult>[ 191 processManager.runSync(<String>['sw_vers', '-productName']), 192 processManager.runSync(<String>['sw_vers', '-productVersion']), 193 processManager.runSync(<String>['sw_vers', '-buildVersion']), 194 ]; 195 if (results.every((ProcessResult result) => result.exitCode == 0)) { 196 _name = '${results[0].stdout.trim()} ${results[1].stdout 197 .trim()} ${results[2].stdout.trim()}'; 198 } 199 } 200 _name ??= super.name; 201 } 202 return _name; 203 } 204 205 @override 206 String get pathVarSeparator => ':'; 207} 208 209class _WindowsUtils extends OperatingSystemUtils { 210 _WindowsUtils() : super._private(); 211 212 @override 213 void makeExecutable(File file) {} 214 215 @override 216 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 return const <File>[]; 224 final List<String> lines = result.stdout.trim().split('\n'); 225 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 @override 231 void zip(Directory data, File zipFile) { 232 final Archive archive = Archive(); 233 for (FileSystemEntity entity in data.listSync(recursive: true)) { 234 if (entity is! File) { 235 continue; 236 } 237 final File file = entity; 238 final String path = file.fileSystem.path.relative(file.path, from: data.path); 239 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 @override 246 void unzip(File file, Directory targetDirectory) { 247 final Archive archive = ZipDecoder().decodeBytes(file.readAsBytesSync()); 248 _unpackArchive(archive, targetDirectory); 249 } 250 251 @override 252 bool verifyZip(File zipFile) { 253 try { 254 ZipDecoder().decodeBytes(zipFile.readAsBytesSync(), verify: true); 255 } on FileSystemException catch (_) { 256 return false; 257 } on ArchiveException catch (_) { 258 return false; 259 } 260 return true; 261 } 262 263 @override 264 void unpack(File gzippedTarFile, Directory targetDirectory) { 265 final Archive archive = TarDecoder().decodeBytes( 266 GZipDecoder().decodeBytes(gzippedTarFile.readAsBytesSync()), 267 ); 268 _unpackArchive(archive, targetDirectory); 269 } 270 271 @override 272 bool verifyGzip(File gzipFile) { 273 try { 274 GZipDecoder().decodeBytes(gzipFile.readAsBytesSync(), verify: true); 275 } on FileSystemException catch (_) { 276 return false; 277 } on ArchiveException catch (_) { 278 return false; 279 } 280 return true; 281 } 282 283 void _unpackArchive(Archive archive, Directory targetDirectory) { 284 for (ArchiveFile archiveFile in archive.files) { 285 // The archive package doesn't correctly set isFile. 286 if (!archiveFile.isFile || archiveFile.name.endsWith('/')) 287 continue; 288 289 final File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name)); 290 if (!destFile.parent.existsSync()) 291 destFile.parent.createSync(recursive: true); 292 destFile.writeAsBytesSync(archiveFile.content); 293 } 294 } 295 296 @override 297 File makePipe(String path) { 298 throw UnsupportedError('makePipe is not implemented on Windows.'); 299 } 300 301 String _name; 302 303 @override 304 String get name { 305 if (_name == null) { 306 final ProcessResult result = processManager.runSync( 307 <String>['ver'], runInShell: true); 308 if (result.exitCode == 0) 309 _name = result.stdout.trim(); 310 else 311 _name = super.name; 312 } 313 return _name; 314 } 315 316 @override 317 String get pathVarSeparator => ';'; 318} 319 320/// Find and return the project root directory relative to the specified 321/// 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. 324String 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 if (directory == parent) 332 return null; 333 directory = parent; 334 } 335} 336