-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo
More file actions
executable file
·1580 lines (1297 loc) · 51.7 KB
/
Copy pathdo
File metadata and controls
executable file
·1580 lines (1297 loc) · 51.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Pure Python implementation of the 'just' command runner.
Parses and executes justfiles with support for most just features.
"""
import os
import sys
import re
import subprocess
import shlex
import argparse
import hashlib
import uuid
import platform
import signal
from pathlib import Path
from typing import Dict, List, Optional, Any, Tuple, Set
from dataclasses import dataclass, field
from datetime import datetime
# ============================================================================
# AST Node Definitions
# ============================================================================
@dataclass
class Recipe:
"""Represents a recipe in a justfile."""
name: str
parameters: List['Parameter'] = field(default_factory=list)
dependencies: List[str] = field(default_factory=list)
body: List[str] = field(default_factory=list)
doc_comments: List[str] = field(default_factory=list)
quiet: bool = False
private: bool = False
no_cd: bool = False
no_exit_message: bool = False
shebang: Optional[str] = None
attributes: Dict[str, Any] = field(default_factory=dict)
line_prefixes: List[str] = field(default_factory=list)
group: Optional[str] = None
platform_conditions: List[str] = field(default_factory=list)
@dataclass
class Parameter:
"""Represents a recipe parameter."""
name: str
default: Optional[str] = None
variadic: bool = False
star: bool = False # *
plus: bool = False # +
@dataclass
class Assignment:
"""Represents a variable assignment."""
name: str
value: str
@dataclass
class Alias:
"""Represents a recipe alias."""
name: str
target: str
@dataclass
class Import:
"""Represents an import statement."""
path: str
optional: bool = False
# ============================================================================
# Lexer
# ============================================================================
class Token:
def __init__(self, type_: str, value: str, line: int, column: int):
self.type = type_
self.value = value
self.line = line
self.column = column
def __repr__(self):
return f"Token({self.type}, {self.value!r}, {self.line}, {self.column})"
class Lexer:
"""Tokenizes justfile content."""
def __init__(self, text: str):
self.text = text
self.pos = 0
self.line = 1
self.column = 1
self.tokens: List[Token] = []
def current_char(self) -> Optional[str]:
if self.pos >= len(self.text):
return None
return self.text[self.pos]
def peek_char(self, offset: int = 1) -> Optional[str]:
pos = self.pos + offset
if pos >= len(self.text):
return None
return self.text[pos]
def advance(self):
if self.pos < len(self.text):
if self.text[self.pos] == '\n':
self.line += 1
self.column = 1
else:
self.column += 1
self.pos += 1
def skip_whitespace(self, skip_newline: bool = False):
while self.current_char() in (' ', '\t', '\r'):
self.advance()
if skip_newline:
while self.current_char() in (' ', '\t', '\r', '\n'):
self.advance()
def skip_comment(self):
if self.current_char() == '#':
while self.current_char() and self.current_char() != '\n':
self.advance()
def read_string(self) -> str:
"""Read a quoted string."""
quote = self.current_char()
self.advance() # Skip opening quote
value = []
while self.current_char() and self.current_char() != quote:
if self.current_char() == '\\' and self.peek_char() in (quote, '\\', 'n', 't', 'r', '{'):
self.advance()
escape_char = self.current_char()
if escape_char == 'n':
value.append('\n')
elif escape_char == 't':
value.append('\t')
elif escape_char == 'r':
value.append('\r')
elif escape_char == '{' and self.peek_char() == '{':
value.append('{{')
self.advance()
else:
value.append(escape_char)
self.advance()
else:
value.append(self.current_char())
self.advance()
if self.current_char() == quote:
self.advance() # Skip closing quote
return ''.join(value)
def read_raw_string(self) -> str:
"""Read a raw string (x"..." or x'...')."""
self.advance() # Skip 'x'
quote = self.current_char()
self.advance() # Skip opening quote
value = []
while self.current_char() and self.current_char() != quote:
value.append(self.current_char())
self.advance()
if self.current_char() == quote:
self.advance() # Skip closing quote
return ''.join(value)
def read_identifier(self) -> str:
"""Read an identifier or keyword."""
value = []
while self.current_char() and (self.current_char().isalnum() or self.current_char() in ('_', '-')):
value.append(self.current_char())
self.advance()
return ''.join(value)
def tokenize(self) -> List[Token]:
"""Tokenize the entire justfile."""
while self.pos < len(self.text):
self.skip_whitespace()
if self.current_char() is None:
break
# Skip comments
if self.current_char() == '#':
self.skip_comment()
continue
# Newline
if self.current_char() == '\n':
self.advance()
continue
# String literals
if self.current_char() in ('"', "'"):
start_col = self.column
value = self.read_string()
self.tokens.append(Token('STRING', value, self.line, start_col))
continue
# Raw strings
if self.current_char() == 'x' and self.peek_char() in ('"', "'"):
start_col = self.column
value = self.read_raw_string()
self.tokens.append(Token('STRING', value, self.line, start_col))
continue
# Backtick strings
if self.current_char() == '`':
start_col = self.column
self.advance()
value = []
while self.current_char() and self.current_char() != '`':
value.append(self.current_char())
self.advance()
if self.current_char() == '`':
self.advance()
self.tokens.append(Token('BACKTICK', ''.join(value), self.line, start_col))
continue
# Operators and special characters
if self.current_char() == ':' and self.peek_char() == '=':
start_col = self.column
self.advance()
self.advance()
self.tokens.append(Token('ASSIGN', ':=', self.line, start_col))
continue
if self.current_char() == ':':
start_col = self.column
self.advance()
self.tokens.append(Token('COLON', ':', self.line, start_col))
continue
if self.current_char() == '=':
start_col = self.column
if self.peek_char() == '=':
self.advance()
self.advance()
self.tokens.append(Token('EQ', '==', self.line, start_col))
elif self.peek_char() == '~':
self.advance()
self.advance()
self.tokens.append(Token('REGEX_MATCH', '=~', self.line, start_col))
else:
self.advance()
self.tokens.append(Token('EQUALS', '=', self.line, start_col))
continue
if self.current_char() == '!' and self.peek_char() == '=':
start_col = self.column
self.advance()
self.advance()
self.tokens.append(Token('NE', '!=', self.line, start_col))
continue
if self.current_char() == '|' and self.peek_char() == '|':
start_col = self.column
self.advance()
self.advance()
self.tokens.append(Token('OR', '||', self.line, start_col))
continue
if self.current_char() == '&' and self.peek_char() == '&':
start_col = self.column
self.advance()
self.advance()
self.tokens.append(Token('AND', '&&', self.line, start_col))
continue
# Single character tokens
single_char_tokens = {
'(': 'LPAREN', ')': 'RPAREN',
'[': 'LBRACKET', ']': 'RBRACKET',
'{': 'LBRACE', '}': 'RBRACE',
',': 'COMMA', '@': 'AT',
'+': 'PLUS', '/': 'SLASH',
'*': 'STAR', '!': 'NOT'
}
if self.current_char() in single_char_tokens:
start_col = self.column
char = self.current_char()
self.advance()
self.tokens.append(Token(single_char_tokens[char], char, self.line, start_col))
continue
# Identifiers and keywords
if self.current_char().isalpha() or self.current_char() == '_':
start_col = self.column
value = self.read_identifier()
keywords = {'set', 'alias', 'export', 'import', 'mod', 'if', 'else'}
token_type = 'KEYWORD' if value in keywords else 'IDENT'
self.tokens.append(Token(token_type, value, self.line, start_col))
continue
# Unknown character - skip it
self.advance()
return self.tokens
# ============================================================================
# Parser
# ============================================================================
class Parser:
"""Parses justfile tokens into an AST."""
def __init__(self, text: str, filepath: str = "justfile"):
self.text = text
self.filepath = filepath
self.lines = text.split('\n')
self.recipes: Dict[str, Recipe] = {}
self.assignments: Dict[str, str] = {}
self.aliases: Dict[str, str] = {}
self.imports: List[Import] = []
self.settings: Dict[str, Any] = {}
self.current_line = 0
def parse(self):
"""Parse the justfile."""
self.current_line = 0
while self.current_line < len(self.lines):
line = self.lines[self.current_line].rstrip()
# Skip empty lines and comments
if not line or line.lstrip().startswith('#'):
self.current_line += 1
continue
# Settings
if line.startswith('set '):
self.parse_setting(line)
self.current_line += 1
continue
# Aliases
if line.startswith('alias '):
self.parse_alias(line)
self.current_line += 1
continue
# Exports
if line.startswith('export '):
self.parse_export(line)
self.current_line += 1
continue
# Imports
if line.startswith('import '):
self.parse_import(line)
self.current_line += 1
continue
# Assignments
if ':=' in line and not line.startswith((' ', '\t', '@', '[', '-')):
self.parse_assignment(line)
self.current_line += 1
continue
# Recipes (with attributes or direct)
if line.startswith('[') or (not line.startswith((' ', '\t')) and ':' in line):
self.parse_recipe()
continue
self.current_line += 1
def parse_setting(self, line: str):
"""Parse a setting line."""
match = re.match(r'set\s+([a-z-]+)\s*:=\s*(.+)', line)
if match:
name, value = match.groups()
self.settings[name] = self.evaluate_expression(value.strip())
def parse_alias(self, line: str):
"""Parse an alias."""
match = re.match(r'alias\s+(\S+)\s*:=\s*(\S+)', line)
if match:
alias_name, target = match.groups()
self.aliases[alias_name] = target
def parse_export(self, line: str):
"""Parse an export."""
match = re.match(r'export\s+(\w+)\s*:=\s*(.+)', line)
if match:
name, value = match.groups()
value = self.evaluate_expression(value.strip())
self.assignments[name] = value
os.environ[name] = value
else:
match = re.match(r'export\s+(\w+)', line)
if match:
name = match.group(1)
if name in os.environ:
self.assignments[name] = os.environ[name]
def parse_import(self, line: str):
"""Parse an import."""
match = re.match(r'import\s+(\?)?(.+)', line)
if match:
optional, path = match.groups()
path = path.strip().strip('"\'')
self.imports.append(Import(path, optional is not None))
def parse_assignment(self, line: str):
"""Parse a variable assignment."""
match = re.match(r'(\w+)\s*:=\s*(.+)', line)
if match:
name, value = match.groups()
self.assignments[name] = value.strip()
def parse_recipe(self):
"""Parse a recipe definition."""
# Parse attributes
attributes = {}
platform_conditions = []
while self.current_line < len(self.lines):
line = self.lines[self.current_line].rstrip()
if line.startswith('['):
attrs = self.parse_attributes(line)
attributes.update(attrs)
# Extract platform conditions
for attr in ['linux', 'macos', 'unix', 'windows']:
if attr in attrs:
platform_conditions.append(attr)
self.current_line += 1
else:
break
# Parse recipe header
if self.current_line >= len(self.lines):
return
line = self.lines[self.current_line].rstrip()
# Check for @ prefix (quiet)
quiet = line.startswith('@')
if quiet:
line = line[1:].lstrip()
# Extract recipe name, parameters, and dependencies
if ':' not in line:
self.current_line += 1
return
header_part, _, deps_part = line.partition(':')
header_part = header_part.strip()
deps_part = deps_part.strip()
# Parse recipe name and parameters
parts = header_part.split()
if not parts:
self.current_line += 1
return
recipe_name = parts[0]
parameters = self.parse_parameters(parts[1:])
# Parse dependencies
dependencies = deps_part.split() if deps_part else []
self.current_line += 1
# Parse recipe body
body = []
doc_comments = []
line_prefixes = []
shebang = None
base_indent = None
while self.current_line < len(self.lines):
line = self.lines[self.current_line]
# Check if line is indented
if line and not line[0].isspace():
break
stripped = line.lstrip()
if not stripped:
self.current_line += 1
continue
# Determine base indentation
if base_indent is None and stripped:
base_indent = len(line) - len(stripped)
# Check for doc comments
if stripped.startswith('#') and not stripped.startswith('#!'):
doc_comments.append(stripped[1:].strip())
self.current_line += 1
continue
# Check for shebang
if stripped.startswith('#!'):
shebang = stripped
self.current_line += 1
# Read all following lines for shebang script
while self.current_line < len(self.lines):
line = self.lines[self.current_line]
if line and not line[0].isspace():
break
body.append(line[base_indent:] if base_indent and len(line) > base_indent else line)
self.current_line += 1
break
# Parse line prefix
prefix = ''
if stripped.startswith('@-') or stripped.startswith('-@'):
prefix = stripped[:2]
stripped = stripped[2:].lstrip()
elif stripped.startswith('@'):
prefix = '@'
stripped = stripped[1:].lstrip()
elif stripped.startswith('-'):
prefix = '-'
stripped = stripped[1:].lstrip()
line_prefixes.append(prefix)
body.append(stripped)
self.current_line += 1
# Create recipe
recipe = Recipe(
name=recipe_name,
parameters=parameters,
dependencies=dependencies,
body=body,
doc_comments=doc_comments,
quiet=quiet or attributes.get('private', False),
private=attributes.get('private', False),
no_cd=attributes.get('no-cd', False),
no_exit_message=attributes.get('no-exit-message', False),
shebang=shebang,
attributes=attributes,
line_prefixes=line_prefixes,
group=attributes.get('group'),
platform_conditions=platform_conditions
)
self.recipes[recipe_name] = recipe
def parse_attributes(self, line: str) -> Dict[str, Any]:
"""Parse recipe attributes."""
attrs = {}
match = re.match(r'\[(.*?)\]', line)
if match:
attr_str = match.group(1)
for attr in attr_str.split(','):
attr = attr.strip()
# Handle group attribute
if attr.startswith('group('):
group_match = re.match(r'group\(["\'](.+?)["\']\)', attr)
if group_match:
attrs['group'] = group_match.group(1)
# Handle confirm attribute
elif attr.startswith('confirm'):
confirm_match = re.match(r'confirm(?:\(["\'](.+?)["\']\))?', attr)
if confirm_match:
attrs['confirm'] = confirm_match.group(1) or 'Run this recipe?'
# Simple boolean attributes
else:
attrs[attr] = True
return attrs
def parse_parameters(self, param_parts: List[str]) -> List[Parameter]:
"""Parse recipe parameters."""
parameters = []
for part in param_parts:
# Variadic parameter: *args or *args=default
if part.startswith('*'):
if part == '*':
parameters.append(Parameter('', variadic=True, star=True))
elif part == '+':
parameters.append(Parameter('', variadic=True, plus=True))
else:
rest = part[1:]
if '=' in rest:
name, default = rest.split('=', 1)
parameters.append(Parameter(name, default.strip('"\''), variadic=True))
else:
parameters.append(Parameter(rest, variadic=True))
# Regular parameter with default
elif '=' in part:
name, default = part.split('=', 1)
parameters.append(Parameter(name, default.strip('"\'')))
# Regular parameter
else:
parameters.append(Parameter(part))
return parameters
def evaluate_expression(self, expr: str) -> str:
"""Evaluate a simple expression."""
expr = expr.strip()
# Remove quotes if present
if (expr.startswith('"') and expr.endswith('"')) or \
(expr.startswith("'") and expr.endswith("'")):
return expr[1:-1]
return expr
# ============================================================================
# Expression Evaluator
# ============================================================================
class ExpressionEvaluator:
"""Evaluates expressions in justfiles."""
def __init__(self, context: Dict[str, str], justfile_path: str):
self.context = context
self.justfile_path = Path(justfile_path).resolve()
self.justfile_dir = self.justfile_path.parent
def evaluate(self, expr: str) -> str:
"""Evaluate an expression."""
expr = expr.strip()
# Handle string literals
if (expr.startswith('"') and expr.endswith('"')) or \
(expr.startswith("'") and expr.endswith("'")):
return self.process_string(expr[1:-1])
# Handle backticks
if expr.startswith('`') and expr.endswith('`'):
return self.execute_backtick(expr[1:-1])
# Handle function calls
if '(' in expr and expr.endswith(')'):
return self.evaluate_function(expr)
# Handle conditional expressions
if ' if ' in expr:
return self.evaluate_conditional(expr)
# Handle binary operations
if '==' in expr or '!=' in expr or '=~' in expr:
return self.evaluate_comparison(expr)
if '||' in expr or '&&' in expr:
return self.evaluate_logical(expr)
if '+' in expr or '/' in expr:
return self.evaluate_arithmetic(expr)
# Variable reference
if expr in self.context:
return self.context[expr]
# Environment variable
if expr in os.environ:
return os.environ[expr]
return expr
def process_string(self, s: str) -> str:
"""Process string interpolations."""
result = []
i = 0
while i < len(s):
if i < len(s) - 1 and s[i:i+2] == '{{':
# Find closing }}
j = s.find('}}', i + 2)
if j != -1:
expr = s[i+2:j]
result.append(self.evaluate(expr))
i = j + 2
else:
result.append(s[i])
i += 1
else:
result.append(s[i])
i += 1
return ''.join(result)
def execute_backtick(self, cmd: str) -> str:
"""Execute a backtick command."""
try:
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
cwd=self.justfile_dir
)
return result.stdout.strip()
except Exception:
return ''
def evaluate_function(self, expr: str) -> str:
"""Evaluate a function call."""
match = re.match(r'(\w+)\((.*)\)', expr)
if not match:
return expr
func_name, args_str = match.groups()
args = self.parse_arguments(args_str)
# Evaluate arguments
evaluated_args = [self.evaluate(arg) for arg in args]
return self.call_function(func_name, evaluated_args)
def parse_arguments(self, args_str: str) -> List[str]:
"""Parse function arguments."""
if not args_str.strip():
return []
args = []
current_arg = []
depth = 0
in_string = False
string_char = None
for char in args_str:
if char in ('"', "'") and not in_string:
in_string = True
string_char = char
current_arg.append(char)
elif char == string_char and in_string:
in_string = False
string_char = None
current_arg.append(char)
elif char == '(' and not in_string:
depth += 1
current_arg.append(char)
elif char == ')' and not in_string:
depth -= 1
current_arg.append(char)
elif char == ',' and depth == 0 and not in_string:
args.append(''.join(current_arg).strip())
current_arg = []
else:
current_arg.append(char)
if current_arg:
args.append(''.join(current_arg).strip())
return args
def call_function(self, func_name: str, args: List[str]) -> str:
"""Call a built-in function."""
functions = {
'env_var': self.func_env_var,
'env_var_or_default': self.func_env_var_or_default,
'env': self.func_env,
'justfile': self.func_justfile,
'justfile_directory': self.func_justfile_directory,
'source_directory': self.func_source_directory,
'source_file': self.func_source_file,
'invocation_directory': self.func_invocation_directory,
'invocation_directory_native': self.func_invocation_directory_native,
'home_directory': self.func_home_directory,
'absolute_path': self.func_absolute_path,
'canonicalize': self.func_canonicalize,
'file_name': self.func_file_name,
'file_stem': self.func_file_stem,
'parent_directory': self.func_parent_directory,
'extension': self.func_extension,
'without_extension': self.func_without_extension,
'path_exists': self.func_path_exists,
'join': self.func_join,
'replace': self.func_replace,
'replace_regex': self.func_replace_regex,
'trim': self.func_trim,
'trim_start': self.func_trim_start,
'trim_end': self.func_trim_end,
'trim_start_match': self.func_trim_start_match,
'trim_end_match': self.func_trim_end_match,
'trim_start_matches': self.func_trim_start_matches,
'trim_end_matches': self.func_trim_end_matches,
'uppercase': self.func_uppercase,
'lowercase': self.func_lowercase,
'capitalize': self.func_capitalize,
'titlecase': self.func_titlecase,
'kebabcase': self.func_kebabcase,
'snakecase': self.func_snakecase,
'shoutcase': self.func_shoutcase,
'lowercamelcase': self.func_lowercamelcase,
'uppercamelcase': self.func_uppercamelcase,
'quote': self.func_quote,
'shell': self.func_shell,
'sha256': self.func_sha256,
'sha256_file': self.func_sha256_file,
'blake3': self.func_blake3,
'blake3_file': self.func_blake3_file,
'uuid': self.func_uuid,
'datetime': self.func_datetime,
'datetime_utc': self.func_datetime_utc,
'os': self.func_os,
'os_family': self.func_os_family,
'arch': self.func_arch,
'num_cpus': self.func_num_cpus,
'just_executable': self.func_just_executable,
'just_pid': self.func_just_pid,
'append': self.func_append,
'prepend': self.func_prepend,
'clean': self.func_clean,
'error': self.func_error,
}
if func_name in functions:
return functions[func_name](args)
return f"{func_name}({', '.join(args)})"
# Function implementations
def func_env_var(self, args: List[str]) -> str:
if args and args[0] in os.environ:
return os.environ[args[0]]
raise ValueError(f"Environment variable {args[0]} not set")
def func_env_var_or_default(self, args: List[str]) -> str:
if len(args) >= 2:
return os.environ.get(args[0], args[1])
return os.environ.get(args[0], '') if args else ''
def func_env(self, args: List[str]) -> str:
if len(args) >= 2:
return os.environ.get(args[0], args[1])
return os.environ.get(args[0], '') if args else ''
def func_justfile(self, args: List[str]) -> str:
return str(self.justfile_path)
def func_justfile_directory(self, args: List[str]) -> str:
return str(self.justfile_dir)
def func_source_directory(self, args: List[str]) -> str:
return str(self.justfile_dir)
def func_source_file(self, args: List[str]) -> str:
return str(self.justfile_path)
def func_invocation_directory(self, args: List[str]) -> str:
return os.getcwd()
def func_invocation_directory_native(self, args: List[str]) -> str:
return os.getcwd()
def func_home_directory(self, args: List[str]) -> str:
return str(Path.home())
def func_absolute_path(self, args: List[str]) -> str:
if args:
return str(Path(args[0]).resolve())
return ''
def func_canonicalize(self, args: List[str]) -> str:
if args:
return str(Path(args[0]).resolve())
return ''
def func_file_name(self, args: List[str]) -> str:
if args:
return Path(args[0]).name
return ''
def func_file_stem(self, args: List[str]) -> str:
if args:
return Path(args[0]).stem
return ''
def func_parent_directory(self, args: List[str]) -> str:
if args:
return str(Path(args[0]).parent)
return ''
def func_extension(self, args: List[str]) -> str:
if args:
ext = Path(args[0]).suffix
return ext[1:] if ext else ''
return ''
def func_without_extension(self, args: List[str]) -> str:
if args:
p = Path(args[0])
return str(p.parent / p.stem)
return ''
def func_path_exists(self, args: List[str]) -> str:
if args:
return 'true' if Path(args[0]).exists() else 'false'
return 'false'
def func_join(self, args: List[str]) -> str:
if len(args) >= 2:
return args[1].join(args[0].split())
return args[0] if args else ''
def func_replace(self, args: List[str]) -> str:
if len(args) >= 3:
return args[0].replace(args[1], args[2])
return args[0] if args else ''
def func_replace_regex(self, args: List[str]) -> str:
if len(args) >= 3:
return re.sub(args[1], args[2], args[0])
return args[0] if args else ''
def func_trim(self, args: List[str]) -> str:
return args[0].strip() if args else ''
def func_trim_start(self, args: List[str]) -> str:
return args[0].lstrip() if args else ''
def func_trim_end(self, args: List[str]) -> str:
return args[0].rstrip() if args else ''
def func_trim_start_match(self, args: List[str]) -> str:
if len(args) >= 2 and args[0].startswith(args[1]):
return args[0][len(args[1]):]
return args[0] if args else ''
def func_trim_end_match(self, args: List[str]) -> str:
if len(args) >= 2 and args[0].endswith(args[1]):
return args[0][:-len(args[1])]
return args[0] if args else ''
def func_trim_start_matches(self, args: List[str]) -> str:
if len(args) >= 2:
s = args[0]
while s.startswith(args[1]):
s = s[len(args[1]):]
return s
return args[0] if args else ''
def func_trim_end_matches(self, args: List[str]) -> str:
if len(args) >= 2:
s = args[0]
while s.endswith(args[1]):
s = s[:-len(args[1])]
return s
return args[0] if args else ''
def func_uppercase(self, args: List[str]) -> str:
return args[0].upper() if args else ''
def func_lowercase(self, args: List[str]) -> str:
return args[0].lower() if args else ''
def func_capitalize(self, args: List[str]) -> str:
return args[0].capitalize() if args else ''
def func_titlecase(self, args: List[str]) -> str:
return args[0].title() if args else ''
def func_kebabcase(self, args: List[str]) -> str:
if args:
s = re.sub(r'([a-z0-9])([A-Z])', r'\1-\2', args[0])
s = re.sub(r'[\s_]+', '-', s)
return s.lower()
return ''
def func_snakecase(self, args: List[str]) -> str:
if args:
s = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', args[0])
s = re.sub(r'[\s-]+', '_', s)
return s.lower()
return ''
def func_shoutcase(self, args: List[str]) -> str:
return self.func_snakecase(args).upper()
def func_lowercamelcase(self, args: List[str]) -> str:
if args:
words = re.split(r'[\s_-]+', args[0])
if words:
return words[0].lower() + ''.join(w.capitalize() for w in words[1:])
return ''
def func_uppercamelcase(self, args: List[str]) -> str:
if args:
words = re.split(r'[\s_-]+', args[0])
return ''.join(w.capitalize() for w in words)