Core Library0.xAPI reference

Choose documentation 3

latest

Current version

latest
English

Early release libtmux is released, and its APIs may still change between releases. This site's structure and URLs may change too.

MoreLess about this notice

method libtmux-dotnet

QueryExtensions.Translate

Translates an expression into a wire document.

Source and package
Qualified name
LibTmux.Query.QueryExtensions.Translate
Namespace
LibTmux.Query
Declared in
QueryExtensions
Package
LibTmux
Source
src/LibTmux/Query/QueryExtensions.cs
Type parameters
  • T

    The filtered element type.

Parameters
Returns

The translated document.

Errors

Examples

Compare LINQ with translated expression and document predicates, preserve cancellation, and capture the hierarchy before filtering its children. Use Linux or macOS with tmux 3.3a or newer, the .NET 10 SDK or newer, and the .NET 8 and 10 runtimes. In an empty directory, save this project as Example.csproj. It references the 0.1.1 release of LibTmux on NuGet: View source

Example.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net8.0;net10.0</TargetFrameworks>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisLevel>10-recommended</AnalysisLevel>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<PackageReference Include="LibTmux" Version="[0.1.1]" />
</ItemGroup>
</Project>

Save this complete program as Program.cs. It creates a private server; await using disposes its owned scopes after success, cancellation or failure. The complete file contains explicit imports, a top-level async entry point and a cancellation deadline. View source

Program.csComplete program
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using LibTmux;
using System.Linq.Expressions;
using LibTmux.Query;
if (OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException("This example requires tmux on Linux or macOS.");
}
using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10));
CancellationToken token = deadline.Token;
string? testTmux = Environment.GetEnvironmentVariable("LIBTMUX_TEST_TMUX");
string? configured = !string.IsNullOrWhiteSpace(testTmux)
? testTmux
: Environment.GetEnvironmentVariable("LIBTMUX_TMUX");
string binary = string.IsNullOrWhiteSpace(configured) ? "tmux" : configured;
using TemporaryDirectory socketRoot = new();
ServerConnectionOptions options = new()
{
SocketPath = Path.Combine(socketRoot.FullName, "tmux.sock"),
ConfigurationFile = "/dev/null",
TmuxBinaryPath = binary,
};
await using OwnedServerScope owned = await Server.CreateOwnedAsync(options, token);
// tmux reports the shell that starts a pane until the shell has become cat. Echo goes off before the
// pane prints ready, so the first line cat prints back is the proof that cat is reading.
const string command = "stty -echo; printf 'ready\\n'; exec /bin/cat";
await using OwnedSessionScope demo = await owned.Value.CreateOwnedSessionAsync(
new NewSessionRequest { Name = "demo", WindowName = "shell", Command = command }, token);
await using OwnedSessionScope worker = await owned.Value.CreateOwnedSessionAsync(
new NewSessionRequest { Name = "worker", WindowName = "jobs", Command = "/bin/cat" }, token);
Server server = await Server.ConnectAsync(options, token);
Window demoWindow = (await demo.Value.GetWindowsAsync(token)).Single();
Pane demoPane = (await demoWindow.GetPanesAsync(token)).Single();
PaneWaitResult ready = await demoPane.WaitForTextAsync(
PaneWaitRequest.FromTextPatterns(["ready"], simpleMatch: true)
with
{ Timeout = TimeSpan.FromSeconds(5) },
token);
if (ready.Outcome is not (PaneWaitOutcome.Matched or PaneWaitOutcome.PresentAtEntry))
{
throw new InvalidOperationException($"The demo pane never signalled that it was ready: {ready.Outcome}.");
}
await demoPane.SendTextAsync("started", cancellationToken: token);
PaneWaitResult started = await demoPane.WaitForTextAsync(
new PaneWaitRequest
{
Patterns = [new Regex("^started$", RegexOptions.CultureInvariant)],
Timeout = TimeSpan.FromSeconds(5),
},
token);
if (started.Outcome is not (PaneWaitOutcome.Matched or PaneWaitOutcome.PresentAtEntry))
{
throw new InvalidOperationException($"The pane never echoed through cat: {started.Outcome}.");
}
IReadOnlyList<Session> sessions = await server.GetSessionsAsync(token);
// LINQ and portable predicates operate on these rows; neither reads tmux.
Session native = sessions.Where(session => session.Name == "demo").Single();
Expression<Func<Session, bool>> predicate = session => session.Name == "demo";
QueryDocument document = QueryExtensions.Translate(predicate);
Session expressionMatch = sessions.Matching(predicate).Single();
Session documentMatch = sessions.Matching(document).Single();
Session cancellableMatch = sessions.Matching(document, token).Single();
if (new[] { native, expressionMatch, documentMatch, cancellableMatch }
.Any(session => session.Id != demo.Value.Id))
{
throw new InvalidOperationException("The native and portable predicates selected different sessions.");
}
// A predicate that traverses children requires an explicitly captured hierarchy.
Server captured = await server.CaptureSnapshotAsync(SnapshotDepth.Panes, token);
Session parent = captured.Sessions.Matching(session =>
session.Windows.Any(window => window.Name == "shell" && window.Panes.Any(pane => pane.CurrentCommand == "cat"))).Single();
if (parent.Id != demo.Value.Id)
{
throw new InvalidOperationException("The hierarchy predicate selected an unexpected parent.");
}
using CancellationTokenSource cancelled = new();
cancelled.Cancel();
try
{
_ = sessions.Matching(document, cancelled.Token);
throw new InvalidOperationException("Cancelled filtering must throw.");
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled filtering remains OperationCanceledException.");
}
Console.WriteLine($"LINQ, expression and document filters: {native.Name}; captured parent: {parent.Name}");
internal sealed class TemporaryDirectory : IDisposable
{
private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("libtmux-example-");
public string FullName => _directory.FullName;
public void Dispose() => _directory.Delete(recursive: true);
}

Build the project and run both supported frameworks. Each program checks its result and exits unsuccessfully after an unhandled error:

Terminal window
$ dotnet build Example.csproj --configuration Release && \
dotnet bin/Release/net8.0/Example.dll && \
dotnet bin/Release/net10.0/Example.dll

Expected program output from each framework:

Cancelled filtering remains OperationCanceledException.
LINQ, expression and document filters: demo; captured parent: demo

Recorded calls

source calls
No call edges in the C# model.

The C# reference records declarations, not calls, so this page shows no callers or callees. That is a limit of the extracted data, not a statement that nothing calls LibTmux.Query.QueryExtensions.Translate.

Esc
Search in

Type to search.

Reference previewOpen reference