0
# Aliases
1
2
## Overview
3
4
Xonsh provides a comprehensive alias system for creating custom commands, function shortcuts, and command transformations. The alias system supports multiple types including function aliases, executable aliases, and partial evaluation aliases for complex command building.
5
6
## Alias Container
7
8
### Aliases Class
9
10
```python { .api }
11
from xonsh.aliases import Aliases
12
13
class Aliases(collections.abc.MutableMapping):
14
"""Container for xonsh aliases with dict-like interface."""
15
16
def __init__(self):
17
"""Initialize alias container."""
18
19
def __getitem__(self, key: str) -> object:
20
"""Get alias by name.
21
22
Parameters
23
----------
24
key : str
25
Alias name
26
27
Returns
28
-------
29
object
30
Alias object (FuncAlias, ExecAlias, etc.)
31
"""
32
33
def __setitem__(self, key: str, value) -> None:
34
"""Set alias.
35
36
Parameters
37
----------
38
key : str
39
Alias name
40
value : str, callable, or Alias object
41
Alias definition
42
"""
43
44
def __delitem__(self, key: str) -> None:
45
"""Delete alias by name.
46
47
Parameters
48
----------
49
key : str
50
Alias name to delete
51
"""
52
53
def register(self, name: str, func: callable = None, **kwargs):
54
"""Register a function as an alias.
55
56
Parameters
57
----------
58
name : str
59
Alias name
60
func : callable, optional
61
Function to register (can be used as decorator)
62
**kwargs
63
Additional alias configuration
64
65
Returns
66
-------
67
callable or None
68
Function (for decorator usage) or None
69
"""
70
71
# Global aliases instance
72
from xonsh.built_ins import XSH
73
aliases = XSH.aliases # Main aliases container
74
```
75
76
## Function Aliases
77
78
### FuncAlias Class
79
80
```python { .api }
81
from xonsh.aliases import FuncAlias
82
83
class FuncAlias:
84
"""Alias that calls a Python function."""
85
86
def __init__(self, func: callable, name: str = None):
87
"""Create function alias.
88
89
Parameters
90
----------
91
func : callable
92
Function to wrap as alias
93
name : str, optional
94
Alias name (defaults to function name)
95
"""
96
97
def __call__(self, args: list[str], stdin=None, **kwargs):
98
"""Execute the alias function.
99
100
Parameters
101
----------
102
args : list[str]
103
Command line arguments
104
stdin : optional
105
Standard input stream
106
**kwargs
107
Additional execution context
108
109
Returns
110
-------
111
object
112
Function return value
113
"""
114
115
# Usage examples
116
def my_command(args, stdin=None):
117
"""Custom command implementation."""
118
print(f"Args: {args}")
119
return 0
120
121
# Create function alias
122
func_alias = FuncAlias(my_command, "mycmd")
123
aliases['mycmd'] = func_alias
124
125
# Direct assignment (automatic FuncAlias creation)
126
def greet(args, stdin=None):
127
name = args[0] if args else "World"
128
print(f"Hello, {name}!")
129
return 0
130
131
aliases['greet'] = greet
132
```
133
134
## Executable Aliases
135
136
### ExecAlias Class
137
138
```python { .api }
139
from xonsh.aliases import ExecAlias
140
141
class ExecAlias:
142
"""Alias that executes a subprocess command."""
143
144
def __init__(self, command: str, name: str = None):
145
"""Create executable alias.
146
147
Parameters
148
----------
149
command : str
150
Shell command to execute
151
name : str, optional
152
Alias name
153
"""
154
155
def __call__(self, args: list[str], stdin=None, **kwargs):
156
"""Execute the command.
157
158
Parameters
159
----------
160
args : list[str]
161
Additional arguments to append
162
stdin : optional
163
Standard input stream
164
**kwargs
165
Execution context
166
167
Returns
168
-------
169
int
170
Command return code
171
"""
172
173
# Usage examples
174
# Simple command alias
175
aliases['ll'] = ExecAlias('ls -la')
176
177
# Command with dynamic arguments
178
aliases['gitlog'] = ExecAlias('git log --oneline')
179
180
# Using the alias
181
"""
182
In xonsh shell:
183
>>> ll # Executes: ls -la
184
>>> ll /tmp # Executes: ls -la /tmp
185
>>> gitlog -10 # Executes: git log --oneline -10
186
"""
187
```
188
189
## String Aliases
190
191
### Simple String Aliases
192
193
```python { .api }
194
# String aliases automatically become ExecAlias instances
195
aliases['la'] = 'ls -la'
196
aliases['grep'] = 'grep --color=auto'
197
aliases['df'] = 'df -h'
198
199
# List-based aliases for complex commands
200
aliases['weather'] = ['curl', 'wttr.in']
201
aliases['myip'] = ['curl', 'ifconfig.me']
202
203
# Aliases with argument placeholders
204
aliases['mkcd'] = 'mkdir -p $arg0 && cd $arg0'
205
```
206
207
## Partial Evaluation Aliases
208
209
### PartialEvalAlias Classes
210
211
```python { .api }
212
from xonsh.aliases import (PartialEvalAlias0, PartialEvalAlias1,
213
PartialEvalAlias2, PartialEvalAlias3)
214
215
# Base class for partial evaluation
216
class PartialEvalAliasBase:
217
"""Base class for partial evaluation aliases."""
218
219
def __init__(self, template: str, name: str = None):
220
"""Create partial evaluation alias.
221
222
Parameters
223
----------
224
template : str
225
Template string with argument placeholders
226
name : str, optional
227
Alias name
228
"""
229
230
# Specific arity aliases
231
class PartialEvalAlias0(PartialEvalAliasBase):
232
"""Partial evaluation alias with 0 arguments."""
233
234
class PartialEvalAlias1(PartialEvalAliasBase):
235
"""Partial evaluation alias with 1 argument."""
236
237
class PartialEvalAlias2(PartialEvalAliasBase):
238
"""Partial evaluation alias with 2 arguments."""
239
240
# Usage examples
241
# Single argument partial evaluation
242
aliases['cdls'] = PartialEvalAlias1('cd $0 && ls')
243
244
# Multiple argument partial evaluation
245
aliases['copyto'] = PartialEvalAlias2('cp $0 $1')
246
247
# Usage in shell:
248
"""
249
>>> cdls /tmp # Executes: cd /tmp && ls
250
>>> copyto a.txt b.txt # Executes: cp a.txt b.txt
251
"""
252
```
253
254
## Advanced Alias Features
255
256
### Contextual Aliases
257
258
```python { .api }
259
from xonsh.built_ins import XSH
260
261
def context_aware_alias(args, stdin=None):
262
"""Alias that behaves differently based on context."""
263
env = XSH.env
264
265
if env.get('DEBUG'):
266
print(f"Debug: executing with args {args}")
267
268
# Different behavior in different directories
269
import os
270
if '/test' in os.getcwd():
271
print("Running in test mode")
272
return 0 # Test version
273
else:
274
print("Running in normal mode")
275
return 0 # Normal version
276
277
aliases['smartcmd'] = context_aware_alias
278
```
279
280
### Conditional Aliases
281
282
```python { .api }
283
def git_smart_status(args, stdin=None):
284
"""Smart git status that adapts to repository state."""
285
import os
286
from xonsh.built_ins import subproc_captured_stdout
287
288
if not os.path.exists('.git'):
289
print("Not a git repository")
290
return 1
291
292
# Check for uncommitted changes
293
status = subproc_captured_stdout(['git', 'status', '--porcelain'])
294
295
if status.strip():
296
# Show detailed status if changes exist
297
return subproc_captured_stdout(['git', 'status', '--short'])
298
else:
299
# Show branch and commit info if clean
300
return subproc_captured_stdout(['git', 'log', '--oneline', '-1'])
301
302
aliases['gs'] = git_smart_status
303
```
304
305
## Alias Management
306
307
### Registration and Discovery
308
309
```python { .api }
310
from xonsh.aliases import Aliases
311
312
# Alias registration patterns
313
def register_development_aliases():
314
"""Register common development aliases."""
315
dev_aliases = {
316
'py': 'python',
317
'py3': 'python3',
318
'ipy': 'ipython',
319
'jn': 'jupyter notebook',
320
'jl': 'jupyter lab',
321
}
322
323
for name, command in dev_aliases.items():
324
aliases[name] = command
325
326
# Conditional alias registration
327
def register_git_aliases():
328
"""Register git aliases if git is available."""
329
from shutil import which
330
331
if which('git'):
332
git_aliases = {
333
'g': 'git',
334
'gs': 'git status',
335
'ga': 'git add',
336
'gc': 'git commit',
337
'gp': 'git push',
338
'gl': 'git log --oneline',
339
}
340
341
for name, command in git_aliases.items():
342
aliases[name] = command
343
```
344
345
### Alias Inspection
346
347
```python { .api }
348
# List all aliases
349
all_aliases = dict(aliases)
350
351
# Check if alias exists
352
if 'myalias' in aliases:
353
print("Alias exists")
354
355
# Get alias type and details
356
alias_obj = aliases.get('ll')
357
if isinstance(alias_obj, ExecAlias):
358
print("Executable alias")
359
elif isinstance(alias_obj, FuncAlias):
360
print("Function alias")
361
362
# Alias information
363
def show_alias_info(name: str):
364
"""Display information about an alias."""
365
if name in aliases:
366
alias = aliases[name]
367
print(f"Alias '{name}': {type(alias).__name__}")
368
if hasattr(alias, '__doc__') and alias.__doc__:
369
print(f"Documentation: {alias.__doc__}")
370
else:
371
print(f"Alias '{name}' not found")
372
```
373
374
## Integration with Xonsh
375
376
### Environment Integration
377
378
```python { .api }
379
from xonsh.built_ins import XSH
380
381
# Access aliases through XSH session
382
session_aliases = XSH.aliases
383
384
# Environment-based alias configuration
385
def setup_conditional_aliases():
386
"""Setup aliases based on environment."""
387
env = XSH.env
388
389
# OS-specific aliases
390
if env.get('XONSH_PLATFORM') == 'win32':
391
aliases['ls'] = 'dir'
392
aliases['cat'] = 'type'
393
394
# Role-specific aliases
395
if env.get('USER_ROLE') == 'developer':
396
register_development_aliases()
397
398
# Project-specific aliases
399
project_root = env.get('PROJECT_ROOT')
400
if project_root:
401
aliases['cdproj'] = f'cd {project_root}'
402
```
403
404
### Startup Configuration
405
406
```python { .api }
407
# In .xonshrc file
408
def load_custom_aliases():
409
"""Load custom aliases at startup."""
410
411
# Personal aliases
412
aliases['ll'] = 'ls -la'
413
aliases['la'] = 'ls -la'
414
aliases['..'] = 'cd ..'
415
aliases['...'] = 'cd ../..'
416
417
# Function aliases
418
def mkcd(args, stdin=None):
419
"""Make directory and change to it."""
420
if not args:
421
print("Usage: mkcd <directory>")
422
return 1
423
424
import os
425
directory = args[0]
426
os.makedirs(directory, exist_ok=True)
427
os.chdir(directory)
428
return 0
429
430
aliases['mkcd'] = mkcd
431
432
# Load project-specific aliases if available
433
try:
434
# Example: load from project configuration file
435
import os
436
if os.path.exists('.xonsh_aliases'):
437
exec(open('.xonsh_aliases').read())
438
except Exception:
439
pass # No project-specific aliases
440
441
# Call at startup
442
load_custom_aliases()
443
```
444
445
The alias system provides powerful command customization capabilities, enabling users to create shortcuts, automate common tasks, and build complex command transformations that integrate seamlessly with xonsh's Python-shell hybrid environment.