Skip to content

Commit 11444ea

Browse files
committed
docs: Add new Topics
1 parent 253a920 commit 11444ea

File tree

4 files changed

+622
-0
lines changed

4 files changed

+622
-0
lines changed

docs/topics/advanced_scripting.md

+252
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
---
2+
orphan: true
3+
---
4+
5+
# Advanced Scripting
6+
7+
libtmux enables sophisticated scripting of tmux operations, allowing developers to create robust tools and workflows.
8+
9+
## Complex Window and Pane Layouts
10+
11+
You can create intricate layouts with precise control over window and pane placement:
12+
13+
```python
14+
import libtmux
15+
16+
server = libtmux.Server()
17+
session = server.new_session(session_name="complex-layout")
18+
19+
# Create main window
20+
main = session.new_window(window_name="main-window")
21+
22+
# Create side pane (vertical split)
23+
side_pane = main.split_window(vertical=True)
24+
25+
# Create bottom pane (horizontal split from main pane)
26+
bottom_pane = main.attached_pane.split_window(vertical=False)
27+
28+
# Create a grid layout in another window
29+
grid_window = session.new_window(window_name="grid")
30+
top_left = grid_window.attached_pane
31+
top_right = top_left.split_window(vertical=True)
32+
bottom_left = top_left.split_window(vertical=False)
33+
bottom_right = top_right.split_window(vertical=False)
34+
35+
# Now you can send commands to each pane
36+
top_left.send_keys("echo 'Top Left'", enter=True)
37+
top_right.send_keys("echo 'Top Right'", enter=True)
38+
bottom_left.send_keys("echo 'Bottom Left'", enter=True)
39+
bottom_right.send_keys("echo 'Bottom Right'", enter=True)
40+
```
41+
42+
## Reactive Scripts
43+
44+
Create scripts that react to tmux events or monitor state:
45+
46+
```python
47+
import libtmux
48+
import time
49+
50+
server = libtmux.Server()
51+
session = server.find_where({"session_name": "monitored-session"})
52+
53+
if not session:
54+
print("Session not found!")
55+
exit(1)
56+
57+
def monitor_pane_count():
58+
"""Monitor the number of panes and react to changes"""
59+
initial_pane_count = len(session.list_windows()[0].list_panes())
60+
print(f"Starting monitor with {initial_pane_count} panes")
61+
62+
while True:
63+
time.sleep(5) # Check every 5 seconds
64+
current_pane_count = len(session.list_windows()[0].list_panes())
65+
66+
if current_pane_count > initial_pane_count:
67+
print(f"New pane detected! ({current_pane_count} total)")
68+
# React to new pane - perhaps log it or configure it
69+
newest_pane = session.list_windows()[0].list_panes()[-1]
70+
newest_pane.send_keys("echo 'This pane was auto-configured'", enter=True)
71+
72+
elif current_pane_count < initial_pane_count:
73+
print(f"Pane closed! ({current_pane_count} remaining)")
74+
# React to closed pane
75+
76+
initial_pane_count = current_pane_count
77+
78+
# Use in a script
79+
if __name__ == "__main__":
80+
try:
81+
monitor_pane_count()
82+
except KeyboardInterrupt:
83+
print("Monitoring stopped")
84+
```
85+
86+
## Working with Command Output
87+
88+
libtmux allows you to easily capture and process command output:
89+
90+
```python
91+
import libtmux
92+
93+
server = libtmux.Server()
94+
session = server.new_session(session_name="command-output")
95+
window = session.attached_window
96+
97+
# Send a command and capture its output
98+
window.send_keys("ls -la", enter=True)
99+
100+
# Wait for command to complete
101+
import time
102+
time.sleep(1)
103+
104+
# Capture the pane content
105+
output = window.attached_pane.capture_pane()
106+
107+
# Process the output
108+
for line in output:
109+
if "total " in line:
110+
print(f"Directory size summary: {line}")
111+
break
112+
113+
# Execute a tmux command directly and process its result
114+
running_sessions = server.cmd("list-sessions", "-F", "#{session_name}").stdout
115+
print(f"Current sessions: {running_sessions}")
116+
```
117+
118+
## State Management
119+
120+
Implement state tracking for your tmux sessions:
121+
122+
```python
123+
import libtmux
124+
import json
125+
import os
126+
from datetime import datetime
127+
128+
class TmuxStateManager:
129+
def __init__(self, state_file="~/.tmux_state.json"):
130+
self.state_file = os.path.expanduser(state_file)
131+
self.server = libtmux.Server()
132+
self.state = self._load_state()
133+
134+
def _load_state(self):
135+
if os.path.exists(self.state_file):
136+
with open(self.state_file, 'r') as f:
137+
return json.load(f)
138+
return {"sessions": {}, "last_update": None}
139+
140+
def _save_state(self):
141+
self.state["last_update"] = datetime.now().isoformat()
142+
with open(self.state_file, 'w') as f:
143+
json.dump(self.state, f, indent=2)
144+
145+
def update_session_state(self, session_name):
146+
"""Record information about a session"""
147+
session = self.server.find_where({"session_name": session_name})
148+
if not session:
149+
return False
150+
151+
windows_info = []
152+
for window in session.windows:
153+
panes_info = []
154+
for pane in window.panes:
155+
panes_info.append({
156+
"pane_id": pane.pane_id,
157+
"pane_index": pane.pane_index,
158+
"current_path": pane.current_path,
159+
"current_command": pane.current_command
160+
})
161+
162+
windows_info.append({
163+
"window_id": window.window_id,
164+
"window_name": window.window_name,
165+
"panes": panes_info
166+
})
167+
168+
self.state["sessions"][session_name] = {
169+
"session_id": session.session_id,
170+
"created_at": datetime.now().isoformat(),
171+
"windows": windows_info
172+
}
173+
174+
self._save_state()
175+
return True
176+
177+
def restore_session(self, session_name):
178+
"""Attempt to restore a session based on saved state"""
179+
if session_name not in self.state["sessions"]:
180+
return False
181+
182+
saved_session = self.state["sessions"][session_name]
183+
# Implementation of session restoration logic here
184+
185+
return True
186+
```
187+
188+
## Integration with External APIs
189+
190+
Combine libtmux with external APIs for powerful automation:
191+
192+
```python
193+
import libtmux
194+
import requests
195+
import json
196+
197+
def deploy_and_monitor(repo_name, branch="main"):
198+
# Start a new deployment session
199+
server = libtmux.Server()
200+
session = server.new_session(session_name=f"deploy-{repo_name}")
201+
202+
# Window for deployment log
203+
deploy_window = session.attached_window
204+
deploy_window.rename_window("deployment")
205+
206+
# Window for API responses
207+
api_window = session.new_window(window_name="api-status")
208+
209+
# Trigger deployment via API
210+
deploy_window.send_keys(f"echo 'Starting deployment of {repo_name}:{branch}'", enter=True)
211+
response = requests.post(
212+
"https://api.example.com/deployments",
213+
json={"repository": repo_name, "branch": branch},
214+
headers={"Authorization": "Bearer YOUR_TOKEN"}
215+
)
216+
217+
# Display API response
218+
deployment_id = response.json().get("deployment_id")
219+
api_window.send_keys(f"echo 'Deployment triggered: {deployment_id}'", enter=True)
220+
221+
# Poll status API
222+
for _ in range(10): # Check 10 times
223+
status_response = requests.get(
224+
f"https://api.example.com/deployments/{deployment_id}",
225+
headers={"Authorization": "Bearer YOUR_TOKEN"}
226+
)
227+
status = status_response.json().get("status")
228+
api_window.send_keys(f"echo 'Current status: {status}'", enter=True)
229+
230+
if status in ["complete", "failed"]:
231+
break
232+
233+
# Wait before checking again
234+
import time
235+
time.sleep(30)
236+
237+
# Final deployment result
238+
deploy_window.send_keys(f"echo 'Deployment {deployment_id} finished with status: {status}'", enter=True)
239+
240+
return deployment_id, status
241+
```
242+
243+
## Debugging Tips
244+
245+
When scripting with libtmux, consider these debugging approaches:
246+
247+
1. Use `session.cmd('display-message', 'Debug message')` to display messages in the tmux client
248+
2. Capture pane content with `pane.capture_pane()` to see the current state
249+
3. Use Python's logging module to track script execution
250+
4. Add print statements and redirect your script's output to a file for later inspection
251+
5. When testing complex scripts, use a dedicated testing session to avoid affecting your main workflow
252+
```

docs/topics/automation.md

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
---
2+
orphan: true
3+
---
4+
5+
# Automation
6+
7+
One of the primary values of libtmux is its ability to automate tmux operations programmatically, making it ideal for scripting, testing, and building higher-level applications.
8+
9+
## Common Automation Use Cases
10+
11+
### 1. Development Environment Setup
12+
13+
Automatically set up development environments with specific layouts, services, and commands:
14+
15+
```python
16+
import libtmux
17+
18+
# Connect to tmux server
19+
server = libtmux.Server()
20+
21+
# Create or attach to a session
22+
session = server.new_session(session_name="dev-environment")
23+
24+
# Create windows for different services
25+
editor_window = session.new_window(window_name="editor")
26+
server_window = session.new_window(window_name="server")
27+
logs_window = session.new_window(window_name="logs")
28+
29+
# Set up editor
30+
editor_window.send_keys("cd ~/projects/myapp && vim .", enter=True)
31+
32+
# Start server in another window
33+
server_window.send_keys("cd ~/projects/myapp && npm start", enter=True)
34+
35+
# Set up log monitoring
36+
logs_window.send_keys("cd ~/projects/myapp && tail -f logs/development.log", enter=True)
37+
38+
# Return to the editor window
39+
session.switch_window(0)
40+
```
41+
42+
### 2. Continuous Integration/Deployment
43+
44+
```python
45+
def deploy_application(env="staging"):
46+
server = libtmux.Server()
47+
session = server.new_session(session_name=f"deploy-{env}", kill_session=True)
48+
49+
# Window for deployment
50+
deploy_window = session.new_window(window_name="deploy")
51+
52+
# Run deployment commands
53+
deploy_window.send_keys(f"cd ~/projects/myapp && ./deploy.sh {env}", enter=True)
54+
55+
# Monitor deployment status
56+
monitor_window = session.new_window(window_name="monitor")
57+
monitor_window.send_keys(f"cd ~/projects/myapp && tail -f logs/deploy-{env}.log", enter=True)
58+
59+
return session
60+
```
61+
62+
### 3. System Monitoring Dashboard
63+
64+
Create a terminal-based dashboard with multiple panes showing different system metrics:
65+
66+
```python
67+
def create_monitoring_dashboard():
68+
server = libtmux.Server()
69+
session = server.new_session(session_name="system-monitor", kill_session=True)
70+
71+
window = session.new_window(window_name="dashboard")
72+
73+
# Top-left pane: CPU and memory usage
74+
top_pane = window.attached_pane
75+
top_pane.send_keys("htop", enter=True)
76+
77+
# Top-right pane: Disk usage
78+
right_pane = window.split_window(vertical=True)
79+
right_pane.send_keys("df -h; watch -n 10 df -h", enter=True)
80+
81+
# Bottom-left: Network traffic
82+
bottom_pane = top_pane.split_window(vertical=False)
83+
bottom_pane.send_keys("iftop", enter=True)
84+
85+
# Bottom-right: System logs
86+
bottom_right = right_pane.split_window(vertical=False)
87+
bottom_right.send_keys("journalctl -f", enter=True)
88+
89+
return session
90+
```
91+
92+
## Integration with Other Tools
93+
94+
libtmux's programmatic approach makes it ideal for integration with other tools and frameworks:
95+
96+
- **Task runners**: Integrate with tools like Invoke, Fabric, or make
97+
- **Configuration management**: Use with Ansible, Chef, or Puppet for remote server setup
98+
- **Workflow automation**: Combine with cron jobs or systemd timers for scheduled tasks
99+
- **Custom CLI tools**: Build your own tmux wrapper with domain-specific commands
100+
101+
## Best Practices for Automation
102+
103+
1. **Error handling**: Always handle exceptions properly in your automation scripts
104+
2. **Idempotent operations**: Make your scripts safe to run multiple times
105+
3. **Configuration file support**: Allow customization through config files rather than hardcoding values
106+
4. **Logging**: Implement proper logging for tracking automated actions
107+
5. **Testing**: Use libtmux's pytest plugin to test your automation code
108+
109+
## Real-world Examples
110+
111+
libtmux powers [tmuxp](https://tmuxp.git-pull.com/), a tmux session manager that allows you to configure and save tmux sessions, demonstrating how libtmux can serve as a foundation for more complex tools.
112+
```

docs/topics/index.md

+3
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,7 @@ Explore libtmux’s core functionalities and underlying principles at a high lev
1010
1111
context_managers
1212
traversal
13+
automation
14+
advanced_scripting
15+
use_cases
1316
```

0 commit comments

Comments
 (0)