<commit_before>##########################################################################
#
#  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#     * Neither the name of Image Engine Design nor the names of any
#       other contributors to this software may be used to endorse or
#       promote products derived from this software without specific prior
#       written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################

import math
import random
import unittest
from IECore import *

class TestBoundedKDTree:

	treeSizes = [0, 1, 10, 50, 5000]

	def doIntersectingBounds(self, numBounds):

		self.makeTree(numBounds)

		numTests = 25
		if numBounds:
			numTests = (int)( math.log10( numBounds ) + 1 ) * 25

		for j in range(0, numTests):

			bound = self.makeBound()
			bIdxArray = self.tree.intersectingBounds( bound )

			for bIdx in bIdxArray:
				self.assert_(bIdx >= 0)
				self.assert_(bIdx < numBounds)
				nearestBound = self.bounds[bIdx]

				self.assert_( nearestBound.intersects( bound ) )

class TestBoundedKDTreeBox3f(unittest.TestCase, TestBoundedKDTree):

	def makeBound( self ) :
		b1 = V3f( random.random(), random.random(), random.random() )
		b2 = V3f( random.random(), random.random(), random.random() )
		bound = Box3f( b1 )
		bound.extendBy( b2 )

		return bound

	def makeTree(self, numBounds):
		# Make tree creation repeatable, but different for every size
		random.seed(100 + 5 * numBounds)
		self.bounds = Box3fVectorData()

		for i in range(0, numBounds):
			self.bounds.append( self.makeBound() )

		self.tree = Box3fTree( self.bounds )

	def testConstructors(self):
		"""Test BoundedKDTreeBox3f constructors"""

		for t in self.treeSizes:
			self.makeTree(t)

	def testIntersectingBounds(self):
		"""Test BoundedKDTreeBox3f intersectingBounds"""

		for t in self.treeSizes:
			self.doIntersectingBounds(t)

class TestBoundedKDTreeBox3d(unittest.TestCase, TestBoundedKDTree):

	def makeBound( self ) :
		b1 = V3d( random.random(), random.random(), random.random() )
		b2 = V3d( random.random(), random.random(), random.random() )
		bound = Box3d( b1 )
		bound.extendBy( b2 )

		return bound

	def makeTree(self, numBounds):
		# Make tree creation repeatable, but different for every size
		random.seed(100 + 5 * numBounds)
		self.bounds = Box3dVectorData()

		for i in range(0, numBounds):
			self.bounds.append( self.makeBound() )

		self.tree = Box3dTree( self.bounds )

	def testConstructors(self):
		"""Test BoundedKDTreeBox3d constructors"""

		for t in self.treeSizes:
			self.makeTree(t)

	def testIntersectingBounds(self):
		"""Test BoundedKDTreeBox3d intersectingBounds"""

		for t in self.treeSizes:
			self.doIntersectingBounds(t)

class TestBoundedKDTreeBox2f(unittest.TestCase, TestBoundedKDTree):

	def makeBound( self ) :
		b1 = V2f( random.random(), random.random() )
		b2 = V2f( random.random(), random.random() )
		bound = Box2f( b1 )
		bound.extendBy( b2 )

		return bound

	def makeTree(self, numBounds):
		# Make tree creation repeatable, but different for every size
		random.seed(100 + 5 * numBounds)
		self.bounds = Box2fVectorData()

		for i in range(0, numBounds):
			self.bounds.append( self.makeBound() )

		self.tree = Box2fTree( self.bounds )

	def testConstructors(self):
		"""Test BoundedKDTreeBox2f constructors"""

		for t in self.treeSizes:
			self.makeTree(t)

	def testIntersectingBounds(self):
		"""Test BoundedKDTreeBox2f intersectingBounds"""

		for t in self.treeSizes:
			self.doIntersectingBounds(t)

if __name__ == "__main__":
	unittest.main()
<commit_msg>Added BoundedTreeBox2d test<commit_after>##########################################################################
#
#  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
#     * Neither the name of Image Engine Design nor the names of any
#       other contributors to this software may be used to endorse or
#       promote products derived from this software without specific prior
#       written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################

import math
import random
import unittest
from IECore import *

class TestBoundedKDTree:

	treeSizes = [0, 1, 10, 50, 5000]

	def doIntersectingBounds(self, numBounds):

		self.makeTree(numBounds)

		numTests = 25
		if numBounds:
			numTests = (int)( math.log10( numBounds ) + 1 ) * 25

		for j in range(0, numTests):

			bound = self.makeBound()
			bIdxArray = self.tree.intersectingBounds( bound )

			for bIdx in bIdxArray:
				self.assert_(bIdx >= 0)
				self.assert_(bIdx < numBounds)
				nearestBound = self.bounds[bIdx]

				self.assert_( nearestBound.intersects( bound ) )

class TestBoundedKDTreeBox3f(unittest.TestCase, TestBoundedKDTree):

	def makeBound( self ) :
		b1 = V3f( random.random(), random.random(), random.random() )
		b2 = V3f( random.random(), random.random(), random.random() )
		bound = Box3f( b1 )
		bound.extendBy( b2 )

		return bound

	def makeTree(self, numBounds):
		# Make tree creation repeatable, but different for every size
		random.seed(100 + 5 * numBounds)
		self.bounds = Box3fVectorData()

		for i in range(0, numBounds):
			self.bounds.append( self.makeBound() )

		self.tree = Box3fTree( self.bounds )

	def testConstructors(self):
		"""Test BoundedKDTreeBox3f constructors"""

		for t in self.treeSizes:
			self.makeTree(t)

	def testIntersectingBounds(self):
		"""Test BoundedKDTreeBox3f intersectingBounds"""

		for t in self.treeSizes:
			self.doIntersectingBounds(t)

class TestBoundedKDTreeBox3d(unittest.TestCase, TestBoundedKDTree):

	def makeBound( self ) :
		b1 = V3d( random.random(), random.random(), random.random() )
		b2 = V3d( random.random(), random.random(), random.random() )
		bound = Box3d( b1 )
		bound.extendBy( b2 )

		return bound

	def makeTree(self, numBounds):
		# Make tree creation repeatable, but different for every size
		random.seed(100 + 5 * numBounds)
		self.bounds = Box3dVectorData()

		for i in range(0, numBounds):
			self.bounds.append( self.makeBound() )

		self.tree = Box3dTree( self.bounds )

	def testConstructors(self):
		"""Test BoundedKDTreeBox3d constructors"""

		for t in self.treeSizes:
			self.makeTree(t)

	def testIntersectingBounds(self):
		"""Test BoundedKDTreeBox3d intersectingBounds"""

		for t in self.treeSizes:
			self.doIntersectingBounds(t)

class TestBoundedKDTreeBox2f(unittest.TestCase, TestBoundedKDTree):

	def makeBound( self ) :
		b1 = V2f( random.random(), random.random() )
		b2 = V2f( random.random(), random.random() )
		bound = Box2f( b1 )
		bound.extendBy( b2 )

		return bound

	def makeTree(self, numBounds):
		# Make tree creation repeatable, but different for every size
		random.seed(100 + 5 * numBounds)
		self.bounds = Box2fVectorData()

		for i in range(0, numBounds):
			self.bounds.append( self.makeBound() )

		self.tree = Box2fTree( self.bounds )

	def testConstructors(self):
		"""Test BoundedKDTreeBox2f constructors"""

		for t in self.treeSizes:
			self.makeTree(t)

	def testIntersectingBounds(self):
		"""Test BoundedKDTreeBox2f intersectingBounds"""

		for t in self.treeSizes:
			self.doIntersectingBounds(t)

class TestBoundedKDTreeBox2d(unittest.TestCase, TestBoundedKDTree):

	def makeBound( self ) :
		b1 = V2d( random.random(), random.random() )
		b2 = V2d( random.random(), random.random() )
		bound = Box2d( b1 )
		bound.extendBy( b2 )

		return bound

	def makeTree(self, numBounds):
		# Make tree creation repeatable, but different for every size
		random.seed(100 + 5 * numBounds)
		self.bounds = Box2dVectorData()

		for i in range(0, numBounds):
			self.bounds.append( self.makeBound() )

		self.tree = Box2dTree( self.bounds )

	def testConstructors(self):
		"""Test BoundedKDTreeBox2d constructors"""

		for t in self.treeSizes:
			self.makeTree(t)

	def testIntersectingBounds(self):
		"""Test BoundedKDTreeBox2d intersectingBounds"""

		for t in self.treeSizes:
			self.doIntersectingBounds(t)

if __name__ == "__main__":
	unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
import socket, os
from httplib import responses
from datetime import datetime

def get_size(dirname):
    """Gets the total size of a given directory"""
    size = 0
    for item in os.listdir(dirname):
        if os.path.isfile(item):
            size += os.path.getsize(item)
        elif os.path.isdir(item):
            size += get_size(item)
    return size

def htmlize(drct):
    """Wraps content in html tags"""
    lst = []
    for item in os.listdir(drct):
        lst.append("
%s
"%item)
        content = ("\n").join(lst)
    return "\n\n
\n{content}\n
\n\n".format(content=content)

def parse_request(request):
    parsed = request.split("\r\n")   # <--- Splits the request by new lines so the init req and each header is seperated.
    return parsed                    #      We haven't been asked to do anything with request headers, so for now, if any are passed as
                                     #      as a part of the request, they will sit here.

def parse_init_req_line(req_line):
    """Takes an HTTP request in the form of a string and parses it. Returns a tuple containing
    the URI (or where it should be) and a status code: 200 if the parse was successful, 400/405
    if it was not. Takes the initial request line as argument"""
    if req_line[:3] != "GET":
        status = 405
        # # # Raise Error 405 # # #
    elif req_line[-8:] != "HTTP/1.1":
        status = 400
        # # # Raise Error 400 # # #
    else:
        status = 200
    return (req_line[3:-8].strip(), status)

def responseHeaders(h1, h2, h3):
    """Returns a dict of headers to be used in the response"""
    headers = {}
    headers['Content-Type'] = h1
    headers['Date'] = h2
    headers['Server'] = "ServerTron4000"
    headers['Content-Length'] = h3
    return headers

def buildResponse(init_line, hdrs, body):
    """Build the final response to be sent to the client. Status, headers and all"""
    line1 = init_line + "\r\n"
    header_block = []
    for k, v in hdrs.items():
        header_block.append("%s:  %s"%(k,v))
    headers = ("\r\n").join(header_block)
    bodylines = "\r\n\r\n" + body
    return line1 + headers + bodylines + "\r\n\r\n"

def raiseResponse(status_code):
    """Raise appropriate status response. Makes use of httplib.responses"""
    return "%s %s" % (status_code, responses[status_code])

def getResource(uri):
    """Takes URI as argument; returns a tuple containing the content_type, the content_length, the resource requested as the body, and the status code, in that order"""
    body = ""                                       #
    content_type = ""                               # <--- Initialize the variables to hold the body and headers. For clarity.
    content_length = 0                              #
    type_dict = {'txt':'text', 'html':'text', 'py':'text', 'jpg':'image', 'png':'image'}
    status = 200
    if os.path.exists(uri):                         # <--- If the resource exists, return a body and Headers appropriate to the request.
        if os.path.isfile(uri):                     # <--- If the resource is a file:
            content_length = os.path.getsize(uri)   # <--- Determine its size...
            subtype =  uri.split('.')[-1]           # <--- Grab the extension...
            content_type = "%s/%s" % (type_dict[subtype], subtype)  # <--- Determine content type from file extension, and finally...
            with open(uri, 'rb') as f:              # <--- Open the file as binary data.
                while True:
                    readBytes = f.read(1024)
                    body += readBytes               # <--- Writes contents of file to a string.
                    if readBytes == "":
                        break
        elif os.path.isdir(uri):   # <--- If the resource is a directory:
            content_type = 'text/directory'
            content_length = get_size(uri)   # <--- Gets the size of the directory--the sum of the size of all files and subdirectories.  Maybe the content_length for a directory should just be the length of the content actually displayed...idk.
            body = htmlize(uri)
    else:
        status = 404

    return (content_type, str(content_length), body, status)

def Main():
    pass
    """Here will be the main functionality of the server. We will build sockets, establish connections,
    listen for requests and return responses"""
    host, port = '127.0.0.1', 5000
    s = socket.socket()  # <--- May need to provide parameters... Unsure wheather the provided parameters are defaulted to.
    s.bind((host, port))
    s.listen(1)          # <--- May need to change this parameter. Takes values 0 thru 5.
    print "Server Started\nListening..."

    while True:          # <--- Not yet sure of the significance of this loop. Does it keep the server open and listening for new requests?
        conn, addr = s.accept()
        print "Client connected from ip: <%s>" % str(addr)
        # # # Here we might need to implement a thread to do our bidding while the server listens for requests # # #

        next = conn.recv(1024)
        request = next
        while next != "\r\n":      # <--- If I want to be able to send a body in with the request (which is seperateted
            next = conn.recv(1024) #      from the initial request line and headers with a blank line, then just re-write
            request += next        #      this condition to be 'while "\r\n\r\n" not in request:...'

        request = parse_request(request)  # <--- Now my request is split into chunks: Init line, header1, header2...
        result = parse_init_req_line(request[0])  # <--- tuple of (URI, status code) from init request line
        uri = result[0]
        status = result[1]
        if status != 200:          # <--- If the URI was not parsed correctly, prepare an appropriate response
            init_response_line = "HTTP/1.1 %s" % raiseResponse(status)
            b1 = "Error 405. Only the GET method is supported by this server."
            b2 = "Error 400. Only HTTP version 1.1 is supported by this server."
            response_body = b1 if status == 405 else b2
            headers = responseHeaders('text/html', datetime.now(), len(response_body))
            response = buildResponse(init_response_line, headers, response_body)
            conn.sendall(response)
            conn.shutdown(socket.SHUT_WR)
            conn.close()
        else:
            gather = getResource(uri)
            status = gather[3]
            if status == 404:
                init_response_line = "HTTP/1.1 %s" % raiseResponse(status)
                response_body = "Error 404. <%s> was not found." % uri
                headers = responseHeaders('text/html', datetime.now(), len(response_body))
                response = buildResponse(init_response_line, headers, response_body)
                conn.sendall(response)
                conn.shutdown(socket.SHUT_WR)
                conn.close()

    s.close()

if __name__ == '__main__':
    Main()
<commit_msg>Add functionality to build a proper HTTP/1.1 200 OK response for acceptable requests<commit_after>#!/usr/bin/env python
import socket, os
from httplib import responses
from datetime import datetime

def get_size(dirname):
    """Gets the total size of a given directory"""
    size = 0
    for item in os.listdir(dirname):
        if os.path.isfile(item):
            size += os.path.getsize(item)
        elif os.path.isdir(item):
            size += get_size(item)
    return size

def htmlize(drct):
    """Wraps content in html tags"""
    lst = []
    for item in os.listdir(drct):
        lst.append("
%s
"%item)
        content = ("\n").join(lst)
    return "\n\n
\n{content}\n
\n\n".format(content=content)

def parse_request(request):
    parsed = request.split("\r\n")   # <--- Splits the request by new lines so the init req and each header is seperated.
    return parsed                    #      We haven't been asked to do anything with request headers, so for now, if any are passed as
                                     #      as a part of the request, they will sit here.

def parse_init_req_line(req_line):
    """Takes an HTTP request in the form of a string and parses it. Returns a tuple containing
    the URI (or where it should be) and a status code: 200 if the parse was successful, 400/405
    if it was not. Takes the initial request line as argument"""
    if req_line[:3] != "GET":
        status = 405
        # # # Raise Error 405 # # #
    elif req_line[-8:] != "HTTP/1.1":
        status = 400
        # # # Raise Error 400 # # #
    else:
        status = 200
    return (req_line[3:-8].strip(), status)

def responseHeaders(h1, h2, h3):
    """Returns a dict of headers to be used in the response"""
    headers = {}
    headers['Content-Type'] = h1
    headers['Date'] = h2
    headers['Server'] = "ServerTron4000"
    headers['Content-Length'] = h3
    return headers

def buildResponse(init_line, hdrs, body):
    """Build the final response to be sent to the client. Status, headers and all"""
    line1 = init_line + "\r\n"
    header_block = []
    for k, v in hdrs.items():
        header_block.append("%s:  %s"%(k,v))
    headers = ("\r\n").join(header_block)
    bodylines = "\r\n\r\n" + body
    return line1 + headers + bodylines + "\r\n\r\n"

def raiseResponse(status_code):
    """Raise appropriate status response. Makes use of httplib.responses"""
    return "%s %s" % (status_code, responses[status_code])

def getResource(uri):
    """Takes URI as argument; returns a tuple containing the content_type, the content_length, the resource requested as the body, and the status code, in that order"""
    body = ""                                       #
    content_type = ""                               # <--- Initialize the variables to hold the body and headers. For clarity.
    content_length = 0                              #
    type_dict = {'txt':'text', 'html':'text', 'py':'text', 'jpg':'image', 'png':'image'}
    status = 200
    if os.path.exists(uri):                         # <--- If the resource exists, return a body and Headers appropriate to the request.
        if os.path.isfile(uri):                     # <--- If the resource is a file:
            content_length = os.path.getsize(uri)   # <--- Determine its size...
            subtype =  uri.split('.')[-1]           # <--- Grab the extension...
            content_type = "%s/%s" % (type_dict[subtype], subtype)  # <--- Determine content type from file extension, and finally...
            with open(uri, 'rb') as f:              # <--- Open the file as binary data.
                while True:
                    readBytes = f.read(1024)
                    body += readBytes               # <--- Writes contents of file to a string.
                    if readBytes == "":
                        break
        elif os.path.isdir(uri):   # <--- If the resource is a directory:
            content_type = 'text/directory'
            content_length = get_size(uri)   # <--- Gets the size of the directory--the sum of the size of all files and subdirectories.  Maybe the content_length for a directory should just be the length of the content actually displayed...idk.
            body = htmlize(uri)
    else:
        status = 404

    return (content_type, str(content_length), body, status)

def Main():
    pass
    """Here will be the main functionality of the server. We will build sockets, establish connections,
    listen for requests and return responses"""
    host, port = '127.0.0.1', 5000
    s = socket.socket()  # <--- May need to provide parameters... Unsure wheather the provided parameters are defaulted to.
    s.bind((host, port))
    s.listen(1)          # <--- May need to change this parameter. Takes values 0 thru 5.
    print "Server Started\nListening..."

    while True:          # <--- Not yet sure of the significance of this loop. Does it keep the server open and listening for new requests?
        conn, addr = s.accept()
        print "Client connected from ip: <%s>" % str(addr)
        # # # Here we might need to implement a thread to do our bidding while the server listens for requests # # #

        next = conn.recv(1024)
        request = next
        while next != "\r\n":      # <--- If I want to be able to send a body in with the request (which is seperateted
            next = conn.recv(1024) #      from the initial request line and headers with a blank line, then just re-write
            request += next        #      this condition to be 'while "\r\n\r\n" not in request:...'

        request = parse_request(request)  # <--- Now my request is split into chunks: Init line, header1, header2...
        result = parse_init_req_line(request[0])  # <--- tuple of (URI, status code) from init request line
        uri = result[0]
        status = result[1]
        if status != 200:          # <--- If the URI was not parsed correctly, prepare an appropriate response
            init_response_line = "HTTP/1.1 %s" % raiseResponse(status)
            b1 = "Error 405. Only the GET method is supported by this server."
            b2 = "Error 400. Only HTTP version 1.1 is supported by this server."
            response_body = b1 if status == 405 else b2
            headers = responseHeaders('text/html', datetime.now(), len(response_body))
            response = buildResponse(init_response_line, headers, response_body)
            conn.sendall(response)
            conn.shutdown(socket.SHUT_WR)
            conn.close()
        else:
            gather = getResource(uri)
            status = gather[3]
            if status == 404:
                init_response_line = "HTTP/1.1 %s" % raiseResponse(status)
                response_body = "Error 404. <%s> was not found." % uri
                headers = responseHeaders('text/html', datetime.now(), len(response_body))
            else:
                init_response_line = "HTTP/1.1 %s" % raiseResponse(status)
                response_body = gather[2]
                headers = responseHeaders(gather[0], datetime.now(), gather[1])
            response = buildResponse(init_response_line, headers, response_body)
            conn.sendall(response)
            conn.shutdown(socket.SHUT_WR)
            conn.close()
    s.close()

if __name__ == '__main__':
    Main()
<|endoftext|>


<commit_before>#!/usr/bin/python
#coding:utf8

import os
import sys
import yaml
import re
from optparse import OptionParser

global return_code
global project_path

def check_args():
  global project_path

  parser = OptionParser()
  parser.add_option("-p", "--project_path", dest="project_path",
                  help="path to the project")
  (options, args) = parser.parse_args()

  if options.project_path is None:
    print "property project_path is mandatory, exiting ..."
    sys.exit(2)

  if not os.path.exists(options.project_path):
    print "path {} not valid".format(options.project_path)
    sys.exit(2)
  else:
    project_path=options.project_path

def yaml_load(filename):
  with open(filename, 'r') as stream:
      try:
          return (yaml.load(stream))
      except yaml.YAMLError as exc:
          print(exc)

def _check_file_exist_not_empty(current_file):
  global project_path
  global return_code
  try:
    assert(os.path.exists(current_file)), "file {} not found".format(current_file)
    assert(os.path.getsize(current_file) > 0), "file {} is empty".format(current_file)
  except (AssertionError, OSError) as e:
    return_code = 2
    print e

def check_default_files():
  global project_path

  _check_file_exist_not_empty("{}/{}".format(project_path , "ansible.cfg"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "env_vars/prod.yml"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "env_vars/preprod.yml"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "inventories/prod.ini"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "inventories/preprod.ini"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "inventories/prod.ini"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "requirements.txt"))

  try:
    for filename in os.listdir("{}/plays".format(project_path)):
      _check_file_exist_not_empty("{}/plays/{}".format(project_path , filename))

  except (AssertionError, OSError) as e:
    code_return = 2
    print e

def check_env_vars():
  global project_path

  try:
    for filename in os.listdir("{}/env_vars".format(project_path)):
      current_env_file = "{}/env_vars/{}".format(project_path, filename)
      env_vars = yaml_load(current_env_file)

      if env_vars is None:
        print "file {} doesn't have any variables".format(current_env_file)
        return_code = 2
      else:
        for var_name in env_vars:
          if re.match("^env_.*", var_name) is None:
            print "{} propertie dont respect the naming convention prefix env_ into {}".format(
            var_name,
            current_env_file
            )
            return_code = 2
  except (IOError, KeyError, OSError) as e:
    print "Error: folder {}/env_vars is empty .".format(project_path)
    return_code = 2

def main():
  global return_code
  return_code = 0

  check_args()
  print "Heather Say :"
  check_default_files()
  check_env_vars()

if __name__ == '__main__':
  main()

<commit_msg>folders groups_var not empty<commit_after>#!/usr/bin/python
#coding:utf8

import os
import sys
import yaml
import re
from optparse import OptionParser

global return_code
global project_path

def check_args():
  global project_path

  parser = OptionParser()
  parser.add_option("-p", "--project_path", dest="project_path",
                  help="path to the project")
  (options, args) = parser.parse_args()

  if options.project_path is None:
    print "property project_path is mandatory, exiting ..."
    sys.exit(2)

  if not os.path.exists(options.project_path):
    print "path {} not valid".format(options.project_path)
    sys.exit(2)
  else:
    project_path=options.project_path

def yaml_load(filename):
  with open(filename, 'r') as stream:
      try:
          return (yaml.load(stream))
      except yaml.YAMLError as exc:
          print(exc)

def _check_file_exist_not_empty(current_file):
  global project_path
  global return_code
  try:
    assert(os.path.exists(current_file)), "file {} not found".format(current_file)
    assert(os.path.getsize(current_file) > 0), "file {} is empty".format(current_file)
  except (AssertionError, OSError) as e:
    return_code = 2
    print e

def check_default_files():
  global project_path

  _check_file_exist_not_empty("{}/{}".format(project_path , "ansible.cfg"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "env_vars/prod.yml"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "env_vars/preprod.yml"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "inventories/prod.ini"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "inventories/preprod.ini"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "inventories/prod.ini"))
  _check_file_exist_not_empty("{}/{}".format(project_path , "requirements.txt"))

  try:
    for filename in os.listdir("{}/plays".format(project_path)):
      _check_file_exist_not_empty("{}/plays/{}".format(project_path , filename))

  except (AssertionError, OSError) as e:
    code_return = 2
    print e

def check_env_vars():
  global project_path

  try:
    for filename in os.listdir("{}/env_vars".format(project_path)):
      current_env_file = "{}/env_vars/{}".format(project_path, filename)
      env_vars = yaml_load(current_env_file)

      if env_vars is None:
        print "file {} doesn't have any variables".format(current_env_file)
        return_code = 2
      else:
        for var_name in env_vars:
          if re.match("^env_.*", var_name) is None:
            print "{} propertie dont respect the naming convention prefix env_ into {}".format(
            var_name,
            current_env_file
            )
            return_code = 2
  except (IOError, KeyError, OSError) as e:
    print "Error: folder {}/env_vars is empty .".format(project_path)
    return_code = 2

def check_group_vars():
  global project_path

  try:
    for group_folder in os.listdir("{}/group_vars".format(project_path)):
      try:
        for group_file in os.listdir("{}/group_vars/{}".format(project_path, group_folder)):
          _check_file_exist_not_empty("{}/group_vars/{}".format(project_path, group_folder))

      except (IOError, KeyError, OSError) as e:
        print "Error: folder {}/group_vars is empty .".format(project_path)
        return_code = 2

  except (IOError, KeyError, OSError) as e:
    print "Error: folder {}/group_vars is empty .".format(project_path)
    return_code = 2

def main():
  global return_code
  return_code = 0

  check_args()
  print "Heather Say :"
  check_default_files()
  check_env_vars()
  check_group_vars()
  if return_code is 0 :
    print "Everything is fine, keep the good job :)"
  else:
   print "Now i'am sad :("

  sys.exit(return_code)

if __name__ == '__main__':
  main()

<|endoftext|>


<commit_before>import os
import re
import sys
import time
import errno
from subprocess import Popen, PIPE

from communicate import safe_communicate, OutputLimitExceeded
from error import CompileError
from .resource_proxy import ResourceProxy

try:
    from winutils import max_memory, execution_time
except ImportError:
    windows = False
    max_memory, execution_time = None, None
else:
    windows = True

recomment = re.compile(r'/\*.*?\*/', re.DOTALL)
restring = re.compile(r''''(?:\\.|[^'\\])'|"(?:\\.|[^"\\])*"''', re.DOTALL)
reinline_comment = re.compile(r'//.*?(?=[\r\n])')
reclass = re.compile(r'\bpublic\s+class\s+([_a-zA-Z\$][_0-9a-zA-z\$]*?)\b')
repackage = re.compile(r'\bpackage\s+([^.;]+(?:\.[^.;]+)*?);')
redeunicode = re.compile(r'\\u([0-9a-f]{4})', re.I)
deunicode = lambda x: redeunicode.sub(lambda a: unichr(int(a.group(1), 16)), x)
JAVA_EXECUTOR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'java_executor.jar'))

def find_class(source):
    source = reinline_comment.sub('', restring.sub('', recomment.sub('', source)))
    class_name = reclass.search(source)
    if class_name is None:
        raise CompileError('No public class: your main class must be declared as a "public class"')
    package = repackage.search(source)
    if package:
        raise CompileError('Invalid package %s: do not declare package' % package.group(1))
    return class_name

class JavaProcess(object):
    def __init__(self, java, class_name, cwd, time_limit, memory_limit, statefile, vm='client'):
        self.process = self.spawn_process(class_name, cwd, java, memory_limit, time_limit, vm)
        self.execution_time, self.tle = None, None
        self.max_memory, self.mle = None, None
        self.stderr = None
        self.error_info, self.error = None, None
        self.returncode = None
        self.feedback = None
        self.time_limit = time_limit
        self.memory_limit = memory_limit
        self.statefile = statefile
        self._killed = False
        self._start = time.time()

    def spawn_process(self, class_name, cwd, java, memory_limit, time_limit, vm):
        return Popen(self.get_command_line(class_name, cwd, memory_limit, time_limit, vm),
                     executable=java, cwd=cwd, stdin=PIPE, stdout=PIPE, stderr=PIPE,
                     env=self.get_environ(class_name, cwd, java, memory_limit, time_limit, vm))

    def get_command_line(self, class_name, cwd, memory_limit, time_limit, vm):
        return ['java', '-%s' % vm, '-Xmx%sK' % memory_limit, '-jar', JAVA_EXECUTOR, cwd,
                class_name, str(int(time_limit * 1000)), 'state']

    def get_environ(self, class_name, cwd, java, memory_limit, time_limit, vm):
        return None

    def communicate(self, stdin=None):
        output = self.process.communicate(stdin)
        self._update_stats()
        return output

    def _update_windows_stats(self):
        handle = int(self.process._handle)
        self.execution_time = execution_time(handle)
        self.tie = self.execution_time > self.time_limit
        self.max_memory = max_memory(handle) / 1024.
        self.mle = self.max_memory > self.memory_limit
        if self.returncode is None:
            self.returncode = self.process.returncode

    def _fallback_unix_stats(self):
        self.execution_time = time.time() - self._start
        self.tle = self.execution_time > self.time_limit
        self.max_memory = 0
        self.mle = 0
        self.returncode = -1

    def safe_communicate(self, stdin=None, outlimit=None, errlimit=None):
        try:
            output = safe_communicate(self.process, stdin, outlimit, errlimit)
        except OutputLimitExceeded:
            if windows:
                self._update_windows_stats()
            else:
                self._fallback_unix_stats()
            raise
        else:
            self._update_stats()
            return output

    def _update_stats(self):
        try:
            with open(self.statefile, 'r') as proc:
                self.error_info = proc.read().strip()
        except Exception:
            return
        try:
            data = self.error_info.split(None, 5)
            self.execution_time, self.tle, self.max_memory, self.mle, self.returncode = map(int, data[:5])
            self.feedback = data[5]
        except Exception:
            if not windows:
                print>> sys.stderr, self.error_info
                self._fallback_unix_stats()
                return
        if windows:
            self._update_windows_stats()
        else:
            self.execution_time /= 1000000000.0
        if self.returncode == -1:
            self.returncode = 1
        if self.feedback == 'OK':
            self.feedback = None

    def kill(self):
        self._killed = True
        return self.process.kill()

    def wait(self):
        self.process.wait()
        self._update_stats()
        return self.returncode

    def poll(self):
        if self.returncode is None:
            if self.process.poll() is None:
                return None
            self._update_stats()
        return self.returncode

    @property
    def r_execution_time(self):
        return self.execution_time

    def __getattr__(self, attr):
        return getattr(self.process, attr)

class JavaExecutor(ResourceProxy):
    ext = '.java'
    name = 'JAVA'

    vm = None
    compiler = None
    process_class = JavaProcess

    test_program = ''
    test_name = 'self_test'
    test_time = 1
    test_memory = 65536

    def __init__(self, problem_id, source_code):
        super(JavaExecutor, self).__init__()
        self.statefile = self._file('state')
        self._class_name = None
        self.warning = None
        self.create_files(problem_id, source_code)
        self.compile()

    def create_files(self, problem_id, source_code):
        self._code = self._file(problem_id + self.ext)
        with open(self._code, 'wb') as fo:
            fo.write(source_code)

    def get_compile_args(self):
        raise NotImplementedError()

    def get_compile_env(self):
        return None

    def get_compile_popen_kwargs(self):
        return {}

    def get_compile_process(self):
        kwargs = {'stderr': PIPE, 'cwd': self._dir, 'env': self.get_compile_env()}
        kwargs.update(self.get_compile_popen_kwargs())
        return Popen(self.get_compile_args(), **kwargs)

    def get_compile_output(self, process):
        return process.communicate()[1]

    def is_failed_compile(self, process):
        return process.returncode != 0

    def handle_compile_error(self, output):
        raise CompileError(output)

    def compile(self):
        process = self.get_compile_process()
        output = self.get_compile_output(process)

        if self.is_failed_compile(process):
            self.handle_compile_error(output)
        self.warning = output

    def launch(self, *args, **kwargs):
        return self.process_class(java=self.get_vm(), class_name=self._class_name, cwd=self._dir,
                                  time_limit=kwargs.get('time'), memory_limit=kwargs.get('memory'),
                                  statefile=self.statefile)

    def launch_unsafe(self, *args, **kwargs):
        return Popen(['java', '-client', self._class_name] + list(args),
                     executable=self.get_vm(), cwd=self._dir, **kwargs)

    @classmethod
    def get_vm(cls):
        return cls.vm

    @classmethod
    def get_compiler(cls):
        return cls.compiler

    @classmethod
    def initialize(cls, sandbox=True):
        if cls.get_vm() is None or cls.get_compiler() is None:
            return False
        if not os.path.isfile(cls.get_vm()) or not os.path.isfile(cls.get_compiler()):
            return False
        if not cls.test_program:
            return True

        print 'Self-testing: %s executor:' % cls.name,
        try:
            executor = cls(cls.test_name, cls.test_program)
            proc = executor.launch(time=cls.test_time, memory=cls.test_memory) \
                if sandbox else executor.launch_unsafe()
            test_message = 'echo: Hello, World!'
            stdout, stderr = proc.communicate(test_message)
            res = stdout.strip() == test_message and not stderr
            print ['Failed', 'Success'][res]
            if stderr:
                print>> sys.stderr, stderr
            return res
        except Exception:
            print 'Failed'
            import traceback
            traceback.print_exc()
            return False

class JavacExecutor(JavaExecutor):
    def create_files(self, problem_id, source_code):
        source_code = deunicode(source_code)
        class_name = find_class(source_code)
        self._code = self._file('%s.java' % class_name.group(1))
        try:
            with open(self._code, 'wb') as fo:
                fo.write(source_code)
        except IOError as e:
            if e.errno in (errno.ENAMETOOLONG, errno.ENOENT):
                raise CompileError('Why do you need a class name so long? '
                                   'As a judge, I sentence your code to death.')
            raise
        self._class_name = class_name.group(1)

    def get_compile_args(self):
        return [self.get_compiler(), self._code]

    def handle_compile_error(self, output):
        if 'is public, should be declared in a file named' in output:
            raise CompileError('You are a troll. Trolls are not welcome. '
                               'As a judge, I sentence your code to death.')
        raise CompileError(output)
<commit_msg>Only measure Java execution time when needed #147<commit_after>import os
import re
import sys
import time
import errno
from subprocess import Popen, PIPE

from communicate import safe_communicate, OutputLimitExceeded
from error import CompileError
from .resource_proxy import ResourceProxy

try:
    from winutils import max_memory, execution_time
except ImportError:
    windows = False
    max_memory, execution_time = None, None
else:
    windows = True

recomment = re.compile(r'/\*.*?\*/', re.DOTALL)
restring = re.compile(r''''(?:\\.|[^'\\])'|"(?:\\.|[^"\\])*"''', re.DOTALL)
reinline_comment = re.compile(r'//.*?(?=[\r\n])')
reclass = re.compile(r'\bpublic\s+class\s+([_a-zA-Z\$][_0-9a-zA-z\$]*?)\b')
repackage = re.compile(r'\bpackage\s+([^.;]+(?:\.[^.;]+)*?);')
redeunicode = re.compile(r'\\u([0-9a-f]{4})', re.I)
deunicode = lambda x: redeunicode.sub(lambda a: unichr(int(a.group(1), 16)), x)
JAVA_EXECUTOR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'java_executor.jar'))

def find_class(source):
    source = reinline_comment.sub('', restring.sub('', recomment.sub('', source)))
    class_name = reclass.search(source)
    if class_name is None:
        raise CompileError('No public class: your main class must be declared as a "public class"')
    package = repackage.search(source)
    if package:
        raise CompileError('Invalid package %s: do not declare package' % package.group(1))
    return class_name

class JavaProcess(object):
    def __init__(self, java, class_name, cwd, time_limit, memory_limit, statefile, vm='client'):
        self.process = self.spawn_process(class_name, cwd, java, memory_limit, time_limit, vm)
        self.execution_time, self.tle = None, None
        self.max_memory, self.mle = None, None
        self.stderr = None
        self.error_info, self.error = None, None
        self.returncode = None
        self.feedback = None
        self.time_limit = time_limit
        self.memory_limit = memory_limit
        self.statefile = statefile
        self._killed = False
        self._start = time.time()

    def spawn_process(self, class_name, cwd, java, memory_limit, time_limit, vm):
        return Popen(self.get_command_line(class_name, cwd, memory_limit, time_limit, vm),
                     executable=java, cwd=cwd, stdin=PIPE, stdout=PIPE, stderr=PIPE,
                     env=self.get_environ(class_name, cwd, java, memory_limit, time_limit, vm))

    def get_command_line(self, class_name, cwd, memory_limit, time_limit, vm):
        return ['java', '-%s' % vm, '-Xmx%sK' % memory_limit, '-jar', JAVA_EXECUTOR, cwd,
                class_name, str(int(time_limit * 1000)), 'state']

    def get_environ(self, class_name, cwd, java, memory_limit, time_limit, vm):
        return None

    def communicate(self, stdin=None):
        output = self.process.communicate(stdin)
        self._update_stats()
        return output

    def _update_windows_stats(self):
        handle = int(self.process._handle)
        if self.execution_time is None:
            self.execution_time = execution_time(handle)
        if self.tle is None:
            self.tie = self.execution_time > self.time_limit
        self.max_memory = max_memory(handle) / 1024.
        self.mle = self.max_memory > self.memory_limit
        if self.returncode is None:
            self.returncode = self.process.returncode

    def _fallback_unix_stats(self):
        self.execution_time = time.time() - self._start
        self.tle = self.execution_time > self.time_limit
        self.max_memory = 0
        self.mle = 0
        self.returncode = -1

    def safe_communicate(self, stdin=None, outlimit=None, errlimit=None):
        try:
            output = safe_communicate(self.process, stdin, outlimit, errlimit)
        except OutputLimitExceeded:
            if windows:
                self._update_windows_stats()
            else:
                self._fallback_unix_stats()
            raise
        else:
            self._update_stats()
            return output

    def _update_stats(self):
        try:
            with open(self.statefile, 'r') as proc:
                self.error_info = proc.read().strip()
        except Exception:
            return
        try:
            data = self.error_info.split(None, 5)
            self.execution_time, self.tle, self.max_memory, self.mle, self.returncode = map(int, data[:5])
            self.feedback = data[5]
        except Exception:
            if not windows:
                print>> sys.stderr, self.error_info
                self._fallback_unix_stats()
                return
        if windows:
            self._update_windows_stats()
        else:
            self.execution_time /= 1000000000.0
        if self.returncode == -1:
            self.returncode = 1
        if self.feedback == 'OK':
            self.feedback = None

    def kill(self):
        self._killed = True
        return self.process.kill()

    def wait(self):
        self.process.wait()
        self._update_stats()
        return self.returncode

    def poll(self):
        if self.returncode is None:
            if self.process.poll() is None:
                return None
            self._update_stats()
        return self.returncode

    @property
    def r_execution_time(self):
        return self.execution_time

    def __getattr__(self, attr):
        return getattr(self.process, attr)

class JavaExecutor(ResourceProxy):
    ext = '.java'
    name = 'JAVA'

    vm = None
    compiler = None
    process_class = JavaProcess

    test_program = ''
    test_name = 'self_test'
    test_time = 1
    test_memory = 65536

    def __init__(self, problem_id, source_code):
        super(JavaExecutor, self).__init__()
        self.statefile = self._file('state')
        self._class_name = None
        self.warning = None
        self.create_files(problem_id, source_code)
        self.compile()

    def create_files(self, problem_id, source_code):
        self._code = self._file(problem_id + self.ext)
        with open(self._code, 'wb') as fo:
            fo.write(source_code)

    def get_compile_args(self):
        raise NotImplementedError()

    def get_compile_env(self):
        return None

    def get_compile_popen_kwargs(self):
        return {}

    def get_compile_process(self):
        kwargs = {'stderr': PIPE, 'cwd': self._dir, 'env': self.get_compile_env()}
        kwargs.update(self.get_compile_popen_kwargs())
        return Popen(self.get_compile_args(), **kwargs)

    def get_compile_output(self, process):
        return process.communicate()[1]

    def is_failed_compile(self, process):
        return process.returncode != 0

    def handle_compile_error(self, output):
        raise CompileError(output)

    def compile(self):
        process = self.get_compile_process()
        output = self.get_compile_output(process)

        if self.is_failed_compile(process):
            self.handle_compile_error(output)
        self.warning = output

    def launch(self, *args, **kwargs):
        return self.process_class(java=self.get_vm(), class_name=self._class_name, cwd=self._dir,
                                  time_limit=kwargs.get('time'), memory_limit=kwargs.get('memory'),
                                  statefile=self.statefile)

    def launch_unsafe(self, *args, **kwargs):
        return Popen(['java', '-client', self._class_name] + list(args),
                     executable=self.get_vm(), cwd=self._dir, **kwargs)

    @classmethod
    def get_vm(cls):
        return cls.vm

    @classmethod
    def get_compiler(cls):
        return cls.compiler

    @classmethod
    def initialize(cls, sandbox=True):
        if cls.get_vm() is None or cls.get_compiler() is None:
            return False
        if not os.path.isfile(cls.get_vm()) or not os.path.isfile(cls.get_compiler()):
            return False
        if not cls.test_program:
            return True

        print 'Self-testing: %s executor:' % cls.name,
        try:
            executor = cls(cls.test_name, cls.test_program)
            proc = executor.launch(time=cls.test_time, memory=cls.test_memory) \
                if sandbox else executor.launch_unsafe()
            test_message = 'echo: Hello, World!'
            stdout, stderr = proc.communicate(test_message)
            res = stdout.strip() == test_message and not stderr
            print ['Failed', 'Success'][res]
            if stderr:
                print>> sys.stderr, stderr
            return res
        except Exception:
            print 'Failed'
            import traceback
            traceback.print_exc()
            return False

class JavacExecutor(JavaExecutor):
    def create_files(self, problem_id, source_code):
        source_code = deunicode(source_code)
        class_name = find_class(source_code)
        self._code = self._file('%s.java' % class_name.group(1))
        try:
            with open(self._code, 'wb') as fo:
                fo.write(source_code)
        except IOError as e:
            if e.errno in (errno.ENAMETOOLONG, errno.ENOENT):
                raise CompileError('Why do you need a class name so long? '
                                   'As a judge, I sentence your code to death.')
            raise
        self._class_name = class_name.group(1)

    def get_compile_args(self):
        return [self.get_compiler(), self._code]

    def handle_compile_error(self, output):
        if 'is public, should be declared in a file named' in output:
            raise CompileError('You are a troll. Trolls are not welcome. '
                               'As a judge, I sentence your code to death.')
        raise CompileError(output)
<|endoftext|>


<commit_before>#! /usr/bin/env python3.6
# coding: utf-8
from gargbot_3000.logger import log
import json

import requests
from flask import Flask, request, g, Response

from gargbot_3000 import config
from gargbot_3000 import commands
from gargbot_3000 import database_manager
from gargbot_3000 import quotes
from gargbot_3000 import droppics

app = Flask(__name__)

def get_db():
    db_connection = getattr(g, '_database', None)
    if db_connection is None:
        db_connection = database_manager.connect_to_database()
        g._database = db_connection
    return db_connection

@app.teardown_appcontext
def close_connection(exception):
    db_connection = getattr(g, '_database', None)
    if db_connection is not None:
        db_connection.close()

def attach_buttons(callback_id, result, func, args):
    actions = [
            {
                "name": "share",
                "text": "Del i kanal",
                "type": "button",
                "style": "primary",
                "value": json.dumps({"original_response": result})
            },
            {
                "name": "shuffle",
                "text": "Shuffle",
                "type": "button",
                "value": json.dumps({"original_func": func, "original_args": args})
            },
            {
                "name": "cancel",
                "text": "Avbryt",
                "value": "avbryt",
                "type": "button",
                "style": "danger"
            },
    ]
    try:
        attachment = result["attachments"][-1]
    except KeyError:
        attachment = {}
        result["attachments"] = [attachment]
    attachment["actions"] = actions
    attachment["callback_id"] = callback_id
    return result

@app.route('/')
def hello_world() -> str:
    return "home"

@app.route('/interactive', methods=['POST'])
def interactive():
    log.info("incoming interactive request:")
    data = json.loads(request.form['payload'])
    log.info(data)
    if not data.get('token') == config.v2_verification_token:
        return Response(status=403)
    action = data["actions"][0]["name"]

    if action == "share":
        log.info("Interactive: share")
        response_url = data["response_url"]
        delete_original = {
            "response_type": "ephemeral",
            "replace_original": True,
            "text": "Sharing is caring!"
        }
        r = requests.post(response_url, json=delete_original)
        log.info(r.text)

        result = json.loads(data["actions"][0]["value"])["original_response"]
        result['replace_original'] = False
        result["response_type"] = "in_channel"

    elif action == "cancel":
        log.info("Interactive: cancel")
        result = {
            "response_type": "ephemeral",
            "replace_original": True,
            "text": "Canceled! Går fint det. Ikke noe problem for meg. Hadde ikke lyst uansett."
        }

    elif action == "shuffle":
        log.info("Interactive: shuffle")
        command_str = json.loads(data["actions"][0]["value"])["original_func"]
        args = json.loads(data["actions"][0]["value"])["original_args"]
        callback_id = data["callback_id"]
        result = get_and_execute_command(command_str, args, callback_id)
        result["replace_original"] = True

    log.info(f"result: {result}")
    return Response(
        response=json.dumps(result),
        status=200,
        mimetype='application/json'
    )

@app.route('/slash', methods=['POST'])
def slash_cmds():
    log.info("incoming slash request:")
    data = request.form
    log.info(data)

    if not data.get('token') == config.v2_verification_token:
        return Response(status=403)

    command_str = data["command"][1:]
    args = data['text'].split()
    trigger_id = data["trigger_id"]

    result = get_and_execute_command(command_str, args, trigger_id)

    log.info(f"result: {result}")
    return Response(
        response=json.dumps(result),
        status=200,
        mimetype='application/json'
    )

def get_and_execute_command(command_str, args, callback_id):
    log.info(f"command: {command_str}")
    log.info(f"args: {args}")

    try:
        command_function = commands.command_switch[command_str]
    except KeyError:
        command_function = commands.cmd_not_found
        args = [command_str]

    if command_str in {"msn", "quote", "pic"}:
        db_connection = get_db()
        command_function.keywords["db"] = db_connection

    result = commands.try_or_panic(command_function, args)
    result["response_type"] = "ephemeral"
    if not result.get("text", "").startswith("Error"):
        result = attach_buttons(
            callback_id=callback_id,
            result=result,
            func=command_str,
            args=args
        )
    return result

def setup():
    db_connection = database_manager.connect_to_database()
    quotes_db = quotes.Quotes(db=db_connection)
    commands.command_switch["msn"].keywords["quotes_db"] = quotes_db
    commands.command_switch["quote"].keywords["quotes_db"] = quotes_db

    drop_pics = droppics.DropPics(db=db_connection)
    drop_pics.connect_dbx()
    commands.command_switch["pic"].keywords["drop_pics"] = drop_pics

def main():
    setup()
    log.info("GargBot 3000 server operational!")
    # app.run() uwsgi does this
    pass

if __name__ == '__main__':
    main()
<commit_msg>hvem always in_channel, resp with btn alwas ephemeral<commit_after>#! /usr/bin/env python3.6
# coding: utf-8
from gargbot_3000.logger import log
import json

import requests
from flask import Flask, request, g, Response

from gargbot_3000 import config
from gargbot_3000 import commands
from gargbot_3000 import database_manager
from gargbot_3000 import quotes
from gargbot_3000 import droppics

app = Flask(__name__)

def get_db():
    db_connection = getattr(g, '_database', None)
    if db_connection is None:
        db_connection = database_manager.connect_to_database()
        g._database = db_connection
    return db_connection

@app.teardown_appcontext
def close_connection(exception):
    db_connection = getattr(g, '_database', None)
    if db_connection is not None:
        db_connection.close()

def attach_buttons(callback_id, result, func, args):
    actions = [
            {
                "name": "share",
                "text": "Del i kanal",
                "type": "button",
                "style": "primary",
                "value": json.dumps({"original_response": result})
            },
            {
                "name": "shuffle",
                "text": "Shuffle",
                "type": "button",
                "value": json.dumps({"original_func": func, "original_args": args})
            },
            {
                "name": "cancel",
                "text": "Avbryt",
                "value": "avbryt",
                "type": "button",
                "style": "danger"
            },
    ]
    try:
        attachment = result["attachments"][-1]
    except KeyError:
        attachment = {}
        result["attachments"] = [attachment]
    attachment["actions"] = actions
    attachment["callback_id"] = callback_id
    result["response_type"] = "ephemeral"
    return result

@app.route('/')
def hello_world() -> str:
    return "home"

@app.route('/interactive', methods=['POST'])
def interactive():
    log.info("incoming interactive request:")
    data = json.loads(request.form['payload'])
    log.info(data)
    if not data.get('token') == config.v2_verification_token:
        return Response(status=403)
    action = data["actions"][0]["name"]

    if action == "share":
        log.info("Interactive: share")
        response_url = data["response_url"]
        delete_original = {
            "response_type": "ephemeral",
            "replace_original": True,
            "text": "Sharing is caring!"
        }
        r = requests.post(response_url, json=delete_original)
        log.info(r.text)

        result = json.loads(data["actions"][0]["value"])["original_response"]
        result['replace_original'] = False
        result["response_type"] = "in_channel"

    elif action == "cancel":
        log.info("Interactive: cancel")
        result = {
            "response_type": "ephemeral",
            "replace_original": True,
            "text": "Canceled! Går fint det. Ikke noe problem for meg. Hadde ikke lyst uansett."
        }

    elif action == "shuffle":
        log.info("Interactive: shuffle")
        command_str = json.loads(data["actions"][0]["value"])["original_func"]
        args = json.loads(data["actions"][0]["value"])["original_args"]
        callback_id = data["callback_id"]
        result = get_and_execute_command(command_str, args, callback_id)
        result["replace_original"] = True

    log.info(f"result: {result}")
    return Response(
        response=json.dumps(result),
        status=200,
        mimetype='application/json'
    )

@app.route('/slash', methods=['POST'])
def slash_cmds():
    log.info("incoming slash request:")
    data = request.form
    log.info(data)

    if not data.get('token') == config.v2_verification_token:
        return Response(status=403)

    command_str = data["command"][1:]
    args = data['text'].split()
    trigger_id = data["trigger_id"]

    result = get_and_execute_command(command_str, args, trigger_id)

    log.info(f"result: {result}")
    return Response(
        response=json.dumps(result),
        status=200,
        mimetype='application/json'
    )

def get_and_execute_command(command_str, args, callback_id):
    log.info(f"command: {command_str}")
    log.info(f"args: {args}")

    try:
        command_function = commands.command_switch[command_str]
    except KeyError:
        command_function = commands.cmd_not_found
        args = [command_str]

    if command_str in {"msn", "quote", "pic"}:
        db_connection = get_db()
        command_function.keywords["db"] = db_connection

    result = commands.try_or_panic(command_function, args)
    error = result.get("text", "").startswith("Error")
    if command_str in {"hvem"} and error is False:
        result["response_type"] = "in_channel"
    elif error is False:
        result = attach_buttons(
            callback_id=callback_id,
            result=result,
            func=command_str,
            args=args
        )
    return result

def setup():
    db_connection = database_manager.connect_to_database()
    quotes_db = quotes.Quotes(db=db_connection)
    commands.command_switch["msn"].keywords["quotes_db"] = quotes_db
    commands.command_switch["quote"].keywords["quotes_db"] = quotes_db

    drop_pics = droppics.DropPics(db=db_connection)
    drop_pics.connect_dbx()
    commands.command_switch["pic"].keywords["drop_pics"] = drop_pics

def main():
    setup()
    log.info("GargBot 3000 server operational!")
    # app.run() uwsgi does this
    pass

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>'''
The management of salt command line utilities are stored in here
'''
# Import python libs
import optparse
import os
import sys
import yaml
JSON = False
try:
    import json
    JSON = True
except:
    pass

# Import salt components
import salt.client
import salt.cli.key
import salt.cli.cp
import salt.cli.caller

class SaltCMD(object):
    '''
    The execution of a salt command happens here
    '''
    def __init__(self):
        '''
        Create a SaltCMD object
        '''
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line
        '''
        parser = optparse.OptionParser()

        parser.add_option('-t',
                '--timeout',
                default=5,
                type=int,
                dest='timeout',
                help='Set the return timeout for batch jobs; default=5 seconds')
        parser.add_option('-E',
                '--pcre',
                default=False,
                dest='pcre',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, use pcre regular expressions')
        parser.add_option('-L',
                '--list',
                default=False,
                dest='list_',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, take a comma delimited list of servers.')
        parser.add_option('-G',
                '--grain',
                default=False,
                dest='grain',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' use a grain value to identify targets, the syntax'\
                   + ' for the target is the grain key followed by a pcre'\
                   + ' regular expression:\n"os:Arch.*"')
        parser.add_option('-X',
                '--exsel',
                default=False,
                dest='exsel',
                action='store_true',
                help='Instead of using shell globs use the return code'\
                   + ' of a function.')
        parser.add_option('--return',
                default='',
                dest='return_',
                help='Set an alternative return method. By default salt will'\
                    + ' send the return data from the command back to the'\
                    + ' master, but the return data can be redirected into'\
                    + ' any number of systems, databases or applications.')
        parser.add_option('-Q',
                '--query',
                dest='query',
                default=False,
                action='store_true',
                help='Execute a salt command query, this can be used to find'\
                    + ' the results os a previous function call: -Q test.echo')
        parser.add_option('-c',
                '--config',
                default='/etc/salt/master',
                dest='conf_file',
                help='The location of the salt master configuration file,'\
                    + ' the salt master settings are required to know where'\
                    + ' the connections are; default=/etc/salt/master')
        parser.add_option('--raw-out',
                default=False,
                action='store_true',
                dest='raw_out',
                help='Print the output from the salt command in raw python'\
                   + ' form, this is suitable for re-reading the output into'\
                   + ' an executing python script with eval.')
        if JSON:
            parser.add_option('--json-out',
                    default=False,
                    action='store_true',
                    dest='json_out',
                    help='Print the output from the salt command in json.')

        options, args = parser.parse_args()

        opts = {}

        opts['timeout'] = options.timeout
        opts['pcre'] = options.pcre
        opts['list'] = options.list_
        opts['grain'] = options.grain
        opts['exsel'] = options.exsel
        opts['return'] = options.return_
        opts['conf_file'] = options.conf_file
        opts['raw_out'] = options.raw_out
        if JSON:
            opts['json_out'] = options.json_out
        else:
            opts['json_out'] = False

        if opts['return']:
            if opts['timeout'] == 5:
                opts['timeout'] = 0

        if options.query:
            opts['query'] = options.query
            if len(args) < 1:
                err = 'Please pass in a command to query the old salt calls'\
                    + ' for.'
                sys.stderr.write(err, + '\n')
                sys.exit('2')
            opts['cmd'] = args[0]
        else:
            if opts['list']:
                opts['tgt'] = args[0].split(',')
            else:
                opts['tgt'] = args[0]
            if args[1].count(','):
                opts['fun'] = args[1].split(',')
                opts['arg'] = []
                for comp in ' '.join(args[2:]).split(','):
                    opts['arg'].append(comp.split())
                if len(opts['fun']) != len(opts['arg']):
                    err = 'Cannot execute compound command without defining'\
                        + ' all arguments.'
                    sys.stderr.write(err + '\n')
                    sys.exit(42)
            else:
                opts['fun'] = args[1]
                opts['arg'] = args[2:]

        return opts

    def run(self):
        '''
        Execute the salt command line
        '''
        local = salt.client.LocalClient(self.opts['conf_file'])
        if self.opts.has_key('query'):
            print local.find_cmd(self.opts['cmd'])
        else:
            args = [self.opts['tgt'],
                    self.opts['fun'],
                    self.opts['arg'],
                    self.opts['timeout'],
                    ]
            if self.opts['pcre']:
                args.append('pcre')
            elif self.opts['list']:
                args.append('list')
            elif self.opts['grain']:
                args.append('grain')
            elif self.opts['exsel']:
                args.append('exsel')
            else:
                args.append('glob')

            if self.opts['return']:
                args.append(self.opts['return'])
            ret = local.cmd(*args)

            # Handle special case commands
            if self.opts['fun'] == 'sys.doc':
                self._print_docs(ret)
            else:
                if type(ret) == type(list()) or type(ret) == type(dict()):
                    if self.opts['raw_out']:
                        print ret
                    elif self.opts['json_out']:
                        print json.dumps(ret)
                    else:
                        print yaml.dump(ret)

    def _print_docs(self, ret):
        '''
        Print out the docstrings for all of the functions on the minions
        '''
        docs = {}
        for host in ret:
            for fun in ret[host]:
                if not docs.has_key(fun):
                    if ret[host][fun]:
                        docs[fun] = ret[host][fun]
        for fun in sorted(docs):
            print fun + ':'
            print docs[fun]
            print ''

class SaltCP(object):
    '''
    Run the salt-cp command line client
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line
        '''
        parser = optparse.OptionParser()

        parser.add_option('-t',
                '--timeout',
                default=5,
                type=int,
                dest='timeout',
                help='Set the return timeout for batch jobs; default=5 seconds')
        parser.add_option('-E',
                '--pcre',
                default=False,
                dest='pcre',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, use pcre regular expressions')
        parser.add_option('-L',
                '--list',
                default=False,
                dest='list_',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, take a comma delimited list of servers.')
        parser.add_option('-G',
                '--grain',
                default=False,
                dest='grain',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' use a grain value to identify targets, the syntax'\
                   + ' for the target is the grains key followed by a pcre'\
                   + ' regular expression:\n"os:Arch.*"')
        parser.add_option('-c',
                '--config',
                default='/etc/salt/master',
                dest='conf_file',
                help='The location of the salt master configuration file,'\
                    + ' the salt master settings are required to know where'\
                    + ' the connections are; default=/etc/salt/master')

        options, args = parser.parse_args()

        opts = {}

        opts['timeout'] = options.timeout
        opts['pcre'] = options.pcre
        opts['list'] = options.list_
        opts['grain'] = options.grain
        opts['conf_file'] = options.conf_file

        if opts['list']:
            opts['tgt'] = args[0].split(',')
        else:
            opts['tgt'] = args[0]
        opts['src'] = args[1:-1]
        opts['dest'] = args[-1]

        return opts

    def run(self):
        '''
        Execute salt-cp
        '''
        cp_ = salt.cli.cp.SaltCP(self.opts)
        cp_.run()

class SaltKey(object):
    '''
    Initialize the Salt key manager
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line options for the salt key
        '''
        parser = optparse.OptionParser()

        parser.add_option('-l',
                '--list',
                dest='list_',
                default=False,
                action='store_true',
                help='List the unaccepted public keys')

        parser.add_option('-L',
                '--list-all',
                dest='list_all',
                default=False,
                action='store_true',
                help='List all public keys')

        parser.add_option('-a',
                '--accept',
                dest='accept',
                default='',
                help='Accept the following key')

        parser.add_option('-A',
                '--accept-all',
                dest='accept_all',
                default=False,
                action='store_true',
                help='Accept all pending keys')

        parser.add_option('-p',
                '--print',
                dest='print_',
                default='',
                help='Print the specified public key')

        parser.add_option('-P',
                '--print-all',
                dest='print_all',
                default=False,
                action='store_true',
                help='Print all public keys')

        parser.add_option('-d',
                '--delete',
                dest='delete',
                default='',
                help='Delete the named key')

        parser.add_option('-c',
                '--config',
                dest='config',
                default='/etc/salt/master',
                help='Pass in an alternative configuration file')

        options, args = parser.parse_args()

        opts = {}

        opts['list'] = options.list_
        opts['list_all'] = options.list_all
        opts['accept'] = options.accept
        opts['accept_all'] = options.accept_all
        opts['print'] = options.print_
        opts['print_all'] = options.print_all
        opts['delete'] = options.delete

        opts.update(salt.config.master_config(options.config))

        return opts

    def run(self):
        '''
        Execute saltkey
        '''
        key = salt.cli.key.Key(self.opts)
        key.run()

class SaltCall(object):
    '''
    Used to locally execute a salt command
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line arguments
        '''
        parser = optparse.OptionParser()

        parser.add_option('-g',
                '--grains',
                dest='grains',
                default=False,
                action='store_true',
                help='Return the information generated by the salt grains')
        parser.add_option('-m',
                '--module-dirs',
                dest='module_dirs',
                default='',
                help='Specify an additional directories to pull modules from,'\
                    + ' multiple directories can be delimited by commas')
        parser.add_option('-d',
                '--doc',
                dest='doc',
                default=False,
                action='store_true',
                help="Return the documentation for the specified module of'\
                    + ' for all modules if none are specified")

        options, args = parser.parse_args()

        opts = {}

        opts['grains'] = options.grains
        opts['module_dirs'] = options.module_dirs.split(',')
        opts['doc'] = options.doc
        if len(args) >= 1:
            opts['fun'] = args[0]
            opts['arg'] = args[1:]
        else:
            opts['fun'] = ''
            opts['arg'] = []

        return opts

    def run(self):
        '''
        Execute the salt call!
        '''
        caller = salt.cli.caller.Caller(self.opts)
        caller.run()

class SaltRun(object):
    '''
    Used to execute salt convenience functions
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line arguments
        '''
        parser = optparse.OptionParser()

        parser.add_option('-c',
                '--config',
                dest='config',
                default='/etc/salt/master',
                help='Change the location of the master configuration;'\
                    + ' default=/etc/salt/master')

        options, args = parser.parse_args()

        opts = {}

        opts['config'] = options.config

        if len(args > 0):
            opts['fun'] = args[0]
        else:
            opts['fun'] = ''
        if len(args > 1):
            opts['arg'] = args[1:]
        else:
            opts['arg'] = []

        opts.update(salt.config.master_config(options.config))

        return opts

    def run(self):
        '''
        Execute the salt call!
        '''
        runner = salt.runner.Runner(self.opts)
        runner.run()
<commit_msg>Fix salt-run issues in the cli frontend<commit_after>'''
The management of salt command line utilities are stored in here
'''
# Import python libs
import optparse
import os
import sys
import yaml
JSON = False
try:
    import json
    JSON = True
except:
    pass

# Import salt components
import salt.client
import salt.runner
import salt.cli.key
import salt.cli.cp
import salt.cli.caller

class SaltCMD(object):
    '''
    The execution of a salt command happens here
    '''
    def __init__(self):
        '''
        Create a SaltCMD object
        '''
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line
        '''
        parser = optparse.OptionParser()

        parser.add_option('-t',
                '--timeout',
                default=5,
                type=int,
                dest='timeout',
                help='Set the return timeout for batch jobs; default=5 seconds')
        parser.add_option('-E',
                '--pcre',
                default=False,
                dest='pcre',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, use pcre regular expressions')
        parser.add_option('-L',
                '--list',
                default=False,
                dest='list_',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, take a comma delimited list of servers.')
        parser.add_option('-G',
                '--grain',
                default=False,
                dest='grain',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' use a grain value to identify targets, the syntax'\
                   + ' for the target is the grain key followed by a pcre'\
                   + ' regular expression:\n"os:Arch.*"')
        parser.add_option('-X',
                '--exsel',
                default=False,
                dest='exsel',
                action='store_true',
                help='Instead of using shell globs use the return code'\
                   + ' of a function.')
        parser.add_option('--return',
                default='',
                dest='return_',
                help='Set an alternative return method. By default salt will'\
                    + ' send the return data from the command back to the'\
                    + ' master, but the return data can be redirected into'\
                    + ' any number of systems, databases or applications.')
        parser.add_option('-Q',
                '--query',
                dest='query',
                default=False,
                action='store_true',
                help='Execute a salt command query, this can be used to find'\
                    + ' the results os a previous function call: -Q test.echo')
        parser.add_option('-c',
                '--config',
                default='/etc/salt/master',
                dest='conf_file',
                help='The location of the salt master configuration file,'\
                    + ' the salt master settings are required to know where'\
                    + ' the connections are; default=/etc/salt/master')
        parser.add_option('--raw-out',
                default=False,
                action='store_true',
                dest='raw_out',
                help='Print the output from the salt command in raw python'\
                   + ' form, this is suitable for re-reading the output into'\
                   + ' an executing python script with eval.')
        if JSON:
            parser.add_option('--json-out',
                    default=False,
                    action='store_true',
                    dest='json_out',
                    help='Print the output from the salt command in json.')

        options, args = parser.parse_args()

        opts = {}

        opts['timeout'] = options.timeout
        opts['pcre'] = options.pcre
        opts['list'] = options.list_
        opts['grain'] = options.grain
        opts['exsel'] = options.exsel
        opts['return'] = options.return_
        opts['conf_file'] = options.conf_file
        opts['raw_out'] = options.raw_out
        if JSON:
            opts['json_out'] = options.json_out
        else:
            opts['json_out'] = False

        if opts['return']:
            if opts['timeout'] == 5:
                opts['timeout'] = 0

        if options.query:
            opts['query'] = options.query
            if len(args) < 1:
                err = 'Please pass in a command to query the old salt calls'\
                    + ' for.'
                sys.stderr.write(err, + '\n')
                sys.exit('2')
            opts['cmd'] = args[0]
        else:
            if opts['list']:
                opts['tgt'] = args[0].split(',')
            else:
                opts['tgt'] = args[0]
            if args[1].count(','):
                opts['fun'] = args[1].split(',')
                opts['arg'] = []
                for comp in ' '.join(args[2:]).split(','):
                    opts['arg'].append(comp.split())
                if len(opts['fun']) != len(opts['arg']):
                    err = 'Cannot execute compound command without defining'\
                        + ' all arguments.'
                    sys.stderr.write(err + '\n')
                    sys.exit(42)
            else:
                opts['fun'] = args[1]
                opts['arg'] = args[2:]

        return opts

    def run(self):
        '''
        Execute the salt command line
        '''
        local = salt.client.LocalClient(self.opts['conf_file'])
        if self.opts.has_key('query'):
            print local.find_cmd(self.opts['cmd'])
        else:
            args = [self.opts['tgt'],
                    self.opts['fun'],
                    self.opts['arg'],
                    self.opts['timeout'],
                    ]
            if self.opts['pcre']:
                args.append('pcre')
            elif self.opts['list']:
                args.append('list')
            elif self.opts['grain']:
                args.append('grain')
            elif self.opts['exsel']:
                args.append('exsel')
            else:
                args.append('glob')

            if self.opts['return']:
                args.append(self.opts['return'])
            ret = local.cmd(*args)

            # Handle special case commands
            if self.opts['fun'] == 'sys.doc':
                self._print_docs(ret)
            else:
                if type(ret) == type(list()) or type(ret) == type(dict()):
                    if self.opts['raw_out']:
                        print ret
                    elif self.opts['json_out']:
                        print json.dumps(ret)
                    else:
                        print yaml.dump(ret)

    def _print_docs(self, ret):
        '''
        Print out the docstrings for all of the functions on the minions
        '''
        docs = {}
        for host in ret:
            for fun in ret[host]:
                if not docs.has_key(fun):
                    if ret[host][fun]:
                        docs[fun] = ret[host][fun]
        for fun in sorted(docs):
            print fun + ':'
            print docs[fun]
            print ''

class SaltCP(object):
    '''
    Run the salt-cp command line client
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line
        '''
        parser = optparse.OptionParser()

        parser.add_option('-t',
                '--timeout',
                default=5,
                type=int,
                dest='timeout',
                help='Set the return timeout for batch jobs; default=5 seconds')
        parser.add_option('-E',
                '--pcre',
                default=False,
                dest='pcre',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, use pcre regular expressions')
        parser.add_option('-L',
                '--list',
                default=False,
                dest='list_',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' servers, take a comma delimited list of servers.')
        parser.add_option('-G',
                '--grain',
                default=False,
                dest='grain',
                action='store_true',
                help='Instead of using shell globs to evaluate the target'\
                   + ' use a grain value to identify targets, the syntax'\
                   + ' for the target is the grains key followed by a pcre'\
                   + ' regular expression:\n"os:Arch.*"')
        parser.add_option('-c',
                '--config',
                default='/etc/salt/master',
                dest='conf_file',
                help='The location of the salt master configuration file,'\
                    + ' the salt master settings are required to know where'\
                    + ' the connections are; default=/etc/salt/master')

        options, args = parser.parse_args()

        opts = {}

        opts['timeout'] = options.timeout
        opts['pcre'] = options.pcre
        opts['list'] = options.list_
        opts['grain'] = options.grain
        opts['conf_file'] = options.conf_file

        if opts['list']:
            opts['tgt'] = args[0].split(',')
        else:
            opts['tgt'] = args[0]
        opts['src'] = args[1:-1]
        opts['dest'] = args[-1]

        return opts

    def run(self):
        '''
        Execute salt-cp
        '''
        cp_ = salt.cli.cp.SaltCP(self.opts)
        cp_.run()

class SaltKey(object):
    '''
    Initialize the Salt key manager
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line options for the salt key
        '''
        parser = optparse.OptionParser()

        parser.add_option('-l',
                '--list',
                dest='list_',
                default=False,
                action='store_true',
                help='List the unaccepted public keys')

        parser.add_option('-L',
                '--list-all',
                dest='list_all',
                default=False,
                action='store_true',
                help='List all public keys')

        parser.add_option('-a',
                '--accept',
                dest='accept',
                default='',
                help='Accept the following key')

        parser.add_option('-A',
                '--accept-all',
                dest='accept_all',
                default=False,
                action='store_true',
                help='Accept all pending keys')

        parser.add_option('-p',
                '--print',
                dest='print_',
                default='',
                help='Print the specified public key')

        parser.add_option('-P',
                '--print-all',
                dest='print_all',
                default=False,
                action='store_true',
                help='Print all public keys')

        parser.add_option('-d',
                '--delete',
                dest='delete',
                default='',
                help='Delete the named key')

        parser.add_option('-c',
                '--config',
                dest='config',
                default='/etc/salt/master',
                help='Pass in an alternative configuration file')

        options, args = parser.parse_args()

        opts = {}

        opts['list'] = options.list_
        opts['list_all'] = options.list_all
        opts['accept'] = options.accept
        opts['accept_all'] = options.accept_all
        opts['print'] = options.print_
        opts['print_all'] = options.print_all
        opts['delete'] = options.delete

        opts.update(salt.config.master_config(options.config))

        return opts

    def run(self):
        '''
        Execute saltkey
        '''
        key = salt.cli.key.Key(self.opts)
        key.run()

class SaltCall(object):
    '''
    Used to locally execute a salt command
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line arguments
        '''
        parser = optparse.OptionParser()

        parser.add_option('-g',
                '--grains',
                dest='grains',
                default=False,
                action='store_true',
                help='Return the information generated by the salt grains')
        parser.add_option('-m',
                '--module-dirs',
                dest='module_dirs',
                default='',
                help='Specify an additional directories to pull modules from,'\
                    + ' multiple directories can be delimited by commas')
        parser.add_option('-d',
                '--doc',
                dest='doc',
                default=False,
                action='store_true',
                help="Return the documentation for the specified module of'\
                    + ' for all modules if none are specified")

        options, args = parser.parse_args()

        opts = {}

        opts['grains'] = options.grains
        opts['module_dirs'] = options.module_dirs.split(',')
        opts['doc'] = options.doc
        if len(args) >= 1:
            opts['fun'] = args[0]
            opts['arg'] = args[1:]
        else:
            opts['fun'] = ''
            opts['arg'] = []

        return opts

    def run(self):
        '''
        Execute the salt call!
        '''
        caller = salt.cli.caller.Caller(self.opts)
        caller.run()

class SaltRun(object):
    '''
    Used to execute salt convenience functions
    '''
    def __init__(self):
        self.opts = self.__parse()

    def __parse(self):
        '''
        Parse the command line arguments
        '''
        parser = optparse.OptionParser()

        parser.add_option('-c',
                '--config',
                dest='config',
                default='/etc/salt/master',
                help='Change the location of the master configuration;'\
                    + ' default=/etc/salt/master')

        options, args = parser.parse_args()

        opts = {}

        opts['config'] = options.config

        if len(args) > 0:
            opts['fun'] = args[0]
        else:
            opts['fun'] = ''
        if len(args) > 1:
            opts['arg'] = args[1:]
        else:
            opts['arg'] = []

        opts.update(salt.config.master_config(options.config))

        return opts

    def run(self):
        '''
        Execute the salt call!
        '''
        runner = salt.runner.Runner(self.opts)
        runner.run()
<|endoftext|>