Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ release that first shipped the module.

### Documented

- **The Kotlin and Scala quick starts now run as standalone programs.** Each
includes its build file and starts a private tmux session using the
published libraries. (#203)

- **`:docs:test` now checks the Java examples in Javadoc.** The suite compiles
API comment examples and checks their displayed results against tmux.
Examples that only compile or are skipped carry a reason. (#204)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ abstract class GenerateScalaDocumentationSuite : DefaultTask() {
val beforeIndex = (start - 1 downTo 0).firstOrNull { lines[it].isNotBlank() }
val before = beforeIndex?.let { lines[it].trim() }.orEmpty()
val directive = requireNotNull(DIRECTIVE.matchEntire(before)) {
"$where has an unclassified Scala fence; use a snippet: scala-sync, scala-sync-control, scala-io, scala-io-control, scala-reject or scala-build directive"
"$where has an unclassified Scala fence; use a snippet: scala-main, scala-sync, scala-sync-control, scala-io, scala-io-control, scala-reject or scala-build directive"
}
unusedDirectives.remove(beforeIndex)
val (mode, id, detail) = directive.destructured
Expand All @@ -112,7 +112,7 @@ abstract class GenerateScalaDocumentationSuite : DefaultTask() {
}
snippets
}
require(found.any { it.mode == "sync" || it.mode == "io" }) { "no runnable Scala documentation fences were discovered" }
require(found.any { it.mode == "sync" || it.mode == "io" || it.mode == "main" }) { "no runnable Scala documentation fences were discovered" }
val duplicates = found.groupBy { it.id }.filterValues { it.size > 1 }.keys.sorted()
require(duplicates.isEmpty()) { "duplicate Scala documentation ids: $duplicates" }
return found
Expand All @@ -124,6 +124,9 @@ abstract class GenerateScalaDocumentationSuite : DefaultTask() {
.joinToString(",\n") { quoted(relative(root, it)) + " -> " + quoted(digest(it.readBytes())) }
val names = runnable.joinToString(",\n") { quoted(it.name(root)) }
val declarations = runnable.filterNot { it.mode == "reject" }.joinToString("\n") { snippet ->
if (snippet.mode == "main") {
return@joinToString "private[docs] object ${snippet.objectName} {\n${snippet.code}\n}\n"
}
val synchronous = snippet.mode == "sync" || snippet.mode == "sync-control"
val body = if (synchronous) "DocumentationRuntime.requireUnit {\n${snippet.code}\n}" else "{\n${snippet.code}\n}"
val result = if (synchronous) "Unit" else "_root_.cats.effect.IO[Unit]"
Expand All @@ -132,6 +135,7 @@ abstract class GenerateScalaDocumentationSuite : DefaultTask() {
val cases = runnable.joinToString("\n") { snippet ->
val invoke = snippet.objectName + ".run(fixture.config)"
val body = when (snippet.mode) {
"main" -> "${snippet.objectName}.Main.main(Array.empty[String])"
"sync" -> "io.github.libtmux.scaladsl.fixture.OwnedTmux.use { fixture => $invoke }"
"sync-control" ->
"io.github.libtmux.scaladsl.fixture.OwnedTmux.use { fixture =>\n" +
Expand Down Expand Up @@ -192,7 +196,7 @@ $cases
val IGNORED = setOf(".git", ".gradle", ".bsp", ".metals", ".idea", "target", "build", "node_modules")
val OPENING = Regex("^ {0,3}(`{3,}|~{3,})[ \\t]*([^\\s`]*).*$")
val UNSUPPORTED_SCALA_FENCE = Regex("(?i)^[ \\t>]*(?:`{3,}|~{3,})[ \\t]*(?:scala\\S*|sbt)(?:[ \\t].*)?$")
val DIRECTIVE = Regex("^<!--\\s*snippet:\\s*scala-(sync|sync-control|io|io-control|reject|build):\\s*([a-z0-9][a-z0-9-]*)(?:\\s*\\|\\s*(.+?))?\\s*-->$")
val DIRECTIVE = Regex("^<!--\\s*snippet:\\s*scala-(main|sync|sync-control|io|io-control|reject|build):\\s*([a-z0-9][a-z0-9-]*)(?:\\s*\\|\\s*(.+?))?\\s*-->$")

fun relative(root: File, file: File): String = root.toPath().relativize(file.toPath()).toString().replace('\\', '/')

Expand Down
4 changes: 4 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,10 @@ The generated file is the documentation, so the two cannot drift.
$ ./gradlew :libtmux-kotlin:test
```

- Mark a complete Kotlin entry point with `<!-- snippet: main -->`. Its
generated test calls `main()` with only the imports shown in the program.
A Scala entry point uses `<!-- snippet: scala-main: id -->` and runs
`Main.main(Array.empty[String])`.
- A Kotlin fence gets `server` and nothing else unless its first line asks, the
same rule as the Java `Given:` line: `// Given: config: ServerConfig` or `//
Given: session: Session, window: Window, pane: Pane`.
Expand Down
124 changes: 56 additions & 68 deletions docs/guide/scala/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,106 +14,94 @@ They are on Maven Central and release with the Java artifacts.
- **`libtmux-scala-cats_3`** — Cats Effect resources and FS2 observations.
- **`libtmux-scala-ox_3`** — an Ox `Flow` over subscriptions and live views.

For a new sbt project, save this as `build.sbt`:

<!-- snippet: scala-build: install-core -->
```sbt
libraryDependencies += "io.github.libtmux" %% "libtmux-scala" % "<version>"
scalaVersion := "3.9.0"
scalacOptions += "-release:25"
libraryDependencies += "io.github.libtmux" %% "libtmux-scala" % "0.1.2"
```

For Cats Effect and FS2, or for Ox, add the matching module:

<!-- snippet: scala-build: install-cats -->
```sbt
libraryDependencies += "io.github.libtmux" %% "libtmux-scala-cats" % "<version>"
libraryDependencies += "io.github.libtmux" %% "libtmux-scala-cats" % "0.1.2"
```

<!-- snippet: scala-build: install-ox -->
```sbt
libraryDependencies += "io.github.libtmux" %% "libtmux-scala-ox" % "<version>"
libraryDependencies += "io.github.libtmux" %% "libtmux-scala-ox" % "0.1.2"
```

From Gradle or Maven, name the suffixed artifact directly:
`io.github.libtmux:libtmux-scala_3:<version>`. The core facade depends on
`io.github.libtmux:libtmux-scala_3:0.1.2`. The core facade depends on
`libtmux` and the Scala 3 library, and on nothing else.

## A first client

The function below takes three caller-supplied values and constructs a Java
`ServerConfig` before opening the Scala client:

| Parameter | Value to supply |
| --- | --- |
| `binary` | Absolute path to your tmux executable |
| `socket` | An isolated socket you own under `/tmp/libtmux-java-dev/` |
| `configFile` | Your tmux configuration file, or `/dev/null` for none |

For example, choose `/tmp/libtmux-java-dev/scala-start/socket`; the function
creates its parent directory. Opening the client does not create tmux;
`newSession` does. The operation creates a session, splits its window, verifies
the resulting panes and kills that session. Closing the client is separate
from session cleanup. An existing server's other sessions remain running;
tmux normally exits when its final session closes.
Save this complete program as `src/main/scala/Main.scala`. It selects a fresh
socket under `/tmp/libtmux-java-dev/`, creates a session with two panes, checks
the captured layout, and stops its private daemon before closing the client.
It reads tmux from `PATH`.

Call `firstClient` with your three values from your application.
The final call in this tested snippet takes those inputs from the owned test
fixture's `config`; the function builds and uses its own configuration.

<!-- snippet: scala-sync: getting-started-session -->
<!-- snippet: scala-main: getting-started-session -->
```scala
import io.github.libtmux.{
Layout, ServerConfig, ServerEndpoint, SessionSpec, SplitSpec
}
import io.github.libtmux.scaladsl.{config => _, *}
import io.github.libtmux.scaladsl.*
import java.nio.file.{Files, Path}
import java.time.Duration
import scala.util.Using

def firstClient(binary: String, socket: Path, configFile: Path): Unit = {
require(Path.of(binary).isAbsolute, "supply an absolute tmux executable")
val ownedSocket = socket.toAbsolutePath.normalize()
require(
ownedSocket.startsWith(Path.of("/tmp/libtmux-java-dev")) ||
ownedSocket.startsWith(Path.of("/tmp/libtmux-java-test")),
"choose a socket under an owned libtmux Java directory"
)
Files.createDirectories(ownedSocket.getParent)
val selected = ServerConfig.builder()
.binary(binary)
.endpoint(ServerEndpoint.socketPath(ownedSocket))
.configFile(configFile)
.defaultTimeout(Duration.ofMillis(800))
.build()

Using.resource(Server.open(selected)) { server =>
val session = server.newSession(
SessionSpec.builder().named("scala-start").running("cat", "-").build()
)
try {
val window = session.windows.head
val second = window.split(
SplitSpec.builder().running("cat", "-").build()
)
window.selectLayout(Layout.EVEN_HORIZONTAL)
second.select()
// window.panes is CAPTURED: it answers from window's own frozen capture, taken before the
// split, so this refreshes first rather than reading stale data.
val panes = window.refresh().panes
assert(panes.size == 2)
assert(panes.exists(_.info.id().value() == second.info.id().value()))
} finally session.kill()
object Main {
def main(args: Array[String]): Unit = {
val root = Files.createDirectories(Path.of("/tmp/libtmux-java-dev"))
val directory = Files.createTempDirectory(root, "scala-start-")
val socket = directory.resolve("s")
val config = ServerConfig.builder()
.endpoint(ServerEndpoint.socketPath(socket))
.configFile(Path.of("/dev/null"))
.build()
Using.resource(Server.open(config)) { server =>
try {
val session = server.newSession(
SessionSpec.builder().named("scala-start").running("cat", "-").build()
)
val window = session.windows.head
val second = window.split(
SplitSpec.builder().running("cat", "-").build()
)
window.selectLayout(Layout.EVEN_HORIZONTAL)
second.select()
val panes = window.refresh().panes
assert(panes.size == 2)
assert(panes.exists(_.info.id().value() == second.info.id().value()))
println(s"created ${panes.size} panes")
} finally {
server.killServer()
Files.deleteIfExists(socket)
Files.deleteIfExists(directory)
}
}
}
}
```

config.endpoint() match {
case endpoint: ServerEndpoint.SocketPath =>
firstClient(
config.binaryPath(),
endpoint.path(),
config.configFile().orElse(Path.of("/dev/null"))
)
case _ => throw new IllegalArgumentException("an explicit socket is required")
}
Run it with sbt:

```console
$ sbt run
```

The output includes `created 2 panes`. `window.refresh()` captures the pane
list after the split; the original window's captured list still has one pane.
`Using.resource` closes the library client. The separate `killServer` call
stops the daemon because this program created and owns it. When connecting to
an existing daemon, leave its lifetime with its owner and remove only sessions
your application created.

Pane waits accept `scala.concurrent.duration.FiniteDuration`, converted at the
boundary: `pane.awaitText("$", 5.seconds)`. Java `ServerConfig`, direct-style
live-view waits, and Cats control attachment and acknowledgement parameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,21 +194,21 @@ void theReadmeNamesTheEndsOfTheMatrixItClaims() {
* Every sbt install line the documentation shows is one the sbt consumer build resolves.
*
* <p>That build fetches each artifact from the staged repository exactly as a reader's would, so a
* documented line it does not carry is a line nothing has shown to work. Versions are compared
* as a placeholder: the documents say {@code "<version>"} or the release, the build says
* {@code libtmuxVersion}.
* documented line it does not carry is a line nothing has shown to work. Documents name the
* release the consumer receives through {@code libtmuxVersion}.
*/
@Test
void everyDocumentedSbtLineIsOneTheSbtConsumerResolves() {
Pattern fence = Pattern.compile(
"<!--\\s*snippet:\\s*scala-build:\\s*([a-z0-9-]+)\\s*-->\\s*\\n```sbt\\n(.*?)^```",
Pattern.MULTILINE | Pattern.DOTALL);
Set<String> consumer = sbtLines(read("module-tests/sbt/build.sbt"));
Set<String> consumer = sbtLines(read("module-tests/sbt/build.sbt"), "libtmuxVersion");
String documentedVersion = "\"" + releaseVersion() + "\"";
List<String> unresolved = new ArrayList<>();
for (String document : readerFacing()) {
Matcher found = fence.matcher(read(document));
while (found.find()) {
for (String line : sbtLines(found.group(2))) {
for (String line : sbtLines(found.group(2), documentedVersion)) {
if (!consumer.contains(line)) {
unresolved.add(document + " (" + found.group(1) + "): " + line);
}
Expand All @@ -219,12 +219,12 @@ void everyDocumentedSbtLineIsOneTheSbtConsumerResolves() {
}

/** The {@code libraryDependencies} lines of an sbt fragment, with the version normalized away. */
private static Set<String> sbtLines(String sbt) {
private static Set<String> sbtLines(String sbt, String version) {
return Pattern.compile("libraryDependencies\\s*\\+=[^\\n]*")
.matcher(sbt)
.results()
.map(found -> found.group()
.replaceAll("%\\s*(\"[^\"]*\"|libtmuxVersion)\\s*$", "% VERSION")
.replaceAll("%\\s*" + Pattern.quote(version) + "\\s*$", "% VERSION")
.replaceAll("\\s+", " "))
.collect(Collectors.toCollection(TreeSet::new));
}
Expand Down
72 changes: 70 additions & 2 deletions libtmux-kotlin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,84 @@ tmux](#watch-tmux-change) · [Leaves out](#what-it-leaves-out) ·

## Quick start

Add it through the BOM, which names one version for every module:
Use JDK 25, Gradle 9 and tmux 3.3a or newer. In an empty directory,
save this as `settings.gradle.kts`:

<!-- snippet: skip: build configuration, not library code -->
<!-- snippet: skip: Gradle project settings -->
```kotlin
rootProject.name = "tmux-demo"
```

Save this as `build.gradle.kts`:

<!-- snippet: skip: Gradle build configuration -->
```kotlin
plugins {
kotlin("jvm") version "2.4.21"
application
}

repositories { mavenCentral() }

kotlin { jvmToolchain(25) }

dependencies {
implementation(platform("io.github.libtmux:libtmux-bom:0.1.2"))
implementation("io.github.libtmux:libtmux-kotlin")
}

application { mainClass.set("MainKt") }
```

### Start a private session

Save this complete program as `src/main/kotlin/Main.kt`. It creates a fresh
socket directory under `/tmp/libtmux-java-dev/`, starts its own tmux server,
prints the created session's name, and removes that server before closing the
client. It reads tmux from `PATH`.

<!-- snippet: main -->
```kotlin
import io.github.libtmux.ServerConfig
import io.github.libtmux.ServerEndpoint
import io.github.libtmux.kotlin.killServer
import io.github.libtmux.kotlin.newSession
import io.github.libtmux.kotlin.withServer
import java.nio.file.Files
import java.nio.file.Path
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
val root = Files.createDirectories(Path.of("/tmp/libtmux-java-dev"))
val directory = Files.createTempDirectory(root, "kotlin-start-")
val socket = directory.resolve("s")
val config = ServerConfig.builder()
.endpoint(ServerEndpoint.socketPath(socket))
.configFile(Path.of("/dev/null"))
.build()
withServer(config) { server ->
try {
val session = server.newSession("kotlin-start")
check(session.name == "kotlin-start")
println(session.name)
} finally {
server.killServer()
Files.deleteIfExists(socket)
Files.deleteIfExists(directory)
}
}
}
```

Run the application:

```console
$ gradle run
```

The program prints `kotlin-start`. It calls `killServer` to stop its private
daemon before `withServer` closes the client.

### [`withServer`][with-server]: open a server, close it however the block ends

[`Server`][server], [`Session`][session], [`Window`][window], [`Pane`][pane],
Expand Down
24 changes: 24 additions & 0 deletions libtmux-kotlin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,30 @@ val documentedKotlin =
// the same line would otherwise generate one function twice.
val name = "${where.replace('/', ' ').replace('.', ' ')} line $line"

if (directive == "main") {
val packageName = "io.github.libtmux.docs.kotlin.s$found"
val directory = generated.get().asFile.resolve(packageName.replace('.', '/'))
directory.mkdirs()
// Separate files keep harness imports out of a complete reader program.
directory.resolve("Main.kt").writeText("package $packageName\n\n${match.groupValues[2]}")
directory.resolve("Snippet.kt").writeText(
"""
|package $packageName
|
|import org.junit.jupiter.api.Test
|
|class Snippet {
| @Test
| fun `$name`() {
| main()
| }
|}
|
""".trimMargin(),
)
return@forEach
}

// A shown result becomes an assertion, the same rule the documentation module applies to the
// Java fences: what a reader sees after the arrow is what toString produced, so
// documentation cannot claim a value the library does not give.
Expand Down
2 changes: 1 addition & 1 deletion libtmux-scala-cats/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ API reference: [libtmux.org][reference] for the current trunk,

<!-- snippet: scala-build: cats-readme-install -->
```sbt
libraryDependencies += "io.github.libtmux" %% "libtmux-scala-cats" % "<version>"
libraryDependencies += "io.github.libtmux" %% "libtmux-scala-cats" % "0.1.2"
```

From Gradle or Maven the coordinate is `io.github.libtmux:libtmux-scala-cats_3`.
Expand Down
Loading
Loading