writeDpkLauncher function

String writeDpkLauncher(
  1. List<String> command, {
  2. bool? windows,
})

Writes a dpk launcher for command and returns the directory that holds it, ready to put first on PATH.

Scripts that call dpk then run the same dpk that started them, instead of whichever dpk is installed. The directory lives in the system temp directory and is named after a hash of command, so every run of the same dpk reuses it.

Implementation

String writeDpkLauncher(List<String> command, {bool? windows}) {
  final isWindows = windows ?? Platform.isWindows;
  final directory = Directory(
    p.join(
      Directory.systemTemp.path,
      'dpk-launchers',
      _hash(command.join('\x00')),
    ),
  );
  final launcher = File(p.join(directory.path, isWindows ? 'dpk.cmd' : 'dpk'));
  final content = isWindows
      ? '@echo off\r\n${command.map(_quoteCmd).join(' ')} %*\r\n'
      : '#!/bin/sh\nexec ${command.map(_quoteSh).join(' ')} "\$@"\n';

  if (launcher.existsSync() && launcher.readAsStringSync() == content) {
    return directory.path;
  }

  directory.createSync(recursive: true);
  final temporary = File('${launcher.path}.$pid.tmp')
    ..writeAsStringSync(content);
  if (!isWindows) {
    Process.runSync('chmod', ['755', temporary.path]);
  }
  temporary.renameSync(launcher.path);
  return directory.path;
}