1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00

Add exclude option to filetree module (#10966)

* Added excludes option to filetree module

* Renamed option 'excludes' to 'exclude'

* Corrected issue and PR links

Co-authored-by: Felix Fontein <felix@fontein.de>

* Added version for documentation

Co-authored-by: Felix Fontein <felix@fontein.de>

* Fixed example of using exclude option

Co-authored-by: Felix Fontein <felix@fontein.de>

* Fixed regular expression in example

Co-authored-by: Felix Fontein <felix@fontein.de>

---------

Co-authored-by: Felix Fontein <felix@fontein.de>
This commit is contained in:
Alexey Langer 2025-10-29 23:46:26 +07:00 committed by GitHub
parent e84f59a62d
commit 831787619a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 23 additions and 0 deletions

View file

@ -20,6 +20,11 @@ options:
required: true
type: list
elements: string
exclude:
description:
- A regular expression string to exclude files. Applies to the base name of the file or directory.
type: str
version_added: 12.0.0
"""
EXAMPLES = r"""
@ -55,6 +60,11 @@ EXAMPLES = r"""
- name: list all files under web/
ansible.builtin.debug:
msg: "{{ lookup('community.general.filetree', 'web/') }}"
- name: list all files under web/; exclude .git and .node_modules
ansible.builtin.debug:
msg: >-
{{ lookup('community.general.filetree', 'web/', exclude='^(\.git|\.node_modules)$') }}
"""
RETURN = r"""
@ -118,6 +128,7 @@ import os
import pwd
import grp
import stat
import re
HAVE_SELINUX = False
try:
@ -206,6 +217,10 @@ class LookupModule(LookupBase):
basedir = self.get_basedir(variables)
# Regular expression for exclude
exclude = self.get_option('exclude')
exclude_pattern = re.compile(exclude) if exclude else None
ret = []
for term in terms:
term_file = os.path.basename(term)
@ -213,6 +228,12 @@ class LookupModule(LookupBase):
path = os.path.join(dwimmed_path, term_file)
display.debug(f"Walking '{path}'")
for root, dirs, files in os.walk(path, topdown=True):
# Filter files and directories using a regular expression
if exclude_pattern is not None:
dirs[:] = [d for d in dirs if not exclude_pattern.match(d)]
files[:] = [f for f in files if not exclude_pattern.match(f)]
for entry in dirs + files:
relpath = os.path.relpath(os.path.join(root, entry), path)