// Copyright (C) 2023 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
import 'dart:io';
import 'package:brick_generator/logger.dart';
class Shell {
static Future cp(String source, String destination) {
return _Cmd.run('cp', ['-Rf', source, destination]);
}
static Future mkdir(String destination) {
return _Cmd.run('mkdir', ['-p', destination]);
}
}
class _Cmd {
static Future run(
String cmd,
List args, {
bool throwOnError = true,
String? processWorkingDir,
}) async {
final result = await Process.run(
cmd,
args,
workingDirectory: processWorkingDir,
runInShell: true,
);
if (throwOnError) {
_throwIfProcessFailed(result, cmd, args);
}
return result;
}
static void _throwIfProcessFailed(
ProcessResult pr,
String process,
List args,
) {
if (pr.exitCode != 0) {
final values = {
'Standard out': pr.stdout.toString().trim(),
'Standard error': pr.stderr.toString().trim()
}..removeWhere((k, v) => v.isEmpty);
String message;
if (values.isEmpty) {
message = 'Unknown error';
} else if (values.length == 1) {
message = values.values.single;
} else {
message = values.entries.map((e) => '${e.key}\n${e.value}').join('\n');
}
Logger.throwError(
ProcessException(process, args, message, pr.exitCode),
message,
);
}
}
}