1+ import operator
12from pathlib import Path
2- from typing import Callable , cast
3+ from typing import Callable
34
45from tqdm import tqdm
56
67from .. import core
78
89PREFIXES : dict [str , Callable [[int , int ], int ]] = {
9- "+" : lambda old_size , size_num : old_size + size_num ,
10- "-" : lambda old_size , size_num : old_size - size_num ,
11- "<" : lambda old_size , size_num : min ( old_size , size_num ) ,
12- ">" : lambda old_size , size_num : max ( old_size , size_num ) ,
10+ "+" : operator . add ,
11+ "-" : operator . sub ,
12+ "<" : min ,
13+ ">" : max ,
1314 "/" : lambda old_size , size_num : size_num * (old_size // size_num ),
1415 "%" : lambda old_size , size_num : size_num * - (old_size // - size_num ),
1516}
4849parser .add_option ("-r" , "--reference" , metavar = "RFILE" , help = "base size on RFILE" )
4950
5051
52+ def parse_size_spec (spec : str ) -> tuple [str | None , int ]:
53+ prefix = spec [0 ] if spec [0 ] in frozenset ("+-<>/%" ) else None
54+ return prefix , int (spec [1 :] if prefix else spec )
55+
56+
57+ def get_size_changer (prefix : str | None , num : int | None ) -> Callable [[int ], int ]:
58+ if prefix :
59+ assert num is not None
60+ return lambda old_size : PREFIXES [prefix ](old_size , num )
61+
62+ return (lambda _ : num ) if num is not None else (lambda old_size : old_size )
63+
64+
5165@core .command (parser )
5266def python_userland_truncate (opts , args : list [str ]):
5367 if opts .reference :
@@ -57,11 +71,8 @@ def python_userland_truncate(opts, args: list[str]):
5771 size_num : int | None = None
5872
5973 if opts .size :
60- if opts .size [0 ] in frozenset ("+-<>/%" ):
61- size_prefix = cast (str , opts .size [0 ])
62-
6374 try :
64- size_num = int ( opts . size [ 1 :] if size_prefix else opts .size )
75+ size_prefix , size_num = parse_size_spec ( opts .size )
6576 except ValueError :
6677 parser .error (f"invalid number: '{ opts .size } '" )
6778
@@ -73,17 +84,7 @@ def python_userland_truncate(opts, args: list[str]):
7384 if not args :
7485 parser .error ("missing file operand" )
7586
76- get_new_size : Callable [[int ], int ]
77-
78- if size_prefix :
79- assert size_num is not None
80- get_new_size = lambda old_size : PREFIXES [size_prefix ](old_size , size_num )
81- else :
82- get_new_size = (
83- (lambda _ : size_num )
84- if size_num is not None
85- else (lambda old_size : old_size )
86- )
87+ get_new_size = get_size_changer (size_prefix , size_num )
8788
8889 size_attr = "st_blocks" if opts .io_blocks else "st_size"
8990
0 commit comments