From f12251e199eba20698ffe683664957d5712428bb Mon Sep 17 00:00:00 2001 From: Luca Colagrande Date: Mon, 1 Sep 2025 16:05:36 +0200 Subject: [PATCH] Add list-dependent-make-targets script and create Python package --- .github/workflows/ci.yml | 11 + .github/workflows/publish-pypi.yaml | 32 +++ .gitignore | 3 + LICENSE | 201 ++++++++++++++++++ README.md | 7 +- action.yml | 8 +- list-make-prerequisites.py | 169 --------------- pyproject.toml | 29 +++ src/pymakeutils/__init__.py | 1 + src/pymakeutils/common.py | 161 ++++++++++++++ .../list_dependent_make_targets.py | 45 ++++ src/pymakeutils/list_make_prerequisites.py | 48 +++++ 12 files changed, 540 insertions(+), 175 deletions(-) create mode 100644 .github/workflows/publish-pypi.yaml create mode 100644 .gitignore create mode 100644 LICENSE delete mode 100755 list-make-prerequisites.py create mode 100644 pyproject.toml create mode 100644 src/pymakeutils/__init__.py create mode 100644 src/pymakeutils/common.py create mode 100755 src/pymakeutils/list_dependent_make_targets.py create mode 100755 src/pymakeutils/list_make_prerequisites.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6825b8c..532ca4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,3 +44,14 @@ jobs: run: | test "${{ steps.hash-dir-prerequisite.outputs.prerequisites }}" = "dirprereq" test "${{ steps.hash-dir-prerequisite.outputs.hash }}" = "c64a77871513eadd52ec0e278bfbac1db866b77f66ebe91725b378b8bf43e29c" + - name: Install package + run: | + python -m pip install . + - name: List dependent targets non-recursively + working-directory: test + run: | + test $(list-dependent-make-targets preprereq1) = prereq + - name: List dependent targets recursively + working-directory: test + run: | + test "$(list-dependent-make-targets preprereq1 -r | xargs)" = ".DEFAULT_GOAL prereq test1" \ No newline at end of file diff --git a/.github/workflows/publish-pypi.yaml b/.github/workflows/publish-pypi.yaml new file mode 100644 index 0000000..8f3de01 --- /dev/null +++ b/.github/workflows/publish-pypi.yaml @@ -0,0 +1,32 @@ +name: Build and publish Python package to PyPI + +on: + push: + tags: + - "v*" # e.g. v0.1.0 + +jobs: + build-and-publish: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 # IMPORTANT: setuptools-scm needs tags + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Upgrade build tools + run: python -m pip install --upgrade pip build + + - name: Build sdist and wheel + run: python -m build + + - name: Publish to PyPI (Trusted Publishing) + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8d19a12 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__ +build +*.egg-info \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 42c7d6c..4de168d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ -# list-make-prerequisites -A Python script to list all prerequisites of a Make target. +# pymakeutils + +A collection of CLI utilities and actions to extract information from Makefiles: +- list-make-prerequisites: List all prerequisites of a target (optionally recursively) +- list-dependent-make-targets: List all targets that depend on a certain prerequisite (optionally recursively) diff --git a/action.yml b/action.yml index 0680124..0bcbe37 100644 --- a/action.yml +++ b/action.yml @@ -26,15 +26,15 @@ outputs: runs: using: "composite" steps: - - name: Install Dependencies + - name: Install Package shell: bash - run: python -m pip install -r ${GITHUB_ACTION_PATH}/requirements.txt + run: python -m pip install . - name: List Make Prerequisites id: list-make-prerequisites shell: bash working-directory: ${{ inputs.working-directory }} run: | - hash=$(${GITHUB_ACTION_PATH}/list-make-prerequisites.py ${{ inputs.target }} ${{ inputs.flags }} --hash) - prerequisites=$(${GITHUB_ACTION_PATH}/list-make-prerequisites.py ${{ inputs.target }} ${{ inputs.flags }} | xargs) + hash=$(list-make-prerequisites ${{ inputs.target }} ${{ inputs.flags }} --hash) + prerequisites=$(list-make-prerequisites ${{ inputs.target }} ${{ inputs.flags }} | xargs) echo "hash=$hash" >> $GITHUB_OUTPUT echo "prerequisites=$prerequisites" >> $GITHUB_OUTPUT diff --git a/list-make-prerequisites.py b/list-make-prerequisites.py deleted file mode 100755 index a6ecabd..0000000 --- a/list-make-prerequisites.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/usr/bin/env python3 -# -# Author: Luca Colagrande - -from anytree import Node, RenderTree -import argparse -import hashlib -from pathlib import Path -import re -import subprocess -import sys - - -# Parse arguments from the command line -def parse_args(): - parser = argparse.ArgumentParser( - description="List prerequisites for a specified Makefile target.") - parser.add_argument( - 'target', - help="The make target whose prerequisites you want to list") - parser.add_argument( - '-r', - '--recursive', - action='store_true', - help="Recursively list all prerequisites") - parser.add_argument( - '--hash', - action='store_true', - help="Generate a hash from the contents of all prerequisites") - parser.add_argument( - '-d', - '--debug', - action='store_true', - help="Enable debug output to show intermediate steps") - - return parser.parse_args() - - -# Function to parse all rules from 'make -pq' output -def _parse_makefile(): - # Run 'make -pq' and capture its output - result = subprocess.run( - ['make', '-pq'], - capture_output=True, - text=True) - - # Initialize an empty dictionary to store the targets and their prerequisites - targets = {} - - # Split the output by lines - make_output = result.stdout.splitlines() - - # Regex to capture target and its prerequisites - target_pattern = re.compile(r'^([^\s]+)\s*:\s*([^\|]*)') - - # Parse the make output - for line in make_output: - match = target_pattern.match(line) - if match: - target = match.group(1) - prerequisites = match.group(2).split() - targets[target] = prerequisites - - return targets - - -# Internal function used for recursion. Takes additional arguments to keep track of state. -def _get_prerequisites_recursive(target, targets, recursive=False): - - # Get the prerequisites for the target - prerequisites = targets.get(target.name, []) - - # In non-recursive mode, attach prerequisites to root and that's it - if not recursive: - [Node(prereq, parent=target) for prereq in prerequisites] - - # In recursive mode, if we are at a leaf node, we return the leaf node - # otherwise we attach the current prerequisite node to the parent - else: - - if prerequisites: - for prereq in prerequisites: - - # If recursive, get prerequisites for each prerequisite - if recursive: - _get_prerequisites_recursive( - Node(prereq, parent=target), - targets, - recursive=True) - else: - return target - - -# Function to list prerequisites, optionally recursively -def list_prerequisites(target, recursive=False, debug=False): - - # Parse the makefile - targets = _parse_makefile() - - # Get the prerequisites for the user-provided target, if it exists - if target in targets: - - # Call the function with the user-provided target and recursive/debug flags - root = Node(target) - _get_prerequisites_recursive( - root, - targets, - recursive=recursive) - - # Print tree structure for debugging - if debug: - for pre, fill, node in RenderTree(root): - print(f"{pre}{node.name}") - - # Print a newline to separate debugging output from regular output - print("") - - # Find all leaf prerequisites - leaf_prerequisites = [node.name for node in root.descendants if node.is_leaf] - - # Remove repetitions and sort for consistency - leaf_prerequisites = sorted(list(set(leaf_prerequisites))) - - # Return prerequisites - return leaf_prerequisites - - else: - raise Exception(f"Target '{args.target}' not found in the Makefile.") - - -def hash_files(file_list): - # Create a new SHA-256 hash object - hasher = hashlib.sha256() - - # If any prerequisite is a directory, replace it with its (recursive) contents - expanded_file_list = [] - for file_name in file_list: - file = Path(file_name) - if file.is_dir(): - expanded_file_list.extend([str(f) for f in file.rglob('*') if f.is_file()]) - else: - expanded_file_list.append(file_name) - - # Hash file contents - for file_name in expanded_file_list: - try: - with open(file_name, 'rb') as f: - # Read the file content in chunks to avoid memory issues with large files - while chunk := f.read(8192): # 8192 bytes per chunk - hasher.update(chunk) # Update the hash with each chunk - except FileNotFoundError: - print(f"File '{file_name}' not found.", file=sys.stderr) - - # Return the final hexadecimal hash value - return hasher.hexdigest() - - -if __name__ == "__main__": - args = parse_args() - - prerequisites = list_prerequisites(args.target, recursive=args.recursive, debug=args.debug) - - if args.hash: - # Print a hash of the prerequisites' contents - hash_value = hash_files(prerequisites) - print(hash_value) - else: - # Print the list of prerequisites - print('\n'.join(prerequisites)) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b5655ac --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,29 @@ +[build-system] +requires = ["setuptools>=69", "setuptools-scm>=8", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "pymakeutils" +description = "CLI utilities to extract information from 'make -pq' output" +readme = "README.md" +requires-python = ">=3.8" +license = { file = "LICENSE" } +authors = [{ name = "Luca Colagrande", email = "colluca@iis.ee.ethz.ch" }] +# Version comes from git tags via setuptools-scm +dynamic = ["version", "dependencies"] + +[tool.setuptools_scm] + +[tool.setuptools] +package-dir = {"" = "src"} + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.dynamic] +dependencies = { file = ["requirements.txt"] } + +# Expose your scripts as console commands +[project.scripts] +list-make-prerequisites = "pymakeutils.list_make_prerequisites:main" +list-dependent-make-targets = "pymakeutils.list_dependent_make_targets:main" \ No newline at end of file diff --git a/src/pymakeutils/__init__.py b/src/pymakeutils/__init__.py new file mode 100644 index 0000000..37aa01b --- /dev/null +++ b/src/pymakeutils/__init__.py @@ -0,0 +1 @@ +__all__ = ["common"] diff --git a/src/pymakeutils/common.py b/src/pymakeutils/common.py new file mode 100644 index 0000000..b7d488f --- /dev/null +++ b/src/pymakeutils/common.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# +# Author: Luca Colagrande + +from anytree import Node, RenderTree +from pathlib import Path +import hashlib +import re +import subprocess +import sys + + +# Function to parse all rules from 'make -pq' output +def _parse_makefile(): + # Run 'make -pq' and capture its output + result = subprocess.run( + ['make', '-pq'], + capture_output=True, + text=True) + + # Initialize an empty dictionary to store the targets and their prerequisites + targets = {} + + # Split the output by lines + make_output = result.stdout.splitlines() + + # Regex to capture target and its prerequisites + target_pattern = re.compile(r'^([^\s]+)\s*:\s*([^\|]*)') + + # Parse the make output + for line in make_output: + match = target_pattern.match(line) + if match: + target = match.group(1) + prerequisites = match.group(2).split() + targets[target] = prerequisites + + return targets + + +# Internal function used for building a dependency tree with recursion. +def _get_prerequisites_recursive(target, targets, recursive=False): + + # Get the prerequisites for the target and attach them to the tree + prerequisites = targets.get(target.name, []) + nodes = [Node(prereq, parent=target) for prereq in prerequisites] + + # Recursively travel through prerequisites, to attach their prerequisites to the tree. + if recursive and nodes: + for node in nodes: + _get_prerequisites_recursive(node, targets, recursive=True) + + +# Function to list prerequisites, optionally recursively +def list_prerequisites(target, recursive=False, debug=False): + + # Parse the makefile + targets = _parse_makefile() + + # Handle non-existing target + if target not in targets: + raise Exception(f"Target '{target}' not found in the Makefile.") + + # Build the dependency tree for the specified target + root = Node(target) + _get_prerequisites_recursive(root, targets, recursive=recursive) + + # Print tree structure for debugging + if debug: + for pre, _, node in RenderTree(root): + print(f"{pre}{node.name}") + + # Print a newline to separate debugging output from regular output + print("") + + # Find all leaf prerequisites, uniquify and sort + leaf_prereqs = [n.name for n in root.descendants if n.is_leaf] + return sorted(set(leaf_prereqs)) + + +# Takes in a structure like that returned by _parse_makefile, +# i.e. {target: [prereq1, prereq2, ...], ...}, and reverses it to a structure like +# i.e. {prereq: [target1, target2, ...], ...} listing targets directly depending +# on each prerequisite. +def _build_reverse_dict(targets): + reverse_dict = {} + for target, prerequisites in targets.items(): + for prerequisite in prerequisites: + reverse_dict.setdefault(prerequisite, set()).add(target) + return reverse_dict + + +# Internal function used for building a dependency tree with recursion. +def _get_dependents_recursive(prerequisite, prerequisites, recursive=False): + + # Get the targets directly depending on the prerequisite and attach them to the tree + targets = prerequisites.get(prerequisite.name, []) + nodes = [Node(target, parent=prerequisite) for target in targets] + + # Recursively travel through the direct targets, to attach the targets which in turn directly + # depend on them to tree. + if recursive and nodes: + for node in nodes: + _get_dependents_recursive(node, prerequisites, recursive=True) + + +# Return a sorted list of targets that depend on `prerequisite`. +# If `recursive` is False, only direct dependents are returned. +def list_dependents(prerequisite, recursive=False, debug=False): + + # Parse the makefile + targets = _parse_makefile() + prerequisites = _build_reverse_dict(targets) + + # Handle non-existing prerequisite + if prerequisite not in prerequisites: + raise Exception(f"Prerequisite '{prerequisite}' not found in the Makefile.") + + # Build the dependency tree from the specified prerequisite + root = Node(prerequisite) + _get_dependents_recursive(root, prerequisites, recursive=recursive) + + # Print tree structure for debugging + if debug: + for pre, _, node in RenderTree(root): + print(f"{pre}{node.name}") + + # Print a newline to separate debugging output from regular output + print("") + + # Find all targets, uniquify and sort + dependents = [n.name for n in root.descendants] + return sorted(set(dependents)) + + +# Calculate a SHA-256 hash from the contents of a list of files, expanding directories recursively +def hash_files(file_list): + # Create a new SHA-256 hash object + hasher = hashlib.sha256() + + # If any prerequisite is a directory, replace it with its (recursive) contents + expanded_file_list = [] + for file_name in file_list: + file = Path(file_name) + if file.is_dir(): + expanded_file_list.extend([str(f) for f in file.rglob('*') if f.is_file()]) + else: + expanded_file_list.append(file_name) + + # Hash file contents + for file_name in expanded_file_list: + try: + with open(file_name, 'rb') as f: + # Read the file content in chunks to avoid memory issues with large files + while chunk := f.read(8192): # 8192 bytes per chunk + hasher.update(chunk) # Update the hash with each chunk + except FileNotFoundError: + print(f"File '{file_name}' not found.", file=sys.stderr) + + # Return the final hexadecimal hash value + return hasher.hexdigest() diff --git a/src/pymakeutils/list_dependent_make_targets.py b/src/pymakeutils/list_dependent_make_targets.py new file mode 100755 index 0000000..517e9f9 --- /dev/null +++ b/src/pymakeutils/list_dependent_make_targets.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# +# Author: Luca Colagrande + +import argparse +from pymakeutils.common import list_dependents + + +def parse_args(): + parser = argparse.ArgumentParser( + description="List all targets that depend on one or more prerequisites.") + parser.add_argument( + 'prerequisites', + nargs='+', + help="One or more files/targets whose dependents you want to list") + parser.add_argument( + '-r', + '--recursive', + action='store_true', + help="Recursively include transitive dependents") + parser.add_argument( + '-d', + '--debug', + action='store_true', + help="Enable debug output to show intermediate steps") + return parser.parse_args() + + +def main(): + args = parse_args() + + # Take the union of all dependent targets for the given prerequisites + all_deps = set() + for p in args.prerequisites: + all_deps.update( + list_dependents(p, recursive=args.recursive, debug=args.debug) + ) + dependents = sorted(all_deps) + + # Print the list of dependent targets + print('\n'.join(dependents)) + + +if __name__ == "__main__": + main() diff --git a/src/pymakeutils/list_make_prerequisites.py b/src/pymakeutils/list_make_prerequisites.py new file mode 100755 index 0000000..1571e0b --- /dev/null +++ b/src/pymakeutils/list_make_prerequisites.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +# +# Author: Luca Colagrande + +import argparse +from pymakeutils.common import list_prerequisites, hash_files + + +def parse_args(): + parser = argparse.ArgumentParser( + description="List prerequisites for a specified Makefile target.") + parser.add_argument( + 'target', + help="The make target whose prerequisites you want to list") + parser.add_argument( + '-r', + '--recursive', + action='store_true', + help="Recursively list all prerequisites") + parser.add_argument( + '--hash', + action='store_true', + help="Generate a hash from the contents of all prerequisites") + parser.add_argument( + '-d', + '--debug', + action='store_true', + help="Enable debug output to show intermediate steps") + + return parser.parse_args() + + +def main(): + args = parse_args() + + prerequisites = list_prerequisites(args.target, recursive=args.recursive, debug=args.debug) + + if args.hash: + # Print a hash of the prerequisites' contents + hash_value = hash_files(prerequisites) + print(hash_value) + else: + # Print the list of prerequisites + print('\n'.join(prerequisites)) + + +if __name__ == "__main__": + main()