Skip to content

Commit 251bbb2

Browse files
committed
file based filter: Handle header lib
1 parent 0f25090 commit 251bbb2

File tree

1 file changed

+95
-73
lines changed

1 file changed

+95
-73
lines changed

refresh.template.py

+95-73
Original file line numberDiff line numberDiff line change
@@ -825,7 +825,71 @@ def _convert_compile_commands(aquery_output):
825825

826826

827827
def _get_commands(target: str, flags: str):
828-
"""Yields compile_commands.json entries for a given target and flags, gracefully tolerating errors."""
828+
"""Return compile_commands.json entries for a given target and flags, gracefully tolerating errors."""
829+
def _get_commands(target_statment):
830+
aquery_args = [
831+
'bazel',
832+
'aquery',
833+
# Aquery docs if you need em: https://docs.bazel.build/versions/master/aquery.html
834+
# Aquery output proto reference: https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/analysis_v2.proto
835+
# One bummer, not described in the docs, is that aquery filters over *all* actions for a given target, rather than just those that would be run by a build to produce a given output. This mostly isn't a problem, but can sometimes surface extra, unnecessary, misconfigured actions. Chris has emailed the authors to discuss and filed an issue so anyone reading this could track it: https://github.com/bazelbuild/bazel/issues/14156.
836+
f"mnemonic('(Objc|Cpp)Compile', {target_statment})",
837+
# We switched to jsonproto instead of proto because of https://github.com/bazelbuild/bazel/issues/13404. We could change back when fixed--reverting most of the commit that added this line and tweaking the build file to depend on the target in that issue. That said, it's kinda nice to be free of the dependency, unless (OPTIMNOTE) jsonproto becomes a performance bottleneck compated to binary protos.
838+
'--output=jsonproto',
839+
# We'll disable artifact output for efficiency, since it's large and we don't use them. Small win timewise, but dramatically less json output from aquery.
840+
'--include_artifacts=false',
841+
# Shush logging. Just for readability.
842+
'--ui_event_filters=-info',
843+
'--noshow_progress',
844+
# Disable param files, which would obscure compile actions
845+
# Mostly, people enable param files on Windows to avoid the relatively short command length limit.
846+
# For more, see compiler_param_file in https://bazel.build/docs/windows
847+
# They are, however, technically supported on other platforms/compilers.
848+
# That's all well and good, but param files would prevent us from seeing compile actions before the param files had been generated by compilation.
849+
# Since clangd has no such length limit, we'll disable param files for our aquery run.
850+
'--features=-compiler_param_file',
851+
# Disable layering_check during, because it causes large-scale dependence on generated module map files that prevent header extraction before their generation
852+
# For more context, see https://github.com/hedronvision/bazel-compile-commands-extractor/issues/83
853+
# If https://github.com/clangd/clangd/issues/123 is resolved and we're not doing header extraction, we could try removing this, checking that there aren't erroneous red squigglies squigglies before the module maps are generated.
854+
# If Bazel starts supporting modules (https://github.com/bazelbuild/bazel/issues/4005), we'll probably need to make changes that subsume this.
855+
'--features=-layering_check',
856+
] + additional_flags
857+
858+
aquery_process = subprocess.run(
859+
aquery_args,
860+
capture_output=True,
861+
encoding=locale.getpreferredencoding(),
862+
check=False, # We explicitly ignore errors from `bazel aquery` and carry on.
863+
)
864+
865+
866+
# Filter aquery error messages to just those the user should care about.
867+
missing_targets_warning: typing.Pattern[str] = re.compile(r'(\(\d+:\d+:\d+\) )?(\033\[[\d;]+m)?WARNING: (\033\[[\d;]+m)?Targets were missing from graph:') # Regex handles --show_timestamps and --color=yes. Could use "in" if we ever need more flexibility.
868+
for line in aquery_process.stderr.splitlines():
869+
# Shush known warnings about missing graph targets.
870+
# The missing graph targets are not things we want to introspect anyway.
871+
# Tracking issue https://github.com/bazelbuild/bazel/issues/13007.
872+
if missing_targets_warning.match(line):
873+
continue
874+
875+
print(line, file=sys.stderr)
876+
877+
878+
# Parse proto output from aquery
879+
try:
880+
# object_hook -> SimpleNamespace allows object.member syntax, like a proto, while avoiding the protobuf dependency
881+
parsed_aquery_output = json.loads(aquery_process.stdout, object_hook=lambda d: types.SimpleNamespace(**d))
882+
except json.JSONDecodeError:
883+
print("Bazel aquery failed. Command:", aquery_args, file=sys.stderr)
884+
log_warning(f">>> Failed extracting commands for {target}\n Continuing gracefully...")
885+
return []
886+
887+
if not getattr(parsed_aquery_output, 'actions', None): # Unifies cases: No actions (or actions list is empty)
888+
return []
889+
890+
return _convert_compile_commands(parsed_aquery_output)
891+
892+
829893
# Log clear completion messages
830894
log_info(f">>> Analyzing commands used in {target}")
831895

@@ -855,88 +919,46 @@ def _get_commands(target: str, flags: str):
855919
Try adding them as flags in your refresh_compile_commands rather than targets.
856920
In a moment, Bazel will likely fail to parse.""")
857921

922+
compile_commands = []
858923
# First, query Bazel's C-family compile actions for that configured target
859924
target_statment = f'deps({target})'
860-
if {exclude_external_sources}:
861-
# For efficiency, have bazel filter out external targets (and therefore actions) before they even get turned into actions or serialized and sent to us. Note: this is a different mechanism than is used for excluding just external headers.
862-
target_statment = f"filter('^(//|@//)',{target_statment})"
925+
863926
if file_flags:
864927
file_path = file_flags[0]
865-
if file_path.endswith(_get_files.source_extensions):
866-
target_statment = f"inputs('{re.escape(file_path)}', {target_statment})"
928+
found = False
929+
target_statment_canidates = []
930+
if file_flags[0].endswith(_get_files.source_extensions):
931+
target_statment_canidates.append(f"inputs('{re.escape(file_path)}', {target_statment})")
867932
else:
868-
# For header files we try to find from hdrs and srcs to get the targets
869-
# Since attr function can't query with full path, get the file name to query
870933
fname = os.path.basename(file_path)
871-
target_statment = f"let v = {target_statment} in attr(hdrs, '{fname}', $v) + attr(srcs, '{fname}', $v)"
872-
aquery_args = [
873-
'bazel',
874-
'aquery',
875-
# Aquery docs if you need em: https://docs.bazel.build/versions/master/aquery.html
876-
# Aquery output proto reference: https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/analysis_v2.proto
877-
# One bummer, not described in the docs, is that aquery filters over *all* actions for a given target, rather than just those that would be run by a build to produce a given output. This mostly isn't a problem, but can sometimes surface extra, unnecessary, misconfigured actions. Chris has emailed the authors to discuss and filed an issue so anyone reading this could track it: https://github.com/bazelbuild/bazel/issues/14156.
878-
f"mnemonic('(Objc|Cpp)Compile', {target_statment})",
879-
# We switched to jsonproto instead of proto because of https://github.com/bazelbuild/bazel/issues/13404. We could change back when fixed--reverting most of the commit that added this line and tweaking the build file to depend on the target in that issue. That said, it's kinda nice to be free of the dependency, unless (OPTIMNOTE) jsonproto becomes a performance bottleneck compated to binary protos.
880-
'--output=jsonproto',
881-
# We'll disable artifact output for efficiency, since it's large and we don't use them. Small win timewise, but dramatically less json output from aquery.
882-
'--include_artifacts=false',
883-
# Shush logging. Just for readability.
884-
'--ui_event_filters=-info',
885-
'--noshow_progress',
886-
# Disable param files, which would obscure compile actions
887-
# Mostly, people enable param files on Windows to avoid the relatively short command length limit.
888-
# For more, see compiler_param_file in https://bazel.build/docs/windows
889-
# They are, however, technically supported on other platforms/compilers.
890-
# That's all well and good, but param files would prevent us from seeing compile actions before the param files had been generated by compilation.
891-
# Since clangd has no such length limit, we'll disable param files for our aquery run.
892-
'--features=-compiler_param_file',
893-
# Disable layering_check during, because it causes large-scale dependence on generated module map files that prevent header extraction before their generation
894-
# For more context, see https://github.com/hedronvision/bazel-compile-commands-extractor/issues/83
895-
# If https://github.com/clangd/clangd/issues/123 is resolved and we're not doing header extraction, we could try removing this, checking that there aren't erroneous red squigglies squigglies before the module maps are generated.
896-
# If Bazel starts supporting modules (https://github.com/bazelbuild/bazel/issues/4005), we'll probably need to make changes that subsume this.
897-
'--features=-layering_check',
898-
] + additional_flags
899-
900-
aquery_process = subprocess.run(
901-
aquery_args,
902-
capture_output=True,
903-
encoding=locale.getpreferredencoding(),
904-
check=False, # We explicitly ignore errors from `bazel aquery` and carry on.
905-
)
906-
907-
908-
# Filter aquery error messages to just those the user should care about.
909-
missing_targets_warning: typing.Pattern[str] = re.compile(r'(\(\d+:\d+:\d+\) )?(\033\[[\d;]+m)?WARNING: (\033\[[\d;]+m)?Targets were missing from graph:') # Regex handles --show_timestamps and --color=yes. Could use "in" if we ever need more flexibility.
910-
for line in aquery_process.stderr.splitlines():
911-
# Shush known warnings about missing graph targets.
912-
# The missing graph targets are not things we want to introspect anyway.
913-
# Tracking issue https://github.com/bazelbuild/bazel/issues/13007.
914-
if missing_targets_warning.match(line):
915-
continue
916-
917-
print(line, file=sys.stderr)
918-
919-
920-
# Parse proto output from aquery
921-
try:
922-
# object_hook -> SimpleNamespace allows object.member syntax, like a proto, while avoiding the protobuf dependency
923-
parsed_aquery_output = json.loads(aquery_process.stdout, object_hook=lambda d: types.SimpleNamespace(**d))
924-
except json.JSONDecodeError:
925-
print("Bazel aquery failed. Command:", aquery_args, file=sys.stderr)
926-
log_warning(f">>> Failed extracting commands for {target}\n Continuing gracefully...")
927-
return
928-
929-
if not getattr(parsed_aquery_output, 'actions', None): # Unifies cases: No actions (or actions list is empty)
930-
log_warning(f""">>> Bazel lists no applicable compile commands for {target}
931-
If this is a header-only library, please instead specify a test or binary target that compiles it (search "header-only" in README.md).
932-
Continuing gracefully...""")
933-
return
934-
935-
yield from _convert_compile_commands(parsed_aquery_output)
934+
target_statment_canidates.extend([
935+
f"let v = {target_statment} in attr(hdrs, '{fname}', $v) + attr(srcs, '{fname}', $v)",
936+
f"inputs('{re.escape(file_path)}', {target_statment})",
937+
f'deps({target})',
938+
])
939+
940+
for target_statment in target_statment_canidates:
941+
compile_commands.extend( _get_commands(target_statment))
942+
if any(command['file'].endswith(file_path) for command in reversed(compile_commands)):
943+
found = True
944+
break
945+
if not found:
946+
log_warning(f""">>> Bazel lists no applicable compile commands for {file_path} in {target}.
947+
Continuing gracefully...""")
936948

949+
else:
950+
if {exclude_external_sources}:
951+
# For efficiency, have bazel filter out external targets (and therefore actions) before they even get turned into actions or serialized and sent to us. Note: this is a different mechanism than is used for excluding just external headers.
952+
target_statment = f"filter('^(//|@//)',{target_statment})"
953+
compile_commands.extend(_get_commands(target_statment))
954+
if len(compile_commands) == 0:
955+
log_warning(f""">>> Bazel lists no applicable compile commands for {target}
956+
If this is a header-only library, please instead specify a test or binary target that compiles it (search "header-only" in README.md).
957+
Continuing gracefully...""")
937958

938959
# Log clear completion messages
939960
log_success(f">>> Finished extracting commands for {target}")
961+
return compile_commands
940962

941963

942964
def _ensure_external_workspaces_link_exists():

0 commit comments

Comments
 (0)