Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
pre-commit/pre_commit/xargs.py at main · discord/pre-commit · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
discord
/
pre-commit
Public
forked from
pre-commit/pre-commit
Notifications
You must be signed in to change notification settings
Fork
4
Star
4
Code
Pull requests
1
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Security and quality
Insights
Files
Expand file tree
main
Breadcrumbs
pre-commit
/
pre_commit
/
xargs.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
267 lines (222 loc) · 8.25 KB
main
Breadcrumbs
pre-commit
/
pre_commit
/
xargs.py
Copy path
Top
File metadata and controls
Code
Blame
267 lines (222 loc) · 8.25 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
from
__future__
import
annotations
import
concurrent
.
futures
import
contextlib
import
math
import
multiprocessing
import
os
import
re
import
select
import
shutil
import
subprocess
import
sys
from
collections
.
abc
import
Generator
from
collections
.
abc
import
Iterable
from
collections
.
abc
import
MutableMapping
from
collections
.
abc
import
Sequence
from
typing
import
Any
from
typing
import
Callable
from
typing
import
TypeVar
from
typing
import
Optional
from
pre_commit
import
parse_shebang
from
pre_commit
.
util
import
cmd_output_b
from
pre_commit
.
util
import
cmd_output_p
from
pre_commit
.
output
import
write
from
pre_commit
.
output
import
write_b
TArg
=
TypeVar
(
'TArg'
)
TRet
=
TypeVar
(
'TRet'
)
def
cpu_count
()
->
int
:
try
:
# On systems that support it, this will return a more accurate count of
# usable CPUs for the current process, which will take into account
# cgroup limits
return
len
(
os
.
sched_getaffinity
(
0
))
except
AttributeError
:
pass
try
:
return
multiprocessing
.
cpu_count
()
except
NotImplementedError
:
return
1
def
_environ_size
(
_env
:
MutableMapping
[
str
,
str
]
|
None
=
None
)
->
int
:
environ
=
_env
if
_env
is
not
None
else
getattr
(
os
,
'environb'
,
os
.
environ
)
size
=
8
*
len
(
environ
)
# number of pointers in `envp`
for
k
,
v
in
environ
.
items
():
size
+=
len
(
k
)
+
len
(
v
)
+
2
# c strings in `envp`
return
size
def
_get_platform_max_length
()
->
int
:
# pragma: no cover (platform specific)
if
os
.
name
==
'posix'
:
maximum
=
os
.
sysconf
(
'SC_ARG_MAX'
)
-
2048
-
_environ_size
()
maximum
=
max
(
min
(
maximum
,
2
**
17
),
2
**
12
)
return
maximum
elif
os
.
name
==
'nt'
:
return
2
**
15
-
2048
# UNICODE_STRING max - headroom
else
:
# posix minimum
return
2
**
12
def
_command_length
(
*
cmd
:
str
)
->
int
:
full_cmd
=
' '
.
join
(
cmd
)
# win32 uses the amount of characters, more details at:
# https://github.com/pre-commit/pre-commit/pull/839
if
sys
.
platform
==
'win32'
:
return
len
(
full_cmd
.
encode
(
'utf-16le'
))
//
2
else
:
return
len
(
full_cmd
.
encode
(
sys
.
getfilesystemencoding
()))
class
ArgumentTooLongError
(
RuntimeError
):
pass
def
partition
(
cmd
:
Sequence
[
str
],
varargs
:
Sequence
[
str
],
target_concurrency
:
int
,
_max_length
:
int
|
None
=
None
,
)
->
tuple
[
tuple
[
str
, ...], ...]:
_max_length
=
_max_length
or
_get_platform_max_length
()
# Generally, we try to partition evenly into at least `target_concurrency`
# partitions, but we don't want a bunch of tiny partitions.
max_args
=
max
(
4
,
math
.
ceil
(
len
(
varargs
)
/
target_concurrency
))
cmd
=
tuple
(
cmd
)
ret
=
[]
ret_cmd
:
list
[
str
]
=
[]
# Reversed so arguments are in order
varargs
=
list
(
reversed
(
varargs
))
total_length
=
_command_length
(
*
cmd
)
+
1
while
varargs
:
arg
=
varargs
.
pop
()
arg_length
=
_command_length
(
arg
)
+
1
if
(
total_length
+
arg_length
<=
_max_length
and
len
(
ret_cmd
)
<
max_args
):
ret_cmd
.
append
(
arg
)
total_length
+=
arg_length
elif
not
ret_cmd
:
raise
ArgumentTooLongError
(
arg
)
else
:
# We've exceeded the length, yield a command
ret
.
append
(
cmd
+
tuple
(
ret_cmd
))
ret_cmd
=
[]
total_length
=
_command_length
(
*
cmd
)
+
1
varargs
.
append
(
arg
)
ret
.
append
(
cmd
+
tuple
(
ret_cmd
))
return
tuple
(
ret
)
@
contextlib
.
contextmanager
def
_thread_mapper
(
maxsize
:
int
)
->
Generator
[
Callable
[[
Callable
[[
TArg
],
TRet
],
Iterable
[
TArg
]],
Iterable
[
TRet
]],
]:
if
maxsize
==
1
:
yield
map
else
:
with
concurrent
.
futures
.
ThreadPoolExecutor
(
maxsize
)
as
ex
:
yield
ex
.
map
def
stream_subprocess_output
(
cmd
:
Sequence
[
str
],
**
kwargs
:
Any
)
->
Generator
[
tuple
[
bytes
,
int
|
None
],
None
,
None
]:
"""
Run `cmd` as a subprocess and yield (chunk, returncode) tuples as output becomes available.
Merged stdout + stderr (because of stderr=STDOUT).
returncode is None until the process completes.
"""
proc
=
subprocess
.
Popen
(
cmd
,
stdout
=
subprocess
.
PIPE
,
stderr
=
subprocess
.
STDOUT
,
**
kwargs
,
)
try
:
if
sys
.
platform
==
'win32'
:
# On Windows, select.select() doesn't work with pipes,
# so we use blocking reads.
if
proc
.
stdout
is
None
:
raise
RuntimeError
(
"proc.stdout is None"
)
while
True
:
chunk
=
proc
.
stdout
.
read
(
1024
)
if
chunk
:
yield
chunk
,
None
else
:
break
else
:
while
True
:
process_done
=
(
proc
.
poll
()
is
not
None
)
if
not
process_done
:
ready
,
_
,
_
=
select
.
select
([
proc
.
stdout
], [], [],
0.1
)
if
not
ready
:
continue
chunk
=
proc
.
stdout
.
read1
(
1024
)
if
chunk
:
yield
chunk
,
None
else
:
if
process_done
:
break
finally
:
if
proc
.
stdout
is
not
None
:
proc
.
stdout
.
close
()
proc
.
wait
()
# Yield one final time with the returncode
yield
b''
,
proc
.
returncode
def
xargs
(
cmd
:
tuple
[
str
, ...],
varargs
:
Sequence
[
str
],
*
,
color
:
bool
=
False
,
target_concurrency
:
int
=
1
,
_max_length
:
int
=
_get_platform_max_length
(),
stream_output
:
Optional
[
bool
]
=
None
,
start_msg
:
Optional
[
str
]
=
None
,
**
kwargs
:
Any
,
)
->
tuple
[
int
,
bytes
]:
"""A simplified implementation of xargs.
color: Make a pty if on a platform that supports it
target_concurrency: Target number of partitions to run concurrently
"""
cmd_fn
=
cmd_output_p
if
color
else
cmd_output_b
retcode
=
0
stdout
=
b''
try
:
cmd
=
parse_shebang
.
normalize_cmd
(
cmd
)
except
parse_shebang
.
ExecutableNotFoundError
as
e
:
return
e
.
to_output
()[:
2
]
# on windows, batch files have a separate length limit than windows itself
if
(
sys
.
platform
==
'win32'
and
cmd
[
0
].
lower
().
endswith
((
'.bat'
,
'.cmd'
))
):
# pragma: win32 cover
# this is implementation details but the command gets translated into
# full/path/to/cmd.exe /c *cmd
cmd_exe
=
parse_shebang
.
find_executable
(
'cmd.exe'
)
# 1024 is additionally subtracted to give headroom for further
# expansion inside the batch file
_max_length
=
8192
-
len
(
cmd_exe
)
-
len
(
' /c '
)
-
1024
partitions
=
partition
(
cmd
,
varargs
,
target_concurrency
,
_max_length
)
def
run_cmd_partition
(
run_cmd
:
tuple
[
str
, ...],
)
->
tuple
[
int
,
bytes
,
bytes
|
None
]:
if
not
stream_output
:
return
cmd_fn
(
*
run_cmd
,
check
=
False
,
stderr
=
subprocess
.
STDOUT
,
**
kwargs
,
)
output
=
b''
returncode
=
0
write
(
'
\n
'
)
for
chunk
,
maybe_returncode
in
stream_subprocess_output
(
cmd
):
output
+=
chunk
write_b
(
chunk
)
if
maybe_returncode
is
not
None
:
returncode
=
maybe_returncode
terminal_size
=
shutil
.
get_terminal_size
((
80
,
20
))
strip_ansi
=
re
.
compile
(
rb'\x1B\[[0-?]*[ -/]*[@-~]'
)
plain_output
=
strip_ansi
.
sub
(
b''
,
output
)
standard_lines
=
plain_output
.
split
(
b'
\n
'
)
line_count
=
0
for
line
in
standard_lines
:
displayed_width
=
max
(
1
,
len
(
line
))
line_count
+=
math
.
ceil
(
displayed_width
/
terminal_size
.
columns
)
if
line_count
>=
terminal_size
.
lines
:
# The original hook start message has scrolled out of view
write
(
start_msg
+
'
\n
'
)
# Reprint the status message
line_count
=
1
write
(
'
\033
7'
)
# Save cursor position
write
(
f'
\033
[
{
line_count
}
A
\033
[73C'
)
# Move cursor back to end of the start message
return
returncode
,
output
,
None
threads
=
min
(
len
(
partitions
),
target_concurrency
)
with
_thread_mapper
(
threads
)
as
thread_map
:
results
=
thread_map
(
run_cmd_partition
,
partitions
)
for
proc_retcode
,
proc_out
,
_
in
results
:
if
abs
(
proc_retcode
)
>
abs
(
retcode
):
retcode
=
proc_retcode
stdout
+=
proc_out
return
retcode
,
stdout
You can’t perform that action at this time.