-
Notifications
You must be signed in to change notification settings - Fork 28
/
CliWrapHelper.cs
53 lines (48 loc) · 2.04 KB
/
CliWrapHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using CliWrap;
using CliWrap.Buffered;
using CliWrap.EventStream;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Lombiq.HelpfulLibraries.Cli.Helpers;
public static class CliWrapHelper
{
/// <summary>
/// Returns an executable's full path by looking up its command name. Uses the <c>which</c> command in Unix and the
/// <c>where</c> command in Windows.
/// </summary>
/// <param name="name">The application name you can invoke directly in the command line.</param>
public static async Task<IEnumerable<FileInfo>> WhichAsync(string name)
{
var appName = OperatingSystem.IsWindows() ? "where" : "which";
var result = await CliWrap.Cli.Wrap(appName)
.WithArguments(name)
.WithValidation(CommandResultValidation.None)
.ExecuteBufferedAsync();
return result.StandardOutput
.Split('\n')
.Select(x => x.Trim())
.Where(File.Exists)
.Select(x => new FileInfo(x));
}
/// <summary>
/// Executes the provided command and calls and handles each <see cref="CommandEvent"/> on it.
/// </summary>
/// <param name="program">The path of the program that needs to be called.</param>
/// <param name="arguments">The collection of command line arguments.</param>
/// <param name="handler">The action to be called on each event.</param>
/// <param name="configureCommand">Optional configuration for the <see cref="Command"/> before it's invoked.</param>
public static async Task StreamAsync(
string program,
ICollection<string> arguments,
Action<CommandEvent> handler,
Func<Command, Command> configureCommand = null)
{
var command = CliWrap.Cli.Wrap(program);
if (arguments?.Count != 0) command = command.WithArguments(arguments);
if (configureCommand != null) command = configureCommand(command);
await foreach (var commandEvent in command.ListenAsync()) handler(commandEvent);
}
}