public static async Task <Device[]> GetDevicesAsync(bool includeDefault = false) { BufferedCommandResult result = await Cli.Wrap(_SnapClient()).WithArguments("--list") .ExecuteBufferedAsync(Encoding.UTF8, Encoding.UTF8); return(_GetFromSnapClientListOutput(result.StandardOutput, includeDefault)); }
/// <summary> /// Provides a convenient way to list /// and modify projects in a solution /// file. /// </summary> protected virtual void SlnAction(string solution, IEnumerable <string> projects, ArgumentsBuilder builder) { if (projects.Any()) { CliWrap.Command command = Cli.Wrap("dotnet").WithWorkingDirectory(Path.GetDirectoryName(solution)) .WithArguments(args => args.Add("sln").Add(solution).Add(builder.Build(), false)); BufferedCommandResult result = command.ExecuteBufferedAsync().GetAwaiter().GetResult(); if (!string.IsNullOrWhiteSpace(result.StandardOutput)) { MessageProvider.Clear(); MessageProvider.AddMessage(result.StandardOutput, MessageCategory.ME); } if (!string.IsNullOrWhiteSpace(result.StandardError)) { MessageProvider.Clear(); MessageProvider.AddMessage(result.StandardError, MessageCategory.ER); } } }
public async Task <ExecuteResponse> ExecuteAsync(ExecuteRequest request) { var commandTask = Cli .Wrap(request.FilePath) .WithArguments(request.Arguments) .WithValidation(CommandResultValidation.None) .WithWorkingDirectory(request.WorkingDirectory) .ExecuteBufferedAsync(CancellationToken); BufferedCommandResult result = null; // result is null when cancelled ExecuteResponse executeResponse = null; try { result = await commandTask; } catch (OperationCanceledException) { } if (result != null) { var exitCode = result.ExitCode; var outputList = new List <string>(); var directOutput = string.Join(Environment.NewLine, new[] { result.StandardOutput, Environment.NewLine, result.StandardError } .Where(x => !string.IsNullOrWhiteSpace(x))) .Trim('\r', '\n') .Trim(); if (!string.IsNullOrWhiteSpace(directOutput)) { outputList.Add(directOutput); } var output = string.Join(Environment.NewLine, outputList) .Trim('\r', '\n') .Trim(); executeResponse = new ExecuteResponse { ExitCode = exitCode, ExitTime = result.ExitTime, RunTime = result.RunTime, StartTime = result.StartTime, Output = output }; } return(executeResponse); }
private void InitTargets(CancellationToken cancellationToken = default) { Target( "restore", async() => { bool isPublicRelease = bool.Parse(Environment.GetEnvironmentVariable("NBGV_PublicRelease") ?? "false"); BufferedCommandResult cmd = await Cli.Wrap(_dotnetPath).WithArguments( $"msbuild {_options.FileOrFolder} -noLogo " + "-t:Restore " + "-p:RestoreForce=true " + "-p:RestoreIgnoreFailedSources=True " + $"-p:Configuration={_options.Configuration} " + // for Nerdbank.GitVersioning $"-p:PublicRelease={isPublicRelease} " ) .ToConsole() .ExecuteBufferedAsync(cancellationToken).Task.ConfigureAwait(false); }); Target( "build", async() => { BufferedCommandResult cmd = await Cli.Wrap(_dotnetPath).WithArguments( $"build {_options} -noLogo -c {_options.Configuration}" ) .ToConsole() .ExecuteBufferedAsync(cancellationToken).Task.ConfigureAwait(false); }); Target( "unit_test", async() => { string resultsDirectory = Path.GetFullPath(Path.Combine("artifacts", "tests", "unit", "output")); if (!Directory.Exists(resultsDirectory)) { Directory.CreateDirectory(resultsDirectory); } BufferedCommandResult cmd = await Cli.Wrap(_dotnetPath) .WithArguments( $"test " + "--filter FullyQualifiedName~Unit " + "--nologo " + "--no-restore " + $"--collect:\"XPlat Code Coverage\" --results-directory {resultsDirectory} " + $"--logger trx;LogFileName=\"{Path.Combine(resultsDirectory, "tests.trx").Replace("\"", "\\\"")}\" " + $"-c {_options.Configuration} " + "-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=json,cobertura" ) .ToConsole() .ExecuteBufferedAsync(cancellationToken).Task.ConfigureAwait(false); MoveAttachmentsToResultsDirectory(resultsDirectory, cmd.StandardOutput); TryRemoveTestsOutputDirectories(resultsDirectory);
public static async Task <bool> UpdateIfPossible() { if (!Exists()) // Ignore updating if Update.exe does not exist { log.Warn("No Updater found"); return(false); } string url = await GetUpdateUrl(); log.Info("Trying to update from " + url); BufferedCommandResult result = await Cli.Wrap(relativePath) .WithArguments(b => b.Add($"--checkForUpdate={url}", true)) .WithValidation(CommandResultValidation.None) .ExecuteBufferedAsync(); if (result.ExitCode != 0) { log.Error($"Checked for updates with output and ERROR:\n{result.StandardOutput}\n{result.StandardError}"); return(false); } log.Info($"Checked for updates with output:\n{result.StandardOutput}"); string json = result.StandardOutput.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Last(); SquirrelInfo info = JsonConvert.DeserializeObject <SquirrelInfo>(json); if (info.CurrentVersion == info.FutureVersion) { log.Info($"No update available"); return(false); } result = await Cli.Wrap(relativePath) .WithArguments(b => b.Add($"--update={url}", true)) .WithValidation(CommandResultValidation.None) .ExecuteBufferedAsync(); if (result.ExitCode != 0) { log.Error($"Ran updater with output and ERROR:\n{result.StandardOutput}\n{result.StandardError}"); return(false); } log.Info($"Ran updater with output:\n{result.StandardOutput}"); log.Info("Restarting application for update."); Process.Start(relativePath, string.Format("--processStartAndWait \"{0}\"", exeName)); return(true); }
private static async Task <string> RunProlog(string accion, string arg1 = "0", string arg2 = "", string arg3 = "") { BufferedCommandResult result = await Cli.Wrap("swipl") .WithArguments(new[] { "-q", "-t", accion, "prolog.pl", arg1, arg2, arg3 }) .WithValidation(CommandResultValidation.None) .ExecuteBufferedAsync(Encoding.UTF8); var output = result.StandardOutput; return(output); }
public async Task <BufferedCommandResult> StartAsync() { string command = DockerCommands.Run(this); Console.WriteLine(command); BufferedCommandResult result = await Cli.Wrap(ContainerConfiguration.DefaultShell) .WithArguments(command) .ExecuteBufferedAsync(); return(result); }
public static async Task <BufferedCommandResult> Stop(List <string> containerNames) { string containers = String.Join(" ", containerNames); string command = DockerCommands.Stop(containers); Console.WriteLine(command); BufferedCommandResult result = await Cli.Wrap(ContainerConfiguration.DefaultShell) .WithArguments(command) .ExecuteBufferedAsync(); return(result); }
private async Task <bool> IsAnimated(string ffprobePath, string path) { try { var cacheKey = $"image.animated.{Path.GetFileName(path)}"; if (_memoryCache.TryGetValue(cacheKey, out bool animated)) { return(animated); } BufferedCommandResult result = await Cli.Wrap(ffprobePath) .WithArguments( new[] { "-loglevel", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-print_format", "csv", path }) .WithValidation(CommandResultValidation.None) .ExecuteBufferedAsync(Encoding.UTF8); if (result.ExitCode == 0) { string output = result.StandardOutput; output = output.Replace("stream,", string.Empty); if (int.TryParse(output, out int frameCount)) { bool isAnimated = frameCount > 1; _memoryCache.Set(cacheKey, isAnimated, TimeSpan.FromDays(1)); return(isAnimated); } } else { _logger.LogWarning( "Error checking frame count for file {File}l exit code {ExitCode}", path, result.ExitCode); } } catch (Exception ex) { _logger.LogWarning(ex, "Error checking frame count for file {File}", path); } return(false); }
public async Task Real_implementation_of_console_maps_directly_to_system_console() { // Arrange var command = "Hello world" | Cli.Wrap("dotnet") .WithArguments(a => a .Add(Dummy.Program.Location) .Add("console-test")); // Act BufferedCommandResult result = await command.ExecuteBufferedAsync(); // Assert result.StandardOutput.TrimEnd().Should().Be("Hello world"); result.StandardError.TrimEnd().Should().Be("Hello world"); }
public async Task <BufferedCommandResult> RunAsync(SolutionInfo solutionInfo) { string runCommand = CppCommands.Run(solutionInfo); string command = DockerCommands.Exec(this, runCommand); Console.WriteLine(command); using var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(ContainerConfiguration.ProcessTimeoutSeconds)); BufferedCommandResult result = await Cli.Wrap(ContainerConfiguration.DefaultShell) .WithArguments(command) .WithValidation(CommandResultValidation.None) .ExecuteBufferedAsync(cts.Token); // cts // throws OperationCanceledException return(result); }
private async Task <Unit> ExtractSubtitles( TvContext dbContext, int mediaItemId, string ffmpegPath, CancellationToken cancellationToken) { Option <MediaItem> maybeMediaItem = await dbContext.MediaItems .Include(mi => (mi as Episode).MediaVersions) .ThenInclude(mv => mv.MediaFiles) .Include(mi => (mi as Episode).MediaVersions) .ThenInclude(mv => mv.Streams) .Include(mi => (mi as Episode).EpisodeMetadata) .ThenInclude(em => em.Subtitles) .Include(mi => (mi as Movie).MediaVersions) .ThenInclude(mv => mv.MediaFiles) .Include(mi => (mi as Movie).MediaVersions) .ThenInclude(mv => mv.Streams) .Include(mi => (mi as Movie).MovieMetadata) .ThenInclude(em => em.Subtitles) .Include(mi => (mi as MusicVideo).MediaVersions) .ThenInclude(mv => mv.MediaFiles) .Include(mi => (mi as MusicVideo).MediaVersions) .ThenInclude(mv => mv.Streams) .Include(mi => (mi as MusicVideo).MusicVideoMetadata) .ThenInclude(em => em.Subtitles) .Include(mi => (mi as OtherVideo).MediaVersions) .ThenInclude(mv => mv.MediaFiles) .Include(mi => (mi as OtherVideo).MediaVersions) .ThenInclude(mv => mv.Streams) .Include(mi => (mi as OtherVideo).OtherVideoMetadata) .ThenInclude(em => em.Subtitles) .SelectOneAsync(e => e.Id, e => e.Id == mediaItemId); foreach (MediaItem mediaItem in maybeMediaItem) { foreach (List <Subtitle> allSubtitles in GetSubtitles(mediaItem)) { var subtitlesToExtract = new List <SubtitleToExtract>(); // find each subtitle that needs extraction IEnumerable <Subtitle> subtitles = allSubtitles .Filter( s => s.SubtitleKind == SubtitleKind.Embedded && s.IsExtracted == false && s.Codec != "hdmv_pgs_subtitle" && s.Codec != "dvd_subtitle"); // find cache paths for each subtitle foreach (Subtitle subtitle in subtitles) { Option <string> maybePath = GetRelativeOutputPath(mediaItem.Id, subtitle); foreach (string path in maybePath) { subtitlesToExtract.Add(new SubtitleToExtract(subtitle, path)); } } string mediaItemPath = await GetMediaItemPath(mediaItem); ArgumentsBuilder args = new ArgumentsBuilder() .Add("-nostdin") .Add("-hide_banner") .Add("-i").Add(mediaItemPath); foreach (SubtitleToExtract subtitle in subtitlesToExtract) { string fullOutputPath = Path.Combine(FileSystemLayout.SubtitleCacheFolder, subtitle.OutputPath); Directory.CreateDirectory(Path.GetDirectoryName(fullOutputPath)); if (_localFileSystem.FileExists(fullOutputPath)) { File.Delete(fullOutputPath); } args.Add("-map").Add($"0:{subtitle.Subtitle.StreamIndex}").Add("-c").Add("copy") .Add(fullOutputPath); } BufferedCommandResult result = await Cli.Wrap(ffmpegPath) .WithArguments(args.Build()) .WithValidation(CommandResultValidation.None) .ExecuteBufferedAsync(cancellationToken); if (result.ExitCode == 0) { foreach (SubtitleToExtract subtitle in subtitlesToExtract) { subtitle.Subtitle.IsExtracted = true; subtitle.Subtitle.Path = subtitle.OutputPath; } int count = await dbContext.SaveChangesAsync(cancellationToken); _logger.LogDebug("Successfully extracted {Count} subtitles", count); } else { _logger.LogError("Failed to extract subtitles. {Error}", result.StandardError); } } } return(Unit.Default); }
private static async Task PackageMac(string gameName) { Console.WriteLine("Package mac"); Command dotnetCLI = Cli.Wrap("dotnet").WithWorkingDirectory($"{gameName}.DesktopGL"); var projectRoot = Path.Combine(Directory.GetCurrentDirectory(), $"{gameName}.DesktopGL"); Command publish = dotnetCLI.WithArguments("publish -c Release -r osx-x64 /p:PublishReadyToRun=false /p:TieredCompilation=false --self-contained"); BufferedCommandResult result = await(publish | Console.WriteLine).ExecuteBufferedAsync(); var publishPath = result.StandardOutput.Substring(result.StandardOutput.LastIndexOf(' ')).Trim(); var tempPath = Path.GetFullPath(Path.Combine(publishPath, "..", "temp")); var appRootPublishPath = Path.GetFullPath(Path.Combine(publishPath, $"{gameName}.app")); var macOSPath = Path.Combine(tempPath, "Contents", "MacOS"); var resourcesPath = Path.Combine(tempPath, "Contents", "Resources"); var executingPath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); if (Directory.Exists(appRootPublishPath)) { Directory.Delete(appRootPublishPath, true); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } // Mac folder Directory.CreateDirectory(Directory.GetParent(macOSPath).FullName); Directory.Move(publishPath, macOSPath); // plist var text = File.ReadAllText(Path.Combine(executingPath, "PlistTemplate.xml")); text = text.Replace("{gameName}", gameName); File.WriteAllText(Path.Combine(Path.Combine(tempPath, "Contents"), "Info.plist"), text); Directory.CreateDirectory(resourcesPath); // Content var contentDirectory = Path.Combine(macOSPath, "Content"); if (Directory.Exists(contentDirectory)) { Directory.Move(contentDirectory, Path.Combine(resourcesPath, "Content")); } // Copy icns Directory.CreateDirectory(resourcesPath); var iconPath = Path.Combine(projectRoot, "Icon.icns"); if (File.Exists(iconPath)) { File.Copy(iconPath, Path.Combine(resourcesPath, "Icon.icns")); } // Move to app folder Directory.CreateDirectory(publishPath); Directory.Move(tempPath, appRootPublishPath); }
public static async Task <ExecuteResponse> ExecuteAsync(ExecuteRequest request) { string shellScriptFile = null; string shellScriptOutputFile = null; // create script file shellScriptFile = Path.Combine(request.WorkingDirectory, $"{Guid.NewGuid().ToString().Split('-').First()}.bat"); shellScriptOutputFile = $"{shellScriptFile}.output"; File.WriteAllText(shellScriptFile, $@"""{request.FilePath}"" {request.Arguments} > ""{shellScriptOutputFile}"""); // run script file var commandTask = Cli .Wrap(shellScriptFile) .WithValidation(CommandResultValidation.None) .WithWorkingDirectory(request.WorkingDirectory) .ExecuteBufferedAsync(CancellationToken); BufferedCommandResult result = null; // result is null when cancelled ExecuteResponse executeResponse = null; try { result = await commandTask; } catch (OperationCanceledException) { } if (result != null) { var exitCode = result.ExitCode; // get script output var outputList = new List <string>(); var directOutput = string.Join(Environment.NewLine, new[] { result.StandardOutput, Environment.NewLine, result.StandardError } .Where(x => !string.IsNullOrWhiteSpace(x))) .Trim('\r', '\n') .Trim(); if (!string.IsNullOrWhiteSpace(directOutput)) { outputList.Add(directOutput); } if (File.Exists(shellScriptOutputFile)) { var redirectOutput = File.ReadAllText(shellScriptOutputFile) .Trim('\r', '\n') .Trim(); if (!string.IsNullOrWhiteSpace(redirectOutput)) { outputList.Add(redirectOutput); } } else { // There is a problem if the shellScriptOutputFile is not produced exitCode = FAILED_TO_PRODUCE_OUTPUT_FILE_CODE; } var output = string.Join(Environment.NewLine, outputList) .Trim('\r', '\n') .Trim(); executeResponse = new ExecuteResponse { ExitCode = exitCode, ExitTime = result.ExitTime, RunTime = result.RunTime, StartTime = result.StartTime, Output = output }; } FileSystemInfoDeleteExtensions.TryDelete(shellScriptFile); FileSystemInfoDeleteExtensions.TryDelete(shellScriptOutputFile); return(executeResponse); }