
    Vh\                        d dl mZ dZdZdZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlmZmZ d dlmZ d dlmZ  G d	 d
      ZddZd Zd ZddZd Zd Zd Zedk(  r e        yy)    )annotationsaC  
---
module: find
author: Brian Coca (@bcoca)
version_added: "2.0"
short_description: Return a list of files based on specific criteria
description:
    - Return a list of files based on specific criteria. Multiple criteria are AND'd together.
    - For Windows targets, use the M(ansible.windows.win_find) module instead.
    - This module does not use the C(find) command, it is a much simpler and slower Python implementation.
      It is intended for small and simple uses. Those that need the extra power or speed and have expertise
      with the UNIX command, should use it directly.
options:
    age:
        description:
            - Select files whose age is equal to or greater than the specified time.
            - Use a negative age to find files equal to or less than the specified time.
            - You can choose seconds, minutes, hours, days, or weeks by specifying the
              first letter of any of those words (e.g., "1w").
        type: str
    patterns:
        default: []
        description:
            - One or more (shell or regex) patterns, which type is controlled by O(use_regex) option.
            - The patterns restrict the list of files to be returned to those whose basenames match at
              least one of the patterns specified. Multiple patterns can be specified using a list.
            - The pattern is matched against the file base name, excluding the directory.
            - When using regexen, the pattern MUST match the ENTIRE file name, not just parts of it. So
              if you are looking to match all files ending in .default, you'd need to use C(.*\.default)
              as a regexp and not just C(\.default).
            - This parameter expects a list, which can be either comma separated or YAML. If any of the
              patterns contain a comma, make sure to put them in a list to avoid splitting the patterns
              in undesirable ways.
            - Defaults to V(*) when O(use_regex=False), or V(.*) when O(use_regex=True).
        type: list
        aliases: [ pattern ]
        elements: str
    excludes:
        description:
            - One or more (shell or regex) patterns, which type is controlled by O(use_regex) option.
            - Items whose basenames match an O(excludes) pattern are culled from O(patterns) matches.
              Multiple patterns can be specified using a list.
        type: list
        aliases: [ exclude ]
        version_added: "2.5"
        elements: str
    contains:
        description:
            - A regular expression or pattern which should be matched against the file content.
            - If O(read_whole_file=false) it matches against the beginning of the line (uses
              V(re.match(\))). If O(read_whole_file=true), it searches anywhere for that pattern
              (uses V(re.search(\))).
            - Works only when O(file_type) is V(file).
        type: str
    read_whole_file:
        description:
            - When doing a C(contains) search, determines whether the whole file should be read into
              memory or if the regex should be applied to the file line-by-line.
            - Setting this to C(true) can have performance and memory implications for large files.
            - This uses V(re.search(\)) instead of V(re.match(\)).
        type: bool
        default: false
        version_added: "2.11"
    paths:
        description:
            - List of paths of directories to search. All paths must be fully qualified.
            - From ansible-core 2.18 and onwards, the data type has changed from C(str) to C(path).
        type: list
        required: true
        aliases: [ name, path ]
        elements: path
    file_type:
        description:
            - Type of file to select.
            - The V(link) and V(any) choices were added in Ansible 2.3.
        type: str
        choices: [ any, directory, file, link ]
        default: file
    recurse:
        description:
            - If target is a directory, recursively descend into the directory looking for files.
        type: bool
        default: no
    size:
        description:
            - Select files whose size is equal to or greater than the specified size.
            - Use a negative size to find files equal to or less than the specified size.
            - Unqualified values are in bytes but b, k, m, g, and t can be appended to specify
              bytes, kilobytes, megabytes, gigabytes, and terabytes, respectively.
            - Size is not evaluated for directories.
        type: str
    age_stamp:
        description:
            - Choose the file property against which we compare age.
        type: str
        choices: [ atime, ctime, mtime ]
        default: mtime
    hidden:
        description:
            - Set this to V(true) to include hidden files, otherwise they will be ignored.
        type: bool
        default: no
    mode:
        description:
            - Choose objects matching a specified permission. This value is
              restricted to modes that can be applied using the python
              C(os.chmod) function.
            - The mode can be provided as an octal such as V("0644") or
              as symbolic such as V(u=rw,g=r,o=r).
        type: raw
        version_added: '2.16'
    exact_mode:
        description:
            - Restrict mode matching to exact matches only, and not as a
              minimum set of permissions to match.
        type: bool
        default: true
        version_added: '2.16'
    follow:
        description:
            - Set this to V(true) to follow symlinks in path for systems with python 2.6+.
        type: bool
        default: no
    get_checksum:
        description:
            - Set this to V(true) to retrieve a file's SHA1 checksum.
        type: bool
        default: no
    use_regex:
        description:
            - If V(false), the patterns are file globs (shell).
            - If V(true), they are python regexes.
        type: bool
        default: no
    depth:
        description:
            - Set the maximum number of levels to descend into.
            - Setting O(recurse=false) will override this value, which is effectively depth 1.
            - Default is unlimited depth.
        type: int
        version_added: "2.6"
    encoding:
        description:
            - When doing a O(contains) search, determine the encoding of the files to be searched.
        type: str
        version_added: "2.17"
    limit:
        description:
            - Limit the maximum number of matching paths returned. After finding this many, the find action will stop looking.
            - Matches are made from the top, down (i.e. shallowest directory first).
            - If not set, or set to v(null), it will do unlimited matches.
            - Default is unlimited matches.
        type: int
        version_added: "2.18"
extends_documentation_fragment: action_common_attributes
attributes:
    check_mode:
        details: since this action does not modify the target it just executes normally during check mode
        support: full
    diff_mode:
        support: none
    platform:
        platforms: posix
seealso:
- module: ansible.windows.win_find
a  
- name: Recursively find /tmp files older than 2 days
  ansible.builtin.find:
    paths: /tmp
    age: 2d
    recurse: yes

- name: Recursively find /tmp files older than 4 weeks and equal or greater than 1 megabyte
  ansible.builtin.find:
    paths: /tmp
    age: 4w
    size: 1m
    recurse: yes

- name: Recursively find /var/tmp files with last access time greater than 3600 seconds
  ansible.builtin.find:
    paths: /var/tmp
    age: 3600
    age_stamp: atime
    recurse: yes

- name: Find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz
  ansible.builtin.find:
    paths: /var/log
    patterns: '*.old,*.log.gz'
    size: 10m

# Note that YAML double quotes require escaping backslashes but yaml single quotes do not.
- name: Find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz via regex
  ansible.builtin.find:
    paths: /var/log
    patterns: "^.*?\\.(?:old|log\\.gz)$"
    size: 10m
    use_regex: yes

- name: Find /var/log all directories, exclude nginx and mysql
  ansible.builtin.find:
    paths: /var/log
    recurse: no
    file_type: directory
    excludes: 'nginx,mysql'

# When using patterns that contain a comma, make sure they are formatted as lists to avoid splitting the pattern
- name: Use a single pattern that contains a comma formatted as a list
  ansible.builtin.find:
    paths: /var/log
    file_type: file
    use_regex: yes
    patterns: ['^_[0-9]{2,4}_.*.log$']

- name: Use multiple patterns that contain a comma formatted as a YAML list
  ansible.builtin.find:
    paths: /var/log
    file_type: file
    use_regex: yes
    patterns:
      - '^_[0-9]{2,4}_.*.log$'
      - '^[a-z]{1,5}_.*log$'

- name: Find file containing "wally" without necessarily reading all files
  ansible.builtin.find:
    paths: /var/log
    file_type: file
    contains: wally
    read_whole_file: true
    patterns: "^.*\\.log$"
    use_regex: true
    recurse: true
    limit: 1
a0  
files:
    description: All matches found with the specified criteria (see stat module for full output of each dictionary)
    returned: success
    type: list
    sample: [
        { path: "/var/tmp/test1",
          mode: "0644",
          "...": "...",
          checksum: 16fac7be61a6e4591a33ef4b729c5c3302307523
        },
        { path: "/var/tmp/test2",
          "...": "..."
        },
        ]
matched:
    description: Number of matches
    returned: success
    type: int
    sample: 14
examined:
    description: Number of filesystem objects looked at
    returned: success
    type: int
    sample: 34
skipped_paths:
    description: skipped paths and reasons they were skipped
    returned: success
    type: dict
    sample: {"/laskdfj": "'/laskdfj' is not a directory"}
    version_added: '2.12'
N)to_text	to_native)AnsibleModule)string_typesc                      e Zd Zd Zy)_Objectc                N    |j                         D ]  \  }}t        | ||        y N)itemssetattr)selfkwargskvs       D/home/dcms/DCMS/lib/python3.12/site-packages/ansible/modules/find.py__init__z_Object.__init__+  s'    LLN 	 DAqD!Q	     N)__name__
__module____qualname__r    r   r   r	   r	   *  s     r   r	   c                   |s|sy|r|r2|s0|D ]*  }t        j                  |      }|j                  |       s* y y|ra|r_|D ]Z  }t        j                  |      }|j                  |       s*|D ]+  }t        j                  |      }|j                  |       s*  y  y y|r"|s |D ]  }t        j                  | |      s y y|rA|r?|D ]:  }t        j                  | |      s|D ]  }t        j                  | |      s  y  y y)zfilter using glob patternsTF)recompilematchfnmatch)fpatternsexcludes	use_regexpres          r   pfilterr%   0  s   HH  JJqM771: : 1 (  JJqM771:% )JJqM771:#()   .  H  ??1a(   (  ??1a(% )"??1a0#()    r   c                    |y|dk\  r|t        | d|z        z
  t        |      k\  ry|dk  r|t        | d|z        z
  t        |      k  ryy)zfilter files older than ageTr   zst_%sF)getattrabs)stnowage	timestamps       r   	agefilterr-   W  sY    
{	cGB)(;<<CH	qS72w':;;s3xGr   c                    |y|dk\  r| j                   t        |      k\  ry|dk  r| j                   t        |      k  ryy)zfilter files greater than sizeTr   F)st_sizer(   )r)   sizes     r   
sizefilterr1   b  s?    |	rzzSY.	bjjCI-r   c                   |yt        j                  |      }	 t        | |      5 }|r1t        |j	                  |j                                     cddd       S |D ]  }|j                  |      s ddd       y 	 ddd       y# 1 sw Y   yxY w# t        $ r}|d}~wt        $ r}|d}d|  d| }t        |      |d}~wt        $ r Y yw xY w)a  
    Filter files which contain the given expression
    :arg fsname: Filename to scan for lines matching a pattern
    :arg pattern: Pattern to look for inside of line
    :arg encoding: Encoding of the file to be scanned
    :arg read_whole_file: If true, the whole file is read into memory before the regex is applied against it. Otherwise, the regex is applied line-by-line.
    :rtype: bool
    :returns: True if one of the lines in fsname matches the pattern. Otherwise False
    NT)encodingz@None (default determined by the Python built-in function "open")zFailed to read the file z- due to an encoding error. current encoding: F)
r   r   openboolsearchreadr   LookupErrorUnicodeDecodeError	Exception)	fsnamepatternr3   read_whole_fileprogr   liner$   msgs	            r   contentfilterrA   m  s     ::gD&8, 	 DKK12	  	    ::d#	  	  		 $ %	 $    $YH(0]^f]ghn!# sd   B *B	B B2B3B <B>B BB B 	CBC*CCCc                
   |syt        j                  | j                        }	 t        |d      }t        j                  |      }|r||k(  S t        ||z        S # t        $ r |j                  t        d      |      }Y Qw xY w)NT   r   )st_mode)statS_IMODErD   int
ValueError_symbolic_mode_to_octalr	   r5   )r)   modeexactmodulerD   s        r   mode_filterrM     s    ll2::&GH4| <<D$$  H--ga.@$GHs   A %BBc                   d}d}	 t        j                  | j                        j                  }	 t        j                  | j                        j                  }i ddt        j                  | j                        z  dt        j                  | j                        dt        j                  | j                        dt        j                  | j                        dt        j                  | j                        dt        j                   | j                        d	t        j"                  | j                        d
t        j$                  | j                        d| j                  d| j                  d| j&                  d| j(                  d| j*                  d| j,                  d| j.                  d| j0                  d| j2                  ||t5        | j                  t        j6                  z        t5        | j                  t        j8                  z        t5        | j                  t        j:                  z        t5        | j                  t        j<                  z        t5        | j                  t        j>                  z        t5        | j                  t        j@                  z        t5        | j                  t        jB                  z        t5        | j                  t        jD                  z        t5        | j                  t        jF                  z        t5        | j                  t        jH                  z        t5        | j                  t        jJ                  z        dS # t        $ r Y Lw xY w# t        $ r Y 2w xY w)N rJ   z%04oisdirischrisblkisregisfifoislnkissockuidgidr0   inodedevnlinkatimemtimectime)gr_namepw_namewusrrusrxusrwgrprgrpxgrpwothrothxothisuidisgid)&pwdgetpwuidst_uidr`   r:   grpgetgrgidst_gidr_   rE   rF   rD   S_ISDIRS_ISCHRS_ISBLKS_ISREGS_ISFIFOS_ISLNKS_ISSOCKr/   st_inost_devst_nlinkst_atimest_mtimest_ctimer5   S_IWUSRS_IRUSRS_IXUSRS_IWGRPS_IRGRPS_IXGRPS_IWOTHS_IROTHS_IXOTHS_ISUIDS_ISGID)r)   r`   r_   s      r   statinfor     s   GG,,ryy)11,,ryy)11bjj11bjj) 	bjj) 	bjj)	
 	bjj) 	$--

+ 	bjj) 	$--

+ 	ryy 	ryy 	

 	 	ryy 	 	  	!" 	#$ RZZ$,,./RZZ$,,./RZZ$,,./RZZ$,,./RZZ$,,./RZZ$,,./RZZ$,,./RZZ$,,./RZZ$,,./bjj4<</0bjj4<</0=   
  s"   )M/ )M? /	M<;M<?	NNc                 "   t        t        dSi dt        ddddgd      dt        dg dgd	
      dt        ddgd	      dt        d	      dt        dd      dt        d	dg d      dt        d	      dt        d	dg d      dt        d	      dt        dd      dt        dd      dt        dd      d t        dd      d!t        dd      d"t        d#      d$t        d%      d&t        dd      d't        d	      d(t        d#      d)      } | j                  }|d$   r?t        |d$   t              s,| j                  d*|d$   j                  j                  z  +       |d   s|d!   rd,g|d<   nd-g|d<   g }i fd.}|d   d }nt        j                  d/|d   j                               }d0d1d2d3d4d5}|r=t        |j                  d0            |j                  |j                  d6      d0      z  }n| j                  |d   d78       |d   d }nt        j                  d9|d   j                               }d0d:d;d<d=d>}|r=t        |j                  d0            |j                  |j                  d6      d0      z  }n| j                  |d   d?@       |d(    |d(   dAk  r| j                  dB|d(   z  +       t        j                         }	dC}
dA}d}|d   D ]  }	 t        j                   j#                  |      st%        dDt'        |      z        t        j(                  |||d   dE      D ]  \  }}}|t+        |      z   t+        |      z   }||z   D ]=  }t        j                   j-                  t        j                   j/                  ||            }|d"   r|j1                  t        j                   j2                        t        j                   j2                  z   }t        |j5                  t        j                   j2                              t        |j5                  t        j                   j2                              z
  d0z   }||d"   kD  r|d d = t        j                   j7                  |      j9                  dF      r|d   s6	 t        j:                  |      }d|i}|d   dJk(  rtE        ||d   |d   |d!         rtG        ||	|d         rtI        ||d$   |d&   |       r|jK                  tM        |             tO        jP                  |jR                        r|d    r| jU                  |      |dK<   tO        jP                  |jR                        r tW        |      r|jY                  |       n|jY                  |       ntO        jZ                  |jR                        rt|d   dLk(  rltE        ||d   |d   |d!         rtG        ||	|d         rtI        ||d$   |d&   |       r|jK                  tM        |             |jY                  |       n[tO        jP                  |jR                        r|d   dk(  rtE        ||d   |d   |d!         rtG        ||	|d         r
tW        |      rt]        ||d   |d'   |d         rtI        ||d$   |d&   |       r|jK                  tM        |             |d    r| jU                  |      |dK<   |jY                  |       ntO        j^                  |jR                        ro|d   dMk(  rgtE        ||d   |d   |d!         rPtG        ||	|d         r?tI        ||d$   |d&   |       r+|jK                  tM        |             |jY                  |       t+        |      |d(   k(  s<dN}
 n |d   rt+        |      |d(   k(  s n  |rdQ}
t+        |      }| ja                  |d|
||R       y # t<        t>        f$ r<}| jA                  dG|dHtC        |      dI       tC        |      |<   d}Y d }~d }~ww xY w# t$        $ r?}tC        |      |<   | jA                  dOtC        |      dP|   dI       d}Y d }~d }~ww xY w)TNpathslistTnamepath)typerequiredaliaseselementsr   r<   str)r   defaultr   r   r    exclude)r   r   r   contains)r   r=   r5   F)r   r   	file_typefile)any	directoryr   link)r   r   choicesr+   	age_stampr]   )r\   r^   r]   r0   recursehiddenfollowget_checksumr!   depthrG   rJ   raw
exact_moder3   limit)argument_specsupports_check_modezRargument 'mode' is not a string and conversion is not allowed, value is of type %s)r@   z.**c                    | j                   t         j                  t         j                  t         j                  fv rt	        |       | j
                  <   y | r   )errnoEPERMEACCESENOENTr   filename)r$   skippeds    r   handle_walk_errorsz main.<locals>.handle_walk_errors  s<    77u{{ELL%,,??")!*GAJJr   z^(-?\d+)(s|m|h|d|w)?$   <   i  iQ i:	 )smhdw   zfailed to process age)r+   r@   z^(-?\d+)(b|k|m|g|t)?$i   i   i   @l        )br   r   gtzfailed to process size)r0   r@   r   z+limit cannot be %d (use None for unlimited)zAll paths examinedz'%s' is not a directory)onerrorfollowlinkstopdown.zSkipped entry 'z' due to this access issue: 
r   checksumr   r   zLimit of matches reachedz	Skipped 'z!' path due to this access issue: z2Not all paths examined, check warnings for details)fileschangedr@   matchedexaminedskipped_pathsr   )1r   dictparams
isinstancer   	fail_json	__class__r   r   r   lowerrG   groupgettimeosr   rP   r:   r   walklennormpathjoinrstripsepcountbasename
startswithlstatIOErrorOSErrorwarnr   r%   r-   rM   updater   rE   ru   rD   sha1r1   appendrr   rA   rw   	exit_json)rL   r   filelistr   r+   r   seconds_per_unitr0   bytes_per_unitr*   r@   lookedhas_warningsnpathrootdirsr   fsobjr;   wpathr   r)   r$   r#   r   r   s                            @r   mainr     sU    
FTFF;KV\]
vrI;QVW
 v	{UK
 u%	

 !fe<
 v?cd
 % 
 w@[\
 5!
 fe4
 VU3
 VU3
 659
 6
 E"
  5!!
" 6#
$ u%%
& E"'
* !-F2 ]]Ff~jFdgmntgugg  hI  hI  I 	 	
 *+"&F:"%F:HG e} HH-ve}/B/B/DE!"$UPaggaj/$4$8$8Q$GGC4KLf~ HH-vf~/C/C/EF t'gVqwwqz?^%7%7
A%FFD&.6NOg"vg!';JVT[_\]
))+C
CFL R Q	 77==' 9Ie<L LMM &(WWU<N\bck\lvz%{ H!dE#e*,s4y8#dl CEWW--bggll4.GHFg %RWW[[ 9BGGKK G #FLL$= >U[[QSQXQXQ\Q\E]A^ ^ab b 6'?2 $Q$ww''/::3?xHX !XXf-  (Ak*e3#E6*+=vj?QSYZeSfg )"c3{8K L +Bv|@TV\ ]HHXb\2#||BJJ7F><R06F0C*#||BJJ7#-b$#7$,OOA$6 ( 2bjj1f[6I[6X#E6*+=vj?QSYZeSfg )"c3{8K L +Bv|@TV\ ]HHXb\2$OOA.bjj1f[6IV6S#E6*+=vj?QSYZeSfg )"c3{8K L *2t 4 -ffZ6H&Q[J\^dev^w x +Bv|@TV\ ]HHXb\2%n506F0C*$OOA.bjj1f[6IV6S#E6*+=vj?QSYZeSfg )"c3{8K L +Bv|@TV\ ]HHXb\2$OOA.8}w78GCJ i(CMVG_,LQHR h B(mG
8UWW]mtuC $W- ![acjklcm$no*1!*'+ 	!r  	 $QZGENKKgV[n^efk^lmnL	 sP   9F/a)_8>K.a.aa8a	1`>	8a>a	a	b4b		b__main__)NNF)F)
__future__r   DOCUMENTATIONEXAMPLESRETURNr   r   ro   r   rl   r   rE   r   +ansible.module_utils.common.text.convertersr   r   ansible.module_utils.basicr   ansible.module_utils.sixr   r	   r%   r-   r1   rA   rM   r   r   r   r   r   r   <module>r      s    #ePEN
B   
 	 
 	   J 4 1   $N"J &-`hvV zF r   