Commit 040a39f2 by Brian Coca

there will be only one cli

parent da5e201b
...@@ -31,9 +31,6 @@ from ansible import constants as C ...@@ -31,9 +31,6 @@ from ansible import constants as C
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.utils.unicode import to_bytes from ansible.utils.unicode import to_bytes
# FIXME: documentation for methods here, which have mostly been
# copied directly over from the old utils/__init__.py
class SortedOptParser(optparse.OptionParser): class SortedOptParser(optparse.OptionParser):
'''Optparser which sorts the options by opt before outputting --help''' '''Optparser which sorts the options by opt before outputting --help'''
...@@ -92,6 +89,7 @@ class CLI(object): ...@@ -92,6 +89,7 @@ class CLI(object):
@staticmethod @staticmethod
def ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=False, confirm_vault=False, confirm_new=False): def ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=False, confirm_vault=False, confirm_new=False):
''' prompt for vault password and/or password change '''
vault_pass = None vault_pass = None
new_vault_pass = None new_vault_pass = None
...@@ -122,6 +120,7 @@ class CLI(object): ...@@ -122,6 +120,7 @@ class CLI(object):
def ask_passwords(self): def ask_passwords(self):
''' prompt for connection and become passwords if needed '''
op = self.options op = self.options
sshpass = None sshpass = None
...@@ -162,6 +161,7 @@ class CLI(object): ...@@ -162,6 +161,7 @@ class CLI(object):
def validate_conflicts(self): def validate_conflicts(self):
''' check for conflicting options '''
op = self.options op = self.options
...@@ -186,7 +186,7 @@ class CLI(object): ...@@ -186,7 +186,7 @@ class CLI(object):
@staticmethod @staticmethod
def base_parser(usage="", output_opts=False, runas_opts=False, meta_opts=False, def base_parser(usage="", output_opts=False, runas_opts=False, meta_opts=False,
async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, diff_opts=False): async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, diff_opts=False):
''' create an options parser for any ansible script ''' ''' create an options parser for most ansible scripts '''
parser = SortedOptParser(usage, version=CLI.version("%prog")) parser = SortedOptParser(usage, version=CLI.version("%prog"))
...@@ -290,6 +290,7 @@ class CLI(object): ...@@ -290,6 +290,7 @@ class CLI(object):
@staticmethod @staticmethod
def version(prog): def version(prog):
''' return ansible version '''
result = "{0} {1}".format(prog, __version__) result = "{0} {1}".format(prog, __version__)
gitinfo = _gitinfo() gitinfo = _gitinfo()
if gitinfo: if gitinfo:
...@@ -299,6 +300,7 @@ class CLI(object): ...@@ -299,6 +300,7 @@ class CLI(object):
@staticmethod @staticmethod
def version_info(gitinfo=False): def version_info(gitinfo=False):
''' return full ansible version info '''
if gitinfo: if gitinfo:
# expensive call, user with care # expensive call, user with care
ansible_version_string = version('') ansible_version_string = version('')
...@@ -322,61 +324,63 @@ class CLI(object): ...@@ -322,61 +324,63 @@ class CLI(object):
'minor': ansible_versions[1], 'minor': ansible_versions[1],
'revision': ansible_versions[2]} 'revision': ansible_versions[2]}
def _git_repo_info(repo_path): @staticmethod
''' returns a string containing git branch, commit id and commit date ''' def _git_repo_info(repo_path):
result = None ''' returns a string containing git branch, commit id and commit date '''
if os.path.exists(repo_path): result = None
# Check if the .git is a file. If it is a file, it means that we are in a submodule structure. if os.path.exists(repo_path):
if os.path.isfile(repo_path): # Check if the .git is a file. If it is a file, it means that we are in a submodule structure.
try: if os.path.isfile(repo_path):
gitdir = yaml.safe_load(open(repo_path)).get('gitdir') try:
# There is a possibility the .git file to have an absolute path. gitdir = yaml.safe_load(open(repo_path)).get('gitdir')
if os.path.isabs(gitdir): # There is a possibility the .git file to have an absolute path.
repo_path = gitdir if os.path.isabs(gitdir):
else: repo_path = gitdir
repo_path = os.path.join(repo_path[:-4], gitdir) else:
except (IOError, AttributeError): repo_path = os.path.join(repo_path[:-4], gitdir)
return '' except (IOError, AttributeError):
f = open(os.path.join(repo_path, "HEAD")) return ''
branch = f.readline().split('/')[-1].rstrip("\n") f = open(os.path.join(repo_path, "HEAD"))
f.close() branch = f.readline().split('/')[-1].rstrip("\n")
branch_path = os.path.join(repo_path, "refs", "heads", branch)
if os.path.exists(branch_path):
f = open(branch_path)
commit = f.readline()[:10]
f.close() f.close()
branch_path = os.path.join(repo_path, "refs", "heads", branch)
if os.path.exists(branch_path):
f = open(branch_path)
commit = f.readline()[:10]
f.close()
else:
# detached HEAD
commit = branch[:10]
branch = 'detached HEAD'
branch_path = os.path.join(repo_path, "HEAD")
date = time.localtime(os.stat(branch_path).st_mtime)
if time.daylight == 0:
offset = time.timezone
else:
offset = time.altzone
result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit,
time.strftime("%Y/%m/%d %H:%M:%S", date), int(offset / -36))
else: else:
# detached HEAD result = ''
commit = branch[:10] return result
branch = 'detached HEAD'
branch_path = os.path.join(repo_path, "HEAD") @staticmethod
def _gitinfo():
date = time.localtime(os.stat(branch_path).st_mtime) basedir = os.path.join(os.path.dirname(__file__), '..', '..', '..')
if time.daylight == 0: repo_path = os.path.join(basedir, '.git')
offset = time.timezone result = _git_repo_info(repo_path)
else: submodules = os.path.join(basedir, '.gitmodules')
offset = time.altzone if not os.path.exists(submodules):
result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit, return result
time.strftime("%Y/%m/%d %H:%M:%S", date), int(offset / -36)) f = open(submodules)
else: for line in f:
result = '' tokens = line.strip().split(' ')
return result if tokens[0] == 'path':
submodule_path = tokens[2]
def _gitinfo(): submodule_info =_git_repo_info(os.path.join(basedir, submodule_path, '.git'))
basedir = os.path.join(os.path.dirname(__file__), '..', '..', '..') if not submodule_info:
repo_path = os.path.join(basedir, '.git') submodule_info = ' not found - use git submodule update --init ' + submodule_path
result = _git_repo_info(repo_path) result += "\n {0}: {1}".format(submodule_path, submodule_info)
submodules = os.path.join(basedir, '.gitmodules') f.close()
if not os.path.exists(submodules): return result
return result
f = open(submodules)
for line in f:
tokens = line.strip().split(' ')
if tokens[0] == 'path':
submodule_path = tokens[2]
submodule_info =_git_repo_info(os.path.join(basedir, submodule_path, '.git'))
if not submodule_info:
submodule_info = ' not found - use git submodule update --init ' + submodule_path
result += "\n {0}: {1}".format(submodule_path, submodule_info)
f.close()
return result
#!/usr/bin/env python
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# #
# This file is part of Ansible # This file is part of Ansible
...@@ -18,18 +16,6 @@ ...@@ -18,18 +16,6 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
######################################################## ########################################################
__requires__ = ['ansible']
try:
import pkg_resources
except Exception:
# Use pkg_resources to find the correct versions of libraries and set
# sys.path appropriately when there are multiversion installs. But we
# have code that better expresses the errors in the places where the code
# is actually used (the deps are optional for many code paths) so we don't
# want to fail here.
pass
import os import os
import sys import sys
...@@ -47,7 +33,7 @@ from ansible.vars import VariableManager ...@@ -47,7 +33,7 @@ from ansible.vars import VariableManager
######################################################## ########################################################
class AdHocCli(CLI): class AdHocCLI(CLI):
''' code behind ansible ad-hoc cli''' ''' code behind ansible ad-hoc cli'''
def parse(self): def parse(self):
...@@ -72,8 +58,7 @@ class AdHocCli(CLI): ...@@ -72,8 +58,7 @@ class AdHocCli(CLI):
self.options, self.args = self.parser.parse_args() self.options, self.args = self.parser.parse_args()
if len(self.args) != 1: if len(self.args) != 1:
self.parser.print_help() raise AnsibleOptionsError("Missing target hosts")
sys.exit(1)
self.display.verbosity = self.options.verbosity self.display.verbosity = self.options.verbosity
self.validate_conflicts() self.validate_conflicts()
...@@ -141,10 +126,10 @@ class AdHocCli(CLI): ...@@ -141,10 +126,10 @@ class AdHocCli(CLI):
play = Play().load(play_ds, variable_manager=variable_manager, loader=loader) play = Play().load(play_ds, variable_manager=variable_manager, loader=loader)
# now create a task queue manager to execute the play # now create a task queue manager to execute the play
tqm = None
try: try:
tqm = TaskQueueManager( tqm = TaskQueueManager(
inventory=inventory, inventory=inventory,
callback='minimal',
variable_manager=variable_manager, variable_manager=variable_manager,
loader=loader, loader=loader,
display=self.display, display=self.display,
...@@ -170,23 +155,3 @@ class AdHocCli(CLI): ...@@ -170,23 +155,3 @@ class AdHocCli(CLI):
return poller.results return poller.results
########################################################
if __name__ == '__main__':
display = Display()
try:
cli = AdHocCli(sys.argv, display=display)
cli.parse()
sys.exit(cli.run())
except AnsibleOptionsError as e:
cli.parser.print_help()
display.display(str(e), stderr=True, color='red')
sys.exit(1)
except AnsibleError as e:
display.display(str(e), stderr=True, color='red')
sys.exit(2)
except KeyboardInterrupt:
display.error("interrupted")
sys.exit(4)
#!/usr/bin/env python
######################################################################## ########################################################################
# #
# (C) 2013, James Cammarata <jcammarata@ansible.com> # (C) 2013, James Cammarata <jcammarata@ansible.com>
...@@ -495,24 +493,3 @@ class GalaxyCLI(CLI): ...@@ -495,24 +493,3 @@ class GalaxyCLI(CLI):
version = "(unknown version)" version = "(unknown version)"
self.display.display("- %s, %s" % (path_file, version)) self.display.display("- %s, %s" % (path_file, version))
return 0 return 0
#-------------------------------------------------------------------------------------
# The main entry point
#-------------------------------------------------------------------------------------
if __name__ == '__main__':
display = Display()
try:
cli = GalaxyCLI(sys.argv, display=display)
cli.parse()
sys.exit(cli.run())
except AnsibleOptionsError as e:
cli.parser.print_help()
display.display(str(e), stderr=True, color='red')
sys.exit(1)
except AnsibleError as e:
display.display(str(e), stderr=True, color='red')
sys.exit(2)
except KeyboardInterrupt:
display.error("interrupted")
sys.exit(4)
...@@ -18,20 +18,6 @@ ...@@ -18,20 +18,6 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
######################################################## ########################################################
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
__requires__ = ['ansible']
try:
import pkg_resources
except Exception:
# Use pkg_resources to find the correct versions of libraries and set
# sys.path appropriately when there are multiversion installs. But we
# have code that better expresses the errors in the places where the code
# is actually used (the deps are optional for many code paths) so we don't
# want to fail here.
pass
import os import os
import stat import stat
import sys import sys
...@@ -191,24 +177,3 @@ class PlaybookCLI(CLI): ...@@ -191,24 +177,3 @@ class PlaybookCLI(CLI):
return 0 return 0
else: else:
return results return results
########################################################
if __name__ == "__main__":
display = Display()
try:
cli = PlaybookCLI(sys.argv, display=display)
cli.parse()
sys.exit(cli.run())
except AnsibleOptionsError as e:
cli.parser.print_help()
display.display(str(e), stderr=True, color='red')
sys.exit(1)
except AnsibleError as e:
display.display(str(e), stderr=True, color='red')
sys.exit(2)
except KeyboardInterrupt:
display.error("interrupted")
sys.exit(4)
#!/usr/bin/env python
# (c) 2014, James Tanner <tanner.jc@gmail.com> # (c) 2014, James Tanner <tanner.jc@gmail.com>
# #
# Ansible is free software: you can redistribute it and/or modify # Ansible is free software: you can redistribute it and/or modify
...@@ -18,17 +16,6 @@ ...@@ -18,17 +16,6 @@
# ansible-vault is a script that encrypts/decrypts YAML files. See # ansible-vault is a script that encrypts/decrypts YAML files. See
# http://docs.ansible.com/playbooks_vault.html for more details. # http://docs.ansible.com/playbooks_vault.html for more details.
__requires__ = ['ansible']
try:
import pkg_resources
except Exception:
# Use pkg_resources to find the correct versions of libraries and set
# sys.path appropriately when there are multiversion installs. But we
# have code that better expresses the errors in the places where the code
# is actually used (the deps are optional for many code paths) so we don't
# want to fail here.
pass
import os import os
import sys import sys
import traceback import traceback
...@@ -38,7 +25,7 @@ from ansible.parsing.vault import VaultEditor ...@@ -38,7 +25,7 @@ from ansible.parsing.vault import VaultEditor
from ansible.utils.cli import CLI from ansible.utils.cli import CLI
from ansible.utils.display import Display from ansible.utils.display import Display
class VaultCli(CLI): class VaultCLI(CLI):
""" Vault command line class """ """ Vault command line class """
VALID_ACTIONS = ("create", "decrypt", "edit", "encrypt", "rekey", "view") VALID_ACTIONS = ("create", "decrypt", "edit", "encrypt", "rekey", "view")
...@@ -132,23 +119,3 @@ class VaultCli(CLI): ...@@ -132,23 +119,3 @@ class VaultCli(CLI):
this_editor.rekey_file(new_password) this_editor.rekey_file(new_password)
self.display.display("Rekey successful") self.display.display("Rekey successful")
########################################################
if __name__ == "__main__":
display = Display()
try:
cli = VaultCli(sys.argv, display=display)
cli.parse()
sys.exit(cli.run())
except AnsibleOptionsError as e:
cli.parser.print_help()
display.display(str(e), stderr=True, color='red')
sys.exit(1)
except AnsibleError as e:
display.display(str(e), stderr=True, color='red')
sys.exit(2)
except KeyboardInterrupt:
display.error("interrupted")
sys.exit(4)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment