Skip to content

Instantly share code, notes, and snippets.

@fangpenlin
Created August 11, 2014 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fangpenlin/640c0e1aa647d905c587 to your computer and use it in GitHub Desktop.
Save fangpenlin/640c0e1aa647d905c587 to your computer and use it in GitHub Desktop.
parse_setup ansible module
#!/usr/bin/python
import os
import sys
import ast
import textwrap
def parse_setup(setup_filename):
"""Parse setup.py and return args and keywords args to its setup
function call
"""
dirname = os.path.dirname(setup_filename)
sys.path.append(dirname)
mock_setup = textwrap.dedent('''\
def setup(*args, **kwargs):
__setup_calls__.append((args, kwargs))
''')
parsed_mock_setup = ast.parse(mock_setup, filename=setup_filename)
with open(setup_filename, 'rt') as setup_file:
parsed = ast.parse(setup_file.read())
for index, node in enumerate(parsed.body[:]):
if (
not isinstance(node, ast.Expr) or
not isinstance(node.value, ast.Call) or
node.value.func.id != 'setup'
):
continue
parsed.body[index:index] = parsed_mock_setup.body
break
fixed = ast.fix_missing_locations(parsed)
codeobj = compile(fixed, setup_filename, 'exec')
local_vars = {}
global_vars = {'__setup_calls__': []}
exec(codeobj, global_vars, local_vars)
return global_vars['__setup_calls__'][0]
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(required=True),
),
)
path = module.params['path']
_, kwargs = parse_setup(path)
install_requires = {}
for line in kwargs['install_requires']:
parts = line.split('==')
name = parts[0].split('[')[0]
install_requires[name] = ''.join(parts[1:])
module.exit_json(
failed=False,
changed=False,
install_requires=install_requires,
)
# import module snippets
from ansible.module_utils.basic import *
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment