From 63fd67f156e946420d213b32346aa43212e9634d Mon Sep 17 00:00:00 2001 From: Brian Coca Date: Mon, 14 Dec 2015 21:18:13 -0500 Subject: [PATCH] added mime option to stat module it uses file magic to now return mime_type and charset of a file as per output of `file -i /path` --- lib/ansible/modules/files/stat.py | 35 ++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/ansible/modules/files/stat.py b/lib/ansible/modules/files/stat.py index 1e41185ad6a..02c78f46d46 100644 --- a/lib/ansible/modules/files/stat.py +++ b/lib/ansible/modules/files/stat.py @@ -55,6 +55,15 @@ options: default: sha1 aliases: [ 'checksum_algo' ] version_added: "2.0" + mime: + description: + - Use file magic and return data about the nature of the file. this uses the 'file' utility found on most Linux/Unix systems. + - This will add both `mime_type` and 'charset' fields to the return, if possible. + required: false + choices: [ Yes, No ] + default: No + version_added: "2.1" + aliases: [ 'mime_type', 'mime-type' ] author: "Bruce Pennypacker (@bpennypacker)" ''' @@ -278,6 +287,16 @@ stat: returned: success, path exists and user can read stats and installed python supports it type: string sample: www-data + mime_type: + description: file magic data or mime-type + returned: success, path exists and user can read stats and installed python supports it and the `mime` option was true, will return 'unknown' on error. + type: string + sample: PDF document, version 1.2 + charset: + description: file character set or encoding + returned: success, path exists and user can read stats and installed python supports it and the `mime` option was true, will return 'unknown' on error. + type: string + sample: us-ascii ''' import os @@ -293,7 +312,8 @@ def main(): follow = dict(default='no', type='bool'), get_md5 = dict(default='yes', type='bool'), get_checksum = dict(default='yes', type='bool'), - checksum_algorithm = dict(default='sha1', type='str', choices=['sha1', 'sha224', 'sha256', 'sha384', 'sha512'], aliases=['checksum_algo']) + checksum_algorithm = dict(default='sha1', type='str', choices=['sha1', 'sha224', 'sha256', 'sha384', 'sha512'], aliases=['checksum_algo']), + mime = dict(default=False, type='bool', aliases=['mime_type', 'mime-type']), ), supports_check_mode = True ) @@ -376,6 +396,19 @@ def main(): except: pass + if module.params.get('mime'): + d['mime_type'] = 'unknown' + d['charset'] = 'unknown' + + filecmd = [module.get_bin_path('file', True),'-i', path] + try: + rc, out, err = module.run_command(filecmd) + if rc == 0: + mtype, chset = out.split(':')[1].split(';') + d['mime_type'] = mtype.strip() + d['charset'] = chset.split('=')[1].strip() + except: + pass module.exit_json(changed=False, stat=d)