blob: 902f1eb571ee85f215b21fac5fff0d93dd26d46d [file] [log] [blame]
// Copyright 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package.dart';
import 'useful_directory.dart';
import 'package:file/file.dart';
import 'command.dart';
mixin UnzipBuild on Package {
/// Unzip all [inputs] into the [workingDirectory] using `tar` for `.tar.(bz2|gz)`
/// files and unzip for `.zip` files.
@override
Future<Directory> build(
List<FileSystemEntity> inputs, Directory workingDirectory) async {
final target =
await workingDirectory.resolve('unzipped').create(recursive: true);
for (final archive in inputs) {
if (archive is! File) {
throw StateError('Expected files, but got: $archive');
}
final command = _unzipCommand(archive, target);
final result = await command.run();
if (result.exitCode != 0) {
throw FormatException('Failed to unpack $archive'
' (${command.executable} exited with ${result.exitCode}):\n'
'${result.stderr}');
}
}
return target;
}
Command _unzipCommand(File archive, Directory target) {
var command = 'tar';
List<String> args;
final path = archive.path;
if (path.endsWith('.zip')) {
command = 'unzip';
args = ['-d', target.path, path];
} else if (archive.path.endsWith('.tar.gz')) {
args = ['-xzf', path, '-C', target.path];
} else if (archive.path.endsWith('.tar.bz2')) {
args = ['-xjf', path, '-C', target.path];
} else {
throw StateError('Failed to unpack $archive: unsupported file format.');
}
return Command(command, args);
}
}