code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command-line tools for authenticating via OAuth 1.0
Do the OAuth 1.0 Three Legged Dance for
a command line application. Stores the generated
credentials in a common file that is used by
other example apps in the same directory.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = ["run"]
import BaseHTTPServer
import gflags
import logging
import socket
import sys
from optparse import OptionParser
from apiclient.oauth import RequestError
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('auth_local_webserver', True,
('Run a local web server to handle redirects during '
'OAuth authorization.'))
gflags.DEFINE_string('auth_host_name', 'localhost',
('Host name to use when running a local web server to '
'handle redirects during OAuth authorization.'))
gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
('Port to use when running a local web server to '
'handle redirects during OAuth authorization.'))
class ClientRedirectServer(BaseHTTPServer.HTTPServer):
"""A server to handle OAuth 1.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into query_params and then stops serving.
"""
query_params = {}
class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""A handler for OAuth 1.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into the servers query_params and then stops serving.
"""
def do_GET(s):
"""Handle a GET request
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
def log_message(self, format, *args):
"""Do not log messages to stdout while running as command line program."""
pass
def run(flow, storage):
"""Core code for a command-line application.
Args:
flow: Flow, an OAuth 1.0 Flow to step through.
storage: Storage, a Storage to store the credential in.
Returns:
Credentials, the obtained credential.
Exceptions:
RequestError: if step2 of the flow fails.
Args:
"""
if FLAGS.auth_local_webserver:
success = False
port_number = 0
for port in FLAGS.auth_host_port:
port_number = port
try:
httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port),
ClientRedirectHandler)
except socket.error, e:
pass
else:
success = True
break
FLAGS.auth_local_webserver = success
if FLAGS.auth_local_webserver:
oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
else:
oauth_callback = 'oob'
authorize_url = flow.step1_get_authorize_url(oauth_callback)
print 'Go to the following link in your browser:'
print authorize_url
print
if FLAGS.auth_local_webserver:
print 'If your browser is on a different machine then exit and re-run this'
print 'application with the command-line parameter --noauth_local_webserver.'
print
if FLAGS.auth_local_webserver:
httpd.handle_request()
if 'error' in httpd.query_params:
sys.exit('Authentication request was rejected.')
if 'oauth_verifier' in httpd.query_params:
code = httpd.query_params['oauth_verifier']
else:
accepted = 'n'
while accepted.lower() == 'n':
accepted = raw_input('Have you authorized me? (y/n) ')
code = raw_input('What is the verification code? ').strip()
try:
credentials = flow.step2_exchange(code)
except RequestError:
sys.exit('The authentication has failed.')
storage.put(credentials)
credentials.set_store(storage.put)
print "You have successfully authenticated."
return credentials
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Errors for the library.
All exceptions defined by the library
should be defined in this file.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from anyjson import simplejson
class Error(Exception):
"""Base error for this module."""
pass
class HttpError(Error):
"""HTTP data was invalid or unexpected."""
def __init__(self, resp, content, uri=None):
self.resp = resp
self.content = content
self.uri = uri
def _get_reason(self):
"""Calculate the reason for the error from the response content."""
if self.resp.get('content-type', '').startswith('application/json'):
try:
data = simplejson.loads(self.content)
reason = data['error']['message']
except (ValueError, KeyError):
reason = self.content
else:
reason = self.resp.reason
return reason
def __repr__(self):
if self.uri:
return '<HttpError %s when requesting %s returned "%s">' % (
self.resp.status, self.uri, self._get_reason())
else:
return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
__str__ = __repr__
class InvalidJsonError(Error):
"""The JSON returned could not be parsed."""
pass
class UnknownLinkType(Error):
"""Link type unknown or unexpected."""
pass
class UnknownApiNameOrVersion(Error):
"""No API with that name and version exists."""
pass
class UnacceptableMimeTypeError(Error):
"""That is an unacceptable mimetype for this operation."""
pass
class MediaUploadSizeError(Error):
"""Media is larger than the method can accept."""
pass
class ResumableUploadError(Error):
"""Error occured during resumable upload."""
pass
class BatchError(Error):
"""Error occured during batch operations."""
pass
class UnexpectedMethodError(Error):
"""Exception raised by RequestMockBuilder on unexpected calls."""
def __init__(self, methodId=None):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedMethodError, self).__init__(
'Received unexpected call %s' % methodId)
class UnexpectedBodyError(Error):
"""Exception raised by RequestMockBuilder on unexpected bodies."""
def __init__(self, expected, provided):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedBodyError, self).__init__(
'Expected: [%s] - Provided: [%s]' % (expected, provided))
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Schema processing for discovery based APIs
Schemas holds an APIs discovery schemas. It can return those schema as
deserialized JSON objects, or pretty print them as prototype objects that
conform to the schema.
For example, given the schema:
schema = \"\"\"{
"Foo": {
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of the collection."
},
"kind": {
"type": "string",
"description": "Type of the collection ('calendar#acl').",
"default": "calendar#acl"
},
"nextPageToken": {
"type": "string",
"description": "Token used to access the next
page of this result. Omitted if no further results are available."
}
}
}
}\"\"\"
s = Schemas(schema)
print s.prettyPrintByName('Foo')
Produces the following output:
{
"nextPageToken": "A String", # Token used to access the
# next page of this result. Omitted if no further results are available.
"kind": "A String", # Type of the collection ('calendar#acl').
"etag": "A String", # ETag of the collection.
},
The constructor takes a discovery document in which to look up named schema.
"""
# TODO(jcgregorio) support format, enum, minimum, maximum
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
from apiclient.anyjson import simplejson
class Schemas(object):
"""Schemas for an API."""
def __init__(self, discovery):
"""Constructor.
Args:
discovery: object, Deserialized discovery document from which we pull
out the named schema.
"""
self.schemas = discovery.get('schemas', {})
# Cache of pretty printed schemas.
self.pretty = {}
def _prettyPrintByName(self, name, seen=None, dent=0):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
if name in seen:
# Do not fall into an infinite loop over recursive definitions.
return '# Object with schema name: %s' % name
seen.append(name)
if name not in self.pretty:
self.pretty[name] = _SchemaToStruct(self.schemas[name],
seen, dent).to_str(self._prettyPrintByName)
seen.pop()
return self.pretty[name]
def prettyPrintByName(self, name):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintByName(name, seen=[], dent=1)[:-2]
def _prettyPrintSchema(self, schema, seen=None, dent=0):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName)
def prettyPrintSchema(self, schema):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintSchema(schema, dent=1)[:-2]
def get(self, name):
"""Get deserialized JSON schema from the schema name.
Args:
name: string, Schema name.
"""
return self.schemas[name]
class _SchemaToStruct(object):
"""Convert schema to a prototype object."""
def __init__(self, schema, seen, dent=0):
"""Constructor.
Args:
schema: object, Parsed JSON schema.
seen: list, List of names of schema already seen while parsing. Used to
handle recursive definitions.
dent: int, Initial indentation depth.
"""
# The result of this parsing kept as list of strings.
self.value = []
# The final value of the parsing.
self.string = None
# The parsed JSON schema.
self.schema = schema
# Indentation level.
self.dent = dent
# Method that when called returns a prototype object for the schema with
# the given name.
self.from_cache = None
# List of names of schema already seen while parsing.
self.seen = seen
def emit(self, text):
"""Add text as a line to the output.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text, '\n'])
def emitBegin(self, text):
"""Add text to the output, but with no line terminator.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text])
def emitEnd(self, text, comment):
"""Add text and comment to the output with line terminator.
Args:
text: string, Text to output.
comment: string, Python comment.
"""
if comment:
divider = '\n' + ' ' * (self.dent + 2) + '# '
lines = comment.splitlines()
lines = [x.rstrip() for x in lines]
comment = divider.join(lines)
self.value.extend([text, ' # ', comment, '\n'])
else:
self.value.extend([text, '\n'])
def indent(self):
"""Increase indentation level."""
self.dent += 1
def undent(self):
"""Decrease indentation level."""
self.dent -= 1
def _to_str_impl(self, schema):
"""Prototype object based on the schema, in Python code with comments.
Args:
schema: object, Parsed JSON schema file.
Returns:
Prototype object based on the schema, in Python code with comments.
"""
stype = schema.get('type')
if stype == 'object':
self.emitEnd('{', schema.get('description', ''))
self.indent()
for pname, pschema in schema.get('properties', {}).iteritems():
self.emitBegin('"%s": ' % pname)
self._to_str_impl(pschema)
self.undent()
self.emit('},')
elif '$ref' in schema:
schemaName = schema['$ref']
description = schema.get('description', '')
s = self.from_cache(schemaName, self.seen)
parts = s.splitlines()
self.emitEnd(parts[0], description)
for line in parts[1:]:
self.emit(line.rstrip())
elif stype == 'boolean':
value = schema.get('default', 'True or False')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'string':
value = schema.get('default', 'A String')
self.emitEnd('"%s",' % value, schema.get('description', ''))
elif stype == 'integer':
value = schema.get('default', 42)
self.emitEnd('%d,' % value, schema.get('description', ''))
elif stype == 'number':
value = schema.get('default', 3.14)
self.emitEnd('%f,' % value, schema.get('description', ''))
elif stype == 'null':
self.emitEnd('None,', schema.get('description', ''))
elif stype == 'any':
self.emitEnd('"",', schema.get('description', ''))
elif stype == 'array':
self.emitEnd('[', schema.get('description'))
self.indent()
self.emitBegin('')
self._to_str_impl(schema['items'])
self.undent()
self.emit('],')
else:
self.emit('Unknown type! %s' % stype)
self.emitEnd('', '')
self.string = ''.join(self.value)
return self.string
def to_str(self, from_cache):
"""Prototype object based on the schema, in Python code with comments.
Args:
from_cache: callable(name, seen), Callable that retrieves an object
prototype for a schema with the given name. Seen is a list of schema
names already seen as we recursively descend the schema definition.
Returns:
Prototype object based on the schema, in Python code with comments.
The lines of the code will all be properly indented.
"""
self.from_cache = from_cache
return self._to_str_impl(self.schema)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility module to import a JSON module
Hides all the messy details of exactly where
we get a simplejson module from.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
try: # pragma: no cover
import simplejson
except ImportError: # pragma: no cover
try:
# Try to import from django, should work on App Engine
from django.utils import simplejson
except ImportError:
# Should work for Python2.6 and higher.
import json as simplejson
| Python |
# Early, and incomplete implementation of -04.
#
import re
import urllib
RESERVED = ":/?#[]@!$&'()*+,;="
OPERATOR = "+./;?|!@"
EXPLODE = "*+"
MODIFIER = ":^"
TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE)
VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE)
def _tostring(varname, value, explode, operator, safe=""):
if type(value) == type([]):
if explode == "+":
return ",".join([varname + "." + urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
if type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return urllib.quote(value, safe)
def _tostring_path(varname, value, explode, operator, safe=""):
joiner = operator
if type(value) == type([]):
if explode == "+":
return joiner.join([varname + "." + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return urllib.quote(value, safe)
else:
return ""
def _tostring_query(varname, value, explode, operator, safe=""):
joiner = operator
varprefix = ""
if operator == "?":
joiner = "&"
varprefix = varname + "="
if type(value) == type([]):
if 0 == len(value):
return ""
if explode == "+":
return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return varprefix + ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
if 0 == len(value):
return ""
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
else:
return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return varname + "=" + urllib.quote(value, safe)
else:
return varname
TOSTRING = {
"" : _tostring,
"+": _tostring,
";": _tostring_query,
"?": _tostring_query,
"/": _tostring_path,
".": _tostring_path,
}
def expand(template, vars):
def _sub(match):
groupdict = match.groupdict()
operator = groupdict.get('operator')
if operator is None:
operator = ''
varlist = groupdict.get('varlist')
safe = "@"
if operator == '+':
safe = RESERVED
varspecs = varlist.split(",")
varnames = []
defaults = {}
for varspec in varspecs:
m = VAR.search(varspec)
groupdict = m.groupdict()
varname = groupdict.get('varname')
explode = groupdict.get('explode')
partial = groupdict.get('partial')
default = groupdict.get('default')
if default:
defaults[varname] = default
varnames.append((varname, explode, partial))
retval = []
joiner = operator
prefix = operator
if operator == "+":
prefix = ""
joiner = ","
if operator == "?":
joiner = "&"
if operator == "":
joiner = ","
for varname, explode, partial in varnames:
if varname in vars:
value = vars[varname]
#if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults:
if not value and value != "" and varname in defaults:
value = defaults[varname]
elif varname in defaults:
value = defaults[varname]
else:
continue
retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe))
if "".join(retval):
return prefix + joiner.join(retval)
else:
return ""
return TEMPLATE.sub(_sub, template)
| Python |
#!/usr/bin/env python
# Copyright (c) 2010, Google 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 Google Inc. nor the names of its
# contributors 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.
"""Module to enforce different constraints on flags.
A validator represents an invariant, enforced over a one or more flags.
See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual.
"""
__author__ = 'olexiy@google.com (Olexiy Oryeshko)'
class Error(Exception):
"""Thrown If validator constraint is not satisfied."""
class Validator(object):
"""Base class for flags validators.
Users should NOT overload these classes, and use gflags.Register...
methods instead.
"""
# Used to assign each validator an unique insertion_index
validators_count = 0
def __init__(self, checker, message):
"""Constructor to create all validators.
Args:
checker: function to verify the constraint.
Input of this method varies, see SimpleValidator and
DictionaryValidator for a detailed description.
message: string, error message to be shown to the user
"""
self.checker = checker
self.message = message
Validator.validators_count += 1
# Used to assert validators in the order they were registered (CL/18694236)
self.insertion_index = Validator.validators_count
def Verify(self, flag_values):
"""Verify that constraint is satisfied.
flags library calls this method to verify Validator's constraint.
Args:
flag_values: gflags.FlagValues, containing all flags
Raises:
Error: if constraint is not satisfied.
"""
param = self._GetInputToCheckerFunction(flag_values)
if not self.checker(param):
raise Error(self.message)
def GetFlagsNames(self):
"""Return the names of the flags checked by this validator.
Returns:
[string], names of the flags
"""
raise NotImplementedError('This method should be overloaded')
def PrintFlagsWithValues(self, flag_values):
raise NotImplementedError('This method should be overloaded')
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues, containing all flags.
Returns:
Return type depends on the specific validator.
"""
raise NotImplementedError('This method should be overloaded')
class SimpleValidator(Validator):
"""Validator behind RegisterValidator() method.
Validates that a single flag passes its checker function. The checker function
takes the flag value and returns True (if value looks fine) or, if flag value
is not valid, either returns False or raises an Exception."""
def __init__(self, flag_name, checker, message):
"""Constructor.
Args:
flag_name: string, name of the flag.
checker: function to verify the validator.
input - value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(SimpleValidator, self).__init__(checker, message)
self.flag_name = flag_name
def GetFlagsNames(self):
return [self.flag_name]
def PrintFlagsWithValues(self, flag_values):
return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value)
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
value of the corresponding flag.
"""
return flag_values[self.flag_name].value
class DictionaryValidator(Validator):
"""Validator behind RegisterDictionaryValidator method.
Validates that flag values pass their common checker function. The checker
function takes flag values and returns True (if values look fine) or,
if values are not valid, either returns False or raises an Exception.
"""
def __init__(self, flag_names, checker, message):
"""Constructor.
Args:
flag_names: [string], containing names of the flags used by checker.
checker: function to verify the validator.
input - dictionary, with keys() being flag_names, and value for each
key being the value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(DictionaryValidator, self).__init__(checker, message)
self.flag_names = flag_names
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
dictionary, with keys() being self.lag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc).
"""
return dict([key, flag_values[key].value] for key in self.flag_names)
def PrintFlagsWithValues(self, flag_values):
prefix = 'flags '
flags_with_values = []
for key in self.flag_names:
flags_with_values.append('%s=%s' % (key, flag_values[key].value))
return prefix + ', '.join(flags_with_values)
def GetFlagsNames(self):
return self.flag_names
| Python |
"""SocksiPy - Python SOCKS module.
Version 1.00
Copyright 2006 Dan-Haim. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of Dan Haim nor the names of his contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY DAN HAIM "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 DAN HAIM OR HIS 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, 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 DAMANGE.
This module provides a standard socket-like interface for Python
for tunneling connections through SOCKS proxies.
"""
"""
Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
for use in PyLoris (http://pyloris.sourceforge.net/)
Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
mainly to merge bug fixes found in Sourceforge
"""
import base64
import socket
import struct
import sys
if getattr(socket, 'socket', None) is None:
raise ImportError('socket.socket missing, proxy support unusable')
PROXY_TYPE_SOCKS4 = 1
PROXY_TYPE_SOCKS5 = 2
PROXY_TYPE_HTTP = 3
PROXY_TYPE_HTTP_NO_TUNNEL = 4
_defaultproxy = None
_orgsocket = socket.socket
class ProxyError(Exception): pass
class GeneralProxyError(ProxyError): pass
class Socks5AuthError(ProxyError): pass
class Socks5Error(ProxyError): pass
class Socks4Error(ProxyError): pass
class HTTPError(ProxyError): pass
_generalerrors = ("success",
"invalid data",
"not connected",
"not available",
"bad proxy type",
"bad input")
_socks5errors = ("succeeded",
"general SOCKS server failure",
"connection not allowed by ruleset",
"Network unreachable",
"Host unreachable",
"Connection refused",
"TTL expired",
"Command not supported",
"Address type not supported",
"Unknown error")
_socks5autherrors = ("succeeded",
"authentication is required",
"all offered authentication methods were rejected",
"unknown username or invalid password",
"unknown error")
_socks4errors = ("request granted",
"request rejected or failed",
"request rejected because SOCKS server cannot connect to identd on the client",
"request rejected because the client program and identd report different user-ids",
"unknown error")
def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed.
"""
global _defaultproxy
_defaultproxy = (proxytype, addr, port, rdns, username, password)
def wrapmodule(module):
"""wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category.
"""
if _defaultproxy != None:
module.socket.socket = socksocket
else:
raise GeneralProxyError((4, "no proxy specified"))
class socksocket(socket.socket):
"""socksocket([family[, type[, proto]]]) -> socket object
Open a SOCKS enabled socket. The parameters are the same as
those of the standard socket init. In order for SOCKS to work,
you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
"""
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
_orgsocket.__init__(self, family, type, proto, _sock)
if _defaultproxy != None:
self.__proxy = _defaultproxy
else:
self.__proxy = (None, None, None, None, None, None)
self.__proxysockname = None
self.__proxypeername = None
self.__httptunnel = True
def __recvall(self, count):
"""__recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.
"""
data = self.recv(count)
while len(data) < count:
d = self.recv(count-len(data))
if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
data = data + d
return data
def sendall(self, content, *args):
""" override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed
"""
if not self.__httptunnel:
content = self.__rewriteproxy(content)
return super(socksocket, self).sendall(content, *args)
def __rewriteproxy(self, header):
""" rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
"""
host, endpt = None, None
hdrs = header.split("\r\n")
for hdr in hdrs:
if hdr.lower().startswith("host:"):
host = hdr
elif hdr.lower().startswith("get") or hdr.lower().startswith("post"):
endpt = hdr
if host and endpt:
hdrs.remove(host)
hdrs.remove(endpt)
host = host.split(" ")[1]
endpt = endpt.split(" ")
if (self.__proxy[4] != None and self.__proxy[5] != None):
hdrs.insert(0, self.__getauthheader())
hdrs.insert(0, "Host: %s" % host)
hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
return "\r\n".join(hdrs)
def __getauthheader(self):
auth = self.__proxy[4] + ":" + self.__proxy[5]
return "Proxy-Authorization: Basic " + base64.b64encode(auth)
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be preformed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided.
"""
self.__proxy = (proxytype, addr, port, rdns, username, password)
def __negotiatesocks5(self, destaddr, destport):
"""__negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.
"""
# First we'll send the authentication packages we support.
if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
# The username/password details were supplied to the
# setproxy method so we support the USERNAME/PASSWORD
# authentication (in addition to the standard none).
self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
else:
# No username/password were entered, therefore we
# only support connections with no authentication.
self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
# We'll receive the server's response to determine which
# method was selected
chosenauth = self.__recvall(2)
if chosenauth[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
# Check the chosen authentication method
if chosenauth[1:2] == chr(0x00).encode():
# No authentication is required
pass
elif chosenauth[1:2] == chr(0x02).encode():
# Okay, we need to perform a basic username/password
# authentication.
self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
authstat = self.__recvall(2)
if authstat[0:1] != chr(0x01).encode():
# Bad response
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if authstat[1:2] != chr(0x00).encode():
# Authentication failed
self.close()
raise Socks5AuthError((3, _socks5autherrors[3]))
# Authentication succeeded
else:
# Reaching here is always bad
self.close()
if chosenauth[1] == chr(0xFF).encode():
raise Socks5AuthError((2, _socks5autherrors[2]))
else:
raise GeneralProxyError((1, _generalerrors[1]))
# Now we can request the actual connection
req = struct.pack('BBB', 0x05, 0x01, 0x00)
# If the given destination address is an IP address, we'll
# use the IPv4 address request even if remote resolving was specified.
try:
ipaddr = socket.inet_aton(destaddr)
req = req + chr(0x01).encode() + ipaddr
except socket.error:
# Well it's not an IP number, so it's probably a DNS name.
if self.__proxy[3]:
# Resolve remotely
ipaddr = None
req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr
else:
# Resolve locally
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
req = req + chr(0x01).encode() + ipaddr
req = req + struct.pack(">H", destport)
self.sendall(req)
# Get the response
resp = self.__recvall(4)
if resp[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
elif resp[1:2] != chr(0x00).encode():
# Connection failed
self.close()
if ord(resp[1:2])<=8:
raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
else:
raise Socks5Error((9, _socks5errors[9]))
# Get the bound address/port
elif resp[3:4] == chr(0x01).encode():
boundaddr = self.__recvall(4)
elif resp[3:4] == chr(0x03).encode():
resp = resp + self.recv(1)
boundaddr = self.__recvall(ord(resp[4:5]))
else:
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
boundport = struct.unpack(">H", self.__recvall(2))[0]
self.__proxysockname = (boundaddr, boundport)
if ipaddr != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def getproxysockname(self):
"""getsockname() -> address info
Returns the bound IP address and port number at the proxy.
"""
return self.__proxysockname
def getproxypeername(self):
"""getproxypeername() -> address info
Returns the IP and port number of the proxy.
"""
return _orgsocket.getpeername(self)
def getpeername(self):
"""getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)
"""
return self.__proxypeername
def __negotiatesocks4(self,destaddr,destport):
"""__negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.
"""
# Check if the destination address provided is an IP address
rmtrslv = False
try:
ipaddr = socket.inet_aton(destaddr)
except socket.error:
# It's a DNS name. Check where it should be resolved.
if self.__proxy[3]:
ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
rmtrslv = True
else:
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
# Construct the request packet
req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
# The username parameter is considered userid for SOCKS4
if self.__proxy[4] != None:
req = req + self.__proxy[4]
req = req + chr(0x00).encode()
# DNS name if remote resolving is required
# NOTE: This is actually an extension to the SOCKS4 protocol
# called SOCKS4A and may not be supported in all cases.
if rmtrslv:
req = req + destaddr + chr(0x00).encode()
self.sendall(req)
# Get the response from the server
resp = self.__recvall(8)
if resp[0:1] != chr(0x00).encode():
# Bad data
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
if resp[1:2] != chr(0x5A).encode():
# Server returned an error
self.close()
if ord(resp[1:2]) in (91, 92, 93):
self.close()
raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
else:
raise Socks4Error((94, _socks4errors[4]))
# Get the bound address/port
self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
if rmtrslv != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def __negotiatehttp(self, destaddr, destport):
"""__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
"""
# If we need to resolve locally, we do this now
if not self.__proxy[3]:
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
headers += ["Host: ", destaddr, "\r\n"]
if (self.__proxy[4] != None and self.__proxy[5] != None):
headers += [self.__getauthheader(), "\r\n"]
headers.append("\r\n")
self.sendall("".join(headers).encode())
# We read the response until we get the string "\r\n\r\n"
resp = self.recv(1)
while resp.find("\r\n\r\n".encode()) == -1:
resp = resp + self.recv(1)
# We just need the first line to check if the connection
# was successful
statusline = resp.splitlines()[0].split(" ".encode(), 2)
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
try:
statuscode = int(statusline[1])
except ValueError:
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if statuscode != 200:
self.close()
raise HTTPError((statuscode, statusline[2]))
self.__proxysockname = ("0.0.0.0", 0)
self.__proxypeername = (addr, destport)
def connect(self, destpair):
"""connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
"""
# Do a minimal input check first
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
raise GeneralProxyError((5, _generalerrors[5]))
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatesocks5(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatesocks4(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatehttp(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1],portnum))
if destpair[1] == 443:
self.__negotiatehttp(destpair[0],destpair[1])
else:
self.__httptunnel = False
elif self.__proxy[0] == None:
_orgsocket.connect(self, (destpair[0], destpair[1]))
else:
raise GeneralProxyError((4, _generalerrors[4]))
| Python |
"""
iri2uri
Converts an IRI to a URI.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = []
__version__ = "1.0.0"
__license__ = "MIT"
__history__ = """
"""
import urlparse
# Convert an IRI to a URI following the rules in RFC 3987
#
# The characters we need to enocde and escape are defined in the spec:
#
# iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
# ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
# / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
# / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
# / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
# / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
# / %xD0000-DFFFD / %xE1000-EFFFD
escape_range = [
(0xA0, 0xD7FF ),
(0xE000, 0xF8FF ),
(0xF900, 0xFDCF ),
(0xFDF0, 0xFFEF),
(0x10000, 0x1FFFD ),
(0x20000, 0x2FFFD ),
(0x30000, 0x3FFFD),
(0x40000, 0x4FFFD ),
(0x50000, 0x5FFFD ),
(0x60000, 0x6FFFD),
(0x70000, 0x7FFFD ),
(0x80000, 0x8FFFD ),
(0x90000, 0x9FFFD),
(0xA0000, 0xAFFFD ),
(0xB0000, 0xBFFFD ),
(0xC0000, 0xCFFFD),
(0xD0000, 0xDFFFD ),
(0xE1000, 0xEFFFD),
(0xF0000, 0xFFFFD ),
(0x100000, 0x10FFFD)
]
def encode(c):
retval = c
i = ord(c)
for low, high in escape_range:
if i < low:
break
if i >= low and i <= high:
retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')])
break
return retval
def iri2uri(uri):
"""Convert an IRI to a URI. Note that IRIs must be
passed in a unicode strings. That is, do not utf-8 encode
the IRI before passing it into the function."""
if isinstance(uri ,unicode):
(scheme, authority, path, query, fragment) = urlparse.urlsplit(uri)
authority = authority.encode('idna')
# For each character in 'ucschar' or 'iprivate'
# 1. encode as utf-8
# 2. then %-encode each octet of that utf-8
uri = urlparse.urlunsplit((scheme, authority, path, query, fragment))
uri = "".join([encode(c) for c in uri])
return uri
if __name__ == "__main__":
import unittest
class Test(unittest.TestCase):
def test_uris(self):
"""Test that URIs are invariant under the transformation."""
invariant = [
u"ftp://ftp.is.co.za/rfc/rfc1808.txt",
u"http://www.ietf.org/rfc/rfc2396.txt",
u"ldap://[2001:db8::7]/c=GB?objectClass?one",
u"mailto:John.Doe@example.com",
u"news:comp.infosystems.www.servers.unix",
u"tel:+1-816-555-1212",
u"telnet://192.0.2.16:80/",
u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ]
for uri in invariant:
self.assertEqual(uri, iri2uri(uri))
def test_iri(self):
""" Test that the right type of escaping is done for each part of the URI."""
self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}"))
self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}"))
self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}"))
self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")))
self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8')))
unittest.main()
| Python |
from __future__ import generators
"""
httplib2
A caching http interface that supports ETags and gzip
to conserve bandwidth.
Requires Python 2.3 or later
Changelog:
2007-08-18, Rick: Modified so it's able to use a socks proxy if needed.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger"]
__license__ = "MIT"
__version__ = "0.7.2"
import re
import sys
import email
import email.Utils
import email.Message
import email.FeedParser
import StringIO
import gzip
import zlib
import httplib
import urlparse
import base64
import os
import copy
import calendar
import time
import random
import errno
# remove depracated warning in python2.6
try:
from hashlib import sha1 as _sha, md5 as _md5
except ImportError:
import sha
import md5
_sha = sha.new
_md5 = md5.new
import hmac
from gettext import gettext as _
import socket
try:
from httplib2 import socks
except ImportError:
socks = None
# Build the appropriate socket wrapper for ssl
try:
import ssl # python 2.6
ssl_SSLError = ssl.SSLError
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if disable_validation:
cert_reqs = ssl.CERT_NONE
else:
cert_reqs = ssl.CERT_REQUIRED
# We should be specifying SSL version 3 or TLS v1, but the ssl module
# doesn't expose the necessary knobs. So we need to go with the default
# of SSLv23.
return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file,
cert_reqs=cert_reqs, ca_certs=ca_certs)
except (AttributeError, ImportError):
ssl_SSLError = None
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, install "
"the ssl module, or explicity disable validation.")
ssl_sock = socket.ssl(sock, key_file, cert_file)
return httplib.FakeSocket(sock, ssl_sock)
if sys.version_info >= (2,3):
from iri2uri import iri2uri
else:
def iri2uri(uri):
return uri
def has_timeout(timeout): # python 2.6
if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'):
return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT)
return (timeout is not None)
__all__ = ['Http', 'Response', 'ProxyInfo', 'HttpLib2Error',
'RedirectMissingLocation', 'RedirectLimit', 'FailedToDecompressContent',
'UnimplementedDigestAuthOptionError', 'UnimplementedHmacDigestAuthOptionError',
'debuglevel', 'ProxiesUnavailableError']
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# Python 2.3 support
if sys.version_info < (2,4):
def sorted(seq):
seq.sort()
return seq
# Python 2.3 support
def HTTPResponse__getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise httplib.ResponseNotReady()
return self.msg.items()
if not hasattr(httplib.HTTPResponse, 'getheaders'):
httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception): pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass
class RedirectLimit(HttpLib2ErrorWithResponse): pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class MalformedHeader(HttpLib2Error): pass
class RelativeURIError(HttpLib2Error): pass
class ServerNotFoundError(HttpLib2Error): pass
class ProxiesUnavailableError(HttpLib2Error): pass
class CertificateValidationUnsupported(HttpLib2Error): pass
class SSLHandshakeError(HttpLib2Error): pass
class NotSupportedOnThisPlatform(HttpLib2Error): pass
class CertificateHostnameMismatch(SSLHandshakeError):
def __init__(self, desc, host, cert):
HttpLib2Error.__init__(self, desc)
self.host = host
self.cert = cert
# Open Items:
# -----------
# Proxy support
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
# Default CA certificates file bundled with httplib2.
CA_CERTS = os.path.join(
os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt")
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade']
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')])
return [header for header in response.keys() if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r'^\w+://')
re_slash = re.compile(r'[?/:|]+')
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
try:
if re_url_scheme.match(filename):
if isinstance(filename,str):
filename = filename.decode('utf-8')
filename = filename.encode('idna')
else:
filename = filename.encode('idna')
except UnicodeError:
pass
if isinstance(filename,unicode):
filename=filename.encode('utf-8')
filemd5 = _md5(filename).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_slash.sub(",", filename)
# limit length of filename
if len(filename)>200:
filename=filename[:200]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+')
def _normalize_headers(headers):
return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()])
def _parse_cache_control(headers):
retval = {}
if headers.has_key('cache-control'):
parts = headers['cache-control'].split(',')
parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")]
parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, usefull for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$")
WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$")
UNQUOTE_PAIRS = re.compile(r'\\(.)')
def _parse_www_authenticate(headers, headername='www-authenticate'):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headers.has_key(headername):
try:
authenticate = headers[headername].strip()
www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
while authenticate:
# Break off the scheme at the beginning of the line
if headername == 'authentication-info':
(auth_scheme, the_rest) = ('digest', authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1:
retval = "TRANSPARENT"
if 'cache-control' not in request_headers:
request_headers['cache-control'] = 'no-cache'
elif cc.has_key('no-cache'):
retval = "TRANSPARENT"
elif cc_response.has_key('no-cache'):
retval = "STALE"
elif cc.has_key('only-if-cached'):
retval = "FRESH"
elif response_headers.has_key('date'):
date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date']))
now = time.time()
current_age = max(0, now - date)
if cc_response.has_key('max-age'):
try:
freshness_lifetime = int(cc_response['max-age'])
except ValueError:
freshness_lifetime = 0
elif response_headers.has_key('expires'):
expires = email.Utils.parsedate_tz(response_headers['expires'])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if cc.has_key('max-age'):
try:
freshness_lifetime = int(cc['max-age'])
except ValueError:
freshness_lifetime = 0
if cc.has_key('min-fresh'):
try:
min_fresh = int(cc['min-fresh'])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get('content-encoding', None)
if encoding in ['gzip', 'deflate']:
if encoding == 'gzip':
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == 'deflate':
content = zlib.decompress(content)
response['content-length'] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response['-content-encoding'] = response['content-encoding']
del response['content-encoding']
except IOError:
content = ""
raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content)
return content
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if cc.has_key('no-store') or cc_response.has_key('no-store'):
cache.delete(cachekey)
else:
info = email.Message.Message()
for key, value in response_headers.iteritems():
if key not in ['status','content-encoding','transfer-encoding']:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get('vary', None)
if vary:
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = 'status: %d\r\n' % status
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = "".join([status_header, header_str, content])
cache.set(cachekey, text)
def _cnonce():
dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path):].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-rise this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
class BasicAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip()
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['digest']
qop = self.challenge.get('qop', 'auth')
self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None
if self.challenge['qop'] is None:
raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper()
if self.challenge['algorithm'] != 'MD5':
raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]])
self.challenge['nc'] = 1
def request(self, method, request_uri, headers, content, cnonce = None):
"""Modify the request headers"""
H = lambda x: _md5(x).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge['cnonce'] = cnonce or _cnonce()
request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (self.challenge['nonce'],
'%08x' % self.challenge['nc'],
self.challenge['cnonce'],
self.challenge['qop'], H(A2)
))
headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['nonce'],
request_uri,
self.challenge['algorithm'],
request_digest,
self.challenge['qop'],
self.challenge['nc'],
self.challenge['cnonce'],
)
if self.challenge.get('opaque'):
headers['authorization'] += ', opaque="%s"' % self.challenge['opaque']
self.challenge['nc'] += 1
def response(self, response, content):
if not response.has_key('authentication-info'):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {})
if 'true' == challenge.get('stale'):
self.challenge['nonce'] = challenge['nonce']
self.challenge['nc'] = 1
return True
else:
updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {})
if updated_challenge.has_key('nextnonce'):
self.challenge['nonce'] = updated_challenge['nextnonce']
self.challenge['nc'] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['hmacdigest']
# TODO: self.challenge['domain']
self.challenge['reason'] = self.challenge.get('reason', 'unauthorized')
if self.challenge['reason'] not in ['unauthorized', 'integrity']:
self.challenge['reason'] = 'unauthorized'
self.challenge['salt'] = self.challenge.get('salt', '')
if not self.challenge.get('snonce'):
raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty."))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1')
if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1')
if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm']))
if self.challenge['algorithm'] == 'HMAC-MD5':
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge['pw-algorithm'] == 'MD5':
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join([self.credentials[0], ":",
self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(),
":", self.challenge['realm']
])
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['snonce'],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {})
if challenge.get('reason') in ['integrity', 'stale']:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (
self.credentials[0],
password_digest,
cnonce,
iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
from urllib import urlencode
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
service = challenge['googlelogin'].get('service', 'xapi')
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == 'xapi' and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
#elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent'])
resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'})
lines = content.split('\n')
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d['Auth']
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'GoogleLogin Auth=' + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = file(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = file(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None):
"""The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX
constants. For example:
p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000)
"""
self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass = proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass
def astuple(self):
return (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns,
self.proxy_user, self.proxy_pass)
def isgood(self):
return (self.proxy_host != None) and (self.proxy_port != None)
class HTTPConnectionWithTimeout(httplib.HTTPConnection):
"""
HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port, strict)
self.timeout = timeout
self.proxy_info = proxy_info
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
'Proxy support missing but proxy use was requested!')
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if self.proxy_info and self.proxy_info.isgood():
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(*self.proxy_info.astuple())
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Different from httplib: support timeouts.
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
# End of difference from httplib.
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
"""
This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file,
cert_file=cert_file, strict=strict)
self.timeout = timeout
self.proxy_info = proxy_info
if ca_certs is None:
ca_certs = CA_CERTS
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# The following two methods were adapted from https_wrapper.py, released
# with the Google Appengine SDK at
# http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
# under the following license:
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def _GetValidHostsForCert(self, cert):
"""Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.
"""
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
"Connect to a host on a given (SSL) port."
msg = "getaddrinfo returns an empty list"
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
self.host, self.port, 0, socket.SOCK_STREAM):
try:
if self.proxy_info and self.proxy_info.isgood():
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(*self.proxy_info.astuple())
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock =_ssl_wrap_socket(
sock, self.key_file, self.cert_file,
self.disable_ssl_certificate_validation, self.ca_certs)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
if not self.disable_ssl_certificate_validation:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise CertificateHostnameMismatch(
'Server presented certificate that does not match '
'host %s: %s' % (hostname, cert), hostname, cert)
except ssl_SSLError, e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
# Unfortunately the ssl module doesn't seem to provide any way
# to get at more detailed error information, in particular
# whether the error is due to certificate validation or
# something else (such as SSL protocol mismatch).
if e.errno == ssl.SSL_ERROR_SSL:
raise SSLHandshakeError(e)
else:
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
SCHEME_TO_CONNECTION = {
'http': HTTPConnectionWithTimeout,
'https': HTTPSConnectionWithTimeout
}
# Use a different connection object for Google App Engine
try:
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
raise ImportError # Bail out; we're not actually running on App Engine.
from google.appengine.api.urlfetch import fetch
from google.appengine.api.urlfetch import InvalidURLError
from google.appengine.api.urlfetch import DownloadError
from google.appengine.api.urlfetch import ResponseTooLargeError
from google.appengine.api.urlfetch import SSLCertificateError
class ResponseDict(dict):
"""Is a dictionary that also has a read() method, so
that it can pass itself off as an httlib.HTTPResponse()."""
def read(self):
pass
class AppEngineHttpConnection(object):
"""Emulates an httplib.HTTPConnection object, but actually uses the Google
App Engine urlfetch library. This allows the timeout to be properly used on
Google App Engine, and avoids using httplib, which on Google App Engine is
just another wrapper around urlfetch.
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None, ca_certs=None,
disable_certificate_validation=False):
self.host = host
self.port = port
self.timeout = timeout
if key_file or cert_file or proxy_info or ca_certs:
raise NotSupportedOnThisPlatform()
self.response = None
self.scheme = 'http'
self.validate_certificate = not disable_certificate_validation
self.sock = True
def request(self, method, url, body, headers):
# Calculate the absolute URI, which fetch requires
netloc = self.host
if self.port:
netloc = '%s:%s' % (self.host, self.port)
absolute_uri = '%s://%s%s' % (self.scheme, netloc, url)
try:
response = fetch(absolute_uri, payload=body, method=method,
headers=headers, allow_truncated=False, follow_redirects=False,
deadline=self.timeout,
validate_certificate=self.validate_certificate)
self.response = ResponseDict(response.headers)
self.response['status'] = str(response.status_code)
self.response.status = response.status_code
setattr(self.response, 'read', lambda : response.content)
# Make sure the exceptions raised match the exceptions expected.
except InvalidURLError:
raise socket.gaierror('')
except (DownloadError, ResponseTooLargeError, SSLCertificateError):
raise httplib.HTTPException()
def getresponse(self):
if self.response:
return self.response
else:
raise httplib.HTTPException()
def set_debuglevel(self, level):
pass
def connect(self):
pass
def close(self):
pass
class AppEngineHttpsConnection(AppEngineHttpConnection):
"""Same as AppEngineHttpConnection, but for HTTPS URIs."""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None):
AppEngineHttpConnection.__init__(self, host, port, key_file, cert_file,
strict, timeout, proxy_info)
self.scheme = 'https'
# Update the connection classes to use the Googel App Engine specific ones.
SCHEME_TO_CONNECTION = {
'http': AppEngineHttpConnection,
'https': AppEngineHttpsConnection
}
except ImportError:
pass
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(self, cache=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
"""
The value of proxy_info is a ProxyInfo instance.
If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, basestring):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, 'www-authenticate')
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if challenges.has_key(scheme):
yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
for i in range(2):
try:
if conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except ssl_SSLError:
conn.close()
raise
except socket.error, e:
err = 0
if hasattr(e, 'args'):
err = getattr(e, 'args')[0]
else:
err = e.errno
if err == errno.ECONNREFUSED: # Connection refused
raise
except httplib.HTTPException:
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
if conn.sock is None:
if i == 0:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i == 0:
conn.close()
conn.connect()
continue
try:
response = conn.getresponse()
except (socket.error, httplib.HTTPException):
if i == 0:
conn.close()
conn.connect()
continue
else:
raise
else:
content = ""
if method == "HEAD":
response.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers )
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(host, request_uri, headers, response, content):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers, )
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303):
if self.follow_redirects and response.status in [300, 301, 302, 303, 307]:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if not response.has_key('location') and response.status != 300:
raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if response.has_key('location'):
location = response['location']
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response['location'] = urlparse.urljoin(absolute_uri, location)
if response.status == 301 and method in ["GET", "HEAD"]:
response['-x-permanent-redirect-url'] = response['location']
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if headers.has_key('if-none-match'):
del headers['if-none-match']
if headers.has_key('if-modified-since'):
del headers['if-modified-since']
if response.has_key('location'):
location = response['location']
old_response = copy.deepcopy(response)
if not old_response.has_key('content-location'):
old_response['content-location'] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1)
response.previous = old_response
else:
raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content)
elif response.status in [200, 203] and method in ["GET", "HEAD"]:
# Don't cache 206's since we aren't going to handle byte range requests
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin
with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a string
object.
Any extra headers that are to be sent with the request should be provided in the
'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if not headers.has_key('user-agent'):
headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
domain_port = authority.split(":")[0:2]
if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http':
scheme = 'https'
authority = domain_port[0]
conn_key = scheme+":"+authority
if conn_key in self.connections:
conn = self.connections[conn_key]
else:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if issubclass(connection_type, HTTPSConnectionWithTimeout):
if certs:
conn = self.connections[conn_key] = connection_type(
authority, key_file=certs[0][0],
cert_file=certs[0][1], timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info)
conn.set_debuglevel(debuglevel)
if 'range' not in headers and 'accept-encoding' not in headers:
headers['accept-encoding'] = 'gzip, deflate'
info = email.Message.Message()
cached_value = None
if self.cache:
cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
if cached_value:
# info = email.message_from_string(cached_value)
#
# Need to replace the line above with the kludge below
# to fix the non-existent bug not fixed in this
# bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
try:
info, content = cached_value.split('\r\n\r\n', 1)
feedparser = email.FeedParser.FeedParser()
feedparser.feed(info)
info = feedparser.close()
feedparser._parse = None
except IndexError:
self.cache.delete(cachekey)
cachekey = None
cached_value = None
else:
cachekey = None
if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers:
# http://www.w3.org/1999/04/Editing/
headers['if-match'] = info['etag']
if method not in ["GET", "HEAD"] and self.cache and cachekey:
# RFC 2616 Section 13.10
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in ['GET', 'HEAD'] and 'vary' in info:
vary = info['vary']
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers:
if info.has_key('-x-permanent-redirect-url'):
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "")
(response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info['status'] = '504'
content = ""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers:
headers['if-none-match'] = info['etag']
if info.has_key('last-modified') and not 'last-modified' in headers:
headers['if-modified-since'] = info['last-modified']
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(headers, merged_response, content, self.cache, cachekey)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if cc.has_key('only-if-cached'):
info['status'] = '504'
response = Response(info)
content = ""
else:
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
except Exception, e:
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = "Request Timeout"
response = Response( {
"content-type": "text/plain",
"status": "408",
"content-length": len(content)
})
response.reason = "Request Timeout"
else:
content = str(e)
response = Response( {
"content-type": "text/plain",
"status": "400",
"content-length": len(content)
})
response.reason = "Bad Request"
else:
raise
return (response, content)
class Response(dict):
"""An object more like email.Message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.Message or
# an httplib.HTTPResponse object.
if isinstance(info, httplib.HTTPResponse):
for key, value in info.getheaders():
self[key.lower()] = value
self.status = info.status
self['status'] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.Message.Message):
for key, value in info.items():
self[key] = value
self.status = int(self['status'])
else:
for key, value in info.iteritems():
self[key] = value
self.status = int(self.get('status', self.status))
def __getattr__(self, name):
if name == 'dict':
return self
else:
raise AttributeError, name
| Python |
#!/usr/bin/env python
#
# Copyright (c) 2002, Google 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 Google Inc. nor the names of its
# contributors 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.
#
# ---
# Author: Chad Lester
# Design and style contributions by:
# Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann,
# Eric Veach, Laurence Gonsalves, Matthew Springer
# Code reorganized a bit by Craig Silverstein
"""This module is used to define and parse command line flags.
This module defines a *distributed* flag-definition policy: rather than
an application having to define all flags in or near main(), each python
module defines flags that are useful to it. When one python module
imports another, it gains access to the other's flags. (This is
implemented by having all modules share a common, global registry object
containing all the flag information.)
Flags are defined through the use of one of the DEFINE_xxx functions.
The specific function used determines how the flag is parsed, checked,
and optionally type-converted, when it's seen on the command line.
IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a
'FlagValues' object (typically the global FlagValues FLAGS, defined
here). The 'FlagValues' object can scan the command line arguments and
pass flag arguments to the corresponding 'Flag' objects for
value-checking and type conversion. The converted flag values are
available as attributes of the 'FlagValues' object.
Code can access the flag through a FlagValues object, for instance
gflags.FLAGS.myflag. Typically, the __main__ module passes the command
line arguments to gflags.FLAGS for parsing.
At bottom, this module calls getopt(), so getopt functionality is
supported, including short- and long-style flags, and the use of -- to
terminate flags.
Methods defined by the flag module will throw 'FlagsError' exceptions.
The exception argument will be a human-readable string.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags
take a name, default value, help-string, and optional 'short' name
(one-letter name). Some flags have other arguments, which are described
with the flag.
DEFINE_string: takes any input, and interprets it as a string.
DEFINE_bool or
DEFINE_boolean: typically does not take an argument: say --myflag to
set FLAGS.myflag to true, or --nomyflag to set
FLAGS.myflag to false. Alternately, you can say
--myflag=true or --myflag=t or --myflag=1 or
--myflag=false or --myflag=f or --myflag=0
DEFINE_float: takes an input and interprets it as a floating point
number. Takes optional args lower_bound and upper_bound;
if the number specified on the command line is out of
range, it will raise a FlagError.
DEFINE_integer: takes an input and interprets it as an integer. Takes
optional args lower_bound and upper_bound as for floats.
DEFINE_enum: takes a list of strings which represents legal values. If
the command-line value is not in this list, raise a flag
error. Otherwise, assign to FLAGS.flag as a string.
DEFINE_list: Takes a comma-separated list of strings on the commandline.
Stores them in a python list object.
DEFINE_spaceseplist: Takes a space-separated list of strings on the
commandline. Stores them in a python list object.
Example: --myspacesepflag "foo bar baz"
DEFINE_multistring: The same as DEFINE_string, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of strings),
even if the flag is only on the command line once.
DEFINE_multi_int: The same as DEFINE_integer, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of ints), even if
the flag is only on the command line once.
SPECIAL FLAGS: There are a few flags that have special meaning:
--help prints a list of all the flags in a human-readable fashion
--helpshort prints a list of all key flags (see below).
--helpxml prints a list of all flags, in XML format. DO NOT parse
the output of --help and --helpshort. Instead, parse
the output of --helpxml. For more info, see
"OUTPUT FOR --helpxml" below.
--flagfile=foo read flags from file foo.
--undefok=f1,f2 ignore unrecognized option errors for f1,f2.
For boolean flags, you should use --undefok=boolflag, and
--boolflag and --noboolflag will be accepted. Do not use
--undefok=noboolflag.
-- as in getopt(), terminates flag-processing
FLAGS VALIDATORS: If your program:
- requires flag X to be specified
- needs flag Y to match a regular expression
- or requires any more general constraint to be satisfied
then validators are for you!
Each validator represents a constraint over one flag, which is enforced
starting from the initial parsing of the flags and until the program
terminates.
Also, lower_bound and upper_bound for numerical flags are enforced using flag
validators.
Howto:
If you want to enforce a constraint over one flag, use
gflags.RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS)
After flag values are initially parsed, and after any change to the specified
flag, method checker(flag_value) will be executed. If constraint is not
satisfied, an IllegalFlagValue exception will be raised. See
RegisterValidator's docstring for a detailed explanation on how to construct
your own checker.
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
gflags.DEFINE_integer('my_version', 0, 'Version number.')
gflags.DEFINE_string('filename', None, 'Input file name', short_name='f')
gflags.RegisterValidator('my_version',
lambda value: value % 2 == 0,
message='--my_version must be divisible by 2')
gflags.MarkFlagAsRequired('filename')
NOTE ON --flagfile:
Flags may be loaded from text files in addition to being specified on
the commandline.
Any flags you don't feel like typing, throw them in a file, one flag per
line, for instance:
--myflag=myvalue
--nomyboolean_flag
You then specify your file with the special flag '--flagfile=somefile'.
You CAN recursively nest flagfile= tokens OR use multiple files on the
command line. Lines beginning with a single hash '#' or a double slash
'//' are comments in your flagfile.
Any flagfile=<file> will be interpreted as having a relative path from
the current working directory rather than from the place the file was
included from:
myPythonScript.py --flagfile=config/somefile.cfg
If somefile.cfg includes further --flagfile= directives, these will be
referenced relative to the original CWD, not from the directory the
including flagfile was found in!
The caveat applies to people who are including a series of nested files
in a different dir than they are executing out of. Relative path names
are always from CWD, not from the directory of the parent include
flagfile. We do now support '~' expanded directory names.
Absolute path names ALWAYS work!
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
# Flag names are globally defined! So in general, we need to be
# careful to pick names that are unlikely to be used by other libraries.
# If there is a conflict, we'll get an error at import time.
gflags.DEFINE_string('name', 'Mr. President', 'your name')
gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0)
gflags.DEFINE_boolean('debug', False, 'produces debugging output')
gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender')
def main(argv):
try:
argv = FLAGS(argv) # parse flags
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
sys.exit(1)
if FLAGS.debug: print 'non-flag arguments:', argv
print 'Happy Birthday', FLAGS.name
if FLAGS.age is not None:
print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender)
if __name__ == '__main__':
main(sys.argv)
KEY FLAGS:
As we already explained, each module gains access to all flags defined
by all the other modules it transitively imports. In the case of
non-trivial scripts, this means a lot of flags ... For documentation
purposes, it is good to identify the flags that are key (i.e., really
important) to a module. Clearly, the concept of "key flag" is a
subjective one. When trying to determine whether a flag is key to a
module or not, assume that you are trying to explain your module to a
potential user: which flags would you really like to mention first?
We'll describe shortly how to declare which flags are key to a module.
For the moment, assume we know the set of key flags for each module.
Then, if you use the app.py module, you can use the --helpshort flag to
print only the help for the flags that are key to the main module, in a
human-readable format.
NOTE: If you need to parse the flag help, do NOT use the output of
--help / --helpshort. That output is meant for human consumption, and
may be changed in the future. Instead, use --helpxml; flags that are
key for the main module are marked there with a <key>yes</key> element.
The set of key flags for a module M is composed of:
1. Flags defined by module M by calling a DEFINE_* function.
2. Flags that module M explictly declares as key by using the function
DECLARE_key_flag(<flag_name>)
3. Key flags of other modules that M specifies by using the function
ADOPT_module_key_flags(<other_module>)
This is a "bulk" declaration of key flags: each flag that is key for
<other_module> becomes key for the current module too.
Notice that if you do not use the functions described at points 2 and 3
above, then --helpshort prints information only about the flags defined
by the main module of our script. In many cases, this behavior is good
enough. But if you move part of the main module code (together with the
related flags) into a different module, then it is nice to use
DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort
lists all relevant flags (otherwise, your code refactoring may confuse
your users).
Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own
pluses and minuses: DECLARE_key_flag is more targeted and may lead a
more focused --helpshort documentation. ADOPT_module_key_flags is good
for cases when an entire module is considered key to the current script.
Also, it does not require updates to client scripts when a new flag is
added to the module.
EXAMPLE USAGE 2 (WITH KEY FLAGS):
Consider an application that contains the following three files (two
auxiliary modules and a main module)
File libfoo.py:
import gflags
gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start')
gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.')
... some code ...
File libbar.py:
import gflags
gflags.DEFINE_string('bar_gfs_path', '/gfs/path',
'Path to the GFS files for libbar.')
gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com',
'Email address for bug reports about module libbar.')
gflags.DEFINE_boolean('bar_risky_hack', False,
'Turn on an experimental and buggy optimization.')
... some code ...
File myscript.py:
import gflags
import libfoo
import libbar
gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.')
# Declare that all flags that are key for libfoo are
# key for this module too.
gflags.ADOPT_module_key_flags(libfoo)
# Declare that the flag --bar_gfs_path (defined in libbar) is key
# for this module.
gflags.DECLARE_key_flag('bar_gfs_path')
... some code ...
When myscript is invoked with the flag --helpshort, the resulted help
message lists information about all the key flags for myscript:
--num_iterations, --num_replicas, --rpc2, and --bar_gfs_path.
Of course, myscript uses all the flags declared by it (in this case,
just --num_replicas) or by any of the modules it transitively imports
(e.g., the modules libfoo, libbar). E.g., it can access the value of
FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key
flag for myscript.
OUTPUT FOR --helpxml:
The --helpxml flag generates output with the following structure:
<?xml version="1.0"?>
<AllFlags>
<program>PROGRAM_BASENAME</program>
<usage>MAIN_MODULE_DOCSTRING</usage>
(<flag>
[<key>yes</key>]
<file>DECLARING_MODULE</file>
<name>FLAG_NAME</name>
<meaning>FLAG_HELP_MESSAGE</meaning>
<default>DEFAULT_FLAG_VALUE</default>
<current>CURRENT_FLAG_VALUE</current>
<type>FLAG_TYPE</type>
[OPTIONAL_ELEMENTS]
</flag>)*
</AllFlags>
Notes:
1. The output is intentionally similar to the output generated by the
C++ command-line flag library. The few differences are due to the
Python flags that do not have a C++ equivalent (at least not yet),
e.g., DEFINE_list.
2. New XML elements may be added in the future.
3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can
pass for this flag on the command-line. E.g., for a flag defined
using DEFINE_list, this field may be foo,bar, not ['foo', 'bar'].
4. CURRENT_FLAG_VALUE is produced using str(). This means that the
string 'false' will be represented in the same way as the boolean
False. Using repr() would have removed this ambiguity and simplified
parsing, but would have broken the compatibility with the C++
command-line flags.
5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of
flags: lower_bound, upper_bound (for flags that specify bounds),
enum_value (for enum flags), list_separator (for flags that consist of
a list of values, separated by a special token).
6. We do not provide any example here: please use --helpxml instead.
This module requires at least python 2.2.1 to run.
"""
import cgi
import getopt
import os
import re
import string
import struct
import sys
# pylint: disable-msg=C6204
try:
import fcntl
except ImportError:
fcntl = None
try:
# Importing termios will fail on non-unix platforms.
import termios
except ImportError:
termios = None
import gflags_validators
# pylint: enable-msg=C6204
# Are we running under pychecker?
_RUNNING_PYCHECKER = 'pychecker.python' in sys.modules
def _GetCallingModuleObjectAndName():
"""Returns the module that's calling into this module.
We generally use this function to get the name of the module calling a
DEFINE_foo... function.
"""
# Walk down the stack to find the first globals dict that's not ours.
for depth in range(1, sys.getrecursionlimit()):
if not sys._getframe(depth).f_globals is globals():
globals_for_frame = sys._getframe(depth).f_globals
module, module_name = _GetModuleObjectAndName(globals_for_frame)
if module_name is not None:
return module, module_name
raise AssertionError("No module was found")
def _GetCallingModule():
"""Returns the name of the module that's calling into this module."""
return _GetCallingModuleObjectAndName()[1]
def _GetThisModuleObjectAndName():
"""Returns: (module object, module name) for this module."""
return _GetModuleObjectAndName(globals())
# module exceptions:
class FlagsError(Exception):
"""The base class for all flags errors."""
pass
class DuplicateFlag(FlagsError):
"""Raised if there is a flag naming conflict."""
pass
class CantOpenFlagFileError(FlagsError):
"""Raised if flagfile fails to open: doesn't exist, wrong permissions, etc."""
pass
class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag):
"""Special case of DuplicateFlag -- SWIG flag value can't be set to None.
This can be raised when a duplicate flag is created. Even if allow_override is
True, we still abort if the new value is None, because it's currently
impossible to pass None default value back to SWIG. See FlagValues.SetDefault
for details.
"""
pass
class DuplicateFlagError(DuplicateFlag):
"""A DuplicateFlag whose message cites the conflicting definitions.
A DuplicateFlagError conveys more information than a DuplicateFlag,
namely the modules where the conflicting definitions occur. This
class was created to avoid breaking external modules which depend on
the existing DuplicateFlags interface.
"""
def __init__(self, flagname, flag_values, other_flag_values=None):
"""Create a DuplicateFlagError.
Args:
flagname: Name of the flag being redefined.
flag_values: FlagValues object containing the first definition of
flagname.
other_flag_values: If this argument is not None, it should be the
FlagValues object where the second definition of flagname occurs.
If it is None, we assume that we're being called when attempting
to create the flag a second time, and we use the module calling
this one as the source of the second definition.
"""
self.flagname = flagname
first_module = flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
if other_flag_values is None:
second_module = _GetCallingModule()
else:
second_module = other_flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
msg = "The flag '%s' is defined twice. First from %s, Second from %s" % (
self.flagname, first_module, second_module)
DuplicateFlag.__init__(self, msg)
class IllegalFlagValue(FlagsError):
"""The flag command line argument is illegal."""
pass
class UnrecognizedFlag(FlagsError):
"""Raised if a flag is unrecognized."""
pass
# An UnrecognizedFlagError conveys more information than an UnrecognizedFlag.
# Since there are external modules that create DuplicateFlags, the interface to
# DuplicateFlag shouldn't change. The flagvalue will be assigned the full value
# of the flag and its argument, if any, allowing handling of unrecognized flags
# in an exception handler.
# If flagvalue is the empty string, then this exception is an due to a
# reference to a flag that was not already defined.
class UnrecognizedFlagError(UnrecognizedFlag):
def __init__(self, flagname, flagvalue=''):
self.flagname = flagname
self.flagvalue = flagvalue
UnrecognizedFlag.__init__(
self, "Unknown command line flag '%s'" % flagname)
# Global variable used by expvar
_exported_flags = {}
_help_width = 80 # width of help output
def GetHelpWidth():
"""Returns: an integer, the width of help lines that is used in TextWrap."""
if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None):
return _help_width
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mode returns 0.
# Here we assume that any value below 40 is unreasonable
if columns >= 40:
return columns
# Returning an int as default is fine, int(int) just return the int.
return int(os.getenv('COLUMNS', _help_width))
except (TypeError, IOError, struct.error):
return _help_width
def CutCommonSpacePrefix(text):
"""Removes a common space prefix from the lines of a multiline text.
If the first line does not start with a space, it is left as it is and
only in the remaining lines a common space prefix is being searched
for. That means the first line will stay untouched. This is especially
useful to turn doc strings into help texts. This is because some
people prefer to have the doc comment start already after the
apostrophe and then align the following lines while others have the
apostrophes on a separate line.
The function also drops trailing empty lines and ignores empty lines
following the initial content line while calculating the initial
common whitespace.
Args:
text: text to work on
Returns:
the resulting text
"""
text_lines = text.splitlines()
# Drop trailing empty lines
while text_lines and not text_lines[-1]:
text_lines = text_lines[:-1]
if text_lines:
# We got some content, is the first line starting with a space?
if text_lines[0] and text_lines[0][0].isspace():
text_first_line = []
else:
text_first_line = [text_lines.pop(0)]
# Calculate length of common leading whitespace (only over content lines)
common_prefix = os.path.commonprefix([line for line in text_lines if line])
space_prefix_len = len(common_prefix) - len(common_prefix.lstrip())
# If we have a common space prefix, drop it from all lines
if space_prefix_len:
for index in xrange(len(text_lines)):
if text_lines[index]:
text_lines[index] = text_lines[index][space_prefix_len:]
return '\n'.join(text_first_line + text_lines)
return ''
def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '):
"""Wraps a given text to a maximum line length and returns it.
We turn lines that only contain whitespace into empty lines. We keep
new lines and tabs (e.g., we do not treat tabs as spaces).
Args:
text: text to wrap
length: maximum length of a line, includes indentation
if this is None then use GetHelpWidth()
indent: indent for all but first line
firstline_indent: indent for first line; if None, fall back to indent
tabs: replacement for tabs
Returns:
wrapped text
Raises:
FlagsError: if indent not shorter than length
FlagsError: if firstline_indent not shorter than length
"""
# Get defaults where callee used None
if length is None:
length = GetHelpWidth()
if indent is None:
indent = ''
if len(indent) >= length:
raise FlagsError('Indent must be shorter than length')
# In line we will be holding the current line which is to be started
# with indent (or firstline_indent if available) and then appended
# with words.
if firstline_indent is None:
firstline_indent = ''
line = indent
else:
line = firstline_indent
if len(firstline_indent) >= length:
raise FlagsError('First line indent must be shorter than length')
# If the callee does not care about tabs we simply convert them to
# spaces If callee wanted tabs to be single space then we do that
# already here.
if not tabs or tabs == ' ':
text = text.replace('\t', ' ')
else:
tabs_are_whitespace = not tabs.strip()
line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE)
# Split the text into lines and the lines with the regex above. The
# resulting lines are collected in result[]. For each split we get the
# spaces, the tabs and the next non white space (e.g. next word).
result = []
for text_line in text.splitlines():
# Store result length so we can find out whether processing the next
# line gave any new content
old_result_len = len(result)
# Process next line with line_regex. For optimization we do an rstrip().
# - process tabs (changes either line or word, see below)
# - process word (first try to squeeze on line, then wrap or force wrap)
# Spaces found on the line are ignored, they get added while wrapping as
# needed.
for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()):
# If tabs weren't converted to spaces, handle them now
if current_tabs:
# If the last thing we added was a space anyway then drop
# it. But let's not get rid of the indentation.
if (((result and line != indent) or
(not result and line != firstline_indent)) and line[-1] == ' '):
line = line[:-1]
# Add the tabs, if that means adding whitespace, just add it at
# the line, the rstrip() code while shorten the line down if
# necessary
if tabs_are_whitespace:
line += tabs * len(current_tabs)
else:
# if not all tab replacement is whitespace we prepend it to the word
word = tabs * len(current_tabs) + word
# Handle the case where word cannot be squeezed onto current last line
if len(line) + len(word) > length and len(indent) + len(word) <= length:
result.append(line.rstrip())
line = indent + word
word = ''
# No space left on line or can we append a space?
if len(line) + 1 >= length:
result.append(line.rstrip())
line = indent
else:
line += ' '
# Add word and shorten it up to allowed line length. Restart next
# line with indent and repeat, or add a space if we're done (word
# finished) This deals with words that cannot fit on one line
# (e.g. indent + word longer than allowed line length).
while len(line) + len(word) >= length:
line += word
result.append(line[:length])
word = line[length:]
line = indent
# Default case, simply append the word and a space
if word:
line += word + ' '
# End of input line. If we have content we finish the line. If the
# current line is just the indent but we had content in during this
# original line then we need to add an empty line.
if (result and line != indent) or (not result and line != firstline_indent):
result.append(line.rstrip())
elif len(result) == old_result_len:
result.append('')
line = indent
return '\n'.join(result)
def DocToHelp(doc):
"""Takes a __doc__ string and reformats it as help."""
# Get rid of starting and ending white space. Using lstrip() or even
# strip() could drop more than maximum of first line and right space
# of last line.
doc = doc.strip()
# Get rid of all empty lines
whitespace_only_line = re.compile('^[ \t]+$', re.M)
doc = whitespace_only_line.sub('', doc)
# Cut out common space at line beginnings
doc = CutCommonSpacePrefix(doc)
# Just like this module's comment, comments tend to be aligned somehow.
# In other words they all start with the same amount of white space
# 1) keep double new lines
# 2) keep ws after new lines if not empty line
# 3) all other new lines shall be changed to a space
# Solution: Match new lines between non white space and replace with space.
doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M)
return doc
def _GetModuleObjectAndName(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
A pair consisting of (1) module object and (2) module name (a
string). Returns (None, None) if the module could not be
identified.
"""
# The use of .items() (instead of .iteritems()) is NOT a mistake: if
# a parallel thread imports a module while we iterate over
# .iteritems() (not nice, but possible), we get a RuntimeError ...
# Hence, we use the slightly slower but safer .items().
for name, module in sys.modules.items():
if getattr(module, '__dict__', None) is globals_dict:
if name == '__main__':
# Pick a more informative name for the main module.
name = sys.argv[0]
return (module, name)
return (None, None)
def _GetMainModule():
"""Returns: string, name of the module from which execution started."""
# First, try to use the same logic used by _GetCallingModuleObjectAndName(),
# i.e., call _GetModuleObjectAndName(). For that we first need to
# find the dictionary that the main module uses to store the
# globals.
#
# That's (normally) the same dictionary object that the deepest
# (oldest) stack frame is using for globals.
deepest_frame = sys._getframe(0)
while deepest_frame.f_back is not None:
deepest_frame = deepest_frame.f_back
globals_for_main_module = deepest_frame.f_globals
main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1]
# The above strategy fails in some cases (e.g., tools that compute
# code coverage by redefining, among other things, the main module).
# If so, just use sys.argv[0]. We can probably always do this, but
# it's safest to try to use the same logic as _GetCallingModuleObjectAndName()
if main_module_name is None:
main_module_name = sys.argv[0]
return main_module_name
class FlagValues:
"""Registry of 'Flag' objects.
A 'FlagValues' can then scan command line arguments, passing flag
arguments through to the 'Flag' objects that it owns. It also
provides easy access to the flag values. Typically only one
'FlagValues' object is needed by an application: gflags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via __setitem__:
FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed
as attributes of this 'FlagValues' object, through __getattr__. Both
the long and short name of the original 'Flag' objects can be used to
access its value:
FLAGS.longname # parsed flag value
FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag'
objects through the __call__ method. Unparsed arguments, including
argv[0] (e.g. the program name) are returned.
argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use
of the dictionary-like operator, __getitem__:
x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of
the registered 'Flag' objects.
"""
def __init__(self):
# Since everything in this class is so heavily overloaded, the only
# way of defining and using fields is to access __dict__ directly.
# Dictionary: flag name (string) -> Flag object.
self.__dict__['__flags'] = {}
# Dictionary: module name (string) -> list of Flag objects that are defined
# by that module.
self.__dict__['__flags_by_module'] = {}
# Dictionary: module id (int) -> list of Flag objects that are defined by
# that module.
self.__dict__['__flags_by_module_id'] = {}
# Dictionary: module name (string) -> list of Flag objects that are
# key for that module.
self.__dict__['__key_flags_by_module'] = {}
# Set if we should use new style gnu_getopt rather than getopt when parsing
# the args. Only possible with Python 2.3+
self.UseGnuGetOpt(False)
def UseGnuGetOpt(self, use_gnu_getopt=True):
"""Use GNU-style scanning. Allows mixing of flag and non-flag arguments.
See http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Args:
use_gnu_getopt: wether or not to use GNU style scanning.
"""
self.__dict__['__use_gnu_getopt'] = use_gnu_getopt
def IsGnuGetOpt(self):
return self.__dict__['__use_gnu_getopt']
def FlagDict(self):
return self.__dict__['__flags']
def FlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of defined flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module']
def FlagsByModuleIdDict(self):
"""Returns the dictionary of module_id -> list of defined flags.
Returns:
A dictionary. Its keys are module IDs (ints). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module_id']
def KeyFlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of key flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__key_flags_by_module']
def _RegisterFlagByModule(self, module_name, flag):
"""Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module = self.FlagsByModuleDict()
flags_by_module.setdefault(module_name, []).append(flag)
def _RegisterFlagByModuleId(self, module_id, flag):
"""Records the module that defines a specific flag.
Args:
module_id: An int, the ID of the Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module_id = self.FlagsByModuleIdDict()
flags_by_module_id.setdefault(module_id, []).append(flag)
def _RegisterKeyFlagForModule(self, module_name, flag):
"""Specifies that a flag is a key flag for a module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
key_flags_by_module = self.KeyFlagsByModuleDict()
# The list of key flags for the module named module_name.
key_flags = key_flags_by_module.setdefault(module_name, [])
# Add flag, but avoid duplicates.
if flag not in key_flags:
key_flags.append(flag)
def _GetFlagsDefinedByModule(self, module):
"""Returns the list of flags defined by a module.
Args:
module: A module object or a module name (a string).
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
return list(self.FlagsByModuleDict().get(module, []))
def _GetKeyFlagsForModule(self, module):
"""Returns the list of key flags for a module.
Args:
module: A module object or a module name (a string)
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
# Any flag is a key flag for the module that defined it. NOTE:
# key_flags is a fresh list: we can update it without affecting the
# internals of this FlagValues object.
key_flags = self._GetFlagsDefinedByModule(module)
# Take into account flags explicitly declared as key for a module.
for flag in self.KeyFlagsByModuleDict().get(module, []):
if flag not in key_flags:
key_flags.append(flag)
return key_flags
def FindModuleDefiningFlag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module, flags in self.FlagsByModuleDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module
return default
def FindModuleIdDefiningFlag(self, flagname, default=None):
"""Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module_id, flags in self.FlagsByModuleIdDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module_id
return default
def AppendFlagValues(self, flag_values):
"""Appends flags registered in another FlagValues instance.
Args:
flag_values: registry to copy from
"""
for flag_name, flag in flag_values.FlagDict().iteritems():
# Each flags with shortname appears here twice (once under its
# normal name, and again with its short name). To prevent
# problems (DuplicateFlagError) with double flag registration, we
# perform a check to make sure that the entry we're looking at is
# for its normal name.
if flag_name == flag.name:
try:
self[flag_name] = flag
except DuplicateFlagError:
raise DuplicateFlagError(flag_name, self,
other_flag_values=flag_values)
def RemoveFlagValues(self, flag_values):
"""Remove flags that were previously appended from another FlagValues.
Args:
flag_values: registry containing flags to remove.
"""
for flag_name in flag_values.FlagDict():
self.__delattr__(flag_name)
def __setitem__(self, name, flag):
"""Registers a new flag variable."""
fl = self.FlagDict()
if not isinstance(flag, Flag):
raise IllegalFlagValue(flag)
if not isinstance(name, type("")):
raise FlagsError("Flag name must be a string")
if len(name) == 0:
raise FlagsError("Flag name cannot be empty")
# If running under pychecker, duplicate keys are likely to be
# defined. Disable check for duplicate keys when pycheck'ing.
if (name in fl and not flag.allow_override and
not fl[name].allow_override and not _RUNNING_PYCHECKER):
module, module_name = _GetCallingModuleObjectAndName()
if (self.FindModuleDefiningFlag(name) == module_name and
id(module) != self.FindModuleIdDefiningFlag(name)):
# If the flag has already been defined by a module with the same name,
# but a different ID, we can stop here because it indicates that the
# module is simply being imported a subsequent time.
return
raise DuplicateFlagError(name, self)
short_name = flag.short_name
if short_name is not None:
if (short_name in fl and not flag.allow_override and
not fl[short_name].allow_override and not _RUNNING_PYCHECKER):
raise DuplicateFlagError(short_name, self)
fl[short_name] = flag
fl[name] = flag
global _exported_flags
_exported_flags[name] = flag
def __getitem__(self, name):
"""Retrieves the Flag object for the flag --name."""
return self.FlagDict()[name]
def __getattr__(self, name):
"""Retrieves the 'value' attribute of the flag --name."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
return fl[name].value
def __setattr__(self, name, value):
"""Sets the 'value' attribute of the flag --name."""
fl = self.FlagDict()
fl[name].value = value
self._AssertValidators(fl[name].validators)
return value
def _AssertAllValidators(self):
all_validators = set()
for flag in self.FlagDict().itervalues():
for validator in flag.validators:
all_validators.add(validator)
self._AssertValidators(all_validators)
def _AssertValidators(self, validators):
"""Assert if all validators in the list are satisfied.
Asserts validators in the order they were created.
Args:
validators: Iterable(gflags_validators.Validator), validators to be
verified
Raises:
AttributeError: if validators work with a non-existing flag.
IllegalFlagValue: if validation fails for at least one validator
"""
for validator in sorted(
validators, key=lambda validator: validator.insertion_index):
try:
validator.Verify(self)
except gflags_validators.Error, e:
message = validator.PrintFlagsWithValues(self)
raise IllegalFlagValue('%s: %s' % (message, str(e)))
def _FlagIsRegistered(self, flag_obj):
"""Checks whether a Flag object is registered under some name.
Note: this is non trivial: in addition to its normal name, a flag
may have a short name too. In self.FlagDict(), both the normal and
the short name are mapped to the same flag object. E.g., calling
only "del FLAGS.short_name" is not unregistering the corresponding
Flag object (it is still registered under the longer name).
Args:
flag_obj: A Flag object.
Returns:
A boolean: True iff flag_obj is registered under some name.
"""
flag_dict = self.FlagDict()
# Check whether flag_obj is registered under its long name.
name = flag_obj.name
if flag_dict.get(name, None) == flag_obj:
return True
# Check whether flag_obj is registered under its short name.
short_name = flag_obj.short_name
if (short_name is not None and
flag_dict.get(short_name, None) == flag_obj):
return True
# The flag cannot be registered under any other name, so we do not
# need to do a full search through the values of self.FlagDict().
return False
def __delattr__(self, flag_name):
"""Deletes a previously-defined flag from a flag object.
This method makes sure we can delete a flag by using
del flag_values_object.<flag_name>
E.g.,
gflags.DEFINE_integer('foo', 1, 'Integer flag.')
del gflags.FLAGS.foo
Args:
flag_name: A string, the name of the flag to be deleted.
Raises:
AttributeError: When there is no registered flag named flag_name.
"""
fl = self.FlagDict()
if flag_name not in fl:
raise AttributeError(flag_name)
flag_obj = fl[flag_name]
del fl[flag_name]
if not self._FlagIsRegistered(flag_obj):
# If the Flag object indicated by flag_name is no longer
# registered (please see the docstring of _FlagIsRegistered), then
# we delete the occurrences of the flag object in all our internal
# dictionaries.
self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj)
def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj):
"""Removes a flag object from a module -> list of flags dictionary.
Args:
flags_by_module_dict: A dictionary that maps module names to lists of
flags.
flag_obj: A flag object.
"""
for unused_module, flags_in_module in flags_by_module_dict.iteritems():
# while (as opposed to if) takes care of multiple occurrences of a
# flag in the list for the same module.
while flag_obj in flags_in_module:
flags_in_module.remove(flag_obj)
def SetDefault(self, name, value):
"""Changes the default value of the named flag object."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
fl[name].SetDefault(value)
self._AssertValidators(fl[name].validators)
def __contains__(self, name):
"""Returns True if name is a value (flag) in the dict."""
return name in self.FlagDict()
has_key = __contains__ # a synonym for __contains__()
def __iter__(self):
return iter(self.FlagDict())
def __call__(self, argv):
"""Parses flags from argv; stores parsed flags into this FlagValues object.
All unparsed arguments are returned. Flags are parsed using the GNU
Program Argument Syntax Conventions, using getopt:
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt
Args:
argv: argument list. Can be of any type that may be converted to a list.
Returns:
The list of arguments not parsed as options, including argv[0]
Raises:
FlagsError: on any parsing error
"""
# Support any sequence type that can be converted to a list
argv = list(argv)
shortopts = ""
longopts = []
fl = self.FlagDict()
# This pre parses the argv list for --flagfile=<> options.
argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False)
# Correct the argv to support the google style of passing boolean
# parameters. Boolean parameters may be passed by using --mybool,
# --nomybool, --mybool=(true|false|1|0). getopt does not support
# having options that may or may not have a parameter. We replace
# instances of the short form --mybool and --nomybool with their
# full forms: --mybool=(true|false).
original_argv = list(argv) # list() makes a copy
shortest_matches = None
for name, flag in fl.items():
if not flag.boolean:
continue
if shortest_matches is None:
# Determine the smallest allowable prefix for all flag names
shortest_matches = self.ShortestUniquePrefixes(fl)
no_name = 'no' + name
prefix = shortest_matches[name]
no_prefix = shortest_matches[no_name]
# Replace all occurrences of this boolean with extended forms
for arg_idx in range(1, len(argv)):
arg = argv[arg_idx]
if arg.find('=') >= 0: continue
if arg.startswith('--'+prefix) and ('--'+name).startswith(arg):
argv[arg_idx] = ('--%s=true' % name)
elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg):
argv[arg_idx] = ('--%s=false' % name)
# Loop over all of the flags, building up the lists of short options
# and long options that will be passed to getopt. Short options are
# specified as a string of letters, each letter followed by a colon
# if it takes an argument. Long options are stored in an array of
# strings. Each string ends with an '=' if it takes an argument.
for name, flag in fl.items():
longopts.append(name + "=")
if len(name) == 1: # one-letter option: allow short flag type also
shortopts += name
if not flag.boolean:
shortopts += ":"
longopts.append('undefok=')
undefok_flags = []
# In case --undefok is specified, loop to pick up unrecognized
# options one by one.
unrecognized_opts = []
args = argv[1:]
while True:
try:
if self.__dict__['__use_gnu_getopt']:
optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts)
else:
optlist, unparsed_args = getopt.getopt(args, shortopts, longopts)
break
except getopt.GetoptError, e:
if not e.opt or e.opt in fl:
# Not an unrecognized option, re-raise the exception as a FlagsError
raise FlagsError(e)
# Remove offender from args and try again
for arg_index in range(len(args)):
if ((args[arg_index] == '--' + e.opt) or
(args[arg_index] == '-' + e.opt) or
(args[arg_index].startswith('--' + e.opt + '='))):
unrecognized_opts.append((e.opt, args[arg_index]))
args = args[0:arg_index] + args[arg_index+1:]
break
else:
# We should have found the option, so we don't expect to get
# here. We could assert, but raising the original exception
# might work better.
raise FlagsError(e)
for name, arg in optlist:
if name == '--undefok':
flag_names = arg.split(',')
undefok_flags.extend(flag_names)
# For boolean flags, if --undefok=boolflag is specified, then we should
# also accept --noboolflag, in addition to --boolflag.
# Since we don't know the type of the undefok'd flag, this will affect
# non-boolean flags as well.
# NOTE: You shouldn't use --undefok=noboolflag, because then we will
# accept --nonoboolflag here. We are choosing not to do the conversion
# from noboolflag -> boolflag because of the ambiguity that flag names
# can start with 'no'.
undefok_flags.extend('no' + name for name in flag_names)
continue
if name.startswith('--'):
# long option
name = name[2:]
short_option = 0
else:
# short option
name = name[1:]
short_option = 1
if name in fl:
flag = fl[name]
if flag.boolean and short_option: arg = 1
flag.Parse(arg)
# If there were unrecognized options, raise an exception unless
# the options were named via --undefok.
for opt, value in unrecognized_opts:
if opt not in undefok_flags:
raise UnrecognizedFlagError(opt, value)
if unparsed_args:
if self.__dict__['__use_gnu_getopt']:
# if using gnu_getopt just return the program name + remainder of argv.
ret_val = argv[:1] + unparsed_args
else:
# unparsed_args becomes the first non-flag detected by getopt to
# the end of argv. Because argv may have been modified above,
# return original_argv for this region.
ret_val = argv[:1] + original_argv[-len(unparsed_args):]
else:
ret_val = argv[:1]
self._AssertAllValidators()
return ret_val
def Reset(self):
"""Resets the values to the point before FLAGS(argv) was called."""
for f in self.FlagDict().values():
f.Unparse()
def RegisteredFlags(self):
"""Returns: a list of the names and short names of all registered flags."""
return list(self.FlagDict())
def FlagValuesDict(self):
"""Returns: a dictionary that maps flag names to flag values."""
flag_values = {}
for flag_name in self.RegisteredFlags():
flag = self.FlagDict()[flag_name]
flag_values[flag_name] = flag.value
return flag_values
def __str__(self):
"""Generates a help string for all known flags."""
return self.GetHelp()
def GetHelp(self, prefix=''):
"""Generates a help string for all known flags."""
helplist = []
flags_by_module = self.FlagsByModuleDict()
if flags_by_module:
modules = sorted(flags_by_module)
# Print the help for the main module first, if possible.
main_module = _GetMainModule()
if main_module in modules:
modules.remove(main_module)
modules = [main_module] + modules
for module in modules:
self.__RenderOurModuleFlags(module, helplist)
self.__RenderModuleFlags('gflags',
_SPECIAL_FLAGS.FlagDict().values(),
helplist)
else:
# Just print one long list of flags.
self.__RenderFlagList(
self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(),
helplist, prefix)
return '\n'.join(helplist)
def __RenderModuleFlags(self, module, flags, output_lines, prefix=""):
"""Generates a help string for a given module."""
if not isinstance(module, str):
module = module.__name__
output_lines.append('\n%s%s:' % (prefix, module))
self.__RenderFlagList(flags, output_lines, prefix + " ")
def __RenderOurModuleFlags(self, module, output_lines, prefix=""):
"""Generates a help string for a given module."""
flags = self._GetFlagsDefinedByModule(module)
if flags:
self.__RenderModuleFlags(module, flags, output_lines, prefix)
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""):
"""Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line.
"""
key_flags = self._GetKeyFlagsForModule(module)
if key_flags:
self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
def ModuleHelp(self, module):
"""Describe the key flags of a module.
Args:
module: A module object or a module name (a string).
Returns:
string describing the key flags of a module.
"""
helplist = []
self.__RenderOurModuleKeyFlags(module, helplist)
return '\n'.join(helplist)
def MainModuleHelp(self):
"""Describe the key flags of the main module.
Returns:
string describing the key flags of a module.
"""
return self.ModuleHelp(_GetMainModule())
def __RenderFlagList(self, flaglist, output_lines, prefix=" "):
fl = self.FlagDict()
special_fl = _SPECIAL_FLAGS.FlagDict()
flaglist = [(flag.name, flag) for flag in flaglist]
flaglist.sort()
flagset = {}
for (name, flag) in flaglist:
# It's possible this flag got deleted or overridden since being
# registered in the per-module flaglist. Check now against the
# canonical source of current flag information, the FlagDict.
if fl.get(name, None) != flag and special_fl.get(name, None) != flag:
# a different flag is using this name now
continue
# only print help once
if flag in flagset: continue
flagset[flag] = 1
flaghelp = ""
if flag.short_name: flaghelp += "-%s," % flag.short_name
if flag.boolean:
flaghelp += "--[no]%s" % flag.name + ":"
else:
flaghelp += "--%s" % flag.name + ":"
flaghelp += " "
if flag.help:
flaghelp += flag.help
flaghelp = TextWrap(flaghelp, indent=prefix+" ",
firstline_indent=prefix)
if flag.default_as_str:
flaghelp += "\n"
flaghelp += TextWrap("(default: %s)" % flag.default_as_str,
indent=prefix+" ")
if flag.parser.syntactic_help:
flaghelp += "\n"
flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help,
indent=prefix+" ")
output_lines.append(flaghelp)
def get(self, name, default):
"""Returns the value of a flag (if not None) or a default value.
Args:
name: A string, the name of a flag.
default: Default value to use if the flag value is None.
"""
value = self.__getattr__(name)
if value is not None: # Can't do if not value, b/c value might be '0' or ""
return value
else:
return default
def ShortestUniquePrefixes(self, fl):
"""Returns: dictionary; maps flag names to their shortest unique prefix."""
# Sort the list of flag names
sorted_flags = []
for name, flag in fl.items():
sorted_flags.append(name)
if flag.boolean:
sorted_flags.append('no%s' % name)
sorted_flags.sort()
# For each name in the sorted list, determine the shortest unique
# prefix by comparing itself to the next name and to the previous
# name (the latter check uses cached info from the previous loop).
shortest_matches = {}
prev_idx = 0
for flag_idx in range(len(sorted_flags)):
curr = sorted_flags[flag_idx]
if flag_idx == (len(sorted_flags) - 1):
next = None
else:
next = sorted_flags[flag_idx+1]
next_len = len(next)
for curr_idx in range(len(curr)):
if (next is None
or curr_idx >= next_len
or curr[curr_idx] != next[curr_idx]):
# curr longer than next or no more chars in common
shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1]
prev_idx = curr_idx
break
else:
# curr shorter than (or equal to) next
shortest_matches[curr] = curr
prev_idx = curr_idx + 1 # next will need at least one more char
return shortest_matches
def __IsFlagFileDirective(self, flag_string):
"""Checks whether flag_string contain a --flagfile=<foo> directive."""
if isinstance(flag_string, type("")):
if flag_string.startswith('--flagfile='):
return 1
elif flag_string == '--flagfile':
return 1
elif flag_string.startswith('-flagfile='):
return 1
elif flag_string == '-flagfile':
return 1
else:
return 0
return 0
def ExtractFilename(self, flagfile_str):
"""Returns filename from a flagfile_str of form -[-]flagfile=filename.
The cases of --flagfile foo and -flagfile foo shouldn't be hitting
this function, as they are dealt with in the level above this
function.
"""
if flagfile_str.startswith('--flagfile='):
return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip())
elif flagfile_str.startswith('-flagfile='):
return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip())
else:
raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str)
def __GetFlagFileLines(self, filename, parsed_file_list):
"""Returns the useful (!=comments, etc) lines from a file with flags.
Args:
filename: A string, the name of the flag file.
parsed_file_list: A list of the names of the files we have
already read. MUTATED BY THIS FUNCTION.
Returns:
List of strings. See the note below.
NOTE(springer): This function checks for a nested --flagfile=<foo>
tag and handles the lower file recursively. It returns a list of
all the lines that _could_ contain command flags. This is
EVERYTHING except whitespace lines and comments (lines starting
with '#' or '//').
"""
line_list = [] # All line from flagfile.
flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags.
try:
file_obj = open(filename, 'r')
except IOError, e_msg:
raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg)
line_list = file_obj.readlines()
file_obj.close()
parsed_file_list.append(filename)
# This is where we check each line in the file we just read.
for line in line_list:
if line.isspace():
pass
# Checks for comment (a line that starts with '#').
elif line.startswith('#') or line.startswith('//'):
pass
# Checks for a nested "--flagfile=<bar>" flag in the current file.
# If we find one, recursively parse down into that file.
elif self.__IsFlagFileDirective(line):
sub_filename = self.ExtractFilename(line)
# We do a little safety check for reparsing a file we've already done.
if not sub_filename in parsed_file_list:
included_flags = self.__GetFlagFileLines(sub_filename,
parsed_file_list)
flag_line_list.extend(included_flags)
else: # Case of hitting a circularly included file.
sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' %
(sub_filename,))
else:
# Any line that's not a comment or a nested flagfile should get
# copied into 2nd position. This leaves earlier arguments
# further back in the list, thus giving them higher priority.
flag_line_list.append(line.strip())
return flag_line_list
def ReadFlagsFromFiles(self, argv, force_gnu=True):
"""Processes command line args, but also allow args to be read from file.
Args:
argv: A list of strings, usually sys.argv[1:], which may contain one or
more flagfile directives of the form --flagfile="./filename".
Note that the name of the program (sys.argv[0]) should be omitted.
force_gnu: If False, --flagfile parsing obeys normal flag semantics.
If True, --flagfile parsing instead follows gnu_getopt semantics.
*** WARNING *** force_gnu=False may become the future default!
Returns:
A new list which has the original list combined with what we read
from any flagfile(s).
References: Global gflags.FLAG class instance.
This function should be called before the normal FLAGS(argv) call.
This function scans the input list for a flag that looks like:
--flagfile=<somefile>. Then it opens <somefile>, reads all valid key
and value pairs and inserts them into the input list between the
first item of the list and any subsequent items in the list.
Note that your application's flags are still defined the usual way
using gflags DEFINE_flag() type functions.
Notes (assuming we're getting a commandline of some sort as our input):
--> Flags from the command line argv _should_ always take precedence!
--> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile.
It will be processed after the parent flag file is done.
--> For duplicate flags, first one we hit should "win".
--> In a flagfile, a line beginning with # or // is a comment.
--> Entirely blank lines _should_ be ignored.
"""
parsed_file_list = []
rest_of_args = argv
new_argv = []
while rest_of_args:
current_arg = rest_of_args[0]
rest_of_args = rest_of_args[1:]
if self.__IsFlagFileDirective(current_arg):
# This handles the case of -(-)flagfile foo. In this case the
# next arg really is part of this one.
if current_arg == '--flagfile' or current_arg == '-flagfile':
if not rest_of_args:
raise IllegalFlagValue('--flagfile with no argument')
flag_filename = os.path.expanduser(rest_of_args[0])
rest_of_args = rest_of_args[1:]
else:
# This handles the case of (-)-flagfile=foo.
flag_filename = self.ExtractFilename(current_arg)
new_argv.extend(
self.__GetFlagFileLines(flag_filename, parsed_file_list))
else:
new_argv.append(current_arg)
# Stop parsing after '--', like getopt and gnu_getopt.
if current_arg == '--':
break
# Stop parsing after a non-flag, like getopt.
if not current_arg.startswith('-'):
if not force_gnu and not self.__dict__['__use_gnu_getopt']:
break
if rest_of_args:
new_argv.extend(rest_of_args)
return new_argv
def FlagsIntoString(self):
"""Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/p/google-gflags
"""
s = ''
for flag in self.FlagDict().values():
if flag.value is not None:
s += flag.Serialize() + '\n'
return s
def AppendFlagsIntoFile(self, filename):
"""Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
"""
out_file = open(filename, 'a')
out_file.write(self.FlagsIntoString())
out_file.close()
def WriteHelpInXMLFormat(self, outfile=None):
"""Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
http://code.google.com/p/google-gflags
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout.
"""
outfile = outfile or sys.stdout
outfile.write('<?xml version=\"1.0\"?>\n')
outfile.write('<AllFlags>\n')
indent = ' '
_WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]),
indent)
usage_doc = sys.modules['__main__'].__doc__
if not usage_doc:
usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
else:
usage_doc = usage_doc.replace('%s', sys.argv[0])
_WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent)
# Get list of key flags for the main module.
key_flags = self._GetKeyFlagsForModule(_GetMainModule())
# Sort flags by declaring module name and next by flag name.
flags_by_module = self.FlagsByModuleDict()
all_module_names = list(flags_by_module.keys())
all_module_names.sort()
for module_name in all_module_names:
flag_list = [(f.name, f) for f in flags_by_module[module_name]]
flag_list.sort()
for unused_flag_name, flag in flag_list:
is_key = flag in key_flags
flag.WriteInfoInXMLFormat(outfile, module_name,
is_key=is_key, indent=indent)
outfile.write('</AllFlags>\n')
outfile.flush()
def AddValidator(self, validator):
"""Register new flags validator to be checked.
Args:
validator: gflags_validators.Validator
Raises:
AttributeError: if validators work with a non-existing flag.
"""
for flag_name in validator.GetFlagsNames():
flag = self.FlagDict()[flag_name]
flag.validators.append(validator)
# end of FlagValues definition
# The global FlagValues instance
FLAGS = FlagValues()
def _StrOrUnicode(value):
"""Converts value to a python string or, if necessary, unicode-string."""
try:
return str(value)
except UnicodeEncodeError:
return unicode(value)
def _MakeXMLSafe(s):
"""Escapes <, >, and & from s, and removes XML 1.0-illegal chars."""
s = cgi.escape(s) # Escape <, >, and &
# Remove characters that cannot appear in an XML 1.0 document
# (http://www.w3.org/TR/REC-xml/#charsets).
#
# NOTE: if there are problems with current solution, one may move to
# XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;).
s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s)
# Convert non-ascii characters to entities. Note: requires python >=2.3
s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'uΈ'
return s
def _WriteSimpleXMLElement(outfile, name, value, indent):
"""Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output.
"""
value_str = _StrOrUnicode(value)
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
value_str = value_str.lower()
safe_value_str = _MakeXMLSafe(value_str)
outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name))
class Flag:
"""Information about a command-line flag.
'Flag' objects define the following fields:
.name - the name for this flag
.default - the default value for this flag
.default_as_str - default value as repr'd string, e.g., "'true'" (or None)
.value - the most recent parsed value of this flag; set by Parse()
.help - a help string or None if no help is available
.short_name - the single letter alias for this flag (or None)
.boolean - if 'true', this flag does not accept arguments
.present - true if this flag was parsed from command line flags.
.parser - an ArgumentParser object
.serializer - an ArgumentSerializer object
.allow_override - the flag may be redefined without raising an error
The only public method of a 'Flag' object is Parse(), but it is
typically only called by a 'FlagValues' object. The Parse() method is
a thin wrapper around the 'ArgumentParser' Parse() method. The parsed
value is saved in .value, and the .present attribute is updated. If
this flag was already present, a FlagsError is raised.
Parse() is also called during __init__ to parse the default value and
initialize the .value attribute. This enables other python modules to
safely use flags even if the __main__ module neglects to parse the
command line arguments. The .present attribute is cleared after
__init__ parsing. If the default value is set to None, then the
__init__ parsing step is skipped and the .value attribute is
initialized to None.
Note: The default value is also presented to the user in the help
string, so it is important that it be a legal value for this flag.
"""
def __init__(self, parser, serializer, name, default, help_string,
short_name=None, boolean=0, allow_override=0):
self.name = name
if not help_string:
help_string = '(no help available)'
self.help = help_string
self.short_name = short_name
self.boolean = boolean
self.present = 0
self.parser = parser
self.serializer = serializer
self.allow_override = allow_override
self.value = None
self.validators = []
self.SetDefault(default)
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return self is other
def __lt__(self, other):
if isinstance(other, Flag):
return id(self) < id(other)
return NotImplemented
def __GetParsedValueAsString(self, value):
if value is None:
return None
if self.serializer:
return repr(self.serializer.Serialize(value))
if self.boolean:
if value:
return repr('true')
else:
return repr('false')
return repr(_StrOrUnicode(value))
def Parse(self, argument):
try:
self.value = self.parser.Parse(argument)
except ValueError, e: # recast ValueError as IllegalFlagValue
raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e))
self.present += 1
def Unparse(self):
if self.default is None:
self.value = None
else:
self.Parse(self.default)
self.present = 0
def Serialize(self):
if self.value is None:
return ''
if self.boolean:
if self.value:
return "--%s" % self.name
else:
return "--no%s" % self.name
else:
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
return "--%s=%s" % (self.name, self.serializer.Serialize(self.value))
def SetDefault(self, value):
"""Changes the default value (and current value too) for this Flag."""
# We can't allow a None override because it may end up not being
# passed to C++ code when we're overriding C++ flags. So we
# cowardly bail out until someone fixes the semantics of trying to
# pass None to a C++ flag. See swig_flags.Init() for details on
# this behavior.
# TODO(olexiy): Users can directly call this method, bypassing all flags
# validators (we don't have FlagValues here, so we can not check
# validators).
# The simplest solution I see is to make this method private.
# Another approach would be to store reference to the corresponding
# FlagValues with each flag, but this seems to be an overkill.
if value is None and self.allow_override:
raise DuplicateFlagCannotPropagateNoneToSwig(self.name)
self.default = value
self.Unparse()
self.default_as_str = self.__GetParsedValueAsString(self.value)
def Type(self):
"""Returns: a string that describes the type of this Flag."""
# NOTE: we use strings, and not the types.*Type constants because
# our flags can have more exotic types, e.g., 'comma separated list
# of strings', 'whitespace separated list of strings', etc.
return self.parser.Type()
def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''):
"""Writes common info about this flag, in XML format.
This is information that is relevant to all flags (e.g., name,
meaning, etc.). If you defined a flag that has some other pieces of
info, then please override _WriteCustomInfoInXMLFormat.
Please do NOT override this method.
Args:
outfile: File object we write to.
module_name: A string, the name of the module that defines this flag.
is_key: A boolean, True iff this flag is key for main module.
indent: A string that is prepended to each generated line.
"""
outfile.write(indent + '<flag>\n')
inner_indent = indent + ' '
if is_key:
_WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent)
_WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent)
# Print flag features that are relevant for all flags.
_WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent)
if self.short_name:
_WriteSimpleXMLElement(outfile, 'short_name', self.short_name,
inner_indent)
if self.help:
_WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent)
# The default flag value can either be represented as a string like on the
# command line, or as a Python object. We serialize this value in the
# latter case in order to remain consistent.
if self.serializer and not isinstance(self.default, str):
default_serialized = self.serializer.Serialize(self.default)
else:
default_serialized = self.default
_WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent)
_WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent)
_WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent)
# Print extra flag features this flag may have.
self._WriteCustomInfoInXMLFormat(outfile, inner_indent)
outfile.write(indent + '</flag>\n')
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
"""Writes extra info about this flag, in XML format.
"Extra" means "not already printed by WriteInfoInXMLFormat above."
Args:
outfile: File object we write to.
indent: A string that is prepended to each generated line.
"""
# Usually, the parser knows the extra details about the flag, so
# we just forward the call to it.
self.parser.WriteCustomInfoInXMLFormat(outfile, indent)
# End of Flag definition
class _ArgumentParserCache(type):
"""Metaclass used to cache and share argument parsers among flags."""
_instances = {}
def __call__(mcs, *args, **kwargs):
"""Returns an instance of the argument parser cls.
This method overrides behavior of the __new__ methods in
all subclasses of ArgumentParser (inclusive). If an instance
for mcs with the same set of arguments exists, this instance is
returned, otherwise a new instance is created.
If any keyword arguments are defined, or the values in args
are not hashable, this method always returns a new instance of
cls.
Args:
args: Positional initializer arguments.
kwargs: Initializer keyword arguments.
Returns:
An instance of cls, shared or new.
"""
if kwargs:
return type.__call__(mcs, *args, **kwargs)
else:
instances = mcs._instances
key = (mcs,) + tuple(args)
try:
return instances[key]
except KeyError:
# No cache entry for key exists, create a new one.
return instances.setdefault(key, type.__call__(mcs, *args))
except TypeError:
# An object in args cannot be hashed, always return
# a new instance.
return type.__call__(mcs, *args)
class ArgumentParser(object):
"""Base class used to parse and convert arguments.
The Parse() method checks to make sure that the string argument is a
legal value and convert it to a native type. If the value cannot be
converted, it should throw a 'ValueError' exception with a human
readable explanation of why the value is illegal.
Subclasses should also define a syntactic_help string which may be
presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached
and shared between flags. Initializer arguments are allowed, but all
member variables must be derived from initializer arguments only.
"""
__metaclass__ = _ArgumentParserCache
syntactic_help = ""
def Parse(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
def Type(self):
return 'string'
def WriteCustomInfoInXMLFormat(self, outfile, indent):
pass
class ArgumentSerializer:
"""Base class for generating string representations of a flag value."""
def Serialize(self, value):
return _StrOrUnicode(value)
class ListSerializer(ArgumentSerializer):
def __init__(self, list_sep):
self.list_sep = list_sep
def Serialize(self, value):
return self.list_sep.join([_StrOrUnicode(x) for x in value])
# Flags validators
def RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: string, name of the flag to be checked.
checker: method to validate the flag.
input - value of the corresponding flag (string, boolean, etc.
This value will be passed to checker by the library). See file's
docstring for examples.
output - Boolean.
Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise gflags_validators.Error(desired_error_message).
message: error text to be shown to the user if checker returns False.
If checker raises gflags_validators.Error, message from the raised
Error will be shown.
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name,
checker,
message))
def MarkFlagAsRequired(flag_name, flag_values=FLAGS):
"""Ensure that flag is not None during program execution.
Registers a flag validator, which will follow usual validator
rules.
Args:
flag_name: string, name of the flag
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
RegisterValidator(flag_name,
lambda value: value is not None,
message='Flag --%s must be specified.' % flag_name,
flag_values=flag_values)
def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values):
"""Enforce lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser). Provides lower
and upper bounds, and help text to display.
name: string, name of the flag
flag_values: FlagValues
"""
if parser.lower_bound is not None or parser.upper_bound is not None:
def Checker(value):
if value is not None and parser.IsOutsideBounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise gflags_validators.Error(message)
return True
RegisterValidator(name,
Checker,
flag_values=flag_values)
# The DEFINE functions are explained in mode details in the module doc string.
def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None,
**args):
"""Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser that is used to parse the flag arguments.
name: A string, the flag name.
default: The default value of the flag.
help: A help string.
flag_values: FlagValues object the flag will be registered with.
serializer: ArgumentSerializer that serializes the flag value.
args: Dictionary with extra keyword args that are passes to the
Flag __init__.
"""
DEFINE_flag(Flag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_flag(flag, flag_values=FLAGS):
"""Registers a 'Flag' object with a 'FlagValues' object.
By default, the global FLAGS 'FlagValue' object is used.
Typical users will use one of the more specialized DEFINE_xxx
functions, such as DEFINE_string or DEFINE_integer. But developers
who need to create Flag objects themselves should use this function
to register their flags.
"""
# copying the reference to flag_values prevents pychecker warnings
fv = flag_values
fv[flag.name] = flag
# Tell flag_values who's defining the flag.
if isinstance(flag_values, FlagValues):
# Regarding the above isinstance test: some users pass funny
# values of flag_values (e.g., {}) in order to avoid the flag
# registration (in the past, there used to be a flag_values ==
# FLAGS test here) and redefine flags with the same name (e.g.,
# debug). To avoid breaking their code, we perform the
# registration only if flag_values is a real FlagValues object.
module, module_name = _GetCallingModuleObjectAndName()
flag_values._RegisterFlagByModule(module_name, flag)
flag_values._RegisterFlagByModuleId(id(module), flag)
def _InternalDeclareKeyFlags(flag_names,
flag_values=FLAGS, key_flag_values=None):
"""Declares a flag as key for the calling module.
Internal function. User code should call DECLARE_key_flag or
ADOPT_module_key_flags instead.
Args:
flag_names: A list of strings that are names of already-registered
Flag objects.
flag_values: A FlagValues object that the flags listed in
flag_names have registered with (the value of the flag_values
argument from the DEFINE_* calls that defined those flags).
This should almost never need to be overridden.
key_flag_values: A FlagValues object that (among possibly many
other things) keeps track of the key flags for each module.
Default None means "same as flag_values". This should almost
never need to be overridden.
Raises:
UnrecognizedFlagError: when we refer to a flag that was not
defined yet.
"""
key_flag_values = key_flag_values or flag_values
module = _GetCallingModule()
for flag_name in flag_names:
if flag_name not in flag_values:
raise UnrecognizedFlagError(flag_name)
flag = flag_values.FlagDict()[flag_name]
key_flag_values._RegisterKeyFlagForModule(module, flag)
def DECLARE_key_flag(flag_name, flag_values=FLAGS):
"""Declares one flag as key to the current module.
Key flags are flags that are deemed really important for a module.
They are important when listing help messages; e.g., if the
--helpshort command-line flag is used, then only the key flags of the
main module are listed (instead of all flags, as in the case of
--help).
Sample usage:
gflags.DECLARED_key_flag('flag_1')
Args:
flag_name: A string, the name of an already declared flag.
(Redeclaring flags as key, including flags implicitly key
because they were declared in this module, is a no-op.)
flag_values: A FlagValues object. This should almost never
need to be overridden.
"""
if flag_name in _SPECIAL_FLAGS:
# Take care of the special flags, e.g., --flagfile, --undefok.
# These flags are defined in _SPECIAL_FLAGS, and are treated
# specially during flag parsing, taking precedence over the
# user-defined flags.
_InternalDeclareKeyFlags([flag_name],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
return
_InternalDeclareKeyFlags([flag_name], flag_values=flag_values)
def ADOPT_module_key_flags(module, flag_values=FLAGS):
"""Declares that all flags key to a module are key to the current module.
Args:
module: A module object.
flag_values: A FlagValues object. This should almost never need
to be overridden.
Raises:
FlagsError: When given an argument that is a module name (a
string), instead of a module object.
"""
# NOTE(salcianu): an even better test would be if not
# isinstance(module, types.ModuleType) but I didn't want to import
# types for such a tiny use.
if isinstance(module, str):
raise FlagsError('Received module name %s; expected a module object.'
% module)
_InternalDeclareKeyFlags(
[f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)],
flag_values=flag_values)
# If module is this flag module, take _SPECIAL_FLAGS into account.
if module == _GetThisModuleObjectAndName()[0]:
_InternalDeclareKeyFlags(
# As we associate flags with _GetCallingModuleObjectAndName(), the
# special flags defined in this module are incorrectly registered with
# a different module. So, we can't use _GetKeyFlagsForModule.
# Instead, we take all flags from _SPECIAL_FLAGS (a private
# FlagValues, where no other module should register flags).
[f.name for f in _SPECIAL_FLAGS.FlagDict().values()],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
#
# STRING FLAGS
#
def DEFINE_string(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be any string."""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# BOOLEAN FLAGS
#
class BooleanParser(ArgumentParser):
"""Parser of boolean values."""
def Convert(self, argument):
"""Converts the argument to a boolean; raise ValueError on errors."""
if type(argument) == str:
if argument.lower() in ['true', 't', '1']:
return True
elif argument.lower() in ['false', 'f', '0']:
return False
bool_argument = bool(argument)
if argument == bool_argument:
# The argument is a valid boolean (True, False, 0, or 1), and not just
# something that always converts to bool (list, string, int, etc.).
return bool_argument
raise ValueError('Non-boolean argument to boolean flag', argument)
def Parse(self, argument):
val = self.Convert(argument)
return val
def Type(self):
return 'bool'
class BooleanFlag(Flag):
"""Basic boolean flag.
Boolean flags do not take any arguments, and their value is either
True (1) or False (0). The false value is specified on the command
line by prepending the word 'no' to either the long or the short flag
name.
For example, if a Boolean flag was created whose long name was
'update' and whose short name was 'x', then this flag could be
explicitly unset through either --noupdate or --nox.
"""
def __init__(self, name, default, help, short_name=None, **args):
p = BooleanParser()
Flag.__init__(self, p, None, name, default, help, short_name, 1, **args)
if not self.help: self.help = "a boolean value"
def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args):
"""Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to
specify a false value explicitly, the long option beginning with 'no'
must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible
if default=None and the user does not specify the flag on the command
line.
"""
DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values)
# Match C++ API to unconfuse C++ people.
DEFINE_bool = DEFINE_boolean
class HelpFlag(BooleanFlag):
"""
HelpFlag is a special boolean flag that prints usage information and
raises a SystemExit exception if it is ever found in the command
line arguments. Note this is called with allow_override=1, so other
apps can define their own --help flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "help", 0, "show this help",
short_name="?", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = str(FLAGS)
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
class HelpXMLFlag(BooleanFlag):
"""Similar to HelpFlag, but generates output in XML format."""
def __init__(self):
BooleanFlag.__init__(self, 'helpxml', False,
'like --help, but generates XML output',
allow_override=1)
def Parse(self, arg):
if arg:
FLAGS.WriteHelpInXMLFormat(sys.stdout)
sys.exit(1)
class HelpshortFlag(BooleanFlag):
"""
HelpshortFlag is a special boolean flag that prints usage
information for the "main" module, and rasies a SystemExit exception
if it is ever found in the command line arguments. Note this is
called with allow_override=1, so other apps can define their own
--helpshort flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "helpshort", 0,
"show usage only for this module", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = FLAGS.MainModuleHelp()
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
#
# Numeric parser - base class for Integer and Float parsers
#
class NumericParser(ArgumentParser):
"""Parser of numeric values.
Parsed value may be bounded to a given upper and lower bound.
"""
def IsOutsideBounds(self, val):
return ((self.lower_bound is not None and val < self.lower_bound) or
(self.upper_bound is not None and val > self.upper_bound))
def Parse(self, argument):
val = self.Convert(argument)
if self.IsOutsideBounds(val):
raise ValueError("%s is not %s" % (val, self.syntactic_help))
return val
def WriteCustomInfoInXMLFormat(self, outfile, indent):
if self.lower_bound is not None:
_WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent)
if self.upper_bound is not None:
_WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent)
def Convert(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
# End of Numeric Parser
#
# FLOAT FLAGS
#
class FloatParser(NumericParser):
"""Parser of floating point values.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "a"
number_name = "number"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(FloatParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
"""Converts argument to a float; raises ValueError on errors."""
return float(argument)
def Type(self):
return 'float'
# End of FloatParser
def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must be
within the given range.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# INTEGER FLAGS
#
class IntegerParser(NumericParser):
"""Parser of an integer value.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "an"
number_name = "integer"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(IntegerParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 1:
sh = "a positive %s" % self.number_name
elif upper_bound == -1:
sh = "a negative %s" % self.number_name
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
__pychecker__ = 'no-returnvalues'
if type(argument) == str:
base = 10
if len(argument) > 2 and argument[0] == "0" and argument[1] == "x":
base = 16
return int(argument, base)
else:
return int(argument)
def Type(self):
return 'int'
def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# ENUM FLAGS
#
class EnumParser(ArgumentParser):
"""Parser of a string enum value (a string value from a given set).
If enum_values (see below) is not specified, any string is allowed.
"""
def __init__(self, enum_values=None):
super(EnumParser, self).__init__()
self.enum_values = enum_values
def Parse(self, argument):
if self.enum_values and argument not in self.enum_values:
raise ValueError("value should be one of <%s>" %
"|".join(self.enum_values))
return argument
def Type(self):
return 'string enum'
class EnumFlag(Flag):
"""Basic enum flag; its value can be any string from list of enum_values."""
def __init__(self, name, default, help, enum_values=None,
short_name=None, **args):
enum_values = enum_values or []
p = EnumParser(enum_values)
g = ArgumentSerializer()
Flag.__init__(self, p, g, name, default, help, short_name, **args)
if not self.help: self.help = "an enum string"
self.help = "<%s>: %s" % ("|".join(enum_values), self.help)
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
for enum_value in self.parser.enum_values:
_WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent)
def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS,
**args):
"""Registers a flag whose value can be any string from enum_values."""
DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args),
flag_values)
#
# LIST FLAGS
#
class BaseListParser(ArgumentParser):
"""Base class for a parser of lists of strings.
To extend, inherit from this class; from the subclass __init__, call
BaseListParser.__init__(self, token, name)
where token is a character used to tokenize, and name is a description
of the separator.
"""
def __init__(self, token=None, name=None):
assert name
super(BaseListParser, self).__init__()
self._token = token
self._name = name
self.syntactic_help = "a %s separated list" % self._name
def Parse(self, argument):
if isinstance(argument, list):
return argument
elif argument == '':
return []
else:
return [s.strip() for s in argument.split(self._token)]
def Type(self):
return '%s separated list of strings' % self._name
class ListParser(BaseListParser):
"""Parser for a comma-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, ',', 'comma')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
_WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent)
class WhitespaceSeparatedListParser(BaseListParser):
"""Parser for a whitespace-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, None, 'whitespace')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
separators = list(string.whitespace)
separators.sort()
for ws_char in string.whitespace:
_WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent)
def DEFINE_list(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a comma-separated list of strings."""
parser = ListParser()
serializer = ListSerializer(',')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
"""
parser = WhitespaceSeparatedListParser()
serializer = ListSerializer(' ')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# MULTI FLAGS
#
class MultiFlag(Flag):
"""A flag that can appear multiple time on the command-line.
The value of such a flag is a list that contains the individual values
from all the appearances of that flag on the command-line.
See the __doc__ for Flag for most behavior of this class. Only
differences in behavior are described here:
* The default value may be either a single value or a list of values.
A single value is interpreted as the [value] singleton list.
* The value of the flag is always a list, even if the option was
only supplied once, and even if the default value is a single
value
"""
def __init__(self, *args, **kwargs):
Flag.__init__(self, *args, **kwargs)
self.help += ';\n repeat this option to specify a list of values'
def Parse(self, arguments):
"""Parses one or more arguments with the installed parser.
Args:
arguments: a single argument or a list of arguments (typically a
list of default values); a single argument is converted
internally into a list containing one item.
"""
if not isinstance(arguments, list):
# Default value may be a list of values. Most other arguments
# will not be, so convert them into a single-item list to make
# processing simpler below.
arguments = [arguments]
if self.present:
# keep a backup reference to list of previously supplied option values
values = self.value
else:
# "erase" the defaults with an empty list
values = []
for item in arguments:
# have Flag superclass parse argument, overwriting self.value reference
Flag.Parse(self, item) # also increments self.present
values.append(self.value)
# put list of option values back in the 'value' attribute
self.value = values
def Serialize(self):
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
if self.value is None:
return ''
s = ''
multi_value = self.value
for self.value in multi_value:
if s: s += ' '
s += Flag.Serialize(self)
self.value = multi_value
return s
def Type(self):
return 'multi ' + self.parser.Type()
def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS,
**args):
"""Registers a generic MultiFlag that parses its args with a given parser.
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own 'Parser' classes for options
which can appear multiple times can call this module function to
register their flags.
"""
DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of any strings.
Use the flag on the command line multiple times to place multiple
string values into the list. The 'default' may be a single string
(which will be converted into a single-element list) or a list of
strings.
"""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary integers.
Use the flag on the command line multiple times to place multiple
integer values into the list. The 'default' may be a single integer
(which will be converted into a single-element list) or a list of
integers.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary floats.
Use the flag on the command line multiple times to place multiple
float values into the list. The 'default' may be a single float
(which will be converted into a single-element list) or a list of
floats.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
# Now register the flags that we want to exist in all applications.
# These are all defined with allow_override=1, so user-apps can use
# these flagnames for their own purposes, if they want.
DEFINE_flag(HelpFlag())
DEFINE_flag(HelpshortFlag())
DEFINE_flag(HelpXMLFlag())
# Define special flags here so that help may be generated for them.
# NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module.
_SPECIAL_FLAGS = FlagValues()
DEFINE_string(
'flagfile', "",
"Insert flag definitions from the given file into the command line.",
_SPECIAL_FLAGS)
DEFINE_string(
'undefok', "",
"comma-separated list of flag names that it is okay to specify "
"on the command line even if the program does not define a flag "
"with that name. IMPORTANT: flags in this list that have "
"arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
| Python |
#!/usr/bin/python
'''Usage: %s [OPTIONS] <input file(s)>
Generate test source file for CxxTest.
-v, --version Write CxxTest version
-o, --output=NAME Write output to file NAME
--runner=CLASS Create a main() function that runs CxxTest::CLASS
--gui=CLASS Like --runner, with GUI component
--error-printer Same as --runner=ErrorPrinter
--abort-on-fail Abort tests on failed asserts (like xUnit)
--have-std Use standard library (even if not found in tests)
--no-std Don\'t use standard library (even if found in tests)
--have-eh Use exception handling (even if not found in tests)
--no-eh Don\'t use exception handling (even if found in tests)
--longlong=[TYPE] Use TYPE (default: long long) as long long
--template=TEMPLATE Use TEMPLATE file to generate the test runner
--include=HEADER Include HEADER in test runner before other headers
--root Write CxxTest globals
--part Don\'t write CxxTest globals
--no-static-init Don\'t rely on static initialization
'''
import re
import sys
import getopt
import glob
import string
# Global variables
suites = []
suite = None
inBlock = 0
outputFileName = None
runner = None
gui = None
root = None
part = None
noStaticInit = None
templateFileName = None
headers = []
haveExceptionHandling = 0
noExceptionHandling = 0
haveStandardLibrary = 0
noStandardLibrary = 0
abortOnFail = 0
factor = 0
longlong = 0
def main():
'''The main program'''
files = parseCommandline()
scanInputFiles( files )
writeOutput()
def usage( problem = None ):
'''Print usage info and exit'''
if problem is None:
print usageString()
sys.exit(0)
else:
sys.stderr.write( usageString() )
abort( problem )
def usageString():
'''Construct program usage string'''
return __doc__ % sys.argv[0]
def abort( problem ):
'''Print error message and exit'''
sys.stderr.write( '\n' )
sys.stderr.write( problem )
sys.stderr.write( '\n\n' )
sys.exit(2)
def parseCommandline():
'''Analyze command line arguments'''
try:
options, patterns = getopt.getopt( sys.argv[1:], 'o:r:',
['version', 'output=', 'runner=', 'gui=',
'error-printer', 'abort-on-fail', 'have-std', 'no-std',
'have-eh', 'no-eh', 'template=', 'include=',
'root', 'part', 'no-static-init', 'factor', 'longlong='] )
except getopt.error, problem:
usage( problem )
setOptions( options )
return setFiles( patterns )
def setOptions( options ):
'''Set options specified on command line'''
global outputFileName, templateFileName, runner, gui, haveStandardLibrary, factor, longlong
global haveExceptionHandling, noExceptionHandling, abortOnFail, headers, root, part, noStaticInit
for o, a in options:
if o in ('-v', '--version'):
printVersion()
elif o in ('-o', '--output'):
outputFileName = a
elif o == '--template':
templateFileName = a
elif o == '--runner':
runner = a
elif o == '--gui':
gui = a
elif o == '--include':
if not re.match( r'^["<].*[>"]$', a ):
a = ('"%s"' % a)
headers.append( a )
elif o == '--error-printer':
runner = 'ErrorPrinter'
haveStandardLibrary = 1
elif o == '--abort-on-fail':
abortOnFail = 1
elif o == '--have-std':
haveStandardLibrary = 1
elif o == '--no-std':
noStandardLibrary = 1
elif o == '--have-eh':
haveExceptionHandling = 1
elif o == '--no-eh':
noExceptionHandling = 1
elif o == '--root':
root = 1
elif o == '--part':
part = 1
elif o == '--no-static-init':
noStaticInit = 1
elif o == '--factor':
factor = 1
elif o == '--longlong':
if a:
longlong = a
else:
longlong = 'long long'
if noStaticInit and (root or part):
abort( '--no-static-init cannot be used with --root/--part' )
if gui and not runner:
runner = 'StdioPrinter'
def printVersion():
'''Print CxxTest version and exit'''
sys.stdout.write( "This is CxxTest version 3.10.1.\n" )
sys.exit(0)
def setFiles( patterns ):
'''Set input files specified on command line'''
files = expandWildcards( patterns )
if len(files) is 0 and not root:
usage( "No input files found" )
return files
def expandWildcards( patterns ):
'''Expand all wildcards in an array (glob)'''
fileNames = []
for pathName in patterns:
patternFiles = glob.glob( pathName )
for fileName in patternFiles:
fileNames.append( fixBackslashes( fileName ) )
return fileNames
def fixBackslashes( fileName ):
'''Convert backslashes to slashes in file name'''
return re.sub( r'\\', '/', fileName, 0 )
def scanInputFiles(files):
'''Scan all input files for test suites'''
for file in files:
scanInputFile(file)
global suites
if len(suites) is 0 and not root:
abort( 'No tests defined' )
def scanInputFile(fileName):
'''Scan single input file for test suites'''
file = open(fileName)
lineNo = 0
while 1:
line = file.readline()
if not line:
break
lineNo = lineNo + 1
scanInputLine( fileName, lineNo, line )
closeSuite()
file.close()
def scanInputLine( fileName, lineNo, line ):
'''Scan single input line for interesting stuff'''
scanLineForExceptionHandling( line )
scanLineForStandardLibrary( line )
scanLineForSuiteStart( fileName, lineNo, line )
global suite
if suite:
scanLineInsideSuite( suite, lineNo, line )
def scanLineInsideSuite( suite, lineNo, line ):
'''Analyze line which is part of a suite'''
global inBlock
if lineBelongsToSuite( suite, lineNo, line ):
scanLineForTest( suite, lineNo, line )
scanLineForCreate( suite, lineNo, line )
scanLineForDestroy( suite, lineNo, line )
def lineBelongsToSuite( suite, lineNo, line ):
'''Returns whether current line is part of the current suite.
This can be false when we are in a generated suite outside of CXXTEST_CODE() blocks
If the suite is generated, adds the line to the list of lines'''
if not suite['generated']:
return 1
global inBlock
if not inBlock:
inBlock = lineStartsBlock( line )
if inBlock:
inBlock = addLineToBlock( suite, lineNo, line )
return inBlock
std_re = re.compile( r"\b(std\s*::|CXXTEST_STD|using\s+namespace\s+std\b|^\s*\#\s*include\s+<[a-z0-9]+>)" )
def scanLineForStandardLibrary( line ):
'''Check if current line uses standard library'''
global haveStandardLibrary, noStandardLibrary
if not haveStandardLibrary and std_re.search(line):
if not noStandardLibrary:
haveStandardLibrary = 1
exception_re = re.compile( r"\b(throw|try|catch|TSM?_ASSERT_THROWS[A-Z_]*)\b" )
def scanLineForExceptionHandling( line ):
'''Check if current line uses exception handling'''
global haveExceptionHandling, noExceptionHandling
if not haveExceptionHandling and exception_re.search(line):
if not noExceptionHandling:
haveExceptionHandling = 1
suite_re = re.compile( r'\bclass\s+(\w+)\s*:\s*public\s+((::)?\s*CxxTest\s*::\s*)?TestSuite\b' )
generatedSuite_re = re.compile( r'\bCXXTEST_SUITE\s*\(\s*(\w*)\s*\)' )
def scanLineForSuiteStart( fileName, lineNo, line ):
'''Check if current line starts a new test suite'''
m = suite_re.search( line )
if m:
startSuite( m.group(1), fileName, lineNo, 0 )
m = generatedSuite_re.search( line )
if m:
sys.stdout.write( "%s:%s: Warning: Inline test suites are deprecated.\n" % (fileName, lineNo) )
startSuite( m.group(1), fileName, lineNo, 1 )
def startSuite( name, file, line, generated ):
'''Start scanning a new suite'''
global suite
closeSuite()
suite = { 'name' : name,
'file' : file,
'cfile' : cstr(file),
'line' : line,
'generated' : generated,
'object' : 'suite_%s' % name,
'dobject' : 'suiteDescription_%s' % name,
'tlist' : 'Tests_%s' % name,
'tests' : [],
'lines' : [] }
def lineStartsBlock( line ):
'''Check if current line starts a new CXXTEST_CODE() block'''
return re.search( r'\bCXXTEST_CODE\s*\(', line ) is not None
test_re = re.compile( r'^([^/]|/[^/])*\bvoid\s+([Tt]est\w+)\s*\(\s*(void)?\s*\)' )
def scanLineForTest( suite, lineNo, line ):
'''Check if current line starts a test'''
m = test_re.search( line )
if m:
addTest( suite, m.group(2), lineNo )
def addTest( suite, name, line ):
'''Add a test function to the current suite'''
test = { 'name' : name,
'suite' : suite,
'class' : 'TestDescription_%s_%s' % (suite['name'], name),
'object' : 'testDescription_%s_%s' % (suite['name'], name),
'line' : line,
}
suite['tests'].append( test )
def addLineToBlock( suite, lineNo, line ):
'''Append the line to the current CXXTEST_CODE() block'''
line = fixBlockLine( suite, lineNo, line )
line = re.sub( r'^.*\{\{', '', line )
e = re.search( r'\}\}', line )
if e:
line = line[:e.start()]
suite['lines'].append( line )
return e is None
def fixBlockLine( suite, lineNo, line):
'''Change all [E]TS_ macros used in a line to _[E]TS_ macros with the correct file/line'''
return re.sub( r'\b(E?TSM?_(ASSERT[A-Z_]*|FAIL))\s*\(',
r'_\1(%s,%s,' % (suite['cfile'], lineNo),
line, 0 )
create_re = re.compile( r'\bstatic\s+\w+\s*\*\s*createSuite\s*\(\s*(void)?\s*\)' )
def scanLineForCreate( suite, lineNo, line ):
'''Check if current line defines a createSuite() function'''
if create_re.search( line ):
addSuiteCreateDestroy( suite, 'create', lineNo )
destroy_re = re.compile( r'\bstatic\s+void\s+destroySuite\s*\(\s*\w+\s*\*\s*\w*\s*\)' )
def scanLineForDestroy( suite, lineNo, line ):
'''Check if current line defines a destroySuite() function'''
if destroy_re.search( line ):
addSuiteCreateDestroy( suite, 'destroy', lineNo )
def cstr( str ):
'''Convert a string to its C representation'''
return '"' + string.replace( str, '\\', '\\\\' ) + '"'
def addSuiteCreateDestroy( suite, which, line ):
'''Add createSuite()/destroySuite() to current suite'''
if suite.has_key(which):
abort( '%s:%s: %sSuite() already declared' % ( suite['file'], str(line), which ) )
suite[which] = line
def closeSuite():
'''Close current suite and add it to the list if valid'''
global suite
if suite is not None:
if len(suite['tests']) is not 0:
verifySuite(suite)
rememberSuite(suite)
suite = None
def verifySuite(suite):
'''Verify current suite is legal'''
if suite.has_key('create') and not suite.has_key('destroy'):
abort( '%s:%s: Suite %s has createSuite() but no destroySuite()' %
(suite['file'], suite['create'], suite['name']) )
if suite.has_key('destroy') and not suite.has_key('create'):
abort( '%s:%s: Suite %s has destroySuite() but no createSuite()' %
(suite['file'], suite['destroy'], suite['name']) )
def rememberSuite(suite):
'''Add current suite to list'''
global suites
suites.append( suite )
def writeOutput():
'''Create output file'''
if templateFileName:
writeTemplateOutput()
else:
writeSimpleOutput()
def writeSimpleOutput():
'''Create output not based on template'''
output = startOutputFile()
writePreamble( output )
writeMain( output )
writeWorld( output )
output.close()
include_re = re.compile( r"\s*\#\s*include\s+<cxxtest/" )
preamble_re = re.compile( r"^\s*<CxxTest\s+preamble>\s*$" )
world_re = re.compile( r"^\s*<CxxTest\s+world>\s*$" )
def writeTemplateOutput():
'''Create output based on template file'''
template = open(templateFileName)
output = startOutputFile()
while 1:
line = template.readline()
if not line:
break;
if include_re.search( line ):
writePreamble( output )
output.write( line )
elif preamble_re.search( line ):
writePreamble( output )
elif world_re.search( line ):
writeWorld( output )
else:
output.write( line )
template.close()
output.close()
def startOutputFile():
'''Create output file and write header'''
if outputFileName is not None:
output = open( outputFileName, 'w' )
else:
output = sys.stdout
output.write( "/* Generated file, do not edit */\n\n" )
return output
wrotePreamble = 0
def writePreamble( output ):
'''Write the CxxTest header (#includes and #defines)'''
global wrotePreamble, headers, longlong
if wrotePreamble: return
output.write( "#ifndef CXXTEST_RUNNING\n" )
output.write( "#define CXXTEST_RUNNING\n" )
output.write( "#endif\n" )
output.write( "\n" )
if haveStandardLibrary:
output.write( "#define _CXXTEST_HAVE_STD\n" )
if haveExceptionHandling:
output.write( "#define _CXXTEST_HAVE_EH\n" )
if abortOnFail:
output.write( "#define _CXXTEST_ABORT_TEST_ON_FAIL\n" )
if longlong:
output.write( "#define _CXXTEST_LONGLONG %s\n" % longlong )
if factor:
output.write( "#define _CXXTEST_FACTOR\n" )
for header in headers:
output.write( "#include %s\n" % header )
output.write( "#include <cxxtest/TestListener.h>\n" )
output.write( "#include <cxxtest/TestTracker.h>\n" )
output.write( "#include <cxxtest/TestRunner.h>\n" )
output.write( "#include <cxxtest/RealDescriptions.h>\n" )
if runner:
output.write( "#include <cxxtest/%s.h>\n" % runner )
if gui:
output.write( "#include <cxxtest/%s.h>\n" % gui )
output.write( "\n" )
wrotePreamble = 1
def writeMain( output ):
'''Write the main() function for the test runner'''
if gui:
output.write( 'int main( int argc, char *argv[] ) {\n' )
if noStaticInit:
output.write( ' CxxTest::initialize();\n' )
output.write( ' return CxxTest::GuiTuiRunner<CxxTest::%s, CxxTest::%s>( argc, argv ).run();\n' % (gui, runner) )
output.write( '}\n' )
elif runner:
output.write( 'int main() {\n' )
if noStaticInit:
output.write( ' CxxTest::initialize();\n' )
output.write( ' return CxxTest::%s().run();\n' % runner )
output.write( '}\n' )
wroteWorld = 0
def writeWorld( output ):
'''Write the world definitions'''
global wroteWorld, part
if wroteWorld: return
writePreamble( output )
writeSuites( output )
if root or not part:
writeRoot( output )
if noStaticInit:
writeInitialize( output )
wroteWorld = 1
def writeSuites(output):
'''Write all TestDescriptions and SuiteDescriptions'''
for suite in suites:
writeInclude( output, suite['file'] )
if isGenerated(suite):
generateSuite( output, suite )
if isDynamic(suite):
writeSuitePointer( output, suite )
else:
writeSuiteObject( output, suite )
writeTestList( output, suite )
writeSuiteDescription( output, suite )
writeTestDescriptions( output, suite )
def isGenerated(suite):
'''Checks whether a suite class should be created'''
return suite['generated']
def isDynamic(suite):
'''Checks whether a suite is dynamic'''
return suite.has_key('create')
lastIncluded = ''
def writeInclude(output, file):
'''Add #include "file" statement'''
global lastIncluded
if file == lastIncluded: return
output.writelines( [ '#include "', file, '"\n\n' ] )
lastIncluded = file
def generateSuite( output, suite ):
'''Write a suite declared with CXXTEST_SUITE()'''
output.write( 'class %s : public CxxTest::TestSuite {\n' % suite['name'] )
output.write( 'public:\n' )
for line in suite['lines']:
output.write(line)
output.write( '};\n\n' )
def writeSuitePointer( output, suite ):
'''Create static suite pointer object for dynamic suites'''
if noStaticInit:
output.write( 'static %s *%s;\n\n' % (suite['name'], suite['object']) )
else:
output.write( 'static %s *%s = 0;\n\n' % (suite['name'], suite['object']) )
def writeSuiteObject( output, suite ):
'''Create static suite object for non-dynamic suites'''
output.writelines( [ "static ", suite['name'], " ", suite['object'], ";\n\n" ] )
def writeTestList( output, suite ):
'''Write the head of the test linked list for a suite'''
if noStaticInit:
output.write( 'static CxxTest::List %s;\n' % suite['tlist'] )
else:
output.write( 'static CxxTest::List %s = { 0, 0 };\n' % suite['tlist'] )
def writeTestDescriptions( output, suite ):
'''Write all test descriptions for a suite'''
for test in suite['tests']:
writeTestDescription( output, suite, test )
def writeTestDescription( output, suite, test ):
'''Write test description object'''
output.write( 'static class %s : public CxxTest::RealTestDescription {\n' % test['class'] )
output.write( 'public:\n' )
if not noStaticInit:
output.write( ' %s() : CxxTest::RealTestDescription( %s, %s, %s, "%s" ) {}\n' %
(test['class'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' void runTest() { %s }\n' % runBody( suite, test ) )
output.write( '} %s;\n\n' % test['object'] )
def runBody( suite, test ):
'''Body of TestDescription::run()'''
if isDynamic(suite): return dynamicRun( suite, test )
else: return staticRun( suite, test )
def dynamicRun( suite, test ):
'''Body of TestDescription::run() for test in a dynamic suite'''
return 'if ( ' + suite['object'] + ' ) ' + suite['object'] + '->' + test['name'] + '();'
def staticRun( suite, test ):
'''Body of TestDescription::run() for test in a non-dynamic suite'''
return suite['object'] + '.' + test['name'] + '();'
def writeSuiteDescription( output, suite ):
'''Write SuiteDescription object'''
if isDynamic( suite ):
writeDynamicDescription( output, suite )
else:
writeStaticDescription( output, suite )
def writeDynamicDescription( output, suite ):
'''Write SuiteDescription for a dynamic suite'''
output.write( 'CxxTest::DynamicSuiteDescription<%s> %s' % (suite['name'], suite['dobject']) )
if not noStaticInit:
output.write( '( %s, %s, "%s", %s, %s, %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['tlist'],
suite['object'], suite['create'], suite['destroy']) )
output.write( ';\n\n' )
def writeStaticDescription( output, suite ):
'''Write SuiteDescription for a static suite'''
output.write( 'CxxTest::StaticSuiteDescription %s' % suite['dobject'] )
if not noStaticInit:
output.write( '( %s, %s, "%s", %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['object'], suite['tlist']) )
output.write( ';\n\n' )
def writeRoot(output):
'''Write static members of CxxTest classes'''
output.write( '#include <cxxtest/Root.cpp>\n' )
def writeInitialize(output):
'''Write CxxTest::initialize(), which replaces static initialization'''
output.write( 'namespace CxxTest {\n' )
output.write( ' void initialize()\n' )
output.write( ' {\n' )
for suite in suites:
output.write( ' %s.initialize();\n' % suite['tlist'] )
if isDynamic(suite):
output.write( ' %s = 0;\n' % suite['object'] )
output.write( ' %s.initialize( %s, %s, "%s", %s, %s, %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['tlist'], suite['object'], suite['create'], suite['destroy']) )
else:
output.write( ' %s.initialize( %s, %s, "%s", %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['object'], suite['tlist']) )
for test in suite['tests']:
output.write( ' %s.initialize( %s, %s, %s, "%s" );\n' %
(test['object'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' }\n' )
output.write( '}\n' )
main()
| Python |
#!/usr/bin/python
'''Usage: %s [OPTIONS] <input file(s)>
Generate test source file for CxxTest.
-v, --version Write CxxTest version
-o, --output=NAME Write output to file NAME
--runner=CLASS Create a main() function that runs CxxTest::CLASS
--gui=CLASS Like --runner, with GUI component
--error-printer Same as --runner=ErrorPrinter
--abort-on-fail Abort tests on failed asserts (like xUnit)
--have-std Use standard library (even if not found in tests)
--no-std Don\'t use standard library (even if found in tests)
--have-eh Use exception handling (even if not found in tests)
--no-eh Don\'t use exception handling (even if found in tests)
--longlong=[TYPE] Use TYPE (default: long long) as long long
--template=TEMPLATE Use TEMPLATE file to generate the test runner
--include=HEADER Include HEADER in test runner before other headers
--root Write CxxTest globals
--part Don\'t write CxxTest globals
--no-static-init Don\'t rely on static initialization
'''
import re
import sys
import getopt
import glob
import string
# Global variables
suites = []
suite = None
inBlock = 0
outputFileName = None
runner = None
gui = None
root = None
part = None
noStaticInit = None
templateFileName = None
headers = []
haveExceptionHandling = 0
noExceptionHandling = 0
haveStandardLibrary = 0
noStandardLibrary = 0
abortOnFail = 0
factor = 0
longlong = 0
def main():
'''The main program'''
files = parseCommandline()
scanInputFiles( files )
writeOutput()
def usage( problem = None ):
'''Print usage info and exit'''
if problem is None:
print usageString()
sys.exit(0)
else:
sys.stderr.write( usageString() )
abort( problem )
def usageString():
'''Construct program usage string'''
return __doc__ % sys.argv[0]
def abort( problem ):
'''Print error message and exit'''
sys.stderr.write( '\n' )
sys.stderr.write( problem )
sys.stderr.write( '\n\n' )
sys.exit(2)
def parseCommandline():
'''Analyze command line arguments'''
try:
options, patterns = getopt.getopt( sys.argv[1:], 'o:r:',
['version', 'output=', 'runner=', 'gui=',
'error-printer', 'abort-on-fail', 'have-std', 'no-std',
'have-eh', 'no-eh', 'template=', 'include=',
'root', 'part', 'no-static-init', 'factor', 'longlong='] )
except getopt.error, problem:
usage( problem )
setOptions( options )
return setFiles( patterns )
def setOptions( options ):
'''Set options specified on command line'''
global outputFileName, templateFileName, runner, gui, haveStandardLibrary, factor, longlong
global haveExceptionHandling, noExceptionHandling, abortOnFail, headers, root, part, noStaticInit
for o, a in options:
if o in ('-v', '--version'):
printVersion()
elif o in ('-o', '--output'):
outputFileName = a
elif o == '--template':
templateFileName = a
elif o == '--runner':
runner = a
elif o == '--gui':
gui = a
elif o == '--include':
if not re.match( r'^["<].*[>"]$', a ):
a = ('"%s"' % a)
headers.append( a )
elif o == '--error-printer':
runner = 'ErrorPrinter'
haveStandardLibrary = 1
elif o == '--abort-on-fail':
abortOnFail = 1
elif o == '--have-std':
haveStandardLibrary = 1
elif o == '--no-std':
noStandardLibrary = 1
elif o == '--have-eh':
haveExceptionHandling = 1
elif o == '--no-eh':
noExceptionHandling = 1
elif o == '--root':
root = 1
elif o == '--part':
part = 1
elif o == '--no-static-init':
noStaticInit = 1
elif o == '--factor':
factor = 1
elif o == '--longlong':
if a:
longlong = a
else:
longlong = 'long long'
if noStaticInit and (root or part):
abort( '--no-static-init cannot be used with --root/--part' )
if gui and not runner:
runner = 'StdioPrinter'
def printVersion():
'''Print CxxTest version and exit'''
sys.stdout.write( "This is CxxTest version 3.10.1.\n" )
sys.exit(0)
def setFiles( patterns ):
'''Set input files specified on command line'''
files = expandWildcards( patterns )
if len(files) is 0 and not root:
usage( "No input files found" )
return files
def expandWildcards( patterns ):
'''Expand all wildcards in an array (glob)'''
fileNames = []
for pathName in patterns:
patternFiles = glob.glob( pathName )
for fileName in patternFiles:
fileNames.append( fixBackslashes( fileName ) )
return fileNames
def fixBackslashes( fileName ):
'''Convert backslashes to slashes in file name'''
return re.sub( r'\\', '/', fileName, 0 )
def scanInputFiles(files):
'''Scan all input files for test suites'''
for file in files:
scanInputFile(file)
global suites
if len(suites) is 0 and not root:
abort( 'No tests defined' )
def scanInputFile(fileName):
'''Scan single input file for test suites'''
file = open(fileName)
lineNo = 0
while 1:
line = file.readline()
if not line:
break
lineNo = lineNo + 1
scanInputLine( fileName, lineNo, line )
closeSuite()
file.close()
def scanInputLine( fileName, lineNo, line ):
'''Scan single input line for interesting stuff'''
scanLineForExceptionHandling( line )
scanLineForStandardLibrary( line )
scanLineForSuiteStart( fileName, lineNo, line )
global suite
if suite:
scanLineInsideSuite( suite, lineNo, line )
def scanLineInsideSuite( suite, lineNo, line ):
'''Analyze line which is part of a suite'''
global inBlock
if lineBelongsToSuite( suite, lineNo, line ):
scanLineForTest( suite, lineNo, line )
scanLineForCreate( suite, lineNo, line )
scanLineForDestroy( suite, lineNo, line )
def lineBelongsToSuite( suite, lineNo, line ):
'''Returns whether current line is part of the current suite.
This can be false when we are in a generated suite outside of CXXTEST_CODE() blocks
If the suite is generated, adds the line to the list of lines'''
if not suite['generated']:
return 1
global inBlock
if not inBlock:
inBlock = lineStartsBlock( line )
if inBlock:
inBlock = addLineToBlock( suite, lineNo, line )
return inBlock
std_re = re.compile( r"\b(std\s*::|CXXTEST_STD|using\s+namespace\s+std\b|^\s*\#\s*include\s+<[a-z0-9]+>)" )
def scanLineForStandardLibrary( line ):
'''Check if current line uses standard library'''
global haveStandardLibrary, noStandardLibrary
if not haveStandardLibrary and std_re.search(line):
if not noStandardLibrary:
haveStandardLibrary = 1
exception_re = re.compile( r"\b(throw|try|catch|TSM?_ASSERT_THROWS[A-Z_]*)\b" )
def scanLineForExceptionHandling( line ):
'''Check if current line uses exception handling'''
global haveExceptionHandling, noExceptionHandling
if not haveExceptionHandling and exception_re.search(line):
if not noExceptionHandling:
haveExceptionHandling = 1
suite_re = re.compile( r'\bclass\s+(\w+)\s*:\s*public\s+((::)?\s*CxxTest\s*::\s*)?TestSuite\b' )
generatedSuite_re = re.compile( r'\bCXXTEST_SUITE\s*\(\s*(\w*)\s*\)' )
def scanLineForSuiteStart( fileName, lineNo, line ):
'''Check if current line starts a new test suite'''
m = suite_re.search( line )
if m:
startSuite( m.group(1), fileName, lineNo, 0 )
m = generatedSuite_re.search( line )
if m:
sys.stdout.write( "%s:%s: Warning: Inline test suites are deprecated.\n" % (fileName, lineNo) )
startSuite( m.group(1), fileName, lineNo, 1 )
def startSuite( name, file, line, generated ):
'''Start scanning a new suite'''
global suite
closeSuite()
suite = { 'name' : name,
'file' : file,
'cfile' : cstr(file),
'line' : line,
'generated' : generated,
'object' : 'suite_%s' % name,
'dobject' : 'suiteDescription_%s' % name,
'tlist' : 'Tests_%s' % name,
'tests' : [],
'lines' : [] }
def lineStartsBlock( line ):
'''Check if current line starts a new CXXTEST_CODE() block'''
return re.search( r'\bCXXTEST_CODE\s*\(', line ) is not None
test_re = re.compile( r'^([^/]|/[^/])*\bvoid\s+([Tt]est\w+)\s*\(\s*(void)?\s*\)' )
def scanLineForTest( suite, lineNo, line ):
'''Check if current line starts a test'''
m = test_re.search( line )
if m:
addTest( suite, m.group(2), lineNo )
def addTest( suite, name, line ):
'''Add a test function to the current suite'''
test = { 'name' : name,
'suite' : suite,
'class' : 'TestDescription_%s_%s' % (suite['name'], name),
'object' : 'testDescription_%s_%s' % (suite['name'], name),
'line' : line,
}
suite['tests'].append( test )
def addLineToBlock( suite, lineNo, line ):
'''Append the line to the current CXXTEST_CODE() block'''
line = fixBlockLine( suite, lineNo, line )
line = re.sub( r'^.*\{\{', '', line )
e = re.search( r'\}\}', line )
if e:
line = line[:e.start()]
suite['lines'].append( line )
return e is None
def fixBlockLine( suite, lineNo, line):
'''Change all [E]TS_ macros used in a line to _[E]TS_ macros with the correct file/line'''
return re.sub( r'\b(E?TSM?_(ASSERT[A-Z_]*|FAIL))\s*\(',
r'_\1(%s,%s,' % (suite['cfile'], lineNo),
line, 0 )
create_re = re.compile( r'\bstatic\s+\w+\s*\*\s*createSuite\s*\(\s*(void)?\s*\)' )
def scanLineForCreate( suite, lineNo, line ):
'''Check if current line defines a createSuite() function'''
if create_re.search( line ):
addSuiteCreateDestroy( suite, 'create', lineNo )
destroy_re = re.compile( r'\bstatic\s+void\s+destroySuite\s*\(\s*\w+\s*\*\s*\w*\s*\)' )
def scanLineForDestroy( suite, lineNo, line ):
'''Check if current line defines a destroySuite() function'''
if destroy_re.search( line ):
addSuiteCreateDestroy( suite, 'destroy', lineNo )
def cstr( str ):
'''Convert a string to its C representation'''
return '"' + string.replace( str, '\\', '\\\\' ) + '"'
def addSuiteCreateDestroy( suite, which, line ):
'''Add createSuite()/destroySuite() to current suite'''
if suite.has_key(which):
abort( '%s:%s: %sSuite() already declared' % ( suite['file'], str(line), which ) )
suite[which] = line
def closeSuite():
'''Close current suite and add it to the list if valid'''
global suite
if suite is not None:
if len(suite['tests']) is not 0:
verifySuite(suite)
rememberSuite(suite)
suite = None
def verifySuite(suite):
'''Verify current suite is legal'''
if suite.has_key('create') and not suite.has_key('destroy'):
abort( '%s:%s: Suite %s has createSuite() but no destroySuite()' %
(suite['file'], suite['create'], suite['name']) )
if suite.has_key('destroy') and not suite.has_key('create'):
abort( '%s:%s: Suite %s has destroySuite() but no createSuite()' %
(suite['file'], suite['destroy'], suite['name']) )
def rememberSuite(suite):
'''Add current suite to list'''
global suites
suites.append( suite )
def writeOutput():
'''Create output file'''
if templateFileName:
writeTemplateOutput()
else:
writeSimpleOutput()
def writeSimpleOutput():
'''Create output not based on template'''
output = startOutputFile()
writePreamble( output )
writeMain( output )
writeWorld( output )
output.close()
include_re = re.compile( r"\s*\#\s*include\s+<cxxtest/" )
preamble_re = re.compile( r"^\s*<CxxTest\s+preamble>\s*$" )
world_re = re.compile( r"^\s*<CxxTest\s+world>\s*$" )
def writeTemplateOutput():
'''Create output based on template file'''
template = open(templateFileName)
output = startOutputFile()
while 1:
line = template.readline()
if not line:
break;
if include_re.search( line ):
writePreamble( output )
output.write( line )
elif preamble_re.search( line ):
writePreamble( output )
elif world_re.search( line ):
writeWorld( output )
else:
output.write( line )
template.close()
output.close()
def startOutputFile():
'''Create output file and write header'''
if outputFileName is not None:
output = open( outputFileName, 'w' )
else:
output = sys.stdout
output.write( "/* Generated file, do not edit */\n\n" )
return output
wrotePreamble = 0
def writePreamble( output ):
'''Write the CxxTest header (#includes and #defines)'''
global wrotePreamble, headers, longlong
if wrotePreamble: return
output.write( "#ifndef CXXTEST_RUNNING\n" )
output.write( "#define CXXTEST_RUNNING\n" )
output.write( "#endif\n" )
output.write( "\n" )
if haveStandardLibrary:
output.write( "#define _CXXTEST_HAVE_STD\n" )
if haveExceptionHandling:
output.write( "#define _CXXTEST_HAVE_EH\n" )
if abortOnFail:
output.write( "#define _CXXTEST_ABORT_TEST_ON_FAIL\n" )
if longlong:
output.write( "#define _CXXTEST_LONGLONG %s\n" % longlong )
if factor:
output.write( "#define _CXXTEST_FACTOR\n" )
for header in headers:
output.write( "#include %s\n" % header )
output.write( "#include <cxxtest/TestListener.h>\n" )
output.write( "#include <cxxtest/TestTracker.h>\n" )
output.write( "#include <cxxtest/TestRunner.h>\n" )
output.write( "#include <cxxtest/RealDescriptions.h>\n" )
if runner:
output.write( "#include <cxxtest/%s.h>\n" % runner )
if gui:
output.write( "#include <cxxtest/%s.h>\n" % gui )
output.write( "\n" )
wrotePreamble = 1
def writeMain( output ):
'''Write the main() function for the test runner'''
if gui:
output.write( 'int main( int argc, char *argv[] ) {\n' )
if noStaticInit:
output.write( ' CxxTest::initialize();\n' )
output.write( ' return CxxTest::GuiTuiRunner<CxxTest::%s, CxxTest::%s>( argc, argv ).run();\n' % (gui, runner) )
output.write( '}\n' )
elif runner:
output.write( 'int main() {\n' )
if noStaticInit:
output.write( ' CxxTest::initialize();\n' )
output.write( ' return CxxTest::%s().run();\n' % runner )
output.write( '}\n' )
wroteWorld = 0
def writeWorld( output ):
'''Write the world definitions'''
global wroteWorld, part
if wroteWorld: return
writePreamble( output )
writeSuites( output )
if root or not part:
writeRoot( output )
if noStaticInit:
writeInitialize( output )
wroteWorld = 1
def writeSuites(output):
'''Write all TestDescriptions and SuiteDescriptions'''
for suite in suites:
writeInclude( output, suite['file'] )
if isGenerated(suite):
generateSuite( output, suite )
if isDynamic(suite):
writeSuitePointer( output, suite )
else:
writeSuiteObject( output, suite )
writeTestList( output, suite )
writeSuiteDescription( output, suite )
writeTestDescriptions( output, suite )
def isGenerated(suite):
'''Checks whether a suite class should be created'''
return suite['generated']
def isDynamic(suite):
'''Checks whether a suite is dynamic'''
return suite.has_key('create')
lastIncluded = ''
def writeInclude(output, file):
'''Add #include "file" statement'''
global lastIncluded
if file == lastIncluded: return
output.writelines( [ '#include "', file, '"\n\n' ] )
lastIncluded = file
def generateSuite( output, suite ):
'''Write a suite declared with CXXTEST_SUITE()'''
output.write( 'class %s : public CxxTest::TestSuite {\n' % suite['name'] )
output.write( 'public:\n' )
for line in suite['lines']:
output.write(line)
output.write( '};\n\n' )
def writeSuitePointer( output, suite ):
'''Create static suite pointer object for dynamic suites'''
if noStaticInit:
output.write( 'static %s *%s;\n\n' % (suite['name'], suite['object']) )
else:
output.write( 'static %s *%s = 0;\n\n' % (suite['name'], suite['object']) )
def writeSuiteObject( output, suite ):
'''Create static suite object for non-dynamic suites'''
output.writelines( [ "static ", suite['name'], " ", suite['object'], ";\n\n" ] )
def writeTestList( output, suite ):
'''Write the head of the test linked list for a suite'''
if noStaticInit:
output.write( 'static CxxTest::List %s;\n' % suite['tlist'] )
else:
output.write( 'static CxxTest::List %s = { 0, 0 };\n' % suite['tlist'] )
def writeTestDescriptions( output, suite ):
'''Write all test descriptions for a suite'''
for test in suite['tests']:
writeTestDescription( output, suite, test )
def writeTestDescription( output, suite, test ):
'''Write test description object'''
output.write( 'static class %s : public CxxTest::RealTestDescription {\n' % test['class'] )
output.write( 'public:\n' )
if not noStaticInit:
output.write( ' %s() : CxxTest::RealTestDescription( %s, %s, %s, "%s" ) {}\n' %
(test['class'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' void runTest() { %s }\n' % runBody( suite, test ) )
output.write( '} %s;\n\n' % test['object'] )
def runBody( suite, test ):
'''Body of TestDescription::run()'''
if isDynamic(suite): return dynamicRun( suite, test )
else: return staticRun( suite, test )
def dynamicRun( suite, test ):
'''Body of TestDescription::run() for test in a dynamic suite'''
return 'if ( ' + suite['object'] + ' ) ' + suite['object'] + '->' + test['name'] + '();'
def staticRun( suite, test ):
'''Body of TestDescription::run() for test in a non-dynamic suite'''
return suite['object'] + '.' + test['name'] + '();'
def writeSuiteDescription( output, suite ):
'''Write SuiteDescription object'''
if isDynamic( suite ):
writeDynamicDescription( output, suite )
else:
writeStaticDescription( output, suite )
def writeDynamicDescription( output, suite ):
'''Write SuiteDescription for a dynamic suite'''
output.write( 'CxxTest::DynamicSuiteDescription<%s> %s' % (suite['name'], suite['dobject']) )
if not noStaticInit:
output.write( '( %s, %s, "%s", %s, %s, %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['tlist'],
suite['object'], suite['create'], suite['destroy']) )
output.write( ';\n\n' )
def writeStaticDescription( output, suite ):
'''Write SuiteDescription for a static suite'''
output.write( 'CxxTest::StaticSuiteDescription %s' % suite['dobject'] )
if not noStaticInit:
output.write( '( %s, %s, "%s", %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['object'], suite['tlist']) )
output.write( ';\n\n' )
def writeRoot(output):
'''Write static members of CxxTest classes'''
output.write( '#include <cxxtest/Root.cpp>\n' )
def writeInitialize(output):
'''Write CxxTest::initialize(), which replaces static initialization'''
output.write( 'namespace CxxTest {\n' )
output.write( ' void initialize()\n' )
output.write( ' {\n' )
for suite in suites:
output.write( ' %s.initialize();\n' % suite['tlist'] )
if isDynamic(suite):
output.write( ' %s = 0;\n' % suite['object'] )
output.write( ' %s.initialize( %s, %s, "%s", %s, %s, %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['tlist'], suite['object'], suite['create'], suite['destroy']) )
else:
output.write( ' %s.initialize( %s, %s, "%s", %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['object'], suite['tlist']) )
for test in suite['tests']:
output.write( ' %s.initialize( %s, %s, %s, "%s" );\n' %
(test['object'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' }\n' )
output.write( '}\n' )
main()
| Python |
# ; -*- mode: python; tab-width: 4; -*-
| Python |
# ; -*- mode: python; tab-width: 4; -*-
| Python |
# ; -*- mode: python; tab-width: 4; -*-
#source = Glob("./src/*.cpp")
#source.append("./src/fixmessagecounter.l")
debug = int(ARGUMENTS.get("debug", 1))
if debug > 0:
CCFLAGS="-Wall -g"
print "Building WITH debug info."
else:
CCFLAGS="-Wall"
print "Building WITHOUT debug info."
VariantDir("./build", "./src", duplicate=0)
env = Environment()
env.Program(target="./build/focx",
LIBS=["fl"],
# LIBPATH=["/usr/lib", "/usr/local/lib", "/opt/lib"],
source=["./build/fixmessagecounter.l"])
| Python |
# ; -*- mode: python; tab-width: 4; -*-
#source = Glob("./src/*.cpp")
#source.append("./src/fixmessagecounter.l")
debug = int(ARGUMENTS.get("debug", 1))
if debug > 0:
CCFLAGS="-Wall -g"
print "Building WITH debug info."
else:
CCFLAGS="-Wall"
print "Building WITHOUT debug info."
VariantDir("./build", "./src", duplicate=0)
env = Environment()
env.Program(target="./build/focx",
LIBS=["fl"],
# LIBPATH=["/usr/lib", "/usr/local/lib", "/opt/lib"],
source=["./build/fixmessagecounter.l"])
| Python |
# ; -*- mode: python; tab-width: 4; -*-
| Python |
# ; -*- mode: python; tab-width: 4; -*-
| Python |
# ; -*- mode: python; tab-width: 4; -*-
#source = Glob("./src/*.cpp")
#source.append("./src/fixmessagecounter.l")
debug = int(ARGUMENTS.get("debug", 1))
if debug > 0:
CCFLAGS="-Wall -g"
print "Building WITH debug info."
else:
CCFLAGS="-Wall"
print "Building WITHOUT debug info."
VariantDir("./build", "./src", duplicate=0)
env = Environment()
env.Program(target="./build/focx",
LIBS=["fl"],
# LIBPATH=["/usr/lib", "/usr/local/lib", "/opt/lib"],
source=["./build/fixmessagecounter.l"])
| Python |
# ; -*- mode: python; tab-width: 4; -*-
#source = Glob("./src/*.cpp")
#source.append("./src/fixmessagecounter.l")
debug = int(ARGUMENTS.get("debug", 1))
if debug > 0:
CCFLAGS="-Wall -g"
print "Building WITH debug info."
else:
CCFLAGS="-Wall"
print "Building WITHOUT debug info."
VariantDir("./build", "./src", duplicate=0)
env = Environment()
env.Program(target="./build/focx",
LIBS=["fl"],
# LIBPATH=["/usr/lib", "/usr/local/lib", "/opt/lib"],
source=["./build/fixmessagecounter.l"])
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from datetime import datetime
import logging
from mod_python import apache
from mod_python import Session
from mod_python import util
from phunc import *
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger
# legacy namespacing
unquote = utils.unquote
get_formatted_address = utils.get_formatted_address
contact_log,lcontact_log = table.contact_log, table.lcontact_log
save_upload_file = utils.save_upload_file
get_whole_save_path = utils.get_whole_save_path
get_whole_file_name = utils.get_whole_file_name
get_file_name_by_id = utils.get_file_name_by_id
genErrorPage, showErr = error.genErrorPage, error.showErr
GeneralBusinessErr = exception.GeneralBusinessErr
address=block.address
place_of_business_choice = table.place_of_business_choice
def index( req,**params ):
"""displays a list of contacts by company"""
page = Page(req, company_db=True)
page_params = {}
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
page_num = params.has_key('page') and params['page'] and int(params['page']) or 1
sql_str = "SELECT company_name, given_name, surname, phone, TRIM(COALESCE(email, ' ')) AS email, company_id, person_id, iscustomer, issupplier FROM contact_info"
entity_name=None
if params.has_key("entity_name") and params['entity_name'].strip():
entity_name = params['entity_name']
if entity_name:
if "WHERE" in sql_str:
sql_str = sql_str+" AND (lower(company_name) LIKE '%%%s%%' OR lower(given_name) || ' ' || lower(surname) LIKE '%%%s%%')"%(entity_name.strip().lower(),entity_name.strip().lower())
else:
sql_str = sql_str+" WHERE lower(company_name) LIKE '%%%s%%' OR lower(given_name) || ' ' || lower(surname) LIKE '%%%s%%'"%(entity_name.strip().lower(),entity_name.strip().lower())
page_params['entity_name'] = entity_name
searchkey = ''
if params.has_key('searchkey') and params['searchkey']:
searchkey = params['searchkey']
if searchkey.lower()!='all':
if "WHERE" in sql_str:
sql_str = sql_str+" AND lower(company_name) LIKE '%s%%' OR (company_name IS NULL AND lower(given_name) || ' ' || lower(surname) LIKE '%s%%')"%(searchkey.lower(),searchkey.lower())
else:
sql_str = sql_str+" WHERE lower(company_name) LIKE '%s%%' OR (company_name IS NULL AND lower(given_name) || ' ' || lower(surname) LIKE '%s%%')"%(searchkey.lower(),searchkey.lower())
page_params['searchkey'] = searchkey
page.content = {
'no_render':table.contacts_by_company(page.company_db.cursor(), info.query_string,page.session['skin'],sql_str,page_num,10,"/bin/crm.py",page_params)
}
page.setup = {
'breadcrumbs':['CRM'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Search',
'broadcast_message':broadcast_message,
'template':'no_render.opt'
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def get_company_info( req,**params ):
"""displays a page of company information, with edit links, etc"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
company_info = db_tools.exec_action(dbc,'get_customer_company_info',[params['id']])
person_list = db_tools.exec_action(dbc,'get_person_id_list',[params['id']])
page.content = {
'id':params['id'],
'office_list':[],
'lcontact_log':lcontact_log(dbc,person_list,int(params['id']),page.session['skin']),
'iscustomer':False
}
company_name = ''
if len(company_info) > 0:
page.content['iscustomer'] = True
customer_id = company_info[0]['id']
company_name = company_info[0]['name']
page.content['custmer_id'] = customer_id
else:
company_info = db_tools.exec_action(dbc,'get_company_info2',[params['id']])
company_name = len(company_info)>0 and company_info[0]['name'] or ""
broadcast_message = None
pob_info_all=db_tools.exec_action(dbc,'get_pop_info1',[params['id']])
rowcount = len(pob_info_all)
for pob_info in pob_info_all:
if company_name == '':
company_name = pob_info['name']
address = ''
if pob_info['address_id'] != None:
office_address = db_tools.exec_action(dbc,'get_address_info',[pob_info['address_id']])[0]
address = get_formatted_address(office_address,return_one_line=True)
contact_info = {
'name':pob_info['name'] != None and pob_info['name'] or "",
'phone':pob_info['phone'] != None and pob_info['phone'] or "",
'fax':pob_info['fax'] != None and pob_info['fax'] or "",
'address':address
}
page.content['office_list'].append( contact_info )
list_setup={
'classid':{'main':'title title2','detail':'table'},
'template_dir':info.getTemplateDir(req),
'isfo':page.content['office_list'],
'title1':['Address','Phone','Fax'],
'key':['address','phone','fax'],
'main':'name',
}
ulist = form.user_div(**list_setup)
page.content['ulist']=ulist
page.setup = {
'breadcrumbs':['crm',company_name],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':company_name,
'broadcast_message':broadcast_message,
'template':'crm/sc.opt'
}
page.info = {
'query_string':info.query_string,
'name':company_name
}
return page.render()
def get_person_log( req,**params ):
"""displays a form for editing an action item or contact log item"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
p_id = params['pid']
c_id = params['cid']
person_name=db_tools.exec_action(dbc,'get_person_name2',[p_id])[0]['person_name']
if params.has_key('close') and params['close']!='':
logid = params['close']
log_entry=db_tools.exec_action(dbc,'get_log_entry',[logid])[0]
personid = log_entry['entity_id']
comment = log_entry['comment']
filename = log_entry['filename']
if filename != '':
filepath = get_whole_file_name(get_whole_save_path(personid, logid), get_file_name_by_id(logid, filename))
else:
filepath = ''
action = log_entry['action']
page_title = 'Close Action'
submit_label = 'Close Action / Save Changes'
elif params.has_key('edit') and params['edit']!='':
logid = params['edit']
log_entry=db_tools.exec_action(dbc,'get_log_entry',[logid])[0]
personid = log_entry['entity_id']
comment = log_entry['comment']
filename = log_entry['filename']
if filename != '':
filepath =get_whole_file_name(get_whole_save_path(personid, logid),get_file_name_by_id(logid, filename))[13:]
else:
filepath = ''
action = log_entry['action']
page_title = 'Edit Contact Log / Action'
submit_label = 'Save Changes'
else:
logid = ''
comment = ''
filename = ''
filepath = ''
action = ''
page_title = 'New Contact Log Entry'
submit_label = 'Create'
page.content = {
'logid':logid,
'comment':comment,
'filename':filename,
'filepath':filepath,
'action':action,
'submit_label':submit_label,
'params_name':params.keys(),
'params_list':params
}
page.setup = {
'breadcrumbs':['crm','person',page_title],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':page_title,
'template':'crm/sle.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
'query_params':{'pid':p_id,'cid':c_id},
'name':person_name
}
return page.render()
def create_contact( req,**params ):
"""displays form 1 of 3 for creating a new contact - basic info"""
page = Page(req)
page.setup = {
'breadcrumbs':['crm','New Contact'],
'menu_title':'CRM Portal',
'menu':['newcontact!'],
'content_title':'New Contact',
'template':'crm/scc1.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def create_contact_step2( req,**params ):
"""displays form 2 of 3 for entering a new contact - location match chooser/company chooser & creator"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
matches = db_tools.exec_action(dbc,'get_place_of_business_info1',[params['phone'][:-3]])
if len(matches) == 0 and params.has_key('fax') and params['fax']!='':
matches=db_tools.exec_action(dbc,'get_place_of_business_info2',[params['fax'][:-3]])
companies = db_tools.exec_action(dbc,'get_companies')
entity_types = db_tools.exec_action(dbc,'get_c_entity_types')
page.content = {
'matches':matches,
'companies':companies,
'entity_types':entity_types,
'params_name':params.keys(),
'params_list':params
}
if len(matches) > 0:
match_list=[]
for match in matches:
match_dict={}
address_bits_1 = [match['line1'],match['line2'],match['suburb'],match['region']]
if address_bits_1.count(None) > 0:
address_bits_1.remove(None)
match_dict['id']=match['id']
match_dict['address_bits_1']=address_bits_1
match_list.append(match_dict)
content['match_list']=match_list
page.setup = {
'breadcrumbs':['crm','New Contact'],
'menu_title':'CRM Portal',
'menu':['newcontact!'],
'content_title':'New Contact',
'template':'crm/scc2.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_contact_step3( req,**params ):
"""display form 3 of 3 for creating a new contact - work location"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
if params.has_key('place_of_business_id') and params['place_of_business_id']:
var_map={'p_company_id':'null','p_company_name':'','entity_type':'','p_line1':'','p_line2':'','p_suburb':'','p_region':'','p_code':'','p_country':'','p_location_name':'','loc_phone':'','loc_fax':'','p_location_id':'null','p_surname':'','p_given_name':'','p_position':'','p_phone':'','p_fax':'','p_email':'','p_mobile':'','p_sms':''}
var_map['p_location_id'] = params['place_of_business_id']
pob_details = db_tools.exec_action(dbc,'get_pop_details',[params['place_of_business_id']])[0]
other_possible_keys = ['given_name', 'surname', 'position', 'phone', 'fax', 'email', 'mobile', 'sms']
# if work phone or fax is an exact match, don't store it
if params['phone'] == pob_details['phone']:
other_possible_keys.remove('phone')
if params.has_key('fax') and params['fax'] == pob_details['fax']:
other_possible_keys.remove('fax')
for key in other_possible_keys:
if params.has_key(key) and params[key]!='':
var_map['p_'+key] = params[key]
result = db_tools.exec_action(dbc,'create_contact',conn,[var_map['p_surname'],var_map['p_given_name'],var_map['p_company_name'],var_map['p_position'],var_map['p_line1'],var_map['p_line2'],var_map['p_suburb'],var_map['p_region'],var_map['p_code'],var_map['p_country'],var_map['p_location_id'],var_map['loc_phone'],var_map['loc_fax'],var_map['p_phone'],var_map['p_fax'],var_map['p_email'],var_map['p_mobile'],var_map['p_sms'],var_map['p_company_id'],var_map['p_location_name'],var_map['entity_type']])[0]['create_contact']
util.redirect(req,"/bin/crm.py/index?broadcast_message=%s"%str(result))
page.content = {
'address':address('validate-all-or-none'),
'is_place_of_business_id':False,
'is_company_id':False,
'is_name':False,
'params_name':params.keys(),
'params_list':params
}
if params.has_key('company_id') and params['company_id']:
page.content['is_company_id']=True
work_location_choices = table.place_of_business_choice(dbc, params['company_id'], False)
page.content['work_location_choices']=work_location_choices
if params.has_key('name') and params['name']!='':
page.content['is_name']=True
broadcast = None
page_title = 'New Contact'
page.setup = {
'breadcrumbs':['crm','New Contact'],
'menu_title':'CRM Portal',
'menu':['newcontact!'],
'content_title' :page_title,
'broadcast_message' :broadcast,
'template':'crm/scc3.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_contact_complet( req,**params ):
"""actually creates a new contact -- redirects to crm index page (contacts by company)"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map={'p_company_id':'null','p_company_name':'','entity_type':'','p_line1':'','p_line2':'','p_suburb':'','p_region':'','p_code':'','p_country':'','p_location_name':'','loc_phone':'','loc_fax':'','p_location_id':'null','p_surname':'','p_given_name':'','p_position':'','p_phone':'','p_fax':'','p_email':'','p_mobile':'','p_sms':''}
pob_id = None
need_alt_location = False
if params.has_key('company_id') and params['company_id']!='':
company_id = params['company_id']
var_map['p_company_id'] = params['company_id']
elif params.has_key('name') and params['name']!='':
var_map['p_company_name'] = params['name']
var_map['entity_type'] = params['entity_type']
if params.has_key('line1') and params['line1']!='':
if params.has_key('line2') and params['line2']!='':
var_map['p_line2'] = params['line2']
var_map['p_line1'] = params['line1']
var_map['p_suburb'] = params['suburb'].lower()
var_map['p_region'] = params['region'].lower()
var_map['p_code'] = params['code'].lower()
var_map['p_country'] = params['country'].lower()
if params.has_key('pob_name') and params['pob_name']!='':
var_map['p_location_name'] = params['pob_name']
if params.has_key('pob_phone') and params['pob_phone']!='':
var_map['loc_phone'] = params['pob_phone']
if params.has_key('pob_fax') and params['pob_fax']!='':
var_map['loc_fax'] = params['pob_fax']
elif params.has_key('place_of_business_id') and params['place_of_business_id']!='':
pob_id = params['place_of_business_id']
var_map['p_location_id'] = pob_id
other_possible_keys = ['given_name', 'surname', 'position', 'phone', 'fax', 'email', 'mobile', 'sms']
if pob_id != None:
pob_details = db_tools.exec_action(dbc,'get_pop_details2',[str(pob_id)])[0]
if params['phone'] == pob_details['phone']:
other_possible_keys.remove('phone')
if params.has_key('fax') and params['fax'] == pob_details['fax']:
other_possible_keys.remove('fax')
for key in other_possible_keys:
if params.has_key(key) and params[key]!='':
var_map['p_'+key] = params[key]
result = db_tools.exec_action(dbc,'create_contact',[var_map['p_surname'],var_map['p_given_name'],var_map['p_company_name'],var_map['p_position'],var_map['p_line1'],var_map['p_line2'],var_map['p_suburb'],var_map['p_region'],var_map['p_code'],var_map['p_country'],var_map['p_location_id'],var_map['loc_phone'],var_map['loc_fax'],var_map['p_phone'],var_map['p_fax'],var_map['p_email'],var_map['p_mobile'],var_map['p_sms'],var_map['p_company_id'],var_map['p_location_name'],var_map['entity_type']])[0]['create_contact']
logger.debug(result)
conn.commit()
broadcast_message = showErr(int(result))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/crm.py/index?broadcast_message=%s"%broadcast_message)
def get_alt_location( req,**params ):
"""displays a form for creating an alt location (ie, for a contact)"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = ''
p_id=params['pid']
c_id=params['cid']
alt_location_types = []
alt_location_types1=db_tools.exec_action(dbc,'get_alt_location_types')
exist_alt_location_types = db_tools.exec_action(dbc,'get_exist_alt_location_types',[p_id])
if len(alt_location_types1)>0:
if len(exist_alt_location_types)>0:
for alt_location_type in alt_location_types1:
flag=True
for exist_alt_location_type in exist_alt_location_types:
if exist_alt_location_type['name']==alt_location_type['code_value']:
flag=False
break
if flag==True:
alt_location_types.append(alt_location_type)
else:
alt_location_types=alt_location_types1
if len(alt_location_types1)>0 and c_id.upper()!='NONE':
for alt_location_type in alt_location_types:
if alt_location_type['code_value']=='work':
alt_location_types.remove(alt_location_type)
break
person = db_tools.exec_action(dbc,'get_entity_by_id',[p_id])[0]
person_name =' '.join([person['given_name'], person['name']])
page.content = {
'alt_location_types':alt_location_types,
'p_id':p_id,
'c_id':c_id
}
page.setup = {
'breadcrumbs':['crm','person','Add Location'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Add Location',
'broadcast_message':broadcast_message,
'template':'crm/sca.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
'query_params':{'pid':p_id,'cid':c_id},
'name':person_name
}
return page.render()
def get_alt_location_submit( req,**params ):
"""actually creates an alt location for a contact -- redirects to person detail page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
c_id = params['cid']
p_id = params['pid']
passthrough_fields = ['cid', 'pid']
field_names = ''
new_values = ''
for field_name in params.keys():
if field_name[:4] != 'old_' and passthrough_fields.count(field_name) == 0 and params[field_name] != '':
field_names = field_names.strip('~:~') + '~:~' + field_name
new_values = new_values.strip('~:~') + '~:~' + params[field_name]
dbc.execute("SELECT edit_contact(%s,'','', string_to_array('%s', '~:~'), string_to_array('%s', '~:~'), 'NOW')" % (p_id, field_names, new_values))
result = dbc.fetchone()[0]
conn.commit()
broadcast_message = showErr(int(result))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/crm.py/get_contact_detail?cid=%s&pid=%s&broadcast_message=%s"%(c_id,p_id,broadcast_message))
def edit_contact2( req,**params ):
"""displays form 1 of 3 for editing contact details"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = ''
p_id=params['pid']
c_id = params['cid']
page.content = {
'p_id':p_id,
'c_id':c_id,
'original_page_load':datetime.now()
}
contact_info = {}
if c_id.upper()=='NONE' or not c_id.strip():
contact_info = db_tools.exec_action(dbc,'get_contact_info',[p_id,'is NULL'])[0]
else:
contact_info = db_tools.exec_action(dbc,'get_contact_info',[p_id,'='+c_id])[0]
page.content['is_address'] = False
page.content['is_location'] = False
pob_id = None
address = None
work_address = None
pob_info = None
if c_id:
if c_id.upper() == 'NONE':
pob_address = db_tools.exec_action(dbc,'get_work_details',[p_id])
if pob_address:
pob_id = pob_address[0]['address_id']
work_address=db_tools.exec_action(dbc,'get_address_info',[str(pob_id)])[0]
page.content['is_address'] = True
page.content['pob_address'] = pob_address
page.content['work_address'] = work_address
else:
##relationship = db_tools.exec_action(dbc,'get_relation_ship',[p_id,c_id])[0]
pob_id = db_tools.exec_action(dbc,'get_pob_id',[p_id,c_id])
if pob_id and pob_id[0]['location_id'] != None:
pob_info=db_tools.exec_action(dbc,'get_pop_info2',[str(pob_id[0]['location_id'])])[0]
if pob_info:
if contact_info['phone'] == pob_info['phone']:
contact_info['phone'] = None
if contact_info['fax'] == pob_info['fax']:
contact_info['fax'] = None
pob_info['phone']=max(pob_info['phone'], '').replace(' ', '')
address = pob_info
page.content['is_location'] = True
address = '<br />'.join([pob_info['name'], get_formatted_address(pob_info)])
page.content['contact_info']=contact_info
logger.debug(contact_info)
page.content['count_none']=contact_info.values().count(None)
page.content['pob_info']=pob_info
person_name = ' '.join([contact_info['given_name'], contact_info['surname']])
if address == None and work_address != None:
address = work_address
page.content['address']=address
page.content['person_name'] = person_name
if pob_info != None or address != None or contact_info.values().count(None) < 7:
if contact_info['email']:
email_link = '<a href="mailto:' + contact_info['email'] + '">' + contact_info['email'] + '</a>'
else:
email_link = ''
page.content['email_link']=email_link
alt_locations = db_tools.exec_action(dbc,'get_alt_locations',[p_id])
page.content['is_alt_locations']=False
if len(alt_locations) > 0:
page.content['is_alt_locations']=True
page.content['alt_locations']=alt_locations
page.content['alt_locations']=alt_locations
page.setup = {
'breadcrumbs':['crm','person','Edit'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Edit Contact - ' + person_name,
'broadcast_message':broadcast_message,
'template':'crm/sce4.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
'query_params':{'pid':p_id,'cid':c_id},
'name':person_name
}
return page.render()
def edit_contact2_submit( req,**params ):
"""actually updates contact details -- redirects to crm index page (contacts by company)"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
if params.has_key('cid'):
c_id = params['cid']
else:
c_id = None
p_id = params['pid']
person_name = params['person_name']
surname = params['surname']
given_name = params['given_name']
passthrough_fields = ['given_name','surname','cid', 'pid', 'person_name', 'original_page_load']
field_names = ''
new_values = ''
old_values = ''
for field_name in params.keys():
if field_name[:4] != 'old_' and passthrough_fields.count(field_name) == 0 and params[field_name] != '':
field_names = field_names.strip('~:~') + '~:~' + field_name
new_values = new_values.strip('~:~') + '~:~' + params[field_name]
dbc.execute("SELECT edit_contact(%s,'%s','%s',string_to_array('%s', '~:~'), string_to_array('%s', '~:~'), '%s')" % (p_id,surname,given_name, field_names, new_values, params['original_page_load']))
result = dbc.fetchone()[0]
conn.commit()
broadcast_message = showErr(int(result))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/crm.py/index?cid=%s&pid=%s&broadcast_message=%s"%(c_id,p_id,broadcast_message))
def edit_contact2_step2( req,**params ):
"""displays form 2 of 3 for editing contact details"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = ''
p_id = params['pid']
c_id = params['cid']
person_name = params['pname']
page.content = {
'p_id':p_id,
'c_id':c_id,
'person_name':person_name,
'original_page_load':params['opl'],
'companies':db_tools.exec_action(dbc,'get_companies'),
'entity_types':db_tools.exec_action(dbc,'get_c_entity_types')
}
dbc.execute("SELECT detail FROM system.contact_detail WHERE entity_id = '%s' AND type = 'phone'" % p_id)
phone = dbc.fetchone()
dbc.execute("SELECT detail FROM system.contact_detail WHERE entity_id = '%s' AND type = 'fax'" % p_id)
fax = dbc.fetchone()
matches = []
if c_id and c_id.upper()!='NONE':
matches = db_tools.exec_action(dbc,'get_place_of_business_info3',[c_id])
if len(matches) == 0 and phone != None:
matches = db_tools.exec_action(dbc,'get_place_of_business_info1',[phone[0][:-3]])
if len(matches) == 0 and fax != None:
matches = db_tools.exec_action(dbc,'get_place_of_business_info2',[fax[0][:-3]])
page.content['matches']=matches
if len(matches) > 0:
match_list=[]
for match in matches:
match_dict={}
address_bits_1 = [match['line1'],match['line2'],match['suburb'],match['region']]
if address_bits_1.count(None) > 0:
address_bits_1.remove(None)
match_dict['id']=match['id']
match_dict['address_bits_1']=address_bits_1
match_list.append(match_dict)
page.content['match_list']=match_list
page.setup = {
'breadcrumbs':['crm','person','Edit'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Edit Contact - ' + person_name,
'broadcast_message':broadcast_message,
'template':'crm/sce5.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
'query_params':{'pid':p_id,'cid':c_id},
'name':person_name
}
return page.render()
def edit_contact2_step3( req,**params ):
"""displays form 3 of 3 for editing contact details"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
p_id = params['pid']
c_id = params['cid']
person_name = params['person_name']
if params.has_key('location_id') and params['location_id']:
dbc.execute("SELECT edit_contact(%s,'','','{location_id}', '{%s}', '%s')" % (p_id, params['location_id'], params['original_page_load']))
result = dbc.fetchone()[0]
page.company_db.commit()
broadcast_message = showErr(result)
util.redirect(req,"/bin/crm.py/index?broadcast_message=%s"%broadcast_message)
page.content = {
'is_company_id':False,
'is_name':False,
'address':block.address('validate-all-or-none'),
'params_name':params.keys(),
'params_list':params
}
if params.has_key('company_id') and params['company_id']:
page.content['is_company_id']=True
work_location_choices = table.place_of_business_choice(dbc, params['company_id'], False)
page.content['work_location_choices']=work_location_choices
if params.has_key('company_name') and params['company_name']!='':
page.content['is_name']=True
broadcast_message = None
page.setup = {
'breadcrumbs':['crm','person','Edit Location'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Edit Location - ' + person_name,
'broadcast_message':broadcast_message,
'template':'crm/sce6.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
'query_params':{'pid':p_id,'cid':c_id},
'name':person_name
}
return page.render()
def edit_contact2_complet( req,**params ):
"""actually updates contact details -- redirects to crm index page (contacts by company)"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
if params.has_key('cid'):
c_id = params['cid']
else:
c_id = None
p_id = params['pid']
person_name = params['person_name']
passthrough_fields = ['cid', 'pid', 'person_name', 'original_page_load']
field_names = ''
new_values = ''
old_values = ''
for field_name in params.keys():
if field_name[:4] != 'old_' and passthrough_fields.count(field_name) == 0 and params[field_name] != '':
field_names = field_names.strip('~:~') + '~:~' + field_name
new_values = new_values.strip('~:~') + '~:~' + params[field_name]
dbc.execute("SELECT edit_contact(%s,'','', string_to_array('%s', '~:~'), string_to_array('%s', '~:~'), '%s')" % (p_id, field_names, new_values, params['original_page_load']))
result = dbc.fetchone()[0]
conn.commit()
broadcast_message = showErr(result)
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/crm.py/index?cid=%s&pid=%s&broadcast_message=%s"%(c_id,p_id,broadcast_message))
def get_contact_detail(req,**params):
"""displays details (including contact log) for a single contact"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = ''
if params.has_key('broadcast_message') and params['broadcast_message']:
broadcast_message = params['broadcast_message']
p_id=int(params['pid'])
if params.has_key('cid') and params['cid'].strip() and params['cid'].upper() != 'NONE':
c_id=int(params['cid'])
else:
c_id=None
page.content = {
'p_id':p_id,
'c_id':c_id,
'is_customer':False
}
customer_id=db_tools.exec_action(dbc,'get_customer_id2',[p_id])
if len(customer_id) > 0:
page.content['is_customer']=True
customer_id = customer_id[0]['id']
page.content['customer_id']=customer_id
#get comments and escapte
if params.has_key('comment') and params['comment'] != '' and params['comment'] != None:
unquote_comment = params['comment']
else:
unquote_comment = ''
#get file name/value and escapte
if params.has_key('file') and params['file']!='' and params['file'].filename != '' and params['file'].filename != None:
filename = params['file'].filename
filevalue = params['file'].file.read()
unquote_filename = filename
else:
filename = ''
filevalue = ''
unquote_filename = filename
#get action and escapte
if params.has_key('action') and params['action'] != '' and params['action'] != None:
unquote_action = params['action']
else:
unquote_action = ''
#operate accroding to diffrent submit value
if params.has_key('submit') and params['submit'] != None:
if params['submit'] == 'Create':
contact_log_id = db_tools.exec_action(dbc,'get_contact_log_id')[0]['num']
db_tools.exec_action(dbc,'insert_contact_log',[int(contact_log_id), int(p_id), unquote_comment, unquote_filename, unquote_action], conn=page.company_db)
save_upload_file(get_whole_save_path(p_id, contact_log_id),get_whole_file_name(get_whole_save_path(p_id, contact_log_id), get_file_name_by_id(contact_log_id, filename)),filevalue)
page.company_db.commit()
broadcast_message = 'Entry added'
elif params['submit'] == 'Close Action / Save Changes':
if filename == '':
db_tools.exec_action(dbc,'update_contact_log1',[unquote_comment, unquote_action, params['logid']])
else:
db_tools.exec_action(dbc,'update_contact_log2',[unquote_comment, unquote_filename, unquote_action, params['logid']])
save_upload_file(get_whole_save_path(p_id, params['logid']),get_whole_file_name(get_whole_save_path(p_id, params['logid']), get_file_name_by_id(params['logid'], filename)),filevalue)
page.company_db.commit()
broadcast_message = 'Action closed'
elif params['submit'] == 'Save Changes':
if filename == '':
db_tools.exec_action(dbc,'update_contact_log3',[unquote_comment, unquote_action, params['logid']])
else:
db_tools.exec_action(dbc,'update_contact_log4',[unquote_comment, unquote_filename, unquote_action, params['logid'] ])
save_upload_file(get_whole_save_path(p_id, params['logid']),get_whole_file_name(get_whole_save_path(p_id, params['logid']), get_file_name_by_id(params['logid'], filename)),filevalue)
page.company_db.commit()
broadcast_message = 'Entry updated'
contact_info = {}
if c_id!=None:
contact_info = db_tools.exec_action(dbc,'get_contact_info',[p_id,'='+str(c_id)])[0]
else:
contact_info = db_tools.exec_action(dbc,'get_contact_info',[p_id,'is NULL'])[0]
pob_info = None
address = None
work_address = None
pob_id = None
page.content['is_address'] = False
page.content['is_location'] = False
if c_id!=None:
pob_id = db_tools.exec_action(dbc,'get_pob_id',[p_id,str(c_id)])[0]['location_id']
if pob_id:
pob_info=db_tools.exec_action(dbc,'get_pop_info2',[str(pob_id)])[0]
if pob_info:
if contact_info['phone'] == pob_info['phone']:
contact_info['phone'] = None
if contact_info['fax'] == pob_info['fax']:
contact_info['fax'] = None
pob_info['phone']=max(pob_info['phone'], '').replace(' ', '')
address = pob_info
page.content['is_location'] = True
address = ','.join([pob_info['name'], get_formatted_address(pob_info,return_one_line=True)])
else:
pob_id = db_tools.exec_action(dbc,'get_work_details',[p_id])
if pob_id:
work_address=db_tools.exec_action(dbc,'get_address_info',[str(pob_id[0]['address_id'])])[0]
page.content['work_address'] = work_address
page.content['is_address'] = True
contact_info['phone']=max(contact_info['phone'], '').replace(' ', '')
#---------------------contact_info------------------------#
page.content['contact_info']=contact_info
page.content['count_none']=contact_info.values().count(None)
page.content['pob_info']=pob_info
#------------------------------------------------------------------------------#
person_name = ' '.join([contact_info['given_name'], contact_info['surname']])
if address == None and work_address != None:
address = get_formatted_address(work_address,return_one_line=True)
#----------address-------------------#
page.content['address']=address
#-----------------------------------------#
if contact_info['email']:
email_link = '<a href="mailto:' + contact_info['email'] + '">' + contact_info['email'] + '</a>'
else:
email_link = ''
#-----------email_link---------------#
page.content['email_link']=email_link
#-----------------------------------------#
alt_locations = db_tools.exec_action(dbc,'get_alt_locations',[p_id])
#----------------------is_alt_locations Boolean------#
page.content['is_alt_locations']=False
#----------------------------------------------------------------#
if len(alt_locations) > 0:
## alt_locations = dictfetch(dbc)
#----------------------is_alt_locations Boolean------#
page.content['is_alt_locations']=True
#----------------------------------------------------------------#
address_list=[]
for alt_location in alt_locations:
alt_location['phone']=max(alt_location['phone'], '').replace(' ', '')
address_dict={}
address_dict['id']=alt_location['id']
address_dict['address']=get_formatted_address(alt_location,return_one_line=True)
if alt_location['type'].find('address') > 0:
address_dict['address_label']=alt_location['type']
else:
address_dict['address_label']='Address'
address_list.append(address_dict)
#---------------address_list,alt_location---------------------#
page.content['alt_locations']=alt_locations
page.content['address_list']=address_list
#-----------------------------------------------------------------------#
#---------------contact_log----------------------#
page.content['contact_log']=contact_log(dbc, p_id, str(c_id), info.query_string,page.session['skin'])
page.content['query_string'] = info.query_string.replace('?', '&')
#--------------------------------------------------------------------------#
page.setup = {
'breadcrumbs':['crm',person_name],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':person_name,
'broadcast_message':broadcast_message,
'template':'crm/sp.opt'
}
page.info = {
'query_string':info.query_string,
'name':person_name
}
return page.render()
def delete_contact(req, **params):
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
person_id = params['pid']
dbc.execute('select delete_contact(%s)'%person_id)
result = dbc.fetchone()[0]
conn.commit()
broadcast_message = error.showErr(result)
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
redirect_to = '/bin/crm.py/index?broadcast_message=%s'%broadcast_message
if params.has_key("entity_name") and params['entity_name'].strip():
redirect_to = redirect_to + '&entity_name='+params['entity_name'].strip()
if params.has_key("searchkey") and params['searchkey'].strip():
redirect_to = redirect_to + '&searchkey=' + params['searchkey'].strip()
util.redirect(req,redirect_to)
def merge_contact_step1(req, **params):
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
pid = params['pid']
persons = db_tools.exec_action(dbc, 'get_persons1', [pid])
page.content = {
'persons': persons,
'person1_id': pid
}
page.setup = {
'breadcrumbs':['crm','Merge Contact'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Merge Contact',
'template':'crm/mc1.opt'
}
page.info = {
'query_string':info.query_string
}
return page.render()
def merge_contact_step2(req, **params):
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
from datetime import datetime
person1 = db_tools.exec_action(dbc, 'get_persons2', [params['person1_id']])[0]
person2 = db_tools.exec_action(dbc, 'get_persons2', [params['person2_id']])[0]
page.content = {
'person1': person1,
'person2': person2,
'original_page_load': datetime.now()
}
page.setup = {
'breadcrumbs':['crm','Merge Contact'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Merge Contact',
'template':'crm/mc2.opt'
}
page.info = {
'query_string':info.query_string
}
return page.render()
def merge_contact_step3(req, **params):
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
person1_id = params['k_person_id']
person2_id = person1_id == params['person1_id'] and params['person2_id'] or params['person1_id']
person1 = db_tools.exec_action(dbc, 'get_persons2', [person1_id])[0]
person2 = db_tools.exec_action(dbc, 'get_persons2', [person2_id])[0]
location1_id = None
if person1['company_id']:
location1_id = db_tools.exec_action(dbc, 'get_location_id', [person1_id, person1['company_id']])[0]['location_id']
person1_locations = db_tools.exec_action(dbc, 'get_person_locations2', [person1_id, location1_id, person1_id, person1_id])
else:
person1_locations = db_tools.exec_action(dbc, 'get_person_locations1', [person1_id, person1_id])
location2_id = None
if person2['company_id']:
location2_id = db_tools.exec_action(dbc, 'get_location_id', [person2_id, person2['company_id']])[0]['location_id']
append_sql = ''
if location1_id:
append_sql = 'and id <> '+ str(location1_id)
person2_locations = db_tools.exec_action(dbc, 'get_person_locations3', [person2_id, location2_id, append_sql, person2_id, person2_id])
else:
person2_locations = db_tools.exec_action(dbc, 'get_person_locations1', [person2_id, person2_id])
for location1 in person1_locations:
location1['checked'] ='Y'
if not location1_id and location2_id and location1['name'] == 'work':
location1['checked'] = 'N'
for location2 in person2_locations:
location2['checked'] = 'N'
if not location1_id and location2_id and location2['combination'].split('_')[0] == 'c':
location2['checked'] = 'Y'
elif location2['name'] != 'work' and location2['combination'].split('_')[0] != 'c':
flag = True
for location1 in person1_locations:
if location1['name'] == location2['name']:
flag = False
if flag:
location2['checked'] = 'Y'
locations = person1_locations + person2_locations
locations.sort()
for location in locations:
address = db_tools.exec_action(dbc, 'get_address_info', [location['address_id']])[0]
location['format_address'] = utils.get_formatted_address(address, return_one_line = True)
del(params['k_person_id'])
page.content = {
'locations': locations,
'params': params
}
page.setup = {
'breadcrumbs':['crm','Merge Contact'],
'menu_title':'CRM Portal',
'menu':['newcontact'],
'content_title':'Merge Contact',
'template':'crm/mc3.opt',
}
page.info = {
'query_string':info.query_string
}
return page.render()
def merge_contact_submit(req, **params):
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
person1_id = params['person1_id']
person2_id = params['person2_id']
passthrough_fields = ['person1_id', 'person2_id', 'original_page_load']
field_names = ''
new_values = ''
locations = ''
for field_name in params.keys():
if passthrough_fields.count(field_name) == 0 and field_name[0:2] != 'c_' and field_name[0:2] != 'p_':
field_names = field_names.strip('~:~') + '~:~' + field_name
if params[field_name]:
new_values = new_values.strip('~:~') + '~:~' + params[field_name]
else:
new_values = new_values + '~:~' + ' '
elif passthrough_fields.count(field_name) == 0:
locations = locations.strip('~:~') + '~:~' + params[field_name]
dbc.execute("SELECT merge_contact(%s,%s, string_to_array('%s', '~:~'), string_to_array('%s', '~:~'),string_to_array('%s', '~:~'), '%s')"%(person1_id, person2_id, field_names, new_values, locations, params['original_page_load']))
conn.commit()
result = dbc.fetchone()[0]
broadcast_message = showErr(int(result))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/crm.py?broadcast_message=%s"%broadcast_message)
def test(req,**params):
session = Session.Session(req,timeout=info.session_timeout)
info.setSessionTimeout(session)
s=''
s += '------------session-------------\n'
s += '%-30s:%s\n' % ('id',session.id() )
s += '%-30s:%s\n' % ('create_time',session.created() )
s += '%-30s:%s\n' % ('last_accessed',session.last_accessed() )
s += '%-30s:%s\n' % ('time_left',session.last_accessed() - session.created() )
return s
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from mod_python import apache
from mod_python import Session
from mod_python import util
from phunc import *
from phunc.cx_wrapper import db_tools
from phunc.form import user_form
from phunc.logger import logger
# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
qtable = table.qtable
def index(req, **params):
"""displays user list"""
page = Page(req, app_db=True)
if not page.session.has_key('login_company'):
raise GeneralBusinessErr('can not connect to company database!')
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
sql_str = "SELECT a.*, b.name AS user_name, c.name AS group_name FROM system.affiliation a, system.user b, system.group c WHERE a.user_id=b.id AND a.group_id=c.id AND a.company_id=%s ORDER BY a.user_id" % page.session['login_company']
page_split_setup={
'cursor':page.app_db.cursor(),
'sql':sql_str,
'skin':page.session['skin'],
'page':params.has_key('page') and params['page'] and int(params['page']) or 1,
'pagesize':8,
'url':"/bin/admin.py",
'params':{}
}
users = table.ControlPage(**page_split_setup)
page.content = {
'user_list':users.result,
'page_split':users.createHtml(),
'query_string':info.query_string.replace('?', '&')
}
page.setup = {
'breadcrumbs':['Admin'],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax','smtpset'],
'content_title':'Users',
'broadcast_message':broadcast_message,
'template':'admin/a.opt',
'javascript':True
}
page.info = {
'query_string':info.query_string,
}
return page.render(debug=True)
#TODO:is system.role in bde database useful?
def create_user_page(req, **params):
"""displays user list and form to create a new user"""
page = Page(req, app_db=True)
group_list = db_tools.exec_action(page.app_db.cursor(),'get_group')
page.content = {
'group_list':group_list
}
page.setup = {
'breadcrumbs':['admin','New User'],
'menu_title':'Admin Portal',
'menu':['newuser!','newsalesagent','newtax','smtpset'],
'content_title':'New User',
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'template':'admin/auc.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_user(req,**params):
"""actually creates a new user -- redirects to index page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
app_db = get_app_connection()
broadcast_message = 'An error occurred. The user was not created'
if not session.has_key('login_company'):
raise GeneralBusinessErr('Cannot connect to company database')
else:
from phunc import user
user_id, create_message = user.createUser(app_db, params['name'], params['password'])
grant_message = user.grantUser(app_db, user_id, int(session['login_company']), int(params['group_id']))
app_db.commit()
broadcast_message = create_message + grant_message
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/admin.py?broadcast_message=%s"%broadcast_message)
def delete_user(req, **params):
"""actually deletes a user -- redirects to index page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
app_db = get_app_connection()
dbc = app_db.cursor()
broadcast_message = "An error occurred"
if not utils.is_root_user(params['user_id'], dbc):
db_tools.exec_action(dbc, 'delete_user', [params['user_id']])
db_tools.exec_action(dbc, 'remove_right_on_user', [params['user_id']])
app_db.commit()
broadcast_message="User '%s' removed" % params['user_name']
else:
broadcast_message = "Superusers can't be deleted from within this portal"
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/admin.py?broadcast_message=%s" % broadcast_message)
def edit_user_page(req, **params):
"""displays a form for editing basic user details"""
page = Page(req, app_db=True)
group_list = db_tools.exec_action(page.app_db.cursor(),'get_group')
page.content = {
'group_list':group_list,
'user_name':params['user_name'],
'user_id':params['user_id'],
'group_id':params['user_group'],
'company_id':params['user_company']
}
page.setup = {
'breadcrumbs':['admin', 'Edit User - ' + params['user_name']],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax','smtpset'],
'content_title':params['user_name'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'template':'admin/aue.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def edit_user(req, **params):
"""actually updates the user -- redirects to index page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
app_db = get_app_connection()
if params.has_key('user_id'):
db_tools.exec_action(app_db.cursor(),'edit_user_group',[params['group_id'],params['user_id'],params['company_id'],params['old_group_id']])
app_db.commit()
broadcast_message = 'User updated'
if int(session['login_user_id'])==int(params['user_id']):
session['login_group'] = params['group_id']
session.save()
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/admin.py?broadcast_message=%s" % broadcast_message)
def show_tables(req, **params):
"""DEPRECATED -- display a list of tables, with links to drill into them"""
from phunc.table import qtable
page = Page(req, company_db=True)
page.content = {
'qtable':qtable(company_db, 'SELECT * FROM ' + info.t + ' ORDER BY id' + info.page_string, '/bin/admin.py/show_tables?t=' + info.t + info.query_string.replace('?', '&'), info.page)
}
page.setup = {
'breadcrumbs':['admin','Raw Table Display - ' + info.t],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax','smtpset'],
'content_title':info.t,
'template':'admin/at.opt'
}
page.info = {
'query_string':info.query_string,
't':info.t
}
return page.render()
def show_views(req, **params):
"""DEPRECATED -- display a list of views, with links to drill into them"""
from phunc.table import qtable
page = Page(req, company_db=True)
page.content = {
'qtable':qtable(company_db, 'SELECT * FROM ' + info.v + info.page_string, '/bin/admin.py/show_views?v=' + info.v + info.query_string.replace('?', '&'), info.page )
}
page.setup = {
'breadcrumbs':['admin','Public View - ' + info.v],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax','smtpset'],
'content_title':info.v,
'template':'admin/av.opt'
}
page.info = {
'query_string':info.query_string,
'v':info.v
}
return page.render()
def create_sales_agent_page(req, **params):
"""display first of 2 forms for creating a new sales agent"""
page = Page(req, company_db=True)
page.content = {
'entitytypes':db_tools.exec_action(page.company_db.cursor(),'get_entity_types')
}
page.setup = {
'breadcrumbs':['admin', 'New Sales Agent'],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent!','newtax','smtpset'],
'content_title':'New Sales Agent',
'template':'admin/aca.opt'
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def create_sales_agent_details(req, **params):
"""display second of 2 forms for creating a new sales agent"""
page = Page(req, company_db=True)
page.content = {
'lcase_entity_type':params['entity_type'].capitalize(),
'entities':db_tools.exec_action(page.company_db.cursor(),'get_all_entities_not_sales_agent', [params['entity_type']])
}
if len(page.content['entities']) == 0:
util.redirect(req,"/bin/admin.py?broadcast_message=%s" % ('No %s entities available' % params['entity_type']))
page.setup = {
'breadcrumbs':['admin', 'New Sales Agent'],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent!','newtax','smtpset'],
'content_title':'New Sales Agent',
'template':'admin/aca2.opt'
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_sales_agent(req, **params):
"""actually creates a sales agent -- redirects to index page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
company_db = get_connection(session)
if(params['entity_id'] == '' or params['commission'] == ''):
broadcast_message = 'Wrong parameters!'
else:
db_tools.exec_action(company_db.cursor(),'insert_sales_agent', [int(params['entity_id']), int(params['commission'])])
company_db.commit()
broadcast_message = 'Sales agent created'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req, '/bin/admin.py?broadcast_message=%s' % broadcast_message)
def send_email_page(req, **params):
"""displays a form for generating a system email"""
page = Page(req)
page.setup = {
'breadcrumbs':['admin', 'Message management'],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax','smtpset'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Create New Message',
'template':'admin/email.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def send_email(req, **params):
"""actually sends a system email -- redirects to email form"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
from_email = params['from']
to_email = params['to'].split(',')
subject = params['subject']
root_path = req.document_root()
attach_length = int(params['attach_length'])
file_path = []
if attach_length>0:
import os
for i in range(attach_length):
if params.has_key('attach_file'+str(i+1)):
filename = params['attach_file'+str(i+1)].filename
filevalue = params['attach_file'+str(i+1)].file.read()
filepath = os.path.join(root_path,filename)
utils.save_upload_file(root_path, filepath, filevalue)
file_path.append(filepath)
email_content = params['content']
if params.has_key('auth_required') and params['auth_required']:
auth_required = 1
smtp_server = params['smtp_server']
smtp_user = params['smtp_user']
smtp_pass = params['smtp_pass']
user_email.send_mail(send_from = from_email,send_to = to_email,subject = subject,text = email_content,files = file_path,server=smtp_server,auth_required = auth_required,smtp_user = smtp_user,smtp_pass = smtp_pass)
else:
user_email.send_mail(send_from = from_email,send_to = to_email,subject = subject,text = email_content,files = file_path)
broadcast_message = "Email sent"
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/admin.py/send_email_page?broadcast_message=%s"%broadcast_message)
def smtp_server_setting(req, **params):
"""display a form for setting smtp server defaults"""
page = Page(req)
page.setup = {
'breadcrumbs':['admin', 'Configure SMTP Settings'],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax','smtpset!'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Configure SMTP Settings',
'template':'admin/smtp_set.opt',
'form':True,
}
page.info = {
'query_string':info.query_string
}
return page.render()
def set_smtp_server(req, **params):
"""actually set the smpt server defaults -- redirects to set smtp server form"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
company_db = get_connection(session)
dbc = company_db.cursor()
for code_id in [info.THIS_EMAIL,info.SMTP_SERVER,info.SMTP_USER,info.SMTP_PASS]:
code_value = db_tools.exec_action(dbc,'get_sys_code', [code_id])
if not code_value:
db_tools.exec_action(dbc,'insert_sys_code', [code_id,params[code_id],code_id])
else:
db_tools.exec_action(dbc,'update_sys_code', [params[code_id],code_id,code_id])
company_db.commit()
broadcast_message = "SMTP server set"
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/admin.py/smtp_server_setting?broadcast_message=%s"%broadcast_message)
def insert_transaction_tax(req, **params):
"""displays a form for creating a transaction tax"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
dbc.execute('SELECT * FROM system.transaction_tax')
page.content = {
'has_taxes':dbc.rowcount > 0,
'tax_list':utils.dictfetch(dbc),
'default_tax_is_null':db_tools.exec_action(dbc, 'default_tax_is_null')[0]['bool']
}
page.setup = {
'breadcrumbs':['admin','New Transaction Tax'],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax!','smtpset'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'New Transaction Tax',
'template':'admin/insert_tr_tax.opt',
'form':True,
}
return page.render()
def create_transaction_tax(req, **params):
"""actually creates a transaction tax -- redirects to transaction tax form"""
try:
session = Session.Session(req)
check_access(req, session, req.uri)
company_db = get_connection(session)
dbc = company_db.cursor()
dbc.execute('''
INSERT INTO system.transaction_tax (shortname, name, tax_page_id, rate, included_in_unit_price_default, track_on_purchases)
VALUES ('%s', '%s', 0, %s, '%s', '%s')
''' % (
params['shortname'],
params['name'],
params['rate'],
params['default_included'],
params['track_on_purchases']
))
if params.has_key('default_tax') and params['default_tax'] == 'yes':
dbc.execute('''
UPDATE system.sys_code
SET code_value = '%s'
WHERE code_id = 'default_tax'
''' % (
params['shortname']
))
company_db.commit()
broadcast_message = 'Tax created'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req, '/bin/admin.py/insert_transaction_tax?broadcast_message=%s' % broadcast_message)
def additional_setup(req, **params):
"""assesses company setup status, provides some useful links"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page.content = {
'taxes_required':False,
'tax_page_updated':False,
'special_accounts_required':False
}
# check for transaction taxes
dbc.execute('SELECT * FROM system.transaction_tax')
if dbc.rowcount == 0:
page.content['taxes_required'] = True
# check if tax page was updated
if params.has_key('broadcast_message') and params['broadcast_message'].find('New') >= 0:
page.content['tax_page_updated'] = True
# check for special accounts
special_params = [{'param_id':'special_ac_sales_rev','param_name':'Sales Revenue','param_desc':'Sales Revenue'},{'param_id':'special_ac_cash','param_name':'CASH','param_desc':'CASH'}]
special_params_len = len(special_params)
exist_special_params_len = db_tools.exec_action(page.company_db.cursor(), 'exist_special_params_len', [tuple([a['param_id'] for a in special_params])])[0]['special_params_len']
if special_params_len!=exist_special_params_len and 'finance' in page.session['user_access'].values():
page.content['special_accounts_required'] = True
page.setup = {
'breadcrumbs':['admin','Additional Setup'],
'menu_title':'Admin Portal',
'menu':['newuser','newsalesagent','newtax','smtpset'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Additional Setup',
'template':'admin/additional_setup.opt'
}
return page.render()
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from mod_python import apache
from mod_python import Session
from mod_python import util
from phunc import *
from phunc.cx_wrapper import db_tools
from phunc.logger import logger
# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage, showErr = error.genErrorPage, error.showErr
address = block.address
alt_location_choice = table.alt_location_choice
def index( req, **params ):
"""displays a customer list and search box"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page_params = {}
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
flag = params.has_key('flag') and params['flag'] or 'customer'
page_params = {'flag':flag}
page_num=1
if params.has_key('page') and params['page']:
page_num = int(params['page'])
sql_str = ''
if flag=="customer":
sql_str = "SELECT * FROM customer_info"
if flag=="supplier":
sql_str = "SELECT * FROM supplier_info"
entity_type = params.has_key("entity_type") and params['entity_type'].strip() or None
entity_name = params.has_key("entity_name") and params['entity_name'].strip() or None
searchkey = params.has_key('searchkey') and params['searchkey'] or ''
if entity_type:
if "WHERE" in sql_str:
sql_str = sql_str+" AND type='%s'"%entity_type.strip()
else:
sql_str = sql_str+" WHERE type='%s'"%entity_type.strip()
page_params['entity_type'] = entity_type
if entity_name:
if "WHERE" in sql_str:
sql_str = sql_str+" AND name LIKE '%%%s%%'"%entity_name.strip()
else:
sql_str = sql_str+" WHERE name LIKE '%%%s%%'"%entity_name.strip()
page_params['entity_name'] = entity_name
if searchkey.lower()!='all':
if "WHERE" in sql_str:
sql_str = sql_str+" AND lower(name) LIKE '%s%%'"%searchkey.lower()
else:
sql_str = sql_str+" WHERE lower(name) LIKE '%s%%'"%searchkey.lower()
page_params['searchkey'] = searchkey
page_split_setup={
'cursor':dbc,
'sql':sql_str,
'skin':page.session['skin'],
'page':page_num,
'pagesize':8,
'url':"/bin/operations.py",
'params':page_params
}
business = table.ControlPage(**page_split_setup)
page.content = {
'results':business.result,
'page_split':business.createHtml(),
'index_list':utils.get_index_list(),
'entitytypes':db_tools.exec_action(dbc,'get_entity_types'),
'page_params':page_params
}
page.setup = {
'breadcrumbs':['Operations'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'Search',
'broadcast_message':broadcast_message,
'template':flag=='customer' and 'operations/o_customer.opt' or 'operations/o_supplier.opt'
}
page.info = {
'query_string':info.query_string
}
return page.render()
#CREATE CUSTOMER
def create_customer_entity_type(req, **params):
"""displays form 1 of 4 for creating a customer"""
page = Page(req, company_db=True)
entitytypes = db_tools.exec_action(page.company_db.cursor(),'get_entity_types')
form_setup={
'id':'customer',
'action':'/bin/operations.py/create_customer_entity_details',
'fieldsets':[{
'id':None,
'classid':'form',
'legend':'Entity Type',
'items':[
{'type':'select','label':'Customer is a','id':'entity_type','name':'entity_type','classid':'required','option':entitytypes,'option_value':{'split':None,'items':['id'],'default_value':''},'option_text':{'split':None,'items':['id'],'default_text':'-- Please select --'},'selected_type':2,'selected_value':'company','selected_key':None},
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {'type':'div','id':None,'classid':'bottom input','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Continue'}]},
}
uform = form.user_form(**form_setup)
page.content = {
'uform':uform,
'entitytypes':entitytypes
}
page.setup = {
'breadcrumbs':['operations', 'New Customer'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'New Customer',
'template':'operations/occ1.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_customer_entity_details( req, **params ):
"""displays form 2 of 4 for creating a customer"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
#billing_methods = [{'id':1,'name':'hard copy'},{'id':2,'name':'email'},{'id':3,'name':'fax'}]
billing_methods = db_tools.exec_action(dbc,'get_billing_methods')
SMTP_SERVER_OK=True
for code_id in [info.THIS_EMAIL,info.SMTP_SERVER,info.SMTP_USER,info.SMTP_PASS]:
code_value = db_tools.exec_action(dbc,'get_sys_code', paramlist = [code_id])
if not code_value:
SMTP_SERVER_OK=False
break
exists_company_ids=db_tools.exec_action(dbc,'get_company_ids_from_customer')
entities2=db_tools.exec_action(dbc,'get_company_entities',[params['entity_type']])
form_action = '/bin/operations.py/create_customer_other_entity_billing'
entities=[]
if len(entities2)>0:
if len(exists_company_ids)>0:
for entity in entities2:
flag=True
for company_id in exists_company_ids:
if company_id['company_id']!=None:
if int(entity['id'].split(':')[0])==int(company_id['company_id']):
flag=False
break
if flag==True:
entities.append(entity)
else:
entities=entities2
if params['entity_type'] == 'person':
exists_person_ids=db_tools.exec_action(dbc,'get_person_ids_from_customer')
entities2=db_tools.exec_action(dbc,'get_person_entities',[params['entity_type']])
form_action = '/bin/operations.py/create_customer_person_billing'
entities=[]
if len(entities2)>0:
if len(exists_person_ids)>0:
for entity in entities2:
flag=True
for person_id in exists_person_ids:
if person_id['person_id']!=None:
if int(entity['id'].split(':')[0])==int(person_id['person_id']):
flag=False
break
if flag==True:
entities.append(entity)
else:
entities=entities2
page.content={
'billing_methods':billing_methods,
'entities':entities,
'lcase_entity_type':params['entity_type'].capitalize(),
'entity_type':params['entity_type'],
'form_action':form_action,
'METHOD_ONE':info.BILLING_METHOD_ONE,
'METHOD_TWO':info.BILLING_METHOD_TWO,
'METHOD_THREE':info.BILLING_METHOD_THREE,
'SMTP_SERVER_OK':SMTP_SERVER_OK,
'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
}
page.setup = {
'breadcrumbs':['operations', 'New Customer'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'New Customer',
'template':'operations/occ2.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_customer_other_entity_billing(req, **params):
"""displays form 3 of 4 for creating a customer"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page.content = {
'has_entity_id':False,
'salesagents':db_tools.exec_action(dbc,'get_salesagents'),
'params_name':params.keys(),
'params_list':params,
'METHOD_ONE':info.BILLING_METHOD_ONE,
'METHOD_TWO':info.BILLING_METHOD_TWO,
'METHOD_THREE':info.BILLING_METHOD_THREE
}
if params.has_key('entity_id') and params['entity_id'].strip():
page.content['has_entity_id'] = True
company_id = params['entity_id'].split(':')[0]
page.content['billing_method'] = params['update_billing_method']
if page.content['billing_method']==info.BILLING_METHOD_ONE:
billing_address_choices = table.place_of_business_choice(dbc, str(company_id))
page.content['billing_address_choices']=billing_address_choices
if not billing_address_choices:
validation_class = 'required'
else:
validation_class = 'validate-one-if-none'
else:
validation_class = 'required'
else:
page.content['billing_method'] = params['billing_method']
validation_class = 'required'
page.content['validation_class']=validation_class
page.content['address']=address(validation_class)
page.setup = {
'breadcrumbs':['operations', 'New Customer'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'New Customer',
'template':'operations/occ3.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_customer_person_billing( req, **params ):
"""displays form 4 of 4 for creating a customer"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page.content = {
'salesagents':db_tools.exec_action(dbc,'get_salesagents'),
'has_key':False,
'alt_location_types':db_tools.exec_action(dbc,'get_alt_location_types'),
'params_name':params.keys(),
'params_list':params,
'METHOD_ONE':info.BILLING_METHOD_ONE,
'METHOD_TWO':info.BILLING_METHOD_TWO,
'METHOD_THREE':info.BILLING_METHOD_THREE
}
validation_class = ''
if params.has_key('entity_id') and params['entity_id']!='':
page.content['has_key']=True
page.content['billing_method'] = params['update_billing_method']
person_id = params['entity_id'].split(':')[0]
if page.content['billing_method']==info.BILLING_METHOD_ONE:
billing_address_choices = alt_location_choice(dbc, str(person_id))
page.content['billing_address_choices']=billing_address_choices
if not billing_address_choices:
validation_class = 'required'
else:
validation_class = 'validate-one-if-none'
else:
validation_class = 'required'
else:
page.content['billing_method'] = params['billing_method']
validation_class = 'required'
page.content['validation_class']=validation_class
page.content['address']=address(validation_class)
page.setup = {
'breadcrumbs':['operations', 'New Customer'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'New Customer',
'template':'operations/occ4.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_customer_submit( req, **params ):
"""actually creates a customer -- redirects to operations index"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
entity_type = params['entity_type']
billing_method = None
if params.has_key('entity_id') and params['entity_id']!='':
# test whether it's a company_id or person_id and use it to get the actual entity_id
billing_method = params['update_billing_method']
company_or_person_id = params['entity_id'].split(':')[0]
entity_id = company_or_person_id
if params.has_key('update_abn') and params['update_abn']!='':
abn = db_tools.exec_action(dbc,'get_if_exist_abn',[str(entity_id)])
if abn:
db_tools.exec_action(dbc,'update_abn',[params['update_abn'],str(entity_id)])
else:
db_tools.exec_action(dbc,'insert_abn',[str(entity_id),params['update_abn']])
else:
billing_method = params['billing_method']
if entity_type == 'person':
db_tools.exec_action(dbc,'insert_person',[params['surname'],params['given_name'],str(entity_type)])
else:
db_tools.exec_action(dbc,'insert_company',[params['name'],str(entity_type)])
entity_id=db_tools.exec_action(dbc,'get_entity_id')[0]['id']
# otherwise create an entity and return the entity_id
if params.has_key('abn') and params['abn']!='':
db_tools.exec_action(dbc,'insert_abn',[entity_id,params['abn']])
if billing_method==info.BILLING_METHOD_ONE:#hard copy
if params.has_key('place_of_business_id') and params['place_of_business_id']!='':
# get the address_id (for the customer's billing address) from the selected place of business
address_id= db_tools.exec_action(dbc,'get_address_id',[params['place_of_business_id']])[0]['address_id']
elif params.has_key('alt_location_id') and params['alt_location_id']!='':
# otherwise try to get it from the selected alt_location (remember if it's negative
# it's actually the person_id so get the pob_id from system.person then the address for that pob)
address_id= db_tools.exec_action(dbc,'get_address_id',[params['alt_location_id']])[0]['address_id']
else:
# otherwise create an address and return the address_id
if params.has_key('line2') and params['line2']!='':
db_tools.exec_action(dbc,'insert_address1',[params['line1'],params['line2'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
else:
db_tools.exec_action(dbc,'insert_address2',[params['line1'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
address_id = db_tools.exec_action(dbc,'get_address_id4')[0]['id']
if params.has_key('pob_name') and params['pob_name']!='':
# also create place_of_business if possible
other_possible_keys = ['pob_name', 'pob_phone', 'pob_fax']
other_keys = []
other_values = []
for key in other_possible_keys:
if params.has_key(key) and params[key]!='':
other_keys = other_keys + [key]
other_values = other_values + [params[key]]
db_tools.exec_action(dbc,'insert_address3',[', '.join(other_keys).replace('pob_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
elif params.has_key('al_type') and params['al_type']!='':
# or alt_location if possible
other_possible_keys = ['al_type', 'al_phone', 'al_fax']
other_keys = []
other_values = []
for key in other_possible_keys:
if params.has_key(key) and params[key]!='':
other_keys = other_keys + [key]
other_values = other_values + [params[key]]
db_tools.exec_action(dbc,'insert_address3',[ ', '.join(other_keys).replace('al_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
elif entity_type == 'person':
# otherwise (if it's a person) call it a postal_address and be done with it
db_tools.exec_action(dbc,'insert_address5',[str(entity_id),str(address_id)])
# create the customer record, with or without sales_agent info
if params.has_key('sales_agent_id') and params['sales_agent_id']!='':
db_tools.exec_action(dbc,'insert_customer1',[ str(entity_id),str(params['sales_agent_id']),billing_method,str(address_id)])
else:
db_tools.exec_action(dbc,'insert_customer2',[ str(entity_id),billing_method,str(address_id)])
if billing_method==info.BILLING_METHOD_TWO:#email
email = params['email']
db_tools.exec_action(dbc,'insert_contact_detail',[ str(entity_id),info.CONTACT_TYPE_EMAIL,email])
if params.has_key('sales_agent_id') and params['sales_agent_id']!='':
db_tools.exec_action(dbc,'insert_customer3',[ str(entity_id),str(params['sales_agent_id']),billing_method])
else:
db_tools.exec_action(dbc,'insert_customer4',[ str(entity_id),billing_method])
if billing_method==info.BILLING_METHOD_THREE:#fax
fax = params['fax']
db_tools.exec_action(dbc,'insert_contact_detail',[ str(entity_id),info.CONTACT_TYPE_FAX,fax])
if params.has_key('sales_agent_id') and params['sales_agent_id']!='':
db_tools.exec_action(dbc,'insert_customer3',[ str(entity_id),str(params['sales_agent_id']),billing_method])
else:
db_tools.exec_action(dbc,'insert_customer4',[ str(entity_id),billing_method])
# get the customer_id and use it to create an accounts receivable account
#customer_id = db_tools.exec_action(dbc,'get_customer_id',[str(dbc.lastrowid)])[0]['id']
customer_id = db_tools.exec_action(dbc,'get_customer_id')[0]['id']
#db_tools.exec_action(dbc,'insert_ledger_ar_chart_of_accounts',[str(customer_id)])
nid = db_tools.exec_action(dbc,'get_next_ar_seq')[0]['id']
db_tools.exec_action(dbc,'insert_ledger_ar_chart_of_accounts',[nid,str(customer_id)])
conn.commit()
broadcast_message='Customer created'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/operations.py?flag=customer&broadcast_message=%s'%broadcast_message)
#CREATE SUPPLIER
def create_supplier_entity_type(req, **params):
"""displays form 1 of 4 for creating a supplier"""
page = Page(req, company_db=True)
entitytypes = db_tools.exec_action(page.company_db.cursor(),'get_entity_types')
form_setup={
'id':'supplier',
'action':'/bin/operations.py/create_supplier_entity_details',
'fieldsets':[{
'id':None,
'classid':'form',
'legend':'Entity Type',
'items':[
{'type':'select','label':'Supplier is a','id':'entity_type','name':'entity_type','classid':'required','option':entitytypes,'option_value':{'split':None,'items':['id'],'default_value':''},'option_text':{'split':None,'items':['id'],'default_text':'-- Please select --'},'selected_type':2,'selected_value':'company','selected_key':None},
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {
'type':'div',
'id':None,
'classid':'bottom input',
'style':None,
'items':[
{'type':'submit','id':'submit','name':'submit','value':'Continue'},
]
},
}
uform = form.user_form(**form_setup)
page.content = {
'uform':uform,
'entitytypes':entitytypes
}
page.setup = {
'breadcrumbs':['operations', 'New Supplier'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
'content_title':'New Supplier',
'template':'operations/ocsu1.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_supplier_entity_details( req, **params ):
"""displays form 2 of 4 for creating a supplier"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
entity_type = params['entity_type']
exists_company_ids=db_tools.exec_action(dbc,'get_company_ids_from_supplier')
entities2=db_tools.exec_action(dbc,'get_company_entities',[entity_type])
form_action = '/bin/operations.py/create_supplier_other_entity_billing'
entities=[]
if len(entities2)>0:
if len(exists_company_ids)>0:
for entity in entities2:
flag=True
for company_id in exists_company_ids:
if company_id['company_id']!=None:
if int(entity['id'].split(':')[0])==int(company_id['company_id']):
flag=False
break
if flag==True:
entities.append(entity)
else:
entities=entities2
if entity_type == 'person':
exists_person_ids=db_tools.exec_action(dbc,'get_person_ids_from_supplier')
entities2=db_tools.exec_action(dbc,'get_person_entities',[entity_type])
form_action = '/bin/operations.py/create_supplier_person_billing'
entities=[]
if len(entities2)>0:
if len(exists_person_ids)>0:
for entity in entities2:
flag=True
for person_id in exists_person_ids:
if person_id['person_id']!=None:
if int(entity['id'].split(':')[0])==int(person_id['person_id']):
flag=False
break
if flag==True:
entities.append(entity)
else:
entities=entities2
page.content={
'entities':entities,
'lcase_entity_type':entity_type.capitalize(),
'entity_type':entity_type,
'form_action':form_action,
'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
}
page.setup = {
'breadcrumbs':['operations', 'New Supplier'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
'content_title':'New Supplier',
'template':'operations/ocsu2.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_supplier_other_entity_billing(req, **params):
"""displays form 3 of 4 for creating a supplier"""
page = Page(req, company_db=True)
page.content = {
'has_entity_id':False,
'params_name':params.keys(),
'params_list':params
}
if params.has_key('entity_id') and params['entity_id']!='':
page.content['has_entity_id']=True
company_id = params['entity_id'].split(':')[0]
billing_address_choices = table.place_of_business_choice(page.company_db.cursor(), str(company_id))
page.content['billing_address_choices']=billing_address_choices
if billing_address_choices == '':
validation_class = 'required'
else:
validation_class = 'validate-all-or-none'
else:
validation_class = 'required'
page.content['validation_class']=validation_class
page.content['address']=address(validation_class)
page.setup = {
'breadcrumbs':['operations', 'New Supplier'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
'content_title':'New Supplier',
'template':'operations/ocsu3.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def create_supplier_person_billing( req, **params ):
"""displays form 4 of 4 for creating a supplier"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page.content = {
'has_key':False,
'alt_location_types':db_tools.exec_action(dbc,'get_alt_location_types'),
'params_name':params.keys(),
'params_list':params
}
validation_class = ''
if params.has_key('entity_id') and params['entity_id']!='':
page.content['has_key']=True
person_id = params['entity_id'].split(':')[0]
billing_address_choices = alt_location_choice(dbc, str(person_id))
page.content['billing_address_choices']=billing_address_choices
if billing_address_choices == '':
validation_class = 'required'
else:
validation_class = 'validate-all-or-none'
else:
validation_class = 'required'
page.content['address']=address(validation_class)
page.setup = {
'breadcrumbs':['operations', 'New Supplier'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
'content_title':'New Supplier',
'template':'operations/ocsu4.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_supplier_submit( req, **params ):
"""actually creates a supplier -- redirects to operations index"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
entity_type = params['entity_type']
if params.has_key('entity_id') and params['entity_id']!='':
# test whether it's a company_id or person_id and use it to get the actual entity_id
company_or_person_id = params['entity_id'].split(':')[0]
entity_id = company_or_person_id
if params.has_key('update_abn') and params['update_abn']!='':
abn = db_tools.exec_action(dbc,'get_if_exist_abn',[str(entity_id)])
if abn:
db_tools.exec_action(dbc,'update_abn',[params['update_abn'],str(entity_id)])
else:
db_tools.exec_action(dbc,'insert_abn',[str(entity_id),params['update_abn']])
else:
if entity_type == 'person':
db_tools.exec_action(dbc,'insert_person',[params['surname'],params['given_name'],str(entity_type)])
else:
db_tools.exec_action(dbc,'insert_company',[params['name'],str(entity_type)])
entity_id=db_tools.exec_action(dbc,'get_entity_id')[0]['id']
# otherwise create an entity and return the entity_id
if params.has_key('abn') and params['abn']!='':
db_tools.exec_action(dbc,'insert_abn',[entity_id,params['abn']])
if params.has_key('place_of_business_id') and params['place_of_business_id']!='':
# get the address_id (for the supplier's billing address) from the selected place of business
address_id= db_tools.exec_action(dbc,'get_address_id',[params['place_of_business_id']])[0]['address_id']
elif params.has_key('alt_location_id') and params['alt_location_id']!='':
# otherwise try to get it from the selected alt_location (remember if it's negative
# it's actually the person_id so get the pob_id from system.person then the address for that pob)
address_id= db_tools.exec_action(dbc,'get_address_id',[params['alt_location_id']])[0]['address_id']
else:
# otherwise create an address and return the address_id
if params.has_key('line2') and params['line2']!='':
db_tools.exec_action(dbc,'insert_address1',[params['line1'],params['line2'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
else:
db_tools.exec_action(dbc,'insert_address2',[params['line1'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
address_id = db_tools.exec_action(dbc,'get_address_id4')[0]['id']
if params.has_key('pob_name') and params['pob_name']!='':
# also create place_of_business if possible
other_possible_keys = ['pob_name', 'pob_phone', 'pob_fax']
other_keys = []
other_values = []
for key in other_possible_keys:
if params.has_key(key) and params[key]!='':
other_keys = other_keys + [key]
other_values = other_values + [params[key]]
db_tools.exec_action(dbc,'insert_address3',[', '.join(other_keys).replace('pob_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
elif params.has_key('al_type') and params['al_type']!='':
# or alt_location if possible
other_possible_keys = ['al_type', 'al_phone', 'al_fax']
other_keys = []
other_values = []
for key in other_possible_keys:
if params.has_key(key) and params[key]!='':
other_keys = other_keys + [key]
other_values = other_values + [params[key]]
db_tools.exec_action(dbc,'insert_address3',[ ', '.join(other_keys).replace('al_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
elif entity_type == 'person':
# otherwise (if it's a person) call it a postal_address and be done with it
db_tools.exec_action(dbc,'insert_address5',[str(entity_id),str(address_id)])
# create the supplier record
db_tools.exec_action(dbc,'insert_supplier',[str(entity_id),str(address_id)])
# get the customer_id and use it to create an accounts receivable account
#supplier_id = db_tools.exec_action(dbc,'get_supplier_id',[str(dbc.lastrowid)])[0]['id']
supplier_id = db_tools.exec_action(dbc,'get_supplier_id')[0]['id']
nid = db_tools.exec_action(dbc,'get_next_ap_seq')[0]['id']
db_tools.exec_action(dbc,'insert_ledger_ap_chart_of_accounts',[nid,str(supplier_id)])
conn.commit()
broadcast_message='Supplier created'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/operations.py?flag=supplier&broadcast_message=%s'%broadcast_message)
def customer_page( req, **params ):
"""displays an information page for a single customer"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
cid=params['cid']
if cid==None:
cid=1
page.content = {
'customer_id':cid
}
customer_billing_info=db_tools.exec_action(dbc,'get_customer_billing_info',[int(cid)])
if not customer_billing_info:
raise GeneralBusinessErr('customer_not_exist','/bin/login.py/login_out')
customer_billing_info = customer_billing_info[0]
#get customer billing method
billing_method = customer_billing_info['billing_method']
page.content['billing_method'] = billing_method
page.content['title']=customer_billing_info['customer_name']
if billing_method==info.BILLING_METHOD_ONE:#hard copy
billing_address = {
'line1':customer_billing_info['line1'],
'line2':customer_billing_info['line2'],
'suburb':customer_billing_info['suburb'],
'region':customer_billing_info['region'],
'code':customer_billing_info['code'],
'country':customer_billing_info['country']
}
page.content['customer_billing_address']=utils.get_formatted_address(billing_address,return_one_line=True)
else:
customer_billing_address=None
if billing_method==info.BILLING_METHOD_TWO:#email
customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_billing_info['entity_id'],info.CONTACT_TYPE_EMAIL])
if billing_method==info.BILLING_METHOD_THREE:#fax
customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_billing_info['entity_id'],info.CONTACT_TYPE_FAX])
if not customer_billing_address:
page.content['customer_billing_address'] = ''
else:
page.content['customer_billing_address'] = customer_billing_address[0]['detail']
page.content['customer_salse_agent']=str(customer_billing_info["sales_agent"] or ' ')
delivery_invoiceset = db_tools.exec_action(dbc,'get_delivery_invoices')
for delivery_invoice in delivery_invoiceset:
if delivery_invoice['method'] ==info.BILLING_METHOD_ONE:
if delivery_invoice['address_id']:
address_details = db_tools.exec_action(dbc,'get_address_info',[delivery_invoice['address_id']])
if address_details:
delivery_invoice['detail'] = utils.get_formatted_address(address_details[0],return_one_line=True)
else:
raise genErrorPage('ADDRESS_NOT_EXISTS','/bin/login.py/login_out')
else:
raise genErrorPage('SYSTEM_ERROR','/bin/login.py/login_out')
delivery_invoice['date'] = str(delivery_invoice['date'])[:10]
page.content['delivery_invoiceset'] = delivery_invoiceset
#----------------------------#
#------------invoice info--------------#
#----------------------------#
page_num = 1
if params.has_key('page') and params['page']:
page_num = int(params['page'])
sql_str = "SELECT * FROM system.invoice_info where customer_id=%d ORDER BY id"%int(cid)
split_page_setup={
'cursor':dbc,
'sql':sql_str,
'skin':page.session['skin'],
'page':page_num,
'pagesize':8,
'url':"/bin/operations.py/customer_page",
'params':{'pid':cid}
}
invoices = table.ControlPage(**split_page_setup)
invoices_info = invoices.result
page_split = invoices.createHtml()
for invoice_info in invoices_info:
invoice_info['date'] = str(invoice_info['date'])[:10]
page.content['invoices_info']=invoices_info
page.content['page_split'] = page_split
page.setup = {
'breadcrumbs':['operations','Customer Details - ' + customer_billing_info['customer_name']],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'Customer Details - ' + customer_billing_info['customer_name'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'template':'operations/ocii.opt',
'form':True,
}
page.info = {
'query_string':info.query_string,
'name':customer_billing_info['customer_name']
}
return page.render()
def supplier_page(req, **params):
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
pid=params['pid']
if pid==None:
pid=1
page.content = {
'has_billing_address':False
}
supplier_billing_info=db_tools.exec_action(dbc,'get_supplier_billing_info',[int(pid)])
if len(supplier_billing_info)>0:
page.content['has_billing_address']=True
supplier_billing_info=supplier_billing_info[0]
title=supplier_billing_info['supplier_name']
page.content['title']=title
billing_address = {
'line1':supplier_billing_info['line1'],
'line2':supplier_billing_info['line2'],
'suburb':supplier_billing_info['suburb'],
'region':supplier_billing_info['region'],
'code':supplier_billing_info['code'],
'country':supplier_billing_info['country']
}
page.content['supplier_billing_address']=utils.get_formatted_address(billing_address,return_one_line=True)
#----------------------------#
#------------purchase order info--------------#
#----------------------------#
page_num = 1
if params.has_key('page') and params['page']:
page_num = int(params['page'])
sql_str = "SELECT * FROM system.purchase_order_info where supplier_id=%d ORDER BY id"%int(pid)
split_page_setup={
'cursor':dbc,
'sql':sql_str,
'skin':page.session['skin'],
'page':page_num,
'pagesize':8,
'url':"/bin/operations.py/supplier_page",
'params':{'pid':pid}
}
purchase_orders = table.ControlPage(**split_page_setup)
purchase_orders_info = purchase_orders.result
page_split = purchase_orders.createHtml()
for purchase_orders in purchase_orders_info:
purchase_orders['date'] = str(purchase_orders['date'])[:10]
page.content['purchase_orders_info']=purchase_orders_info
page.content['page_split'] = page_split
page.setup = {
'breadcrumbs':['operations','Supplier Details - ' + title],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'Supplier Details - ' + title,
'template':'operations/ocpi.opt'
}
page.info = {
'query_string':info.query_string,
'name':title
}
return page.render()
def insert_invoice( req,**params ):
"""displays a form for creating an invoice"""
import datetime
page = Page(req, company_db=True)
session = page.session
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
#check the 'ar' account
control = db_tools.exec_action(dbc,'get_coa2',['ar'])
if not control:
if broadcast_message:
broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/insert_account?short_name=ar'>create</a> an Account(finance) with Subledger 'ar'." or "<br />You must create an Account(finance) with Subledger 'ar'."
else:
broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/insert_account?short_name=ar'>create</a> an Account(finance) with Subledger 'ar'." or "You must create an Account(finance) with Subledger 'ar'."
#check customers
customers = db_tools.exec_action(dbc,'get_customers')
if not customers:
if broadcast_message:
broadcast_message += "<br />You must <a href='/bin/operations.py/create_customer_entity_type'>create</a> some customers before you create an invoice."
else:
broadcast_message = "You must <a href='/bin/operations.py/create_customer_entity_type'>create</a> some customers before you create an invoice."
#check special accounts
special_params = [{'param_id':'special_ac_comm_pay','param_name':'Commissions Payable','param_desc':'Commissions Payable'},{'param_id':'special_ac_sales_rev','param_name':'Sales Revenue','param_desc':'Sales Revenue'}]
special_params_len = len(special_params)
exist_special_params_len = db_tools.exec_action(dbc, 'exist_special_params_len', [tuple([a['param_id'] for a in special_params])])[0]['special_params_len']
if special_params_len!=exist_special_params_len:
if broadcast_message:
broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice." or "<br />You must setup the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice."
else:
broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice." or "You must setup the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice."
#redirect
if special_params_len!=exist_special_params_len or not customers or not control:
util.redirect(req, '/bin/operations.py?broadcast_message=%s' % broadcast_message)
#check tax list and default tax
tax_list = db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail sale'])
default_tax = db_tools.exec_action(dbc, 'get_default_tax')
if not tax_list:
if broadcast_message:
broadcast_message += 'finance' in session['user_access'].values() and "<br />You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Sale)(finance) before you create an invoice." or "<br />You'd better setup the Tax accounts(Retail Sale)(finance) before you create an invoice."
else:
broadcast_message += 'finance' in session['user_access'].values() and "You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Sale)(finance) before you create an invoice." or "You'd better setup the Tax accounts(Retail Sale)(finance) before you create an invoice."
if not default_tax:
if broadcast_message:
broadcast_message += 'admin' in session['user_access'].values() and "<br />You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create an invoice." or "<br />You'd better setup the Default Tax(admin) before you create an invoice."
else:
broadcast_message += 'admin' in session['user_access'].values() and "You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create an invoice." or "You'd better setup the Default Tax(admin) before you create an invoice."
if default_tax:
default_tax=default_tax[0]
else:
default_tax=None
#if control:
# ledger = control[0]['name']
for customer in customers:
billing_method = customer['billing_method']
customer_billing_address=None
if billing_method==info.BILLING_METHOD_TWO:#email
customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer['person_id'] or customer['company_id'],info.CONTACT_TYPE_EMAIL])
if billing_method==info.BILLING_METHOD_THREE:#fax
customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer['person_id'] or customer['company_id'],info.CONTACT_TYPE_FAX])
if not customer_billing_address:
customer['customer_billing_address'] = ''
else:
customer['customer_billing_address'] = customer_billing_address[0]['detail']
page.content = {
'invoicer':db_tools.exec_action(dbc,'get_invoicer')[0],
'tax_list':tax_list,
'default_tax':default_tax,
'invoicer_address':utils.get_formatted_address(db_tools.exec_action(dbc, 'get_invoicer')[0],return_one_line=True),
'METHOD_ONE':info.BILLING_METHOD_ONE,
'METHOD_TWO':info.BILLING_METHOD_TWO,
'METHOD_THREE':info.BILLING_METHOD_THREE,
'customers':customers,
'invoice_id':db_tools.exec_action(dbc, 'get_invoicer_id')[0]['invoice_id'],
'today':datetime.date.today().isoformat(),
'sales':db_tools.exec_action(dbc, 'get_sales_agents'),
'sl':'ar',
'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
}
page.setup = {
'breadcrumbs':['operations', 'New Invoice'],
'menu_title':'Operations Portal',
'menu':['invoice!','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'Create Invoice',
'broadcast_message':broadcast_message,
'template':'finance/fic.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def create_invoice( req,**params ):
"""actually create an invoice -- redirects to invoice list"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map = {'p_customer_id':'','p_sales_agent_id':params['sales_agent_id'],'p_invoice_id':params['invoice_id'],'p_item_qty':'','p_item_description':'','p_item_unit_price':'','p_item_tax_ids':'','p_item_tax_inclusions':''}
if params.has_key('customer_info') and params['customer_info']:#customer id
var_map['p_customer_id'] = params['customer_info'].split('|')[1]
else:
util.redirect(req,"/bin/operations.py/insert_invoice?sl=%s" % params['sl'])
total_amount = 0
if type(params['description']) == type([]):
for i in xrange(len(params['description'])):
var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'][i])+'",'
var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'][i])+'",'
var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'][i])+'",'
var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][i][:-1]+'",'
var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][i][:-1]+'",'
var_map['p_item_description'] = var_map['p_item_description'][:-1]
var_map['p_item_qty'] = var_map['p_item_qty'][:-1]
var_map['p_item_unit_price'] = var_map['p_item_unit_price'][:-1]
var_map['p_item_tax_ids'] = var_map['p_item_tax_ids'][:-1]
var_map['p_item_tax_inclusions'] = var_map['p_item_tax_inclusions'][:-1]
else:
var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'])+'"'
var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'])+'"'
var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'])+'"'
var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][:-1]+'"'
var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][:-1]+'"'
result = db_tools.exec_action(dbc,'create_invoice',[var_map['p_customer_id'],var_map['p_sales_agent_id'],var_map['p_invoice_id'], params['invoice_date'], var_map['p_item_qty'],var_map['p_item_description'],var_map['p_item_unit_price'],var_map['p_item_tax_ids'],var_map['p_item_tax_inclusions']], nullify=True, escaped=True)[0]['create_invoice']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
util.redirect(req,"/bin/operations.py/show_invoice?sl=%s&broadcast_message=%s" % (params['sl'], broadcast_message))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/operations.py?broadcast_message=%s" % broadcast_message)
def show_invoice( req,**params ):
"""displays a list of invoice links"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
invoiceset = db_tools.exec_action(dbc,'get_invoices')
for invoice in invoiceset:
invoice['date'] = str(invoice['date'])[:10]
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0] # what's this for?
ledger = control['name'] # and this?
page.content = {
'invoiceset':invoiceset
}
page.setup = {
'breadcrumbs':['operations', 'Invoices'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'Search',
'broadcast_message':broadcast_message,
'template':'finance/fis.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def show_purchase_order( req,**params ):
"""displays a list of purchase orders"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
purchase_order_sets = db_tools.exec_action(dbc,'get_purchase_orders')
for purchase_order in purchase_order_sets:
purchase_order['date'] = str(purchase_order['date'])[:10]
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
page.content = {
'purchase_order_sets':purchase_order_sets
}
page.setup = {
'breadcrumbs':['operations', 'Purchase Orders'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
'content_title':'Search',
'broadcast_message':broadcast_message,
'template':'finance/fps.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def insert_purchase_order( req,**params ):
"""displays a form for creating a purchase order"""
import datetime
page = Page(req, company_db=True)
session = page.session
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
#check the 'ap' account
control = db_tools.exec_action(dbc,'get_coa2',['ap'])
if not control:
if broadcast_message:
broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/insert_account?short_name=ap'>create</a> an Account(finance) with Subledger 'ap'." or "<br />You must create an Account(finance) with Subledger 'ap'."
else:
broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/insert_account?short_name=ap'>create</a> an Account(finance) with Subledger 'ap'." or "You must create an Account(finance) with Subledger 'ap'."
#check supplier
suppliers = db_tools.exec_action(dbc,'get_suppliers')
if not suppliers:
if broadcast_message:
broadcast_message += "<br />You must <a href='/bin/operations.py/create_supplier_entity_type'>create</a> some suppliers before you create a purchase order."
else:
broadcast_message = "You must <a href='/bin/operations.py/create_supplier_entity_type'>create</a> some suppliers before you create a purchase order."
#check equip account
equip_account = db_tools.exec_action(dbc,'get_equip_account')
baccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['EXPENSE'])
if not equip_account and not baccounts:
if broadcast_message:
broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/insert_account?account_type_id=EXPENSE'>create</a> an Account(finance) with type 'EXPENSE' and without Subledger or <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Capital Equipment)(finance)." or "<br />You must create some Accounts(finance) with type 'EXPENSE' and without Subledger or setup the Special accounts(Capital Equipment)(finance)."
else:
broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/insert_account?account_type_id=EXPENSE'>create</a> an Account(finance) with type 'EXPENSE' and without Subledger or <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Capital Equipment)(finance)." or "You must create some Accounts(finance) with type 'EXPENSE' and without Subledger or setup the Special accounts(Capital Equipment)(finance)."
if not control or not suppliers or (not equip_account and not baccounts):
util.redirect(req,"/bin/operations.py?broadcast_message=%s"%broadcast_message)
#check tax list,default tax,equip account
default_taxes = db_tools.exec_action(dbc,'get_default_tax')
taxes = db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail purchase'])
if not taxes:
if broadcast_message:
broadcast_message += 'finance' in session['user_access'].values() and "<br />You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order." or "<br />You'd better setup the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order."
else:
broadcast_message += 'finance' in session['user_access'].values() and "You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order." or "You'd better setup the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order."
if not default_taxes:
if broadcast_message:
broadcast_message += 'admin' in session['user_access'].values() and "<br />You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create a Purcharse Order." or "<br />You'd better setup the Default Tax(admin) before you create a Purcharse Order."
else:
broadcast_message += 'admin' in session['user_access'].values() and "You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create a Purcharse Order." or "You'd better setup the Default Tax(admin) before you create a Purcharse Order."
buyer = db_tools.exec_action(dbc,'get_buyer')[0]
if default_taxes:
default_tax=default_taxes[0]
else:
default_tax=None
#if control:
# ledger = control[0]['name']
this_entity_id = db_tools.exec_action(dbc,'app_get_company_entity_id')[0]['code_value']
page.content = {
'buyer':buyer,
'buyer_address':utils.get_formatted_address(buyer,return_one_line=True),
'suppliers':suppliers,
'delivery_address':db_tools.exec_action(dbc,'get_delivery_address',[this_entity_id]),
'purchase_order_id':db_tools.exec_action(dbc, 'get_purchase_order_id')[0]['purchase_order_id'],
'today':datetime.date.today().isoformat(),
'taxes':taxes,
'tax_counter':len(taxes),
'sl':'ap',
'default_tax':default_tax,
'baccounts':baccounts,
'equip_account':equip_account,
'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
}
page.setup = {
'breadcrumbs':['operations', 'Create Purchase Order'],
'broadcast_message':broadcast_message,
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder!','billpayment','spacer','newsupplier'],
'content_title':'Create Purchase Order',
'template':'finance/fpc.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
#'ledger':ledger
}
return page.render()
def create_purchase_order( req,**params ):
"""actually create a purchase order -- redirects to purchase order list"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map = {'p_supplier_id':'','p_purchase_order_id':params['purchase_order_id'],'p_delivery_location_id':'','p_expense_account_id':'','p_item_qty':'','p_item_description':'','p_item_unit_price':'','p_item_tax_ids':'','p_item_tax_inclusions':''}
if params.has_key('supplier_info') and params['supplier_info']:#customer id
var_map['p_supplier_id'] = params['supplier_info'].split('|')[8]
else:
util.redirect(req,"/bin/operations.py/insert_purchase_order?sl=%s" % params['sl'])
if params.has_key('balance_account') and params['balance_account']:
var_map['p_expense_account_id'] = params['balance_account']
else:
util.redirect(req,"/bin/operations.py/insert_purchase_order?sl=%s" % params['sl'])
if params.has_key('delivery_address') and params['delivery_address']:
var_map['p_delivery_location_id'] = params['delivery_address'].split('|')[7]
else:
util.redirect(req,"/bin/operations.py/insert_purchase_order?sl=%s" % params['sl'])
total_amount = 0
if type(params['description']) == type([]):
for i in xrange(len(params['description'])):
var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'][i])+'",'
var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'][i])+'",'
var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'][i])+'",'
var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][i][:-1]+'",'
var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][i][:-1]+'",'
var_map['p_item_description'] = var_map['p_item_description'][:-1]
var_map['p_item_qty'] = var_map['p_item_qty'][:-1]
var_map['p_item_unit_price'] = var_map['p_item_unit_price'][:-1]
var_map['p_item_tax_ids'] = var_map['p_item_tax_ids'][:-1]
var_map['p_item_tax_inclusions'] = var_map['p_item_tax_inclusions'][:-1]
else:
var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'])+'"'
var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'])+'"'
var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'])+'"'
var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][:-1]+'"'
var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][:-1]+'"'
result = db_tools.exec_action(dbc,'create_purchase_order',[var_map['p_supplier_id'],var_map['p_purchase_order_id'],var_map['p_delivery_location_id'],var_map['p_expense_account_id'],params['purchase_order_date'],var_map['p_item_qty'],var_map['p_item_description'],var_map['p_item_unit_price'],var_map['p_item_tax_ids'],var_map['p_item_tax_inclusions']], nullify=True, escaped=True)[0]['create_purchase_order']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
broadcast_message += " <a href='/bin/operations.py/print_purchase_order?id=%s'>print purchase order</a>"%params['purchase_order_id']
util.redirect(req,"/bin/operations.py/show_purchase_order?sl=%s&broadcast_message=%s" % (params['sl'], broadcast_message))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/operations.py?broadcast_message=%s" % broadcast_message)
def print_invoice(req, **params):
"""displays an invoice in printer-friendly format"""
page = Page(req, company_db=True, no_menu=True)
dbc = page.company_db.cursor()
import locale
locale.setlocale(locale.LC_ALL,'')
invoicer = db_tools.exec_action(dbc,'get_invoicer')[0]
invoicer_address = utils.get_formatted_address(invoicer)
if params.has_key('id'):
invoices = db_tools.exec_action(dbc,'get_invoices1',[int(params['id'])])
elif params.has_key('start_id'):
invoices = db_tools.exec_action(dbc,'get_invoices2',[int(params['start_id'])])
elif page.session.has_key('invoice_id_list'):
invoices = db_tools.exec_action(dbc,'get_invoices3',[tuple(page.session.pop('invoice_id_list'))])
page.session.save()
for invoice in invoices:
customer_info = db_tools.exec_action(dbc,'get_customer_by_id',[invoice['customer_id']])[0]
if customer_info['billing_method']==info.BILLING_METHOD_ONE:
address_details = db_tools.exec_action(dbc,'get_address_info',[invoice['address_id']])[0]
invoice['address'] = utils.get_formatted_address(address_details)
elif customer_info['billing_method']==info.BILLING_METHOD_TWO:
invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])[0]['detail']
elif customer_info['billing_method']==info.BILLING_METHOD_THREE:
invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_FAX])[0]['detail']
#TODO:BUG!!not only gst tax.
invoice['items'] = db_tools.exec_action(dbc,'get_invoice_items_info',[int(invoice['id'])])
for item in invoice['items']:
item['total_ex'] = locale.format('%.2f', round(utils.float_no_exception(item['total_ex']), 2), True)
item['combined_tax'] = locale.format('%.2f', round(utils.float_no_exception(item['combined_tax']), 2), True)
item['total_inc'] = locale.format('%.2f', round(utils.float_no_exception(item['total_inc']), 2), True)
invoice['tax_aggregation'] = db_tools.exec_action(dbc, 'get_invoice_tax_aggregation', [int(invoice['id'])])
if len(invoice['tax_aggregation']) == 1:
invoice['tax_name'] = invoice['tax_aggregation'][0]['shortname']
else:
invoice['tax_name'] = 'Tax'
remit_msgs = db_tools.exec_action(dbc,'get_remit_msg')
page.content = {
'invoicer_address':invoicer_address,
'invoicer':invoicer,
'invoices':invoices,
'remit_msg':'<li>'+'</li><li>'.join([remit_msg['code_desc'] for remit_msg in remit_msgs]) + '</li>',
'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
}
page.setup = {
'template':'finance/pi.opt'
}
return page.render()
def print_purchase_order( req,**params ):
"""displays a purchase order in printer-friendly format"""
page = Page(req, company_db=True, no_menu=True)
dbc = page.company_db.cursor()
import locale
locale.setlocale(locale.LC_ALL,'')
purchase_order_host = db_tools.exec_action(dbc,'get_buyer')[0]#TODO get_purchase_order
purchase_order_address = utils.get_formatted_address(purchase_order_host)
if params.has_key('id'):
purchase_orders = db_tools.exec_action(dbc,'get_purchase_orders1',[int(params['id'])])
else:
purchase_orders = db_tools.exec_action(dbc,'get_purchase_orders2',[int(params['start_id'])])
for purchase_order in purchase_orders:
address_details = db_tools.exec_action(dbc,'get_address_info',[purchase_order['address_id']])[0]
delivery_address_details = db_tools.exec_action(dbc,'get_delivery_address_info',[purchase_order['delivery_location_id']])[0]
delivery_address = utils.get_formatted_address(delivery_address_details)
purchase_order['delivery_address_name'] = delivery_address_details['name']
purchase_order['delivery_address'] = delivery_address
purchase_order['items'] = db_tools.exec_action(dbc,'get_purchase_order_items_info',[int(purchase_order['id'])])
purchase_order['address'] = utils.get_formatted_address(address_details)
for item in purchase_order['items']:
item['total_ex'] = locale.format('%.2f', round(utils.float_no_exception(item['total_ex']), 2), True)
item['combined_tax'] = locale.format('%.2f', round(utils.float_no_exception(item['combined_tax']), 2), True)
item['total_inc'] = locale.format('%.2f', round(utils.float_no_exception(item['total_inc']), 2), True)
purchase_order['tax_aggregation'] = db_tools.exec_action(dbc, 'get_po_tax_aggregation', [int(purchase_order['id'])])
if len(purchase_order['tax_aggregation']) == 1:
purchase_order['tax_name'] = purchase_order['tax_aggregation'][0]['shortname']
else:
purchase_order['tax_name'] = 'Tax'
page.content = {
'purchase_order_address':purchase_order_address,
'purchase_order_host':purchase_order_host,
'purchase_orders':purchase_orders,
'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
}
page.setup = {
'template':'finance/pp.opt'
}
return page.render()
def payment_list_page(req,**params):
"""displays a form for creating a receipt"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
import datetime
page.content = {
'today':datetime.date.today().isoformat(),
'customers':db_tools.exec_action(dbc,'get_customers'),
#TODO:add date condition to select all invoices which have not paid yet.
'invoice_list':db_tools.exec_action(dbc,'get_all_invoices'),
'skin':page.session['skin']
}
page.setup = {
'breadcrumbs':['operations', 'Issue Receipt'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt!','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
'broadcast_message': params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Issue Receipt',
'template':'operations/opl.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_receive_payment(req, **params):
"""actually creates a receipt -- redirects to receipt form"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map = {'p_receipt_id':'','p_customer_id':params['customer'], 'p_amount':utils.escape_comma_in_number(params['amount']), 'p_comment':params['comment'],'p_invoice_ids':''}
if type(params['invoice_id']) == list:
for i in xrange(len(params['invoice_id'])):
var_map['p_invoice_ids'] += '"'+params['invoice_id'][i]+'",'
var_map['p_invoice_ids'] = var_map['p_invoice_ids'][:-1]
else:
var_map['p_invoice_ids'] += '"'+params['invoice_id']+'"'
result = db_tools.exec_action(dbc,'generate_receipt', [var_map['p_receipt_id'],var_map['p_customer_id'],params['receipt_date'],var_map['p_amount'],var_map['p_comment'],var_map['p_invoice_ids']], True)[0]['generate_receipt']
conn.commit()
broadcast_message = showErr(int(result))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/operations.py/payment_list_page?broadcast_message=%s' % broadcast_message)
def bill_payment_page( req,**params ):
'''diplays a form for recording a bill payment'''
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
import datetime
page.content = {
'today':datetime.date.today().isoformat(),
#TODO:add date condition
'suppliers':db_tools.exec_action(dbc,'get_suppliers'),
'purchase_order_list':db_tools.exec_action(dbc,'get_all_purchase_orders'),
'expense_accounts':db_tools.exec_action(dbc,'get_same_type_accounts', ['EXPENSE']),
'all_expense_taxes':db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail purchase']),
'tax_aggregation':db_tools.exec_action(dbc, 'get_all_purchase_tax_aggregation'),
'expenses_accounts':db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['EXPENSE']),
'skin':page.session['skin']
}
page.setup = {
'breadcrumbs':['operations', 'Bill Payment'],
'menu_title':'Operations Portal',
'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment!','spacer','newsupplier'],
'broadcast_message': params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Bill Payment',
'template':'operations/obp.opt',
'form':True,
'javascript':True,
}
page.info = {
'query_string':info.query_string
}
return page.render()
def pay_bill( req,**params ):
"""actually pay a bill -- redirects to bill payment list"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map = {'p_supplier_id':params['supplier_id'],'p_amount':utils.escape_comma_in_number(params['amount']),'p_tax_id':'','p_tax_amount':'','p_comment':utils.escape_quotes_in_sql(params['comment']),'p_adjustment_expense_account':params['adjustment_expense_account'],'p_adjustment_comment':utils.escape_quotes_in_sql(params['adjustment_comment']), 'p_purchase_order_ids':''}
if type(params['tax_id']) == list:
for i in xrange(len(params['tax_id'])):
var_map['p_tax_id'] += '"'+params['tax_id'][i]+'",'
var_map['p_tax_amount'] += '"'+utils.escape_comma_in_number(params['tax_amount'][i])+'",'
var_map['p_tax_id'] = var_map['p_tax_id'][:-1]
var_map['p_tax_amount'] = var_map['p_tax_amount'][:-1]
else:
var_map['p_tax_id'] += '"'+params['tax_id']+'"'
var_map['p_tax_amount'] += '"'+utils.escape_comma_in_number(params['tax_amount'])+'"'
if type(params['purchase_order_ids']) == list:
for i in xrange(len(params['purchase_order_ids'])):
var_map['p_purchase_order_ids'] += '"'+params['purchase_order_ids'][i]+'",'
var_map['p_purchase_order_ids'] = var_map['p_purchase_order_ids'][:-1]
else:
var_map['p_purchase_order_ids'] += '"'+params['purchase_order_ids']+'"'
result = db_tools.exec_action(dbc,'pay_bill',[var_map['p_supplier_id'],params['payment_date'],var_map['p_amount'], var_map['p_tax_id'],var_map['p_tax_amount'],var_map['p_comment'],var_map['p_adjustment_expense_account'],var_map['p_adjustment_comment'],var_map['p_purchase_order_ids']], escaped = True)[0]['pay_bill']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
util.redirect(req,"/bin/operations.py/bill_payment_page?broadcast_message=%s" % broadcast_message)
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/operations.py?broadcast_message=%s" % broadcast_message)
def send_invoice( req,**params ):
"""emails an invoice to a customer"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
customer_id = params['customer_id']
customer_info = db_tools.exec_action(dbc,'get_customer_by_id', [customer_id])
if customer_info:
customer_info = customer_info[0]
else:
raise genErrorPage('customer_not_exist','/bin/login.py/login_out')
invoice_ids = params['invoiceId']
billing_method = customer_info['billing_method']
if billing_method==info.BILLING_METHOD_ONE:
if type(invoice_ids) == list:
invoice_id_list = []
for invoice_id in invoice_ids:
db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_id,billing_method,customer_info['address_id']])
invoice_id_list.append(invoice_id)
conn.commit()
session['invoice_id_list'] = invoice_id_list
session.save()
util.redirect(req,"/bin/operations.py/print_invoice")
else:
db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_ids,billing_method,customer_info['address_id']])
conn.commit()
util.redirect(req,"/bin/operations.py/print_invoice?id=%s"%invoice_ids)
elif billing_method==info.BILLING_METHOD_TWO:#email
if type(invoice_ids) == list:
invoice_file_list = []
import os
for invoice_id in invoice_ids:
invoice_content = create_invoice_file_content(req,session=session,id=invoice_id)
invoice_file_name = "invoice_file_%s.html"%str(invoice_id)
save_path=os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH)
save_file_path = os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH,invoice_file_name)
utils.save_upload_file(save_path,save_file_path, invoice_content)
invoice_file_list.append(save_file_path)
else:
invoice_file_list = []
import os
invoice_content = create_invoice_file_content(req,session=session,id=invoice_ids)
invoice_file_name = "invoice_file_%s.html"%str(invoice_ids)
save_path=os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH)
save_file_path = os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH,invoice_file_name)
utils.save_upload_file(save_path, save_file_path, invoice_content)
invoice_file_list.append(save_file_path)
detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
if detail:
detail=detail[0]['detail']
else:
raise genErrorPage('BILLING_METHOD_ERROR')
#set the email
to_email=[]
to_email.append(detail)
subject="invoice list"
email_content=""
files=invoice_file_list
auth_required=True
#smtp server setting
smtp_server_set={}
for code_id in [info.THIS_EMAIL,info.SMTP_SERVER,info.SMTP_USER,info.SMTP_PASS]:
code_value = db_tools.exec_action(dbc,'get_sys_code', [code_id])
if not code_value:
raise genErrorPage('SMTP_ERROR',req.uri)
else:
smtp_server_set[code_id] = code_value[0]['code_value']
#send it
user_email.send_mail(send_from = smtp_server_set[info.THIS_EMAIL],send_to = to_email,subject = subject,text = email_content,files = files,server=smtp_server_set[info.SMTP_SERVER],auth_required = auth_required,smtp_user = smtp_server_set[info.SMTP_USER],smtp_pass = smtp_server_set[info.SMTP_PASS])
#record it
if type(invoice_ids) == list:
for invoice_id in invoice_ids:
db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
else:
db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
conn.commit()
#return
broadcast_message = 'The invoice has been sent'
elif billing_method==info.BILLING_METHOD_THREE:#fax
#send invoice
if type(invoice_ids) == list:
pass
else:
pass
#record it
detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_FAX])
if detail:
detail=detail[0]['detail']
else:
detail=''
if type(invoice_ids) == list:
for invoice_id in invoice_ids:
db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
else:
db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
conn.commit()
#return
broadcast_message = 'The invoice has been sent'
## invoice_file_url = print_invoice
## detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
## invoice_file_list.append(invoice_file_url)
## conn.commit()
## session['invoice_id_list'] = invoice_id_list
## session.save()
## util.redirect(req,"/bin/operations.py/print_invoice")
## else:
## detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
## conn.commit()
## util.redirect(req,"/bin/operations.py/print_invoice?id=%s"%invoice_ids)
## if type(invoice_ids) == list:
## for invoice_id in invoice_ids:
## #do something
## #1:get the billing_method in the customer table
## customer_info = db_tools.exec_action(dbc,'get_customer_by_invoice_id', [invoice_id])
## if not customer_info:
## raise GeneralBusinessErr('SYSTEM_ERROR','/bin/login.py/login_out')
## else:
## customer_info = customer_info[0]
## billing_method = customer_info['billing_method']
## #'get_customer_by_invoice_id':"SELECT * FROM customer c,system.invoice_info ii WHERE c.id=ii.customer_id AND ii.invoice_id=%s"
## #2:send the invoice
## if billing_method==info.BILLING_METHOD_ONE:#hard copy
## #print invoice
## db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_id,billing_method,customer_info['address_id']])
## if billing_method==info.BILLING_METHOD_TWO:#email
## detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
## if detail:
## detail=detail[0]['detail']
## else:
## detail=''
## #email invoice
## db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
## if billing_method==info.BILLING_METHOD_THREE:#fax
## detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_FAX])
## if detail:
## detail=detail[0]['detail']
## else:
## detail=''
## #fax invoice
## db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
## conn.commit()
## else:
## customer_info = db_tools.exec_action(dbc,'get_customer_by_invoice_id', [invoice_ids])
## if not customer_info:
## raise GeneralBusinessErr('SYSTEM_ERROR','/bin/login.py/login_out')
## else:
## customer_info = customer_info[0]
## billing_method = customer_info['billing_method']
## if billing_method==info.BILLING_METHOD_ONE:#hard copy
## #print invoice
## db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_ids,billing_method,customer_info['address_id']])
## if billing_method==info.BILLING_METHOD_TWO:#email
## detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
## if detail:
## detail=detail[0]['detail']
## else:
## detail=''
## #email invoice
## db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
## if billing_method==info.BILLING_METHOD_THREE:#fax
## detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_FAX])
## if detail:
## detail=detail[0]['detail']
## else:
## detail=''
## #fax invoice
## db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
## conn.commit()
## broadcast_message = 'The invoice sent'
## util.redirect(req,'/bin/operations.py/show_invoice?sl=ar&broadcast_message=%s'%broadcast_message)
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/operations.py/customer_page?cid=%s&broadcast_message=%s'%(customer_id,broadcast_message))
def create_invoice_file_content(req,**params):
"""displays an invoice in printer-friendly format"""
#page = Page(req, company_db=True, no_menu=True)
#dbc = page.company_db.cursor()
session=params['session']
dbc=get_connection(session).cursor()
import locale
locale.setlocale(locale.LC_ALL,'')
invoicer = db_tools.exec_action(dbc,'get_invoicer')[0]
invoicer_address = utils.get_formatted_address(invoicer)
if params.has_key('id'):
invoices = db_tools.exec_action(dbc,'get_invoices1',[int(params['id'])])
for invoice in invoices:
customer_info = db_tools.exec_action(dbc,'get_customer_by_id',[invoice['customer_id']])[0]
if customer_info['billing_method']==info.BILLING_METHOD_ONE:
address_details = db_tools.exec_action(dbc,'get_address_info',[invoice['address_id']])[0]
invoice['address'] = utils.get_formatted_address(address_details)
elif customer_info['billing_method']==info.BILLING_METHOD_TWO:
invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])[0]['detail']
elif customer_info['billing_method']==info.BILLING_METHOD_THREE:
invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_FAX])[0]['detail']
#TODO:BUG!!not only gst tax.
invoice['items'] = db_tools.exec_action(dbc,'get_invoice_items_info',[int(invoice['id'])])
for item in invoice['items']:
item['total_ex'] = locale.format('%.2f', round(utils.float_no_exception(item['total_ex']), 2), True)
item['combined_tax'] = locale.format('%.2f', round(utils.float_no_exception(item['combined_tax']), 2), True)
item['total_inc'] = locale.format('%.2f', round(utils.float_no_exception(item['total_inc']), 2), True)
invoice['tax_aggregation'] = db_tools.exec_action(dbc, 'get_invoice_tax_aggregation', [int(invoice['id'])])
if len(invoice['tax_aggregation']) == 1:
invoice['tax_name'] = invoice['tax_aggregation'][0]['shortname']
else:
invoice['tax_name'] = 'Tax'
remit_msgs = db_tools.exec_action(dbc,'get_remit_msg')
content = {
'invoicer_address':invoicer_address,
'invoicer':invoicer,
'invoices':invoices,
'remit_msg':'<li>'+'</li><li>'.join([remit_msg['code_desc'] for remit_msg in remit_msgs]) + '</li>'
}
from phunc.template import Template
template = Template()
template.parseFile(get_template_dir(req) + 'finance/pi.opt')
html = template.render(content)
return html
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from mod_python import apache
from mod_python import Session
from mod_python import util
import psycopg2
from phunc import *
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger
# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage = error.genErrorPage
def user_exists(cursor, name):
"""
Checks if user exists
Returns a boolean
"""
return len(db_tools.exec_action(cursor, 'app_get_user_info',[name])) > 0
def passwd_is_match(cursor, name, input_passwd):
"""
Checks password against encrypted password in database
Returns a boolean
"""
return len(db_tools.exec_action(cursor, 'app_verify_user_passwd',[name,input_passwd])) > 0
#**************************************************page function start**************************************************
def index(req, **params):
"""Authenticate user, save session, redirect to post-login page"""
try:
session = Session.Session(req,timeout=info.session_timeout)
cursor = get_app_connection().cursor()
if not user_exists(cursor, params['user_name']):
raise GeneralBusinessErr('user_not_exist','/bin/login.py/login_out')
else:
user_info = db_tools.exec_action(cursor, 'app_get_user_info',[params['user_name']])[0]
if not passwd_is_match(cursor, user_info['name'], params['user_password']):
raise GeneralBusinessErr('error_password','/bin/login.py/login_out')
else:
session['login_user_id'] = user_info['id']
session['login_user_name'] = params['user_name']
session['skin'] = user_info['skin']
session['portal_order'] = tuple(user_info['role_id'] or {})
session.save()
util.redirect(req, '/bin/root.py/loginpage')
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def login_out(req,**params):
"""deletes the current user session, redirects to login form"""
try:
session = Session.Session(req)
session.delete()
util.redirect(req,'/index.html?flag=1')
except:
return genErrorPage()
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from mod_python import apache
from mod_python import Session
from mod_python import util
def index( req ):
session = Session.Session(req,timeout=3600)
s = '------------request-------------\n'
s += '%-30s:%s\n' % ('config',req.get_config())
s += '------------session-------------\n'
s += '%-30s:%s\n' % ('id',session.id() )
s += '%-30s:%s\n' % ('create_time',session.created() )
s += '%-30s:%s\n' % ('last_accessed',session.last_accessed() )
s += '%-30s:%s\n' % ('time_left',session.last_accessed() - session.created() )
if session.last_accessed() - session.created()>3599:
s += '%-30s\n' % ('reset session timeout')
session.set_timeout(3600)
s += '%-30s:%s\n' % ('timeout',session.timeout() )
s += 'content: \n'
for key in session.keys():
s = s + '\t%-50s:%s\n' % (key,session[key])
s = s + '---------request--------------\n'
form = util.FieldStorage(req)
for f in form.keys():
s = s + '\t%-50s:%s\n' % (f,form[f])
s = s + '--------other------------------\n'
import os
s = s + "path_info:%s\n" % req.path_info
s = s + "canonical_filename:%s\n" % req.canonical_filename
s = s + "document_root():%s\n" % req.document_root()
return s
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from mod_python import apache
from mod_python import Session
from mod_python import util
from phunc import *
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger
# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage = error.genErrorPage
def index(req, **params):
"""displays a form for setting up account ranges on one of the financial reports"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
max_id = db_tools.exec_action(dbc,'get_max_id',[params['report_id']])
report_menu_items = [params['report_id']==str(key) and value or value[:-1] for key,value in {1:'balsheet!',2:'pl!',3:'taxreport!'}.iteritems()]
page.content = {
'report_detail':db_tools.exec_action(dbc,'get_report_detail',[int(params['report_id'])]),
'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0],
'max_id':max_id[0]['max_id'] or '10'
}
page.setup = {
'breadcrumbs':['finance',page.content['report_info']['name'].replace('&','&')],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked','subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer'] + report_menu_items,
'content_title':page.content['report_info']['name'].replace('&','&'),
'template':'report/create_report.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def add_item_page(req, **params):
"""displays a form for adding a line item to one of the reports"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
report_menu_items = [params['report_id']==str(key) and value or value[:-1] for key,value in {1:'balsheet!',2:'pl!',3:'taxreport!'}.iteritems()]
page.content = {
'sections':db_tools.exec_action(dbc,'get_report_sections',[int(params['report_id'])]),
'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0]
}
page.setup = {
'breadcrumbs':['finance',page.content['report_info']['name'].replace('&','&')],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer'] + report_menu_items,
'content_title':page.content['report_info']['name'].replace('&','&'),
'template':'report/add_item.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def add_item(req,**params):
"""actually adds a line item to one of the financial reports -- redirects to index page"""
try:
session = Session.Session(req)
check_access(req,session,req.uri)
conn = get_connection(session)
dbc = conn.cursor()
report = {
'sections':db_tools.exec_action(dbc,'get_report_sections',[int(params['report_id'])]),
'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0]
}
if report['sections']:
insert_position = db_tools.exec_action(dbc,'get_insert_position1',[params['report_id'],params['section_id']])[0]['order_num']
db_tools.exec_action(dbc,'update_order_num',[insert_position,params['report_id']])
db_tools.exec_action(dbc,'insert_new_item',[params['report_id'],params['section_id'],params['item_name'],params['account_range'].strip(),report['report_info']['default_formula_id'],(insert_position+1)])
else:
insert_position = db_tools.exec_action(dbc,'get_insert_position2',[params['report_id']])[0]['order_num']
insert_position = insert_position and insert_position or 0
db_tools.exec_action(dbc,'insert_new_item',[params['report_id'],'null',params['item_name'],params['account_range'].strip(),report['report_info']['default_formula_id'],(insert_position+1)])
conn.commit()
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/report/create_report.py?report_id=%s'%params['report_id'])
def save_change(req,**params):
"""actually updates the account ranges for the current report -- redirects to index page"""
try:
session = Session.Session(req)
check_access(req,session,req.uri)
conn = get_connection(session)
changed_items=params['changed_items'][:-1]
for item in changed_items.split(';'):
db_tools.exec_action(conn.cursor(),'update_params',[params[item],item])
conn.commit()
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/report/create_report.py?report_id=%s'%params['report_id'])
def report(req,**params):
"""actually runs the report, saves the results and displays them in printer-friendly format"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page.content = {
'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0]
}
db_tools.exec_action(dbc,'del_report_preresult',[params['report_id']])
section_str = ''
for item in db_tools.exec_action(dbc,'get_item_info1',[params['report_id']]):
ac_range_condition_parts = ['(id >= %s AND id <= %s)' % (ac_range.split('-')[0].strip(), ac_range.split('-')[-1].strip()) for ac_range in item['params'].split(',')]
condition = 'WHERE ' + ' OR '.join(ac_range_condition_parts)
sql = content['report_info']['isincl_date'] and item['formula'] % (params['date_start'] ,params['date_end'], condition) or item['formula'] % condition
dbc.execute(sql)
sumamount = dbc.fetchall()[0][0]
if sumamount:
db_tools.exec_action(dbc,'insert_result',[item['report_id'],item['id'],sumamount])
if item['section_id']: section_str = section_str + str(item['section_id']) + ','
for item in db_tools.exec_action(dbc,'get_item_info2',[params['report_id']]):
sql=item['formula']
dbc.execute(sql)
sumamount = dbc.fetchall()[0][0]
if sumamount: db_tools.exec_action(dbc,'insert_result',[item['report_id'],item['id'],sumamount])
section_str = section_str and section_str[:-1] or '-1'
for item in db_tools.exec_action(dbc,'get_item_info0',[params['report_id'],section_str]): db_tools.exec_action(dbc,'insert_result',[item['report_id'],item['id'],'null'])
page.company_db.commit()
page.content['display_report'] = db_tools.exec_action(dbc,'display_report',[params['report_id']])
report_menu_items = [params['report_id']==str(key) and value or value[:-1] for key,value in {1:'balsheet!',2:'pl!',3:'taxreport!'}.iteritems()]
page.setup = {
'breadcrumbs':['finance',page.content['report_info']['name'].replace('&','&')],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer'] + report_menu_items,
'content_title':page.content['report_info']['name'].replace('&','&'),
'template':'report/print_report.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.Utils import COMMASPACE, formatdate
from email import Encoders
from phunc.logger import logger
from phunc.error import genErrorPage,showErr
'''
function:
send email
parameter:
send_from = 'from@test.com' #the email send from address
send_to = ['to@test.com'] #the email send to address
subject = 'test' #the email subject
text = 'hello,this is a test' #the email content
files = ['test.txt'] #email attachment
server = 'stmp.test.com' #send email server
auth_required = 0 #if you need to use SMTP AUTH set to 1
smtpuser = 'liangtianyou' #for SMTP AUTH, set SMTP username here
smtppass = '******' #for SMTP AUTH, set SMTP password here
'''
def send_mail(send_from='liangtianyou@obolsoftware.com', send_to=['liangtianyou@obolsoftware.com'], subject='test',text='Hello,world', files=[],server="mail.obolsoftware.com",auth_required=0,smtp_user='',smtp_pass=''):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
if files:
for file in files:
try:
ctype, encoding = mimetypes.guess_type(file)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
fp = open(file)
# Note: we should handle calculating the charset
part = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'image':
fp = open(file, 'rb')
part = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(file, 'rb')
part = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(file, 'rb')
part = MIMEBase(maintype, subtype)
part.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
Encoders.encode_base64(part)
# Set the filename parameter
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(part)
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
errmsg = errmsg.replace('<','').replace('>','').replace('.__str__','')
logger.debug(errmsg)
smtp = smtplib.SMTP(server)
if auth_required:
result = smtp.login(smtp_user, smtp_pass)
smtp.sendmail(send_from, send_to, msg.as_string())
return
## except Exception,e:
## errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
## errmsg = errmsg.replace('<','').replace('>','').replace('.__str__','')
## logger.debug(errmsg)
if __name__=='__main__':
send_mail()
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from mod_python import apache
from mod_python import Session
from mod_python import util
import psycopg2
from phunc.cx_wrapper import db_tools
from exception import GeneralBusinessErr
from error import genErrorPage
from logger import logger
from template import Template
__all__ = [
'app_db_ip',
'app_db_name',
'app_db_user',
'app_db_passwd',
'check_session',
'check_access',
'get_connection',
'get_app_connection',
'get_template_dir',
'user_is_root',
'gen_site_map',
'gen_menu',
'Page',
'info',
'exception',
'error',
'block',
'table',
'form',
'constants',
'utils',
'user_email',
'DataBaseConnErr',
]
app_db_ip = 'localhost'
app_db_name = 'fivedash'
app_db_user = 'fivedash'
app_db_passwd = '{{password}}'
class DataBaseConnErr(Exception):
pass
def check_session(req,session):
if not session.has_key('login_user_name') and not session.has_key('login_user_id'):
#raise GeneralBusinessErr('user_not_login','/bin/login.py/login_out')
util.redirect(req,'/bin/root.py/access_forbit')
def check_access(req,session, url):
"""
Bugs out if the user does not have the required permissions.
Returns True otherwise.
"""
if not session.has_key('login_user_name'):
util.redirect(req,'/bin/root.py/access_forbit')
#access_list = session['user_access'].split(',')
access_list = session['user_access'].values()
if url=='/' or url.rfind('index') > 0:
return True
else:
for access in access_list:
logger.debug("%s %s" % (url, "/"+access+"/") )
if url.rfind( "/" + access ) > 0:
return True
util.redirect(req,'/bin/root.py/access_forbit')
def get_connection(session):
"""
Connects to a 'managed company' database.
Returns a connection object.
"""
for item in ['ip', 'name','user','passwd']:
if not session.has_key('company_db_'+item) or len(session['company_db_'+item]) == 0:
raise GeneralBusinessErr('can not connect to company database!')
logger.debug('<connect>')
cx = psycopg2.connect('host=%s dbname=%s user=%s password=%s' % (session['company_db_ip'], session['company_db_name'], app_db_user,app_db_passwd))
logger.debug('</connect>')
return cx
def get_app_connection(host=app_db_ip,dbname=app_db_name,user=app_db_user,passwd=app_db_passwd):
"""
Connects to app database.
Returns a connection object.
"""
try:
conn=psycopg2.connect('host=%s dbname=%s user=%s password=%s' % (host,dbname,user,passwd))
return conn
except:
raise DataBaseConnErr
def get_template_dir(req):
"""
Locates the base directory for page templates.
Returns a string.
"""
return req.document_root()[:req.document_root().rindex('skins')]+ 'templates/'
def user_is_root(session, cursor):
"""
Checks for root privileges.
Returns a boolean.
"""
return db_tools.exec_action(cursor, 'user_is_root', [int(session['login_user_id'])])[0]['is_root']
def gen_site_map(is_root_page=True, is_root_user=False, company_name=None, person_name=None, ledger=None):
"""
Selects/creates the relevant 'site structure' info - mostly for breadcrumbs.
Returns a dictionary.
"""
if is_root_page:
return {
'root':[is_root_user and 'Root Menu' or 'Global Menu','loginpage'],
'users':['Users','user_management'],
'groups':['Groups','group_management'],
'grants':['Grants','grant_right_page'],
'companies':['Managed Companies','company_management'],
'myprefs':['My Prefs','mypage']
}
else:
return {
'operations':['Operations','index'],
'invoices':['Invoices','show_invoice'],
'porders':['Purchase Orders','show_purchase_order'],
'finance':['Finance','index'],
'journals':['Journals','list_journal'],
'subledger':[ledger + ' Ledger','sub_account_index'],
'subjournals':['Journals','list_sub_journal'],
'crm':['CRM','index'],
'person':[person_name,'get_contact_detail'],
'admin':['Admin','index'],
'extras':['Extras','index'],
'root':['My Prefs','mypage'],
}
def gen_menu(is_root_page, url, query_string=None, sl=None):
"""
Selects/creates the relevant menu labels and links.
Returns a dictionary.
"""
if url.rfind('mybin') > 0:
from extras_lib import menu
menu['operations'] = ['Operations','/bin/operations.py']
menu['finance'] = ['Finance','/bin/finance.py']
menu['crm'] = ['CRM','/bin/crm.py']
menu['admin'] = ['Admin','/bin/admin.py']
menu['extras'] = ['Extras','/mybin/extras.py']
return menu
elif is_root_page:
return {
'users':['Manage Users','/bin/root.py/user_management'],
'groups':['Manage Groups','/bin/root.py/group_management'],
'grants':['Grant User Rights','/bin/root.py/grant_right_page'],
'companies':['Modify Company Details','/bin/root.py/company_management'],
'passwd':['Change Password','/bin/root.py/change_password_page'],
'skin':['Change Skin','/bin/root.py/change_skin_page'],
'portal':['Change Default Portal','/bin/root.py/change_default_portal_page']
}
else:
return {
'operations':['Operations','/bin/operations.py'],
'invoice':['Create Invoice', '/bin/operations.py/insert_invoice' + get_query_string(query_string)],
'receipt':['Issue Receipt', '/bin/operations.py/payment_list_page' + get_query_string(query_string)],
'billpayment':['Bill Payment', '/bin/operations.py/bill_payment_page' + get_query_string(query_string)],
'porder':['Create Purchase Order', '/bin/operations.py/insert_purchase_order' + get_query_string(query_string)],
'newcustomer':['New Customer', '/bin/operations.py/create_customer_entity_type' + get_query_string(query_string)],
'newsupplier':['New Supplier', '/bin/operations.py/create_supplier_entity_type' + get_query_string(query_string)],
'finance':['Finance','/bin/finance.py'],
'recordexp':['Record Expenses', '/bin/finance.py/insert_expenses' + get_query_string(query_string)],
'account':['Create an Account', '/bin/finance.py/insert_account' + get_query_string(query_string)],
'special':['Set Special Accounts','/bin/finance.py/special_params_setting_page' + get_query_string(query_string)],
'linked':['Set Tax Accounts','/bin/finance.py/linked_account_setting_page' + get_query_string(query_string)],
'subledger':['Create a Subsidiary Ledger', '/bin/finance.py/insert_sub_ledger' + get_query_string(query_string)],
'journal':['Write a Journal', '/bin/finance.py/insert_journal' + get_query_string(query_string)],
'editjournal':['Edit or Delete Journals', '/bin/finance.py/list_journal' + get_query_string(query_string)],
'postjournal':['Post Journals', '/bin/finance.py/list_post_journal' + get_query_string(query_string)],
'balsheet':['Balance Sheet', '/bin/report/create_report.py?report_id=1' + query_string.replace('?', '&')],
'pl':['Profit & Loss Report', '/bin/report/create_report.py?report_id=2' + query_string.replace('?', '&')],
'taxreport':['Tax Report', '/bin/report/create_report.py?report_id=3' + query_string.replace('?', '&')],
'subaccount':['Create an Account', '/bin/finance.py/insert_sub_account1?sl=' + sl + query_string.replace('?', '&')],
'subjournal':['Write a Journal', '/bin/finance.py/insert_sub_journal?sl=' + sl + query_string.replace('?', '&')],
'editsubjournal':['Edit or Delete Journals', '/bin/finance.py/list_sub_journal?sl=' + sl + query_string.replace('?', '&')],
'postsubjournal':['Post Journals', '/bin/finance.py/list_sub_post_journal?sl=' + sl + query_string.replace('?', '&')],
'crm':['CRM','/bin/crm.py'],
'newcontact':['New Contact', '/bin/crm.py/create_contact' + get_query_string(query_string)],
'admin':['Admin','/bin/admin.py'],
'newuser':['New User','/bin/admin.py/create_user_page' + get_query_string(query_string)],
'newsalesagent':['New Sales Agent', '/bin/admin.py/create_sales_agent_page' + get_query_string(query_string)],
'newtax':['New Transaction Tax', '/bin/admin.py/insert_transaction_tax'],
'smtpset':['Configure SMTP Settings','/bin/admin.py/smtp_server_setting' + get_query_string(query_string)],
'extras':['Extras','/mybin/extras.py'],
'passwd':['Change Password','/bin/root.py/change_password_page'],
'skin':['Change Skin','/bin/root.py/change_skin_page'],
'portal':['Change Default Portal','/bin/root.py/change_default_portal_page']
}
def get_query_string(query_string):
if query_string.find('&')==0:
return query_string[:5].replace('&','?')+query_string[5:]
elif query_string.find('&')==0:
return query_string[:1].replace('&','?')+query_string[1:]
else:
return query_string
storedSession = {}
lastAccessed = None
def setSessionTimeout(session):
global storedSession
global lastAccessed
if lastAccessed:
if lastAccessed-session.created()>=info.RESET_TIME_LIMIT:
for key,value in session.iteritems():
storedSession[key] = value
else:
for key,value in session.iteritems():
storedSession[key] = value
if session.is_new():
if lastAccessed:
if session.created()-lastAccessed<info.session_timeout:
for key,value in storedSession.iteritems():
session[key] = value
session.save()
session.set_timeout(info.session_timeout-session.created()+lastAccessed)
#eval lastAccessed
lastAccessed = session.last_accessed()
class Page:
"""
This is the main class of the application.
Each page in the application (with the exception of the login form) is an instance
of this class. Access control, merging of templates with associated values from the
instantiating script to generate output html, and basic error handling all happen here.
Connections are created (if required) that can be shared by the instantiating script.
This is the preferred method of getting a database connection.
The is_root_page parameter of __init__ informs as to whether the page lives
in the 'Root Menu' area, or within the portals area of a managed company's system
(there are significant differences between the page structures of those two areas).
Note that is_root_page=True overrides app_db=False and creates the connection anyway.
"""
def __init__(self, req, app_db=False, company_db=False, is_root_page=False, superuser_only=False, no_menu=False):
"""Check access, create connections, initialise page dictionaries, reset session timeout"""
#try:
self.session = Session.Session(req,timeout=info.session_timeout)
#self.session.load()
setSessionTimeout(self.session)
if is_root_page:
check_session(req,self.session)
else:
check_access(req,self.session, req.uri)
if app_db or is_root_page: self.app_db = get_app_connection()
if superuser_only and not user_is_root(self.session, self.app_db.cursor()):
raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
if company_db: self.company_db = get_connection(self.session)
self.req = req
self.is_root_page = is_root_page
self.no_menu = no_menu
self.info = {}
self.setup = {}
self.content = {}
#except GeneralBusinessErr, e:
#return genErrorPage(e.getErrMsg(), e.getURL())
def __setitem__(self,name,value):
if name=='is_root_page':
self.is_root_page=value
def __getitem__(self,name):
if name=='is_root_page':
return self.is_root_page
def render(self, debug=False):
"""Apply templates & defaults, generate page"""
if debug:
# drop the error handling
# -- this is a copy of the try block below
# -- unfriendly formatting for the sake of brevity
template = Template()
template.parseFile((self.req.uri.rfind('mybin') > 0 and '/var/fivedash/custom/templates/' or get_template_dir(self.req)) + self.setup['template'])
page_content = template.render(self.content)
if self.no_menu: return page_content
setup_defaults = {'window_title':'Fivedash','breadcrumbs':['Undefined area'],'menu_title':'Admin Process','menu':['spacer'],'content_title':'','broadcast_message':None,'form':False,'javascript':False,}
info_defaults = {'session':self.session,'query_string':'','ledger':'','sl':'','a':None,'name':None,'id':None,'j':'','v':'x.x','t':'x.x','query_params':{},'group':None}
for key, value in setup_defaults.iteritems(): self.setup[key] = self.setup.has_key(key) and self.setup[key] or value
for key, value in info_defaults.iteritems(): self.info[key] = self.info.has_key(key) and self.info[key] or value
# js file
if self.setup['javascript']:
import os
js_file_name=os.path.splitext(os.path.split(self.setup['template'])[1])[0]+'.js'
template.parseFile(os.path.join(get_template_dir(self.req)[:get_template_dir(self.req).rindex('templates')] ,'js',js_file_name))
js_content = template.render(self.content)
js_file_path = os.path.join(info.JS_TEMP_PATH,js_file_name)
utils.save_upload_file(info.JS_TEMP_PATH, js_file_path, js_content)
self.setup['js_file']=js_file_name
# js file end
self.setup['breadcrumb_links'] = self.setup['breadcrumbs'][:-1]
query_params_str = None
if self.info['query_params']:
query_params_str=''
for key,value in self.info['query_params'].items():
query_params_str += '%s=%s&'%(str(key),str(value))
query_params_str=query_params_str[:-5]
if self.is_root_page: site_map = gen_site_map(is_root_user=user_is_root(self.session, self.app_db.cursor()))
else: site_map = gen_site_map(False, False, self.session['company_name'], self.info['name'], self.info['ledger'])
menu_items = gen_menu(self.is_root_page, self.req.uri, self.info['query_string'], self.info['sl'])
self.session.save()
#self.session['user_access'] = (self.session.has_key('user_access') and self.session['user_access']) and self.session['user_access'].split(',') or None
self.session['user_access'] = self.session.has_key('user_access') and self.session['user_access'] or None
content = {'page_setup':self.setup,'page_info':self.info,'page_content':page_content,'session':self.session,'site_map':site_map,'menu_items':menu_items,'query_params_str':query_params_str}
template = Template()
template.parseFile(get_template_dir(self.req) + (self.is_root_page and 'html_root.opt' or 'html.opt'))
html = template.render(content)
return html
else:
try:
# apply template
template = Template()
template.parseFile(
(self.req.uri.rfind('mybin') > 0 and '/var/fivedash/custom/templates/' or get_template_dir(self.req)) +
self.setup['template']
)
page_content = template.render(self.content)
if self.no_menu: return page_content
# apply defaults
setup_defaults = {
'window_title':'Fivedash',
'breadcrumbs':['Undefined area'],
'menu_title':'Admin Process',
'menu':['spacer'],
'content_title':'',
'broadcast_message':None,
'form':False,
'javascript':False
}
info_defaults = {
'session':self.session,
'query_string':'',
'ledger':'',
'sl':'',
'a':None,
'name':None,
'id':None,
'j':'',
'v':'x.x',
't':'x.x',
'query_params':{},
'group':None
}
for key, value in setup_defaults.iteritems():
self.setup[key] = self.setup.has_key(key) and self.setup[key] or value
for key, value in info_defaults.iteritems():
self.info[key] = self.info.has_key(key) and self.info[key] or value
# create javascript file if necessary - this is for XHMTL 1.1 compliance
if self.setup['javascript']:
import os
js_file_name=os.path.splitext(os.path.split(self.setup['template'])[1])[0]+'.js'
template.parseFile(os.path.join(get_template_dir(self.req)[:get_template_dir(self.req).rindex('templates')] ,'js',js_file_name))
js_content = template.render(self.content)
js_file_path = os.path.join(info.JS_TEMP_PATH,js_file_name)
utils.save_upload_file(info.JS_TEMP_PATH,js_file_path, js_content)
self.setup['js_file']=js_file_name
# pander to the renderer's inability to slice lists
self.setup['breadcrumb_links'] = self.setup['breadcrumbs'][:-1]
# generate query string if necessary
query_params_str = None
if self.info['query_params']:
query_params_str=''
for key,value in self.info['query_params'].items():
query_params_str += '%s=%s&'%(str(key),str(value))
query_params_str=query_params_str[:-5]
# generate site map and menu items
if self.is_root_page:
site_map = gen_site_map(is_root_user=user_is_root(self.session, self.app_db.cursor()))
else:
site_map = gen_site_map(False, False, self.session['company_name'], self.info['name'], self.info['ledger'])
menu_items = gen_menu(self.is_root_page, self.req.uri, self.info['query_string'], self.info['sl'])
# reset session timeout and prepare user_access to be spoon fed to the renderer as a list
self.session.save()
#self.session['user_access'] = (self.session.has_key('user_access') and self.session['user_access']) and self.session['user_access'].split(',') or None
self.session['user_access'] = self.session.has_key('user_access') and self.session['user_access'] or None
# put it all together
content = {
'page_setup':self.setup,
'page_info':self.info,
'page_content':page_content,
'session':self.session,
'site_map':site_map,
'menu_items':menu_items,
'query_params_str':query_params_str
}
# invoke renderer
template = Template()
logger.debug("****************************************")
logger.debug(self.is_root_page)
template.parseFile(get_template_dir(self.req) + (self.is_root_page and 'html_root.opt' or 'html.opt'))
html = template.render(content)
return html
except GeneralBusinessErr, e:
return genErrorPage(e.getErrMsg(), e.getURL())
except Exception, e:
errmsg = '%s'.replace('<','').replace('>','').replace('.__str__','') % e.__str__ + ': ' + ','.join([str(arg) for arg in e.args])
return genErrorPage(errmsg, self.req.uri)
except:
return genErrorPage(errurl=self.req.uri)
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import datetime
from phunc import info
from phunc.logger import *
from phunc.exception import GeneralBusinessErr
from random import choice
import string
def unquote(string_with_embedded):
"""
Prepares a string with embedded quotes for inclusion in a query.
The string is returned wrapped in single quotes, so don't
re-wrap it when you create the query.
Embedded single quotes are properly escaped.
"""
return repr(string_with_embedded + '"')[:-2] + "'"
def is_root_user(user_id, app_db_cursor):
is_root_user=False
if user_id:
app_db_cursor.execute("SELECT company_id,group_id FROM system.affiliation WHERE user_id=%s"%user_id)
company_group_list = dictfetch(app_db_cursor)
if app_db_cursor.rowcount>0:
is_root_user=False
for item in company_group_list:
app_db_cursor.execute("select lower(name)='root' as is_root from system.group where id = %d"%int(item['group_id']))
if app_db_cursor.rowcount>0:
if dictfetch(app_db_cursor)[0]['is_root']:
is_root_user = True
break
return is_root_user
def dictfetch(cursor, num_rows=0):
"""
Returns a result set as a list of dictionaries from a DB API 2.0
compliant cursor (ie, a dictionary for each row).
Default behaviour is fetchall().
num_rows=1 returns one row as a dictionary (without the list wrapper)
"""
if num_rows == 0:
result_set = cursor.fetchall()
elif num_rows == 1:
result_set = [cursor.fetchone()]
else:
result_set = cursor.fetchmany(num_rows)
result = []
for rec in result_set:
rec_dict = {}
for i in range(len(rec)):
rec_dict[cursor.description[i][0]] = rec[i]
result = result + [rec_dict]
if num_rows == 1 and len(result) > 0:
return result[0]
else:
return result
def get_formatted_address(rec_dict, return_one_line=None):
"""
Takes a dictionary with generic address keys:
line1, line2, suburb, region, code, country
and returns the address as a 3 or 4 line HTML block, forcing
appropriate capitalisation.
Optionally returns a single line, appropriately capitalised
and punctuated.
"""
for key in rec_dict.keys():
if rec_dict[key] == None:
rec_dict[key] = ''
if return_one_line:
addr = ', '.join([rec_dict['line1'], rec_dict['line2'], rec_dict['suburb'].capitalize(), ' '.join([rec_dict['region'].upper(), rec_dict['code'], rec_dict['country'].upper()])])
return addr.replace(', ,', ',')
else:
addr = '<br />'.join([HTMLEncode(rec_dict['line1']), HTMLEncode(rec_dict['line2']), ' '.join([HTMLEncode(rec_dict['suburb'].title()), HTMLEncode(rec_dict['region'].upper()), rec_dict['code']]), rec_dict['country'].upper()])
return addr.replace('<br /><br />', '<br />')
def get_whole_save_path(person_id, contact_log_id):
"""
Make up a whole path to save upload file with person_id , contact_log_id.
Return a string (ie. '/tmp/upload/1/1/').
"""
person_id_str = str(person_id)
contact_log_id_str = str(contact_log_id)
sub_save_path = "/"+person_id_str[-1]+"/"+contact_log_id_str[-1]+"/"
return info.basic_save_path + sub_save_path
def get_whole_file_name(path, file_name):
"""
Make up a whole file name with path and file name.
Return a string (ie. '/tmp/upload/1/1/file.txt').
"""
return str(path) + str(file_name)
def get_file_name_by_id(contact_log_id, file_name):
"""
Make up a file name with contact_log_id and filename extension.
Return a string (ie. '1.txt').
"""
contact_log_id_str = str(contact_log_id)
return contact_log_id_str + "_" + file_name
def save_upload_file(save_path, save_file, upload_file_content):
"""
Save file into path which has made up.
"""
import os
if not os.path.exists(save_path):
os.makedirs(save_path)
f = open(save_file, 'wb')
f.write(upload_file_content)
f.close()
def read_file_content_online(url):
import urllib
f = urllib.urlopen(url)
content = f.read()
f.close()
return content
def read_file_content_local(file):
f = open(file,'rb')
content = f.read()
f.close()
return content
##def map_fun_dic(fun, dic):
## """
## Map function to handle dictionary type data.
## """
## for k, v in dic.items():
## dic[k] = fun(k, v)
## return dic
##
##def map_class_dic(cla, dic):
## """
## Map function to handle dictionary type data use a class method.
## """
## obj = cla(dic)
## obj.do()
def shorten(string):
"""
Strip leading , encapsulated and trailing space characters and make lower case.
"""
tmp = ''
for str in string.split(' '):
if str != '':
tmp = tmp + str
return tmp.lower()
##def incMonth( date ):
## if date.month + 1 > 12:
## return datetime.date( date.year+1,1,date.day)
## else:
## return datetime.date( date.year,date.month + 1,date.day)
##
##def check_value( params, value_name, check_func,default = None, uri = None ):
## if params[value_name] != None and params[value_name] != '':
## params[value_name] = check_func( params[value_name] )
## else:
## if default == None:
## raise GeneralBusinessErr( '%s_not_null' % value_name, uri )
## else:
## params[value_name] = default
##
##def check_command( params, check_list ):
## for check in check_list:
## check['params'] = params
## check_value( **check )
##
##def gen_passwd(length=8, chars=string.letters + string.digits):
## return ''.join([choice(chars) for i in range(length)])
def get_index_list():
import string
li = list(string.ascii_uppercase)
li.append('ALL')
return li
def float_no_exception(arg):
try:
return float(arg)
except TypeError:
return float(0)
except ValueError:
return float(0)
def nullify(sql_function):
if type(sql_function) == str:
sql_function = sql_function.replace("'None'","NULL").replace("''","NULL")
return sql_function
def escape_comma_in_number(params):
if type(params) == str:
params = params.replace(",", "")
return params
def escape_quotes_in_sql(params):
if type(params) == str:
params = params.replace('"', '\\"').replace("'", "\\'")
return params
def escape_quotes_in_procedure(params):
if type(params) == str:
params = params.replace('"','\\\\"').replace("'", "\\'")
return params
HTMLCodes = [
['&', '&'],
['<', '<'],
['>', '>'],
['"', '"'],
]
def HTMLEncode(s, codes=HTMLCodes):
''' Returns the HTML encoded version of the given string. This is useful to display a plain ASCII text string on a web page. (We could get this from WebUtils, but we're keeping CGIAdaptor independent of everything but standard Python.) '''
if type(s) == str:
for code in codes:
s = s.replace(code[0], code[1])
return s
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from phunc.utils import dictfetch, get_formatted_address,get_whole_save_path,get_whole_file_name,get_file_name_by_id,get_index_list
from phunc.logger import logger
from phunc.template import Template as Template
def atable(dbc, acviewname, query_string):
dbc.execute("SELECT * FROM ledger.%s" % acviewname)
account = dictfetch(dbc)
ledgerid = acviewname.split('_')[0]
if ledgerid == 'general':
jpage = 'finance.py/journal_details?j='
else:
jpage = 'finance.py/sub_journal_details?sl=%s&j=' % ledgerid
html='''<table class="title title2 fin-table" >
<tr>
<th>ID</th>
<th>Date</th>
<th>Description</th>
<th>DR</th>
<th>CR</th>
</tr>
{% for item in account %}
<tr>
<td><a href="/bin/{{jpage}}{{item['journal_id']}}{{query_string}}">{{item['journal_id']}}</a></td>
<td>{{item['date']}}</td>
<td>{{item['description']}}</td>
<td>{% if item['dr'] %}{{item['dr']}}{% else %} {% endif %}</td>
<td>{% if item['cr'] %}{{item['cr']}}{% else %} {% endif %}</td>
</tr>
{% endfor %}
</table>
<div class="img-line"> </div>
'''
for item in account:
dr = item['dr']
cr = item['cr']
if dr == None:
item['dr'] = ''
if cr == None:
item['cr'] = ''
content={
'query_string': query_string.replace('?', '&'),
'account':account,
'jpage':jpage
}
template = Template()
template.parseString( html)
return template.render( content )
#----------------------
def jtable(dbc, j, query_string):
dbc.execute('SELECT * FROM system.general_journal_item WHERE journal_id = ' + j)
items = dictfetch(dbc)
html = '''<table class="title title2 admin">
<tr>
<th>ID</th>
<th>Description</th>
<th>DR</th>
<th>CR</th>
</tr>
{% for item in items %}
<tr>
<td><a href="/bin/finance.py/show_account_details?a={{item['account_id']}}{{ query_string}}">{{item['account_id']}}</a></td>
<td>{{HTMLEncode(item['description'])}}</td>
{% if item['drcr']=='CR'%}
<td></td>
<td>{{ str(item['amount'])}}</td>
{% else %}
<td>{{ str(item['amount'])}}</td>
<td></td>
{% endif %}
</tr>
{% endfor %}
</table> '''
content={
'items':items,
'query_string':query_string.replace('?', '&')
}
template = Template()
template.parseString(html)
return template.render( content )
#----------------------
def sljtable(dbc, j, sl, ca, query_string):
dbc.execute('SELECT * FROM system.' + sl + '_journal_item WHERE journal_id = ' + j)
sitems = dictfetch(dbc)
dbc.execute('SELECT * FROM system.general_journal_item WHERE journal_id = ' + j)
gitems = dictfetch(dbc)
html = '''<table class="title title2 admin">
<tr>
<th>ID</th>
<th>Description</th>
<th>DR</th>
<th>CR</th>
</tr>
{% for item in sitems %}
<tr>
<td><a href="/bin/finance.py/show_sub_account_details?sl={{sl}}&a={{str(item['account_id'])}}{{query_string}}">{{item['account_id2']}}</a></td>
<td>{{item['description']}}</td>
{% if item['drcr']=='CR'%}
<td></td>
<td>{{ str(item['amount'])}}</td>
{% else %}
<td>{{ str(item['amount'])}}</td>
<td></td>
{% endif %}
</tr>
{% endfor %}
{% for item in gitems %}
<tr>
<td><a href="/bin/finance.py/show_account_details?a={{item['account_id']}}{{query_string}}">{{item['account_id']}}</a>
</td>
<td>{{item['description']}}{{item['flag']}}</td>
{% if item['drcr']=='CR'%}
<td></td>
<td>{{ str(item['amount'])}}</td>
{% else %}
<td>{{ str(item['amount'])}}</td>
<td></td>
{% endif %}
</tr>
{% endfor %}
</table>
'''
for item in sitems:
dbc.execute("SELECT id FROM ledger." + sl + "_info WHERE id='" + ca + ".'||LPAD('" + str(item['account_id']) + "', 5, '0')")
account_id = dictfetch(dbc,1)['id']
item['account_id2']=account_id
for item in gitems:
if item['account_id'] == ca:
flag = '<span class="weaker"> (control entry)</span>'
else:
flag = ''
item['flag']=flag
content={
'sitems':sitems,
'gitems':gitems,
'query_string':query_string.replace('?', '&'),
'sl':sl
}
template = Template()
template.parseString(html)
return template.render( content )
#----------------------
def qtable(dbc, sql, uri_query_string=None, page=None):
dbc.execute(sql)
table = dictfetch(dbc)
template = Template()
html_page='''
<table class="center spacebelow" cellspacing="0">
<tr>
{% for col in col_desc %}
<th>{{col[0]}}</th>
{% endfor %}
</tr>
{% for rec in recset %}
<tr>
{% for col in col_desc %}
<td>{{rec[col[0]]}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
'''
template.parseString( html_page )
pre_page = page and page - 1 or 0
next_page = page and page + 1 or 0
content = {'col_desc':dbc.description,
'recset':table,
'uri_query_string':uri_query_string,
'page':page,
'pre_page':str(pre_page),
'next_page':str(next_page),
}
return template.render( content )
#----------------------
def contacts_by_company(dbc, query_string,skin,sql,page,pagesize,url,page_params):
html='''
<div class="search">
<div> </div>
<form id="search" action="/bin/crm.py" method="post" onsubmit="">
<fieldset>
<label for="entity_name">Name:</label>
<input id="entity_name" name="entity_name" type="text"{% if page_params.has_key('entity_name') %} value="{{page_params['entity_name']}}"{% endif %} />
<input name="submit" type="submit" value="Search" class="search-button" />
<input name="reset" type="button" value="Clear" onclick="clear_form();" class="search-button" />
</fieldset>
</form>
<script type="text/javascript">
function clear_form(){
document.getElementById('entity_name').value='';
}
</script>
<div> </div>
<ul>
{% for a in index_list %}
<li><a href="/bin/crm.py?searchkey={{a}}">{{a}}</a></li>
{% endfor %}
</ul>
</div>'''
page_split_setup={
'cursor':dbc,
'sql':sql,
'skin':skin,
'page':page,
'pagesize':pagesize,
'url':url,
'params':page_params,
}
contacts = ControlPage(**page_split_setup)
results=contacts.result
page_split = contacts.createHtml()
content={
'index_list':get_index_list(),
'page_params':page_params,
}
template = Template()
template.parseString(html)
html = template.render( content )
## dbc.execute("SELECT company_name, given_name, surname, phone, TRIM(COALESCE(email, ' ')) AS email, company_id, person_id FROM contact_info")
## contacts = dictfetch(dbc)
del_linkpart = '<a href="/bin/crm.py/delete_contact?pid='
if page_params.has_key("entity_name") and page_params['entity_name'].strip():
del_linkpart = '<a href="/bin/crm.py/delete_contact?entity_name=' +page_params['entity_name'].strip() + '&pid='
if page_params.has_key("searchkey") and page_params['searchkey'].strip():
del_linkpart = '<a href="/bin/crm.py/delete_contact?searchkey=' +page_params['searchkey'].strip() + '&pid='
if len(results) > 0:
if results[0]['company_id']:
previous_row_company_name = results[0]['company_name']
previous_row_company_link = '<a href="/bin/crm.py/get_company_info?id=%d">%s</a>' % (results[0]['company_id'], results[0]['company_name'])
c_id_str = 'cid=' + str(results[0]['company_id']) + '&'
else:
previous_row_company_name = results[0]['company_name']
previous_row_company_link = 'No location'
c_id_str = ''
else:
previous_row_company_name = ''
previous_row_company_link = 'No location'
html = html+'''
<div class="title"><div>'''+previous_row_company_link+'''</div></div>
'''
for contact in results:
if contact['company_name'] != previous_row_company_name:
if contact['company_id']:
previous_row_company_name = contact['company_name']
previous_row_company_link = '<a href="/bin/crm.py/get_company_info?id=%d%s">%s</a>' % (contact['company_id'], query_string.replace('?', '&'), contact['company_name'].capitalize())
c_id_str = 'cid=' + str(contact['company_id']) + '&'
else:
previous_row_company_name = contact['company_name']
previous_row_company_link = 'No location'
c_id_str = ''
html = html + '''
<div class="title">
<div>'''+previous_row_company_link+'''</div>
</div>
'''
if not contact['email']:
email_link = ' '
else:
email_link = '<a href="mailto:' + contact['email'] + '">' + contact['email'] + '</a>'
if contact['phone'] == None:
contact['phone'] = ' '
if len(contact['given_name'] + ' ' + contact['surname'] )>=20:
stab= '''
<dl class="fin">
<dd><a href="/bin/crm.py/get_contact_detail?'''+c_id_str+'''pid='''+str(contact['person_id'])+query_string.replace('?', '&') +'''" title="'''+contact['given_name'] + ' ' + contact['surname'] + '''" >'''+contact['given_name'] + ' ' + contact['surname'] + '''</a></dd>
<dd>'''+contact['phone']+'''</dd>
<dd>'''+email_link+'''</dd>
<dt>''' + del_linkpart + str(contact['person_id']) + '''">del</a> <a href="/bin/crm.py/merge_contact_step1?'''+c_id_str+'''pid='''+str(contact['person_id']) + '''&iscustomer=''' + str(contact['iscustomer']) + '''&issupplier=''' + str(contact['issupplier']) + '''">merge</a></dt>
</dl>
'''
else:
stab= '''
<dl class="fin">
<dd><a href="/bin/crm.py/get_contact_detail?'''+c_id_str+'''pid='''+str(contact['person_id'])+query_string.replace('?', '&') +'''" >'''+contact['given_name'] + ' ' + contact['surname'] + '''</a></dd>
<dd>'''+contact['phone']+'''</dd>
<dd>'''+email_link+'''</dd>
<dt>''' + del_linkpart + str(contact['person_id']) + '''">del</a> <a href="/bin/crm.py/merge_contact_step1?'''+c_id_str+'''pid='''+str(contact['person_id']) + '''&iscustomer=''' + str(contact['iscustomer']) + '''&issupplier=''' + str(contact['issupplier']) + '''">merge</a></dt>
</dl>
'''
html = html +stab
#previous_row_company_name = contact['company_name']
html = html + page_split
return html;
#----------------------
#------------------------
def place_of_business_choice(dbc, company_id, validate=True, heading='Select from known locations'):
#dbc.execute("SELECT * FROM system.place_of_business_info WHERE id IN (SELECT id FROM system.place_of_business WHERE company_id = " + company_id + ")")
#---------------------------------template-------------------#
html = '''{% if len(matches)>0 %}
<div class="new-oth">{{heading}}</div>
<dl class="chek">
{% for match in matches %}
<dt>
<input class="explain-color select{% if validate %} validate-one-if-none{% endif %}" type="checkbox" name="place_of_business_id" value="{{str(match['id'])}}" onchange="hideUnhide(this, 'address-block', true)" />{{match['company_name']}}({{match['name']}})
</dt>
<dd>{{match['format_address']}}</dd>
{% endfor %}
</dl>
{% else %}
""
{% endif %}
'''
#---------------------------------template-------------------#
dbc.execute("SELECT * FROM system.company_location_info WHERE id IN (SELECT id FROM system.location WHERE entity_id = " + company_id + ")")
matches = dictfetch(dbc)
if len(matches)>0:
for match in matches:
match['format_address']=get_formatted_address(match, True)
content={
'matches':matches,
'heading':heading,
'validate':validate
}
template = Template()
template.parseString(html)
return template.render( content )
else:
return None
#-----------------------
def alt_location_choice(dbc, person_id, validate=True, heading='Select from known locations'):
dbc.execute("SELECT * FROM system.person_location_info WHERE line1 NOTNULL AND person_id = %s" % person_id)
matches = dictfetch(dbc)
#---------------------------------template-------------------#
html='''{% if len(matches)>0 %}
<div class="new-oth">{{heading}}</div>
<dl class="chek">
{% for match in matches %}
<dt>
<input class="explain-color select {{validation_class}}" type="checkbox" name="alt_location_id" value="{{match['id']}}" onchange="hideUnhide(this, 'address-block', true)"/>{{match['title_bits']}}
</dt>
<dd>{{match['format_address']}}</dd>
</dt>
{% endfor %}
</dl>
{% else %}
""
{% endif %}
'''
#---------------------------------template-------------------#
if matches:
validation_class = ''
for match in matches:
if match['type'] == 'place of business':
pob_id = match['id']
dbc.execute("SELECT company_name, name FROM system.company_location_info WHERE id = %s" % pob_id)
company_details = dictfetch(dbc, 1)
title_bits = '%s, (%s)<br/>' % (company_details['company_name'], company_details['name'])
else:
title_bits = '%s<br/>' % match['type'].upper()
match['title_bits']=title_bits
match['format_address']=get_formatted_address(match, True)
if validate:
validation_class = ' class="validate-one-if-none"'
content={
'matches':matches,
'heading':heading,
'validation_class':validation_class,
}
template = Template()
template.parseString(html)
return template.render( content )
else:
return None
#------------------------
def contact_log(dbc, person_id, company_id, query_string,skin):
dbc.execute("SELECT * FROM contact_log WHERE entity_id = %s ORDER BY id DESC LIMIT 10" % person_id)
recent_entries = dictfetch(dbc)
dbc.execute("SELECT * FROM contact_log WHERE entity_id = %s AND action NOTNULL AND closed ISNULL AND id NOT IN (SELECT id FROM contact_log WHERE entity_id = %s ORDER BY id DESC LIMIT 10) ORDER BY id DESC" % (person_id, person_id))
open_actions = dictfetch(dbc)
content={}
content['query_string']=query_string.replace('?', '&')
content['person_id']=person_id
content['company_id'] = company_id
if company_id.upper() != 'NONE':
cid_str = 'cid=' + company_id + '&'
else:
cid_str = 'cid=&'
#---------------------------------template-------------------#
html='''
{% if len(recent_entries) > 0 %}
<div id="table">
<dl class="dl-titile">
<dd class="re">Recent contact</dd>
<dd class="at">attachment</dd>
<dd class="ac">action</dd>
<dt>date closed</dt>
</dl>
<div id="change-bg">
{% for log_entry in recent_entries %}
{% if log_entry['flag']==0 %}
<dl class="dl-body col-font">
<dd class="re">
<ul>
<li class="date">{{log_entry['log_date']}}</li>
<li class="contact">{{HTMLEncode(log_entry['comment'])}}</li>
<li class="edit-img"><a href="/bin/crm.py/get_person_log?pid={{person_id}}&cid={{company_id}}&edit={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/edit.gif" alt="edit" /></a></li>
</ul>
</dd>
<dd class="at"><a href="{{log_entry['whole_file_name'][13:]}}">{{HTMLEncode(log_entry['filename'])}}</a></dd>
<dd class="ac">{{HTMLEncode(log_entry['action'])}}</dd>
<dt>{{log_entry['closed']}}</dt>
</dl>
{% else %}
<dl class="dl-body">
<dd class="re">
<ul>
<li class="date">{{log_entry['log_date']}}</li>
<li class="contact">{{HTMLEncode(log_entry['comment'])}}</li>
<li class="edit-img"><a href="/bin/crm.py/get_person_log?pid={{person_id}}&cid={{company_id}}&edit={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/edit.gif" alt="edit" /></a></li>
</ul>
</dd>
<dd class="at"><a href="{{log_entry['whole_file_name'][13:]}}">{{HTMLEncode(log_entry['filename'])}}</a></dd>
<dd class="ac">{{HTMLEncode(log_entry['action'])}}</dd>
<dt>{{log_entry['closed']}}</dt>
</dl>
{% endif %}
{% endfor %}
{% for log_entry in open_actions %}
<dl class="dl-body">
<dd class="re">
<ul>
<li class="date">{{log_entry['log_date']}}</li>
<li class="contact">{{HTMLEncode(log_entry['comment'])}}</li>
<li class="edit-img"><a href="/bin/crm.py/get_person_log?pid={{person_id}}&cid={{company_id}}&edit={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/edit.gif" alt="edit" /></a></li>
</ul>
</dd>
<dd class="at"><a href="{{log_entry['whole_file_name'][13:]}}">{{HTMLEncode(log_entry['filename'])}}</a></dd>
<dd class="ac">{{HTMLEncode(log_entry['action'])}}</dd>
<dt><a href="/bin/sle.py?pid={{person_id}}&cid={{company_id}}&close={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/del.gif" alt="del" /></a></dt>
</dl>
{% endfor %}
</div>
</div>
{% else %}
<div id="table">
<dl class="dl-titile">
<dd class="re">Recent contact</dd>
<dd class="at">attachment</dd>
<dd class="ac">action</dd>
<dt>date closed</dt>
</dl>
</div>
{% endif %}
'''
#---------------------------------template-------------------#
if len(recent_entries) > 0:
for log_entry in recent_entries:
if log_entry['closed']:
closed = '%s' % log_entry['closed']
log_entry['flag']=0 #closed
else:
if log_entry['action']:
log_entry['flag']=1 #not closed
closed = '<a href="/bin/crm.py/get_person_log?pid=%s&cid=%s&close=%s"><img src="/%s/del.gif" alt="del" /></a>' % (person_id, company_id, log_entry['id'],skin)
else:
log_entry['flag']=2 #no action
closed = ''
log_entry['closed']=closed
log_entry['comment']=log_entry['comment'].strip().replace('\n', '<br/>')
log_entry['action']=max(log_entry['action'], '').strip().replace('\n', '<br/>')
if log_entry['filename']:
whole_file_path = get_whole_save_path(log_entry['entity_id'], log_entry['id'])
whole_file_name = get_whole_file_name(whole_file_path, get_file_name_by_id(log_entry['id'], log_entry['filename']))
log_entry['whole_file_path'] = whole_file_path
log_entry['whole_file_name'] = whole_file_name
else:
log_entry['filename']=''
log_entry['whole_file_path'] = '#'
log_entry['whole_file_name'] = ''
for log_entry in open_actions:
log_entry['comment']=log_entry['comment'].strip().replace('\n', '<br/>')
log_entry['action']=max(log_entry['action'], '').strip().replace('\n', '<br/>')
if log_entry['filename']:
whole_file_path = get_whole_save_path(log_entry['entity_id'], log_entry['id'])
whole_file_name = get_whole_file_name(whole_file_path, get_file_name_by_id(log_entry['id'], log_entry['filename']))
log_entry['whole_file_path'] = whole_file_path
log_entry['whole_file_name'] = whole_file_name
else:
log_entry['filename']=''
log_entry['whole_file_path'] = ''
log_entry['whole_file_name'] = ''
content['recent_entries'] = recent_entries
content['open_actions'] = open_actions
content['skin'] = skin
template = Template()
template.parseString(html)
return template.render( content )
#------------------------
def lcontact_log(dbc, person_id_list,company_id,skin):
"""
Get the conatct_log from person_id_list.
Get contact_log from contact_log
Get person's name from system.person
"""
content={}
person_id = ",".join(["%s" % p['person_id'] for p in person_id_list])
dbc.execute("SELECT s.id, s.log_date, s.comment, COALESCE(s.action, ' ') AS action, s.closed, s.entity_id,e.given_name||' '||e.name as personname FROM contact_log s,system.entity e WHERE s.entity_id in (" + person_id + ") and s.entity_id=e.id ORDER BY s.id DESC LIMIT 10")
recent_entries = dictfetch(dbc)
dbc.execute("SELECT s.id, s.log_date, s.comment, COALESCE(s.action, ' ') AS action, s.closed, s.entity_id,e.given_name||' '||e.name as personname FROM contact_log s,system.entity e WHERE s.entity_id in (" + person_id + ") AND action <> ' ' AND s.closed ISNULL AND s.id NOT IN (SELECT id FROM contact_log d WHERE d.entity_id in (" + person_id + ") ORDER BY d.id DESC LIMIT 10) AND s.entity_id = e.id ORDER BY s.id DESC")
open_actions = dbc.fetchall()
add_entry_href = ''
for log_entry in recent_entries:
if log_entry['closed']:
log_entry['closed'] = str(log_entry['closed'])
else:
if log_entry['action'] == ' ':
log_entry['closed'] = ' '
else:
log_entry['closed'] = '<a href="/bin/crm.py/get_contact_detail?pid=' + str(log_entry['entity_id']) + '&cid='+str(company_id)+'&close=' + str(log_entry['id']) + '"><img src="/%s/del.gif" alt="del" /></a>'%skin
log_entry['add_entry_href'] = '''<a href="/bin/crm.py/get_contact_detail?pid=''' + str(log_entry['entity_id']) + '''&cid='''+str(company_id)+'''">'''
log_entry['comment']=log_entry['comment'].strip().replace('\n', '<br/>')
log_entry['action']=log_entry['action'].strip().replace('\n', '<br/>')
for log_entry in open_actions:
add_entry_href = '''<a href="/bin/crm.py/get_contact_detail?pid=''' + str(log_entry['entity_id']) + '''&cid='''+str(company_id)+'''">'''
log_entry['add_entry_href']=add_entry_href
content['recent_entries']=recent_entries
content['open_actions']=open_actions
#---------------------------------template-------------------#
html='''
<table id="contact-log" class="title title2 crm">
<tr>
<th colspan="2">Recent contact</th>
<th>action item</th>
<th>action</th>
<th id="border-0">date closed</th>
</tr>
{% if len(recent_entries)>0 %}
{% for log_entry in recent_entries %}
<tr>
<td >{{log_entry['log_date']}}</td>
<td >{{ log_entry['add_entry_href']}}{{log_entry['personname']}}</a></td>
<td >{{ log_entry['comment']}}</td>
<td >{{log_entry['action']}}</td>
<td >{{log_entry['closed']}}</td>
</tr>
{% endfor %}
{% for log_entry in open_actions %}
<tr>
<td>{{log_entry['log_date']}}</td>
<td >{{log_entry['add_entry_href']{{log_entry['personname']}}</a></td>
<td >{{log_entry['log_date']}}</td>
<td >{{log_entry['comment']}}</td>
<td><a href="/bin/crm.py/get_person_log?id={{str(log_entry['entity_id'])}}&close={{str(log_entry['id'])}}">*</a></td>
</tr>
{% endfor %}
{% endif %}
</table>
'''
#---------------------------------template-------------------#
template = Template()
template.parseString(html)
return template.render( content )
#----------page split---------#
class Page:
def __init__(self,cursor=None,sql=None,pagesize=10):
self.cursor = cursor
self.sql = sql
self.pagesize = pagesize
self.page = 1
self.pagecount = 0
def __getitem__(self,name):
if name=='pagecount':
return self.pagecount
def getPage(self):
return self.page
def setPage(self,page):
self.page = int(page)
def countPage(self):
logger.debug(self.cursor)
logger.debug(self.sql)
self.cursor.execute( self.sql )
result = self.cursor.rowcount
logger.debug(result)
if self.cursor==None or self.sql==None or self.sql.strip()=="":
return
else:
try:
self.cursor.execute( self.sql )
result = self.cursor.rowcount
if result % self.pagesize ==0:
self.pagecount = result / self.pagesize
else:
self.pagecount = result / self.pagesize + 1
return
except:
return
def getResultPage(self):
result_map = {'result':[],'pagecount':0}
if self.cursor==None or self.sql==None or self.sql.strip()=="":
return result
else:
extend_sql = self.sql + ' LIMIT %d OFFSET '%int(self.pagesize) + str((self.page - 1) * self.pagesize)
logger.debug(extend_sql)
try:
self.cursor.execute( extend_sql )
result_map['result'] = dictfetch(self.cursor)
result_map['pagecount'] = self.pagecount
return result_map
except:
return result_map
class ControlPage:
'''
#flag=1:just for the loginpage
#default flag=0
'''
def __init__(self,cursor=None,sql=None,skin=None,page=1,pagesize=10,url=None,params={},flag=0):
self.skin = skin
self.page = int(page)
self.url = url
self.query_string = ''
self.flag = flag
if params:
for key,value in params.iteritems():
self.query_string = self.query_string+"&%s=%s"%(str(key),str(value))
pageObj = Page(cursor,sql,pagesize)
pageObj.setPage(page)
pageObj.countPage()
logger.debug(pageObj.pagecount)
self.result = pageObj.getResultPage()['result']
self.pagecount = pageObj.getResultPage()['pagecount']
def __getitem__(self,name):
if name == 'result':
return self.result
if name == 'pagecount':
return self.pagecount
def createHtml(self):
html=""
if self.pagecount<=1:
if self.flag == 1:
html=html+'''
<div>'''
else:
html=html+'''
<div class="next">
<div>'''
html=html+'''
<a href="#"><img src="/%s/next-left.gif" alt="" /></a>
<a href="#"><img src="/%s/next-left2.gif" alt="" /></a>
<a href="#">1</a>
<a href="#"><img src="/%s/next-right2.gif" alt="" /></a>
<a href="#"><img src="/%s/next-right.gif" alt="" /></a>
'''%(self.skin,self.skin,self.skin,self.skin)
if self.flag == 1:
html=html+'''
</div>'''
else:
html=html+'''
</div>
</div>'''
elif self.pagecount<=10:
if self.page==1:
if self.flag == 1:
html=html+'''
<div>'''
else:
html=html+'''
<div class="next">
<div>'''
html=html+'''
<a href="#"><img src="/%s/next-left.gif" alt="" /></a>
<a href="#"><img src="/%s/next-left2.gif" alt="" /></a>
<span>1</span>'''%(self.skin,self.skin)
for i in range(self.pagecount-1):
html=html+'''
<a href="%s?page=%s%s">%s</a>'''%(self.url,str(i+2),self.query_string,str(i+2))
html=html+'''
<a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
'''%(self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
if self.flag == 1:
html=html+'''
</div>'''
else:
html=html+'''
</div>
</div>'''
elif 1<self.page<self.pagecount:
if self.flag == 1:
html=html+'''
<div>'''
else:
html=html+'''
<div class="next">
<div>'''
html=html+'''
<a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)
for i in range(self.pagecount):
if i+1==self.page:
html=html+'''<span>%s</span>'''%str(i+1)
else:
html=html+'''
<a href="%s?page=%s%s">%s</a>'''%(self.url,str(i+1),self.query_string,str(i+1))
html=html+'''
<a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
'''%(self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
if self.flag == 1:
html=html+'''
</div>'''
else:
html=html+'''
</div>
</div>'''
elif self.page>=self.pagecount:
if self.flag == 1:
html=html+'''
<div>'''
else:
html=html+'''
<div class="next">
<div>'''
html=html+'''
<a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)
for i in range(self.pagecount):
if i+1==self.pagecount:
html=html+'''<span>%s</span>'''%str(i+1)
else:
html=html+'''
<a href="%s?page=%s%s">%s</a>'''%(self.url,str(i+1),self.query_string,str(i+1))
html=html+'''
<a href="#"><img src="/%s/next-right2.gif" alt="" /></a>
<a href="#"><img src="/%s/next-right.gif" alt="" /></a>
'''%(self.skin,self.skin)
if self.flag == 1:
html=html+'''
</div>'''
else:
html=html+'''
</div>
</div>'''
else:
pass
else:
if self.page==1:
if self.flag == 1:
html=html+'''
<div>'''
else:
html=html+'''
<div class="next">
<div>'''
html=html+'''
<a href="#"><img src="/%s/next-left.gif" alt="" /></a>
<a href="#"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.skin,self.skin)
html=html+'''
<select name="jumpMenu" id="jumpMenu" onchange="MM_jumpMenu(this,'%s','%s')">'''%(self.url,self.query_string)
for i in range(self.pagecount):
if i+1==int(self.page):
html=html+'''
<option value='%s' selected='selected'>%s</option>'''%(str(i+1),str(i+1))
else:
html=html+'''
<option value='%s'>%s</option>'''%(str(i+1),str(i+1))
html=html+'''
</select> of %s
<a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
'''%(str(self.pagecount),self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
if self.flag == 1:
html=html+'''
</div>'''
else:
html=html+'''
</div>
</div>'''
elif 1<int(self.page)<int(self.pagecount):
if self.flag == 1:
html=html+'''
<div>'''
else:
html=html+'''
<div class="next">
<div>'''
html=html+'''
<a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)
html=html+'''
<select name="jumpMenu" id="jumpMenu" onchange="MM_jumpMenu(this,'%s','%s')">'''%(self.url,self.query_string)
for i in range(self.pagecount):
if i+1==int(self.page):
html=html+'''
<option value='%s' selected='selected'>%s</option>'''%(str(i+1),str(i+1))
else:
html=html+'''
<option value='%s'>%s</option>'''%(str(i+1),str(i+1))
html=html+'''
</select> of %s
<a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
'''%(str(self.pagecount),self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
if self.flag == 1:
html=html+'''
</div>'''
else:
html=html+'''
</div>
</div>'''
elif self.page>=self.pagecount:
if self.flag == 1:
html=html+'''
<div>'''
else:
html=html+'''
<div class="next">
<div>'''
html=html+'''
<a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
<a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)
html=html+'''
<select name="jumpMenu" id="jumpMenu" onchange="MM_jumpMenu(this,'%s','%s')">'''%(self.url,self.query_string)
for i in range(self.pagecount):
if i+1==self.page:
html=html+'''
<option value='%s' selected='selected'>%s</option>'''%(str(i+1),str(i+1))
else:
html=html+'''
<option value='%s'>%s</option>'''%(str(i+1),str(i+1))
html=html+'''
</select> of %s
<a href="#"><img src="/%s/next-right2.gif" alt="" /></a>
<a href="#"><img src="/%s/next-right.gif" alt="" /></a>
'''%(str(self.pagecount),self.skin,self.skin)
if self.flag == 1:
html=html+'''
</div>'''
else:
html=html+'''
</div>
</div>'''
else:
pass
return html
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
DEBUG = False
import scanning
from parseengine import Parse
import time
import fpformat
class Template:
def __init__( self ):
self.__token_list = None
self.__filename = None
def parseFile( self, filename ):
orgstr = self.__getStrFrmFile( filename )
self.parseString( orgstr )
# Template.__cache_file[ filename ] = self.__node_list
def parseString( self, orgstr ):
token_list = scanning.createTokenList( orgstr )
parse = Parse( token_list )
starttime = time.time()
self.__token_list = parse.process()
usedtime = time.time() - starttime
strlist = self.__token_list.debugprt()
if not DEBUG:
from phunc.logger import AppLogger
logger = AppLogger().getHandler()
title = self.__filename != None and self.__filename or ''
logger.debug('--------------<parse_tree(%s)>--------------' % title )
for s in strlist:
logger.debug( '%s' % s)
logger.debug('--------------</parse_tree(%s)>--------------' % title )
logger.debug('prase process used %ss ' % fpformat.fix(usedtime,5) )
if DEBUG:
print '----------------<parse_tree>-----------------------------'
for s in strlist:
print s
print '----------------</parse_tree>-----------------------------'
def __getStrFrmFile( self, filename ):
self.__filename = filename
starttime = time.time()
file = open( filename, 'rb' )
lines = file.readlines()
file.close()
usedtime = time.time() - starttime
orgstr = ''.join( lines )
if not DEBUG:
from phunc.logger import AppLogger
logger = AppLogger().getHandler()
logger.debug('read %s used %ss ' % (filename, fpformat.fix(usedtime,5)) )
return orgstr
def render( self, content ):
#print content for debug
if not DEBUG:
from phunc.logger import AppLogger
logger = AppLogger().getHandler()
logger.debug('----------------<content>-----------------------------')
for n in content.keys():
logger.debug( '%s:%s' % (n,content[n]) )
logger.debug('----------------</content>-----------------------------')
if DEBUG:
print '----------------<content>-----------------------------'
for n in content.keys():
print '%s:%s' % (n,content[n])
print '----------------</content>-----------------------------'
htmllist = self.__token_list.rander( content )
html = ''.join( htmllist )
#replace the None value to
import re
from phunc.logger import logger
nb = re.compile('(?P<first><(?P<tag>[a-zA-Z]+)[^>]*>)\s*(?P<last></(?P=tag)>)')
html = nb.sub(r'\g<first> \g<last>',html)
return html
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import scanning
from templatetag import NodeList as NodeList
from templatetag import TextNode as TextNode
from templatetag import VarNode as VarNode
from templatetag import TranslateNode as TranslateNode
from templatetag import registered_tags as registered_tags
#
class TemplateSyntaxError(Exception):
pass
#parse
class Parse:
def __init__(self, token_list ):
self.token_list = token_list
def next_token( self ):
return self.token_list.pop( 0 )
def back_token( self , token ):
self.token_list.insert( 0, token )
def process( self , until_tag = [] ):
node_list = NodeList()
while self.token_list:
token = self.next_token( )
if token.type == scanning.TOKEN_TEXT:
node_list.append( TextNode( token.value ) )
elif token.type == scanning.TOKEN_VAR:
node_list.append( VarNode( token.value ) )
elif token.type == scanning.TOKEN_TRANSLATE:
node_list.append( TranslateNode( token.value ) )
elif token.type == scanning.TOKEN_BLOCK:
if token.value.strip() in until_tag:
self.back_token( token )
return node_list
operation = token.value.strip().split()[0]
node = registered_tags[ operation ]( self, token )
node_list.append( node )
else:
raise TemplateSyntaxError, "Unsupport tag_type(s): '%d'" % token.type
if until_tag:
raise TemplateSyntaxError, "Unclosed tag(s): '%s'" % ', '.join(until_tag)
return node_list
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import re
#token type
TOKEN_TEXT = 0
TOKEN_VAR = 1
TOKEN_BLOCK = 2
TOKEN_TRANSLATE = 3
#token_tag
BEGIN_BLOCK_TAG = '{%'
END_BLOCK_TAG = '%}'
BEGIN_VAR_TAG = '{{'
END_VAR_TAG = '}}'
BEGIN_TRANSLATE_TAG = '_('
END_TRANSLATE_TAG = ')'
#
class Token:
def __init__( self, type, value ):
self.type = type
self.value = value
def __str__( self ):
self.toStr()
def toStr( self ):
str = ''
if self.type == TOKEN_TEXT:
str = '<text>' + self.value + '\n</text>'
elif self.type == TOKEN_VAR:
str = '<var>' + self.value + '\n</var>'
else:
str = '<block>' + self.value + '\n</block>'
return str
def createToken( token_string ):
if token_string.startswith( BEGIN_BLOCK_TAG ):
return Token( TOKEN_BLOCK, token_string[ len( BEGIN_BLOCK_TAG ) : -len( END_BLOCK_TAG ) ] )
elif token_string.startswith( BEGIN_VAR_TAG ):
return Token( TOKEN_VAR, token_string[ len( BEGIN_VAR_TAG ) : -len( END_VAR_TAG ) ])
elif token_string.startswith( BEGIN_TRANSLATE_TAG ):
return Token( TOKEN_TRANSLATE, token_string[ len( BEGIN_TRANSLATE_TAG ) : -len( END_TRANSLATE_TAG ) ])
else:
return Token( TOKEN_TEXT, token_string )
#separate token from org_string
def createTokenList( org_string ):
tag_re = re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)' %
(re.escape(BEGIN_BLOCK_TAG),
re.escape(END_BLOCK_TAG),
re.escape(BEGIN_VAR_TAG),
re.escape(END_VAR_TAG),
re.escape(BEGIN_TRANSLATE_TAG),
re.escape(END_TRANSLATE_TAG)
))
elements = filter( None,tag_re.split( org_string ) )
token_list = map( createToken, elements )
return token_list
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import re
from phunc.utils import HTMLEncode
from phunc.logger import logger
registered_tags = {}
class NodeValueError(Exception):
pass
class Node:
def debugprt( self, spacessize = 0 ):
pass
def rander(self,content):
pass
class NodeList(list):
def debugprt( self, spacesize = 0 ):
strlist=[]
for node in self:
if isinstance(node, Node):
strlist = strlist + node.debugprt( spacesize )
elif isinstance(node, NodeList):
strlist = strlist + node.debugprt( spacesize )
return strlist
def rander(self, content):
txtlist = []
for node in self:
if isinstance(node, Node):
txtlist.append( node.rander( content ) )
else:
nodestr = '%s' % node
txtlist.append( nodestr )
return ''.join( txtlist )
class TextNode(Node):
def debugprt( self, spacessize = 0 ):
strlist=[]
strlist.append('%sTextNode: len: %s' % ( ' '*spacessize, len( self.text ) ) )
return strlist
def __init__(self, text ):
self.text = text
def rander(self,content):
nodestr = '%s' % self.text
return nodestr
class VarNode(Node):
def debugprt( self, spacessize = 0 ):
strlist=[]
strlist.append('%sVarNode: name: %s' % ( ' '*spacessize, self.varname ) )
return strlist
def __init__(self, varname ):
self.varname = varname
def rander(self, content):
## dictpattern = re.compile(r'''(.*)\['(.*)'\]''')
## sresult = dictpattern.search( self.varname )
## if sresult != None and len(sresult.groups()) == 2:
## dictname = sresult.groups()[0]
## dictindex = sresult.groups()[1]
## varvalue = content[dictname][dictindex]
## else:
## varvalue = content[self.varname]
## for var_key in self.varname:
## if var_key not in content.keys():
## logger.debug("Content have no key: '%s'" % var_key)
## varvalue = None
flag = 0
for ct in content.keys():
if ct in self.varname:
flag = 1
break
if flag==0:
logger.debug("Content have no key: '%s'" % self.varname)
for ct in content.keys():
if ct in self.varname:
locals()[ct] = content[ct]
varvalue = eval( self.varname )
#if varvalue == None:
#logger.debug("Content have no value(s): '%s'" % self.varname)
#NodeValueError, "Content have no value(s): '%s'" % self.varname
# if the varvalue is None ,don't throw out exception
if varvalue == None:
varvalue = ''
nodestr = '%s' % varvalue
return nodestr
class TranslateNode(Node):
def debugprt( self, spacessize = 0 ):
strlist=[]
strlist.append('%sTranslateNode: len: %s' % ( ' '*spacessize, len( self.text ) ) )
return strlist
def __init__(self, text ):
self.text = text
def rander(self,content):
#to_do call the translate func
nodestr = '%s' % self.text
return nodestr
class IfNode(Node):
def debugprt( self, spacessize = 0 ):
strlist=[]
strlist.append('%sIfNode: cond: %s' % ( ' '*spacessize, self.cond ) )
strlist.append('%s true_list:' % (' '*spacessize) )
strlist = strlist + self.true_list.debugprt( spacessize + 16 )
strlist.append('%s false_list:' % (' '*spacessize) )
strlist = strlist + self.false_list.debugprt( spacessize + 16 )
return strlist
def __init__(self, cond, true_list, false_list ):
self.cond,self.true_list,self.false_list = cond,true_list,false_list
def rander(self,content):
#input all content in locals()
for name in content.keys():
locals()[name] = content[name]
if eval( self.cond ):
return self.true_list.rander( content )
else:
return self.false_list.rander( content )
class ForNode(Node):
def debugprt( self, spacessize = 0 ):
strlist=[]
strlist.append('%sForNode: var: %s seq: %s' % ( ' '*spacessize, self.loopvar ,self.seq ) )
strlist.append('%s for_list:' % (' '*spacessize) )
strlist = strlist + self.slist.debugprt( spacessize + 16 )
return strlist
def __init__(self, loopvar, seq , slist):
self.loopvar,self.seq,self.slist = loopvar,seq,slist
def rander(self,content):
node_list = NodeList()
v=[]
vv=[]
if self.seq.strip().find('.')>=0:
elements = self.seq.strip().split('.')
if elements[0].find('[') >=0:
key =re.search("\\[.*\\]",elements[0]).group()
key_elements=elements[0].split('[')
seq_list=content[key_elements[0]][key[1:-1][1:-1]]
if elements[1].find('()')>=0:
if hasattr(seq_list,elements[1][:elements[1].rindex('()')]):
seq_list = getattr(seq_list,elements[1][:elements[1].rindex('()')])()
else:
seq_list = content[elements[0]][elements[1]]
elif self.seq.strip().find('zip')>=0:
elem =re.search("\\(.*\\)",self.seq.strip()).group()[1:-1]
for i in range(len(self.seq.strip().split(','))):
if self.seq.strip().find('[') <0:
locals()["x"+str(i)] =content[elem.split(',')[i]]
else:
locals()["elem"+str(i)]=elem.split(',')[i].split('[')
locals()["key"+str(i)] =re.search("\\[.*\\]",elem.split(',')[i]).group()
locals()["x"+str(i)]=content[locals()["elem"+str(i)][0]][locals()["key"+str(i)][2:-2]]
locals()["a"+str(i)]=[]
v.append(locals()["a"+str(i)])
vv.append(locals()["x"+str(i)])
elif self.seq.strip().find('[') >=0:
key =re.search("\\[.*\\]",self.seq.strip()).group()
elements=self.seq.strip().split('[')
seq_list=content[elements[0]][key[1:-1][1:-1]]
else:
seq_list = content[ self.seq ]
if self.seq.strip().find('zip')>=0:
for v in zip(*vv):
for i in range(len(self.seq.strip().split(','))):
content[self.loopvar.split(',')[i]]=v[i]
for s in self.slist:
node_list.append(s.rander(content))
else:
for seq in seq_list:
content[ self.loopvar ] = seq
for s in self.slist:
node_list.append( s.rander( content ) )
return node_list.rander( content )
# --------------------------------------------------------------------------------------------------------------------------------------------
# do_command
def do_if( parse, curr_token ):
elements = curr_token.value.strip().split('if')
var = elements[1]
true_list = parse.process( ['else','endif'] )
next_token = parse.next_token()
false_list = NodeList()
if next_token.value.strip() == 'else':
false_list = parse.process( ['endif'] )
parse.next_token()
return IfNode( var, true_list, false_list )
def do_for( parse, curr_token ):
elements = curr_token.value.strip().split()
loopvar = elements[1]
sequence = elements[3]
nodelist_loop = parse.process( ['endfor'] )
parse.next_token()
return ForNode( loopvar, sequence, nodelist_loop )
#regist the command
registered_tags['if'] = do_if
registered_tags['for'] = do_for
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import logging
import logging.config
#Singleton pattern. Ensure the logger instance to be only one
class AppLogger:
"""
Application log
"""
__log_single = None #single instance
__log_ini_file = '/usr/local/fivedash/etc/app_log.ini' #log config file
def __init__( self ):
if AppLogger.__log_single == None:
try:
logging.config.fileConfig(AppLogger.__log_ini_file)
except:
pass
AppLogger.__log_single = logging.getLogger(None)
def getHandler(self):
return AppLogger.__log_single
logger = AppLogger().getHandler()
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import action
import phunc.utils as utils
from phunc.logger import logger
#generic sql action function
class ActionNotExistError( Exception ):
pass
def exec_action(cursor, cmd, paramlist = [], nullify = False , conn = None, escaped = False):
result = None
paramlists=[]
if not action.action_map.has_key( cmd ):
raise ActionNotExistError,'ActionNotExistError %s' % cmd
sql = action.action_map[cmd]
for param in paramlist:
if not escaped:
if type(param)==tuple:
ps=[]
for tp in list(param):
tp.replace('"', '\\"').replace("'", "\\'")
ps.append(tp)
param=tuple(ps)
elif type(param)==str:
#if param.find('=')<0 and param.find(',')<0 and param.find('(')<0 and not escaped:
param=param.replace('"', '\\"').replace("'", "\\'")
paramlists.append(param)
if len(paramlists) != 0:
sql = sql % tuple( paramlists )
if nullify:
sql = utils.nullify(sql)
logger.debug("***************sql**************")
logger.debug(sql)
import time
import fpformat
starttime = time.time()
try:
cursor.execute( sql )
except:
#TODO:conn not a parameter
raise
#conn.rollback()
else:
result = cursor.rowcount
usedtime = time.time() - starttime
logger.debug("*******************execute used*********************")
logger.debug('%s execute used %ss ' % (cmd,fpformat.fix(usedtime,5)) )
if sql.strip().lower()[:6] == 'select':
result = utils.dictfetch( cursor )
return result
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
start_sql_map = {'create_init_db_func':
"""CREATE FUNCTION init_db() RETURNS INT AS $init_db$
BEGIN
SET DATESTYLE = 'ISO';
CREATE SCHEMA system;
CREATE SCHEMA ledger;
--app tables
CREATE TABLE system.sys_code (code_id VARCHAR(20) NOT NULL, code_value VARCHAR(100) NOT NULL, code_desc VARCHAR(200), PRIMARY KEY (code_id, code_value));
CREATE TABLE system.row_update_log (table_name VARCHAR(100), where_cond VARCHAR(250), cols_updated VARCHAR(100)[], updated TIMESTAMP, PRIMARY KEY (table_name, where_cond, updated));
INSERT INTO system.sys_code VALUES ('contact_type', 'phone', 'phone');
INSERT INTO system.sys_code VALUES ('contact_type', 'fax', 'fax');
INSERT INTO system.sys_code VALUES ('contact_type', 'email', 'email');
INSERT INTO system.sys_code VALUES ('contact_type', 'mobile', 'mobile');
INSERT INTO system.sys_code VALUES ('contact_type', 'sms', 'sms');
INSERT INTO system.sys_code VALUES ('contact_type', 'abn', 'abn');
INSERT INTO system.sys_code VALUES ('contact_type', 'position', 'position');
INSERT INTO system.sys_code VALUES ('alt_location_type', 'home', NULL);
INSERT INTO system.sys_code VALUES ('alt_location_type', 'work', NULL);
INSERT INTO system.sys_code VALUES ('alt_location_type', 'postal_address', NULL);
INSERT INTO system.sys_code VALUES ('alt_location_type', 'courier_address', NULL);
INSERT INTO system.sys_code VALUES ('alt_location_type', 'other', NULL);
INSERT INTO system.sys_code VALUES ('contact_type', 'other', 'other');
INSERT INTO system.sys_code VALUES ('tax_page_md5','',NULL);
INSERT INTO system.sys_code VALUES ('default_tax', '', 'default tax for invoice');
INSERT INTO system.sys_code VALUES ('default_inv_terms', '30', 'default invoice terms');
INSERT INTO system.sys_code VALUES('billing_method','hard copy','hard copy');
INSERT INTO system.sys_code VALUES('billing_method','email','email');
--INSERT INTO system.sys_code VALUES('billing_method','fax','fax');
-- a function required for one of the financial table definitions below
CREATE FUNCTION system.default_inv_terms() RETURNS SMALLINT AS $$
DECLARE
v_terms SMALLINT;
BEGIN
SELECT INTO v_terms CAST(code_value AS SMALLINT) FROM system.sys_code WHERE code_id = 'default_inv_terms';
RETURN v_terms;
END;
$$ LANGUAGE plpgsql;
-- financial tables
CREATE TABLE system.journal_item_type (id VARCHAR(2) PRIMARY KEY);
CREATE TABLE system.account_type (id VARCHAR(20) PRIMARY KEY, sum VARCHAR(2) REFERENCES system.journal_item_type, ord INT);
CREATE TABLE ledger.general_chart_of_accounts (id VARCHAR(10) PRIMARY KEY, name VARCHAR(100) UNIQUE NOT NULL, account_type_id VARCHAR(20) REFERENCES system.account_type ON UPDATE CASCADE, subsidiary_shortname VARCHAR(100) UNIQUE, opening_balance NUMERIC, is_active BOOLEAN DEFAULT TRUE);
CREATE TABLE system.journal (id SERIAL PRIMARY KEY, date DATE, ledger_shortname VARCHAR(100) REFERENCES ledger.general_chart_of_accounts(subsidiary_shortname) ON UPDATE CASCADE, posted TIMESTAMP);
CREATE TABLE system.general_journal_item (id SERIAL PRIMARY KEY, journal_id INT REFERENCES system.journal ON DELETE CASCADE ON UPDATE CASCADE, description VARCHAR(250) NOT NULL, account_id VARCHAR(10) REFERENCES ledger.general_chart_of_accounts ON UPDATE CASCADE, amount NUMERIC NOT NULL, drcr VARCHAR(2) REFERENCES system.journal_item_type);
CREATE TABLE system.tax_page (id INT PRIMARY KEY, iso_country_code VARCHAR(2) NOT NULL, also_applicable_in VARCHAR(2)[]);
CREATE TABLE system.transaction_tax (id SERIAL PRIMARY KEY, shortname VARCHAR(10), name VARCHAR(250), tax_page_id INT, rate NUMERIC, obsolete TIMESTAMP, included_in_unit_price_default BOOLEAN, track_on_purchases BOOLEAN);
CREATE TABLE system.linked_account (transaction_tax_shortname VARCHAR(10), transaction_type VARCHAR(100), account_id VARCHAR(10) REFERENCES ledger.general_chart_of_accounts, PRIMARY KEY (transaction_tax_shortname, transaction_type));
CREATE TABLE system.report_formula (id INTEGER PRIMARY KEY, description VARCHAR(100), formula VARCHAR(1000));
CREATE TABLE system.report (id SERIAL PRIMARY KEY, name VARCHAR(60) NOT NULL, shortname VARCHAR(20), description VARCHAR(60) NOT NULL, default_formula_id INTEGER REFERENCES system.report_formula(id), isincl_date BOOLEAN);
CREATE TABLE system.report_section (id SERIAL PRIMARY KEY, report_id INTEGER REFERENCES system.report(id), name VARCHAR(60) NOT NULL, insert_position_id INTEGER);
CREATE TABLE system.report_detail (id SERIAL PRIMARY KEY, report_id INT REFERENCES system.report(id) NOT NULL, section_id INT, name VARCHAR(60) NOT NULL, params VARCHAR(60), item_flag INTEGER,report_formula_id INTEGER,order_num INTEGER );
CREATE TABLE system.report_result (report_id INTEGER REFERENCES system.report(id), item_id INTEGER,value NUMERIC);
INSERT INTO system.journal_item_type VALUES ('DR');
INSERT INTO system.journal_item_type VALUES ('CR');
INSERT INTO system.account_type (id, sum, ord) VALUES ('ASSET', 'DR', 1);
INSERT INTO system.account_type (id, sum, ord) VALUES ('XASSET', 'CR', 2);
INSERT INTO system.account_type (id, sum, ord) VALUES ('LIABILITY', 'CR', 3);
INSERT INTO system.account_type (id, sum, ord) VALUES ('EXPENSE', 'DR', 6);
INSERT INTO system.account_type (id, sum, ord) VALUES ('REVENUE', 'CR', 5);
INSERT INTO system.account_type (id, sum, ord) VALUES ('OWNER_EQUITY', 'CR', 4);
INSERT INTO system.report_formula VALUES(1,'balance',E'SELECT sum(amount) as sumamount FROM (SELECT bal(\\\'general_\\\'||id) AS amount FROM ledger.general_chart_of_accounts %s ORDER BY id) as amount');
INSERT INTO system.report_formula VALUES(2,'total asset','SELECT coalesce(sum(value),0) FROM system.report_result a,system.report_detail b WHERE b.report_id = 1 AND a.item_id = b.id AND b.item_flag = 1 AND b.section_id in(1,2)');
INSERT INTO system.report_formula VALUES(3,'total liabilities','SELECT coalesce(sum(value),0) FROM system.report_result a,system.report_detail b WHERE b.report_id = 1 AND a.item_id = b.id AND b.item_flag = 1 AND b.section_id in(3,4)');
INSERT INTO system.report_formula VALUES(4,'net asset','SELECT coalesce(sum(value),0) FROM system.report_result a,system.report_detail b WHERE b.report_id = 1 AND a.item_id = b.id AND b.item_flag = 1 AND b.section_id in(1,2,3,4)');
INSERT INTO system.report_formula VALUES(5,'total equity','SELECT coalesce(sum(value),0) FROM system.report_result a,system.report_detail b WHERE b.report_id = 1 AND a.item_id = b.id AND b.item_flag = 1 AND b.section_id in(5)');
INSERT INTO system.report_formula VALUES(6,'profit',E'SELECT sum(amount) as sumamount FROM (SELECT profit_bal(\\\'general_\\\'||id,%s,%s) AS amount FROM ledger.general_chart_of_accounts %s ORDER BY id) as amount');
INSERT INTO system.report_formula VALUES(7,'gross profit','SELECT coalesce(sum(value),0) FROM system.report_result a,system.report_detail b WHERE b.report_id = 2 AND a.item_id = b.id AND b.item_flag = 1 AND b.section_id in(6)');
INSERT INTO system.report_formula VALUES(8,'net profit before tax','SELECT coalesce(sum(value),0) FROM system.report_result a,system.report_detail b WHERE b.report_id = 2 AND a.item_id = b.id AND b.item_flag = 1 AND b.section_id in(7)');
INSERT INTO system.report_formula VALUES(9,'net profit after tax','SELECT coalesce(sum(value),0) FROM system.report_result a,system.report_detail b WHERE b.report_id = 2 AND a.item_id = b.id AND b.item_flag = 1 AND b.section_id in(8)');
INSERT INTO system.report_formula VALUES(10,'tax',E'SELECT sum(amount) as sumamount FROM (SELECT tax_bal(\\\'general_\\\'||id,%s,%s) AS amount FROM ledger.general_chart_of_accounts %s ORDER BY id) as amount');
INSERT INTO system.report (name, shortname, description, default_formula_id, isincl_date) VALUES ('Balance Sheet Report', 'bsr', 'report of balance sheet',1,false);
INSERT INTO system.report (name, shortname, description, default_formula_id, isincl_date) VALUES ('Profit & Loss Report', 'plr', 'report of profit & loss',6,true);
INSERT INTO system.report (name, shortname, description, default_formula_id, isincl_date) VALUES ('Tax Report', 'tr', 'report of tax',10,true);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(1,'CURRENT ASSETS',4);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(1,'NON-CURRENT ASSETS',9);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(1,'CURRENT LIABILITIES',15);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(1,'NON-CURRENT LIABILITIES',22);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(1,'EQUITY',28);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(2,'Gross profit',0);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(2,'Net profit before tax',6);
INSERT INTO system.report_section (report_id,name,insert_position_id) VALUES(2,'Net profit after tax',9);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,1,'CURRENT ASSETS',null,0,null,1);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,1,'Cash',null,1,1,2);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,1,'Receivables',null,1,1,3);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,1,'Inventory',null,1,1,4);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,1,'Other',null,1,1,5);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,2,'NON-CURRENT ASSETS',null,0,null,6);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,2,'Receivables',null,1,1,7);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,2,'Investments',null,1,1,8);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,2,'LAND',null,1,1,9);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,2,'Property, plant & equipment',null,1,1,10);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,2,'Deferred tax asset',null,1,1,11);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,2,'Total assets',null,2,2,12);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,3,'CURRENT LIABILITIES',null,0,null,13);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,3,'Accounts payable',null,1,1,14);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,3,'Interest bearing liabilities',null,1,1,15);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,3,'Accrued expenses',null,1,1,16);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,3,'Provision for current tax',null,1,1,17);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,3,'Other',null,1,1,18);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,4,'NON-CURRENT LIABILITIES',null,0,null,19);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,4,'Interest bearing liabilities',null,1,1,20);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,4,'Deferred tax liabilities',null,1,1,21);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,4,'Provisions',null,1,1,22);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,4,'Total liabilities',null,2,3,23);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,4,'Net assets',null,2,4,24);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,5,'EQUITY',null,0,null,25);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,5,'Contributed equity',null,1,1,26);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,5,'Reserves',null,1,1,27);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,5,'Retained earnings',null,1,1,28);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(1,5,'Total equity',null,2,5,29);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,6,'Revenue from sales',null,1,6,1);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,6,'Cost of sales',null,1,6,2);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,6,'Gross profit',null,2,7,3);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,7,'Administration',null,1,6,4);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,7,'Interest income',null,1,6,5);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,7,'Interest expense',null,1,6,6);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,7,'Net profit before tax',null,2,8,7);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,8,'Current income tax expense',null,1,6,8);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,8,'Deferred income tax expense',null,1,6,9);
INSERT INTO system.report_detail (report_id,section_id,name,params,item_flag,report_formula_id,order_num) VALUES(2,8,'Net profit after tax',null,2,9,10);
--business tables
CREATE TABLE system.entity_type (id VARCHAR(60) PRIMARY KEY);
CREATE TABLE system.entity (id SERIAL PRIMARY KEY, type VARCHAR(60) NOT NULL REFERENCES system.entity_type, name VARCHAR(100), given_name VARCHAR(100),status varchar(20) default 'ACTIVE');
CREATE TABLE system.contact_detail (id SERIAL PRIMARY KEY, entity_id INT REFERENCES system.entity, type VARCHAR(30), detail VARCHAR(100));
CREATE TABLE system.address (id SERIAL PRIMARY KEY, line1 VARCHAR(100) NOT NULL, line2 VARCHAR(100), suburb VARCHAR(50), region VARCHAR(50) NOT NULL, code VARCHAR(10), country VARCHAR(50) NOT NULL);
CREATE TABLE system.location (id SERIAL PRIMARY KEY, entity_id INT REFERENCES system.entity, name VARCHAR(50), phone VARCHAR(20), fax VARCHAR(20), address_id INT REFERENCES system.address, deactivated TIMESTAMP);
CREATE TABLE system.relationship (id SERIAL PRIMARY KEY, entity_id INT REFERENCES system.entity, rel_entity_id INT REFERENCES system.entity, type VARCHAR(30), location_id INT REFERENCES system.location);
CREATE TABLE contact_log (id SERIAL PRIMARY KEY, entity_id INT REFERENCES system.entity, comment VARCHAR(250), filename VARCHAR(100), log_date DATE DEFAULT CURRENT_DATE, action VARCHAR(100), closed DATE, UNIQUE(entity_id, log_date, comment, action));
CREATE TABLE sales_agent (id SERIAL PRIMARY KEY, entity_id INT REFERENCES system.entity, commission INT);
CREATE TABLE customer (id SERIAL PRIMARY KEY, entity_id INT REFERENCES system.entity, sales_agent_id INT REFERENCES sales_agent, address_id INT REFERENCES system.address, billing_method VARCHAR(20));
CREATE TABLE supplier (id SERIAL PRIMARY KEY, entity_id INT REFERENCES system.entity, address_id INT REFERENCES system.address);
INSERT INTO system.entity_type VALUES ('person');
INSERT INTO system.entity_type VALUES ('company');
INSERT INTO system.entity_type VALUES ('non-profit org');
INSERT INTO system.entity_type VALUES ('government department');
-- more financial tables
CREATE TABLE system.invoice (id BIGSERIAL PRIMARY KEY, date TIMESTAMP, terms SMALLINT DEFAULT system.default_inv_terms(), sales_agent_id INT REFERENCES sales_agent, journal_id BIGINT);
CREATE TABLE system.invoice_item (id BIGSERIAL PRIMARY KEY, invoice_id BIGINT REFERENCES system.invoice ON DELETE CASCADE ON UPDATE CASCADE, qty INT, description VARCHAR(250), unit_price NUMERIC);
CREATE TABLE system.invoice_item_tax (invoice_item_id BIGINT references system.invoice_item, transaction_tax_id INT REFERENCES system.transaction_tax, included_in_unit_price BOOLEAN, PRIMARY KEY (invoice_item_id, transaction_tax_id));
CREATE TABLE system.invoice_delivery_report (id BIGSERIAL PRIMARY KEY, invoice_id BIGINT REFERENCES system.invoice ON DELETE CASCADE ON UPDATE CASCADE,date TIMESTAMP DEFAULT 'NOW',method VARCHAR(20) NOT NULL,address_id INT REFERENCES system.address ON DELETE CASCADE ON UPDATE CASCADE,detail VARCHAR(100));
CREATE TABLE system.receipt (id BIGSERIAL PRIMARY KEY, date TIMESTAMP, invoice_id BIGINT[], journal_id BIGINT REFERENCES system.journal);
CREATE TABLE system.purchase_order (id BIGSERIAL PRIMARY KEY, date TIMESTAMP, supplier_id INT REFERENCES supplier, expense_account_id VARCHAR(10) REFERENCES ledger.general_chart_of_accounts,delivery_location_id INT REFERENCES system.location);
CREATE TABLE system.purchase_order_item (id BIGSERIAL PRIMARY KEY, purchase_order_id BIGINT REFERENCES system.purchase_order, qty INT, description VARCHAR(250), unit_price NUMERIC);
CREATE TABLE system.purchase_item_tax (purchase_order_item_id BIGINT REFERENCES system.purchase_order_item, transaction_tax_id INT REFERENCES system.transaction_tax(id), included_in_unit_price BOOLEAN, PRIMARY KEY(purchase_order_item_id,transaction_tax_id));
CREATE TABLE system.bill_payment (id BIGSERIAL PRIMARY KEY, date TIMESTAMP, purchase_order_id BIGINT[], journal_id BIGINT REFERENCES system.journal);
-- the rest
CREATE VIEW system.pk_lookup AS SELECT table_schema, table_name, column_name, data_type FROM information_schema.columns WHERE ordinal_position = 1 AND table_schema NOT IN ('information_schema', 'pg_catalog');
CREATE VIEW system.data_index AS SELECT '<a href=\"/bin/admin.py/show_tables?t=' || table_schema || '.' || table_name || '$query_string$' ||'\">' || table_name || '</a>' AS table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE';
CREATE VIEW system.info_index AS SELECT '<a href=\"/bin/av.py?v=' || table_schema || '.' || table_name || '$query_string$' ||'\">' || table_name || '</a>' AS view_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'VIEW';
CREATE VIEW system.company_location_info (id, company_name, name, line1, line2, suburb, region, code, country,phone, fax, company_id) AS SELECT l.id,e.name AS company_name,l.name,a.line1,a.line2,INITCAP(a.suburb),UPPER(a.region),a.code,UPPER(a.country),l.phone,l.fax,e.id AS company_id FROM (SELECT * FROM system.entity WHERE type<>'person') e INNER JOIN system.location l ON e.id=l.entity_id LEFT JOIN system.address a ON l.address_id=a.id WHERE l.deactivated IS NULL ORDER BY e.name;
CREATE VIEW contact_info AS SELECT c.name AS company_name, p.given_name, p.name AS surname, cdpos.detail as position, CASE WHEN cdphone.detail IS NOT NULL THEN cdphone.detail ELSE l.phone END AS phone, CASE WHEN cdfax.detail IS NOT NULL THEN cdfax.detail ELSE l.fax END AS fax, cdemail.detail AS email, cdmob.detail AS mobile, cdsms.detail AS sms, c.id AS company_id, p.id AS person_id,CASE WHEN customer.id IS NOT NULL THEN true ELSE false END AS iscustomer,CASE WHEN supplier.id IS NOT NULL THEN true ELSE false END AS issupplier FROM system.entity p LEFT JOIN system.relationship r ON r.entity_id = p.id AND r.type = 'employee' LEFT JOIN system.location l ON r.location_id = l.id AND l.deactivated IS NULL AND l.name NOT IN (SELECT code_value FROM system.sys_code WHERE code_id = 'alt_location_type') LEFT JOIN system.entity c ON r.rel_entity_id = c.id LEFT JOIN system.contact_detail cdpos ON cdpos.entity_id = p.id AND cdpos.type = 'position' LEFT JOIN system.contact_detail cdphone ON cdphone.entity_id = p.id AND cdphone.type = 'phone' LEFT JOIN system.contact_detail cdfax ON cdfax.entity_id = p.id AND cdfax.type = 'fax' LEFT JOIN (select * from system.contact_detail where id in(select min(id) from system.contact_detail group by entity_id,type)) cdemail ON cdemail.entity_id = p.id AND cdemail.type = 'email' LEFT JOIN system.contact_detail cdmob ON cdmob.entity_id = p.id AND cdmob.type = 'mobile' LEFT JOIN system.contact_detail cdsms ON cdsms.entity_id = p.id AND cdsms.type = 'sms' LEFT JOIN customer ON customer.entity_id = p.id LEFT JOIN supplier ON supplier.entity_id = p.id WHERE p.type = 'person' and p.status = 'ACTIVE' ORDER BY company_name, given_name, surname;
CREATE VIEW sales_agent_info AS SELECT s.id, CASE WHEN e.type<>'person' THEN name ELSE NULL END AS name,given_name, CASE WHEN e.type='person' THEN name ELSE NULL END AS surname,s.commission FROM sales_agent s, system.entity e WHERE s.entity_id = e.id ORDER BY name, given_name, surname;
CREATE VIEW system.business_objects AS SELECT DISTINCT vtu.table_schema, RTRIM(vtu.table_name, '_info') AS table_name FROM information_schema.view_table_usage vtu, information_schema.views v WHERE vtu.view_schema = v.table_schema AND vtu.view_name = RTRIM(v.table_name, '_info') AND vtu.view_name = RTRIM(vtu.table_name, '_info') AND vtu.view_schema = 'system' ORDER BY vtu.table_schema, table_name;
CREATE OR REPLACE VIEW customer_billing_info AS SELECT c.id,c.billing_method,c.entity_id, COALESCE(co.name, ((p.given_name::text || ' '::text) || p.name::text)::character varying) AS customer_name, a.line1, a.line2, a.suburb, a.region, a.code, a.country, sai.name, sai.given_name, sai.surname FROM customer c LEFT JOIN sales_agent_info sai ON sai.id = c.sales_agent_id LEFT JOIN "system".address a ON c.address_id=a.id,system.entity e LEFT JOIN (SELECT id ,name,given_name FROM system.entity WHERE type ='person') p ON p.id = e.id LEFT JOIN (SELECT id ,name,given_name FROM system.entity WHERE type <>'person') co ON co.id = e.id WHERE c.entity_id =e.id ORDER BY c.id;
CREATE VIEW supplier_billing_info AS SELECT sp.id, COALESCE(co.name, ((p.given_name::text || ' '::text) || p.name::text)::character varying) AS supplier_name, a.line1, a.line2, a.suburb, a.region, a.code, a.country FROM supplier sp, "system".address a,system.entity e LEFT JOIN (SELECT id ,name,given_name FROM system.entity WHERE type ='person') p ON p.id = e.id LEFT JOIN (SELECT id ,name,given_name FROM system.entity WHERE type <>'person') co ON co.id = e.id WHERE sp.address_id = a.id AND sp.entity_id =e.id ORDER BY sp.id;
CREATE VIEW system.abn_info AS SELECT e.id as entity_id, cdabn.detail as abn FROM system.entity e LEFT JOIN system.contact_detail cdabn ON cdabn.entity_id = e.id AND cdabn.type = 'abn' ORDER BY e.id;
CREATE VIEW system.person_location_info AS SELECT l.id, given_name||' '||e.name AS person_name, 'place of business' AS type, line1, line2, suburb, region, code, country, CASE WHEN cdphone.detail IS NULL THEN l.phone ELSE cdphone.detail END AS phone, CASE WHEN cdfax.detail IS NULL THEN l.fax ELSE cdfax.detail END AS fax, e.id as person_id FROM system.location l, system.relationship r, system.address a, system.entity e LEFT JOIN system.contact_detail cdphone ON cdphone.entity_id = e.id AND cdphone.type = 'phone' LEFT JOIN system.contact_detail cdfax ON cdfax.entity_id = e.id AND cdfax.type = 'fax' WHERE r.location_id = l.id AND r.entity_id = e.id AND l.address_id = a.id AND r.type = 'employee' AND l.deactivated IS NULL UNION SELECT l.id, given_name||' '||e.name AS person_name, l.name AS type, line1, line2, suburb, region, code, country, l.phone, l.fax, e.id as person_id FROM system.location l, system.entity e, system.address a WHERE l.entity_id = e.id AND l.address_id = a.id AND e.type = 'person' AND l.deactivated IS NULL ORDER BY person_name, type;
CREATE OR REPLACE VIEW customer_info AS SELECT c.id,c.billing_method, CASE WHEN e.type='person' THEN given_name||' '||name ELSE name END AS name, type, cd.abn, line1, line2, suburb, region, code, country, CASE WHEN e.type='person' THEN e.id ELSE NULL END AS person_id, CASE WHEN e.type<>'person' THEN e.id ELSE NULL END AS company_id FROM customer c LEFT JOIN system.address a ON c.address_id=a.id, system.entity e, system.abn_info cd WHERE c.entity_id = e.id AND cd.entity_id= e.id ORDER BY name;
CREATE VIEW system.customer (value, label) AS SELECT id, name FROM customer_info;
CREATE VIEW supplier_info AS SELECT c.id, CASE WHEN e.type='person' THEN given_name||' '||name ELSE name END AS name, type, cd.abn, line1, line2, suburb, region, code, country, CASE WHEN e.type='person' THEN e.id ELSE NULL END AS person_id, CASE WHEN e.type<>'person' THEN e.id ELSE NULL END AS company_id FROM supplier c, system.address a, system.entity e, system.abn_info cd WHERE c.entity_id = e.id AND c.address_id = a.id AND cd.entity_id= e.id ORDER BY name;
CREATE VIEW system.supplier (value, label) AS SELECT id, name FROM supplier_info;
CREATE FUNCTION find_name(text) RETURNS VARCHAR(100) AS $$
DECLARE
result VARCHAR(100);
BEGIN
EXECUTE 'SELECT label FROM system.'||SPLIT_PART(SUBSTR($1, 2), ':', 1)||' WHERE value = ' || SPLIT_PART($1, ':', 2) INTO result;
RETURN result;
EXCEPTION
WHEN OTHERS THEN
RETURN 'not found';
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION ledger.create_sub (
p_shortname TEXT,
p_control_id TEXT) RETURNS INT AS $$
BEGIN
EXECUTE 'CREATE TABLE ledger.' || p_shortname || '_chart_of_accounts (id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL)';
EXECUTE 'CREATE TABLE system.' || p_shortname || '_journal_item (id BIGSERIAL PRIMARY KEY, journal_id BIGINT REFERENCES system.journal ON DELETE CASCADE ON UPDATE CASCADE, description VARCHAR(250) NOT NULL, account_id INT REFERENCES ledger.' || p_shortname || '_chart_of_accounts ON UPDATE CASCADE, amount NUMERIC NOT NULL, drcr VARCHAR(2) REFERENCES system.journal_item_type)';
EXECUTE 'CREATE VIEW ledger.' || p_shortname || '_info AS SELECT ''' || p_control_id || '.'' || LPAD(id::TEXT, 5, ''0'') AS id, CASE WHEN name LIKE ''#%'' THEN find_name(name) ELSE name END AS name FROM ledger.' || p_shortname || '_chart_of_accounts ORDER BY id';
EXECUTE $cj$
CREATE OR REPLACE FUNCTION create_$cj$ || p_shortname || $cj$_journal (
p_description TEXT[],
p_account_id TEXT[],
p_amount TEXT[],
p_drcr TEXT[],
p_sl_description TEXT[],
p_sl_account_id TEXT[],
p_sl_amount TEXT[],
p_sl_drcr TEXT[],
p_post BOOLEAN ) RETURNS INT AS $journal$
DECLARE
v_bal NUMERIC := 0;
v_journal_id BIGINT;
v_success_message INT := 30300;
v_error INT;
BEGIN
-- We are assuming that all the general ledger (p_) item arrays are the same length,
-- and that all the subledger (p_sl_ ) item arrays are the same length. Ultimately,
-- it would be good to verify these facts.
-- make sure the journal is balanced
FOR i IN array_lower(p_amount, 1)..array_upper(p_amount, 1) LOOP
IF p_drcr[i] = 'CR' THEN
v_bal := v_bal + CAST(p_amount[i] AS NUMERIC);
ELSE
v_bal := v_bal - CAST(p_amount[i] AS NUMERIC);
END IF;
END LOOP;
IF v_bal != 0 THEN
v_error = 30301;
RAISE EXCEPTION 'journal not balanced';
END IF;
-- We are assuming that the GL items are being written to accounts that allow posting,
-- and that if there are subledger items, there is exactly one control account entry
-- equalling their sum. Ultimately, it would be good to verify these facts.
-- create the journal and get the id
SELECT INTO v_journal_id nextval('system.journal_id_seq');
INSERT INTO system.journal (id,ledger_shortname, date) VALUES (v_journal_id,'$cj$ || p_shortname || $cj$', 'NOW');
-- create the general journal items
FOR i IN array_lower(p_description, 1)..array_upper(p_description, 1) LOOP
INSERT INTO system.general_journal_item (journal_id, description, account_id, amount, drcr) VALUES (v_journal_id , p_description[i] , p_account_id[i] , CAST(p_amount[i] AS NUMERIC), p_drcr[i] );
END LOOP;
-- create the subledger journal items (if there are any)
FOR i IN array_lower(p_sl_description, 1)..array_upper(p_sl_description, 1) LOOP
INSERT INTO system.$cj$ || p_shortname || $cj$_journal_item (journal_id, description, account_id, amount, drcr) VALUES (v_journal_id , p_sl_description[i] , CAST(p_sl_account_id[i] AS INT), CAST(p_sl_amount[i] AS NUMERIC), p_sl_drcr[i] );
END LOOP;
-- post the journal (if directed)
IF p_post THEN
SELECT INTO v_error post_journal(v_journal_id);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
v_success_message := 30400;
END IF;
RETURN v_success_message;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 30399;
END;
$journal$ LANGUAGE plpgsql;$cj$;
IF p_shortname = 'ar' THEN
EXECUTE 'CREATE OR REPLACE VIEW system.invoice_info AS SELECT DISTINCT i.id, date, terms, cu.id AS customer_id,cu.billing_method,find_name(coa.name) AS customer_name,address_id,abn,COALESCE(system.invoice_total_ex_tax(i.id),round(0,2)) AS total_ex,COALESCE(system.invoice_tax(i.id),round(0,2)) AS tax,COALESCE(system.invoice_total(i.id),round(0,2)) AS total_inc FROM system.invoice i,system.abn_info c,customer cu,system.ar_journal_item ji,ledger.ar_chart_of_accounts coa WHERE i.journal_id = ji.journal_id AND ji.account_id = coa.id AND link_object_id(coa.name) = cu.id AND link_object(coa.name) = ''customer'' AND cu.entity_id = c.entity_id';
END IF;
IF p_shortname = 'ap' THEN
EXECUTE 'CREATE VIEW system.purchase_order_info AS SELECT DISTINCT po.id,po.delivery_location_id, date, s.id AS supplier_id,find_name(coa.name) AS supplier_name,address_id,abn,COALESCE(system.purchase_order_total_ex_tax(po.id),round(0,2)) AS total_ex,COALESCE(system.purchase_order_tax(po.id),round(0,2)) AS tax,COALESCE(system.purchase_order_total(po.id),round(0,2)) AS total_inc FROM system.purchase_order po,system.abn_info a,supplier s, ledger.ap_chart_of_accounts coa WHERE po.supplier_id = s.id AND link_object_id(coa.name) = s.id AND link_object(coa.name) = ''supplier'' AND s.entity_id = a.entity_id';
END IF;
RETURN 0;
EXCEPTION
WHEN OTHERS THEN
RETURN 99999;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION create_account (
p_ledger TEXT,
p_id TEXT,
p_name TEXT,
p_account_type_id TEXT,
p_subsidiary_shortname TEXT) RETURNS INT AS $$
DECLARE
v_error INT;
v_id INT;
BEGIN
IF EXISTS (SELECT id,name FROM ledger.general_chart_of_accounts WHERE id =p_id OR name =p_name) THEN
RETURN 30101;
END IF;
IF p_ledger NOTNULL AND p_ledger<>'' THEN
EXECUTE 'INSERT INTO ledger.' || p_ledger || '_chart_of_accounts (name) VALUES (''' || p_name || ''')';
EXECUTE 'SELECT id FROM ledger.'|| p_ledger ||'_chart_of_accounts WHERE name = ''' || p_name || '''' INTO v_id;
EXECUTE 'CREATE VIEW ledger.' || p_ledger || '_' || v_id || ' AS SELECT j.id AS journal_id, date, description, (SELECT amount FROM system.' || p_ledger || '_journal_item ji_sub WHERE ji_sub.id = ji.id AND drcr = ''DR'') AS dr, (SELECT amount FROM system.' || p_ledger || '_journal_item ji_sub WHERE ji_sub.id = ji.id AND drcr = ''CR'') AS cr FROM system.journal j, system.' || p_ledger || '_journal_item ji WHERE j.id = ji.journal_id AND posted NOTNULL AND account_id = ''' || v_id || '''';
ELSE
IF p_subsidiary_shortname IS NULL OR p_subsidiary_shortname = '' THEN
EXECUTE 'INSERT INTO ledger.general_chart_of_accounts (id, name, account_type_id, subsidiary_shortname, opening_balance) VALUES (''' || p_id || ''', ''' || p_name || ''', ''' || p_account_type_id || ''', NULL, NULL)';
EXECUTE 'CREATE VIEW ledger.general_' || p_id || ' AS SELECT j.id AS journal_id, date, description, (SELECT amount FROM system.general_journal_item ji_sub WHERE ji_sub.id = ji.id AND drcr = ''DR'') AS dr, (SELECT amount FROM system.general_journal_item ji_sub WHERE ji_sub.id = ji.id AND drcr = ''CR'') AS cr FROM system.journal j, system.general_journal_item ji WHERE j.id = ji.journal_id AND posted NOTNULL AND account_id = ''' || p_id || '''';
ELSE
EXECUTE 'INSERT INTO ledger.general_chart_of_accounts (id, name, account_type_id, subsidiary_shortname, opening_balance) VALUES (''' || p_id || ''', ''' || p_name || ''', ''' || p_account_type_id || ''', ''' || p_subsidiary_shortname || ''', 0)';
EXECUTE 'CREATE VIEW ledger.general_' || p_id || ' AS SELECT j.id AS journal_id, date, description, (SELECT amount FROM system.general_journal_item ji_sub WHERE ji_sub.id = ji.id AND drcr = ''DR'') AS dr, (SELECT amount FROM system.general_journal_item ji_sub WHERE ji_sub.id = ji.id AND drcr = ''CR'') AS cr FROM system.journal j, system.general_journal_item ji WHERE j.id = ji.journal_id AND posted NOTNULL AND account_id = ''' || p_id || '''';
SELECT INTO v_error ledger.create_sub(p_subsidiary_shortname, p_id);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
END IF;
END IF;
RETURN 30100;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 30199;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION create_subledger (p_shortname TEXT,p_control_id TEXT) RETURNS INT AS $$
DECLARE
v_error INT;
BEGIN
EXECUTE 'UPDATE ledger.general_chart_of_accounts SET subsidiary_shortname = ''' || p_shortname || ''' WHERE id = ''' || p_control_id || '''';
SELECT INTO v_error ledger.create_sub(p_shortname, p_control_id);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
RETURN 30600;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 30699;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION create_journal (
p_description TEXT[],
p_account_id TEXT[],
p_amount TEXT[],
p_drcr TEXT[],
p_sl_description TEXT[],
p_sl_account_id TEXT[],
p_sl_amount TEXT[],
p_sl_drcr TEXT[],
p_post BOOLEAN ) RETURNS INT AS $$
DECLARE
v_bal NUMERIC := 0;
v_journal_id BIGINT;
v_success_message INT := 30300;
v_error INT;
BEGIN
-- We are assuming that all the general ledger (p_) item arrays are the same length,
-- and that all the subledger (p_sl_ ) item arrays are the same length. Ultimately,
-- it would be good to verify these facts.
-- make sure the journal is balanced
FOR i IN array_lower(p_amount, 1)..array_upper(p_amount, 1) LOOP
IF p_drcr[i] = 'CR' THEN
v_bal := v_bal + CAST(p_amount[i] AS NUMERIC);
ELSE
v_bal := v_bal - CAST(p_amount[i] AS NUMERIC);
END IF;
END LOOP;
IF v_bal != 0 THEN
v_error = 30301;
RAISE EXCEPTION 'journal not balanced';
END IF;
-- We are assuming that the GL items are being written to accounts that allow posting,
-- and that if there are subledger items, there is exactly one control account entry
-- equalling their sum. Ultimately, it would be good to verify these facts.
-- create the journal and get the id
SELECT INTO v_journal_id nextval('system.journal_id_seq');
INSERT INTO system.journal (id, date) VALUES (v_journal_id, 'NOW');
-- create the general journal items
FOR i IN array_lower(p_description, 1)..array_upper(p_description, 1) LOOP
INSERT INTO system.general_journal_item (journal_id, description, account_id, amount, drcr) VALUES (v_journal_id , p_description[i] , p_account_id[i] , CAST(p_amount[i] AS NUMERIC), p_drcr[i] );
END LOOP;
-- post the journal (if directed)
IF p_post THEN
SELECT INTO v_error post_journal(v_journal_id);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
v_success_message := 30400;
END IF;
RETURN v_success_message;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 30399;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION edit_journal (
p_journal_id INT,
p_old_g_item_id INT[],
p_old_g_amount INT,
p_old_g_description TEXT,
p_old_d_item_id INT[],
p_description TEXT[],
p_account_id TEXT[],
p_amount TEXT[],
p_drcr TEXT[],
p_subledger TEXT,
p_sl_description TEXT[],
p_sl_account_id TEXT[],
p_sl_amount TEXT[],
p_sl_drcr TEXT[],
p_post BOOLEAN) RETURNS INT AS $$
DECLARE
v_old_g_item_id TEXT[];
v_old_d_item_id TEXT[];
v_control_item_id INT;
v_control_item_drcr TEXT;
v_item RECORD;
v_bal NUMERIC := 0;
v_journal_id BIGINT;
v_success_message INT := 30500;
v_error INT;
v_flag INT;
v_num INT;
BEGIN
-- We are assuming that all the general ledger (p_) item arrays are the same length,
-- and that all the subledger (p_sl_ ) item arrays are the same length. Ultimately,
-- it would be good to verify these facts.
--the journal exists or not
IF p_journal_id IS NULL THEN
v_error = 30302;
RAISE EXCEPTION 'journal not exists';
ELSE
v_journal_id := p_journal_id;
END IF;
-- make sure the journal is balanced
v_num :=1;
FOR v_item IN SELECT id FROM system.general_journal_item WHERE journal_id=v_journal_id LOOP
v_old_g_item_id[v_num] := v_item.id;
v_num := v_num+1;
END LOOP;
IF p_subledger NOTNULL AND p_subledger<>'' THEN
SELECT gj.id INTO v_control_item_id FROM system.general_journal_item gj,system.journal j,ledger.general_chart_of_accounts gc WHERE gj.journal_id=j.id AND j.ledger_shortname = gc.subsidiary_shortname AND gj.account_id=gc.id AND j.id=v_journal_id;
IF array_upper(p_old_g_item_id, 1) IS NOT NULL THEN
FOR i IN array_lower(p_old_g_item_id, 1)..array_upper(p_old_g_item_id, 1) LOOP
IF p_old_g_item_id[i]=v_control_item_id THEN
UPDATE system.general_journal_item SET amount = p_old_g_amount,description=p_old_g_description WHERE id=v_control_item_id;
EXIT;
END IF;
END LOOP;
FOR i IN array_lower(v_old_g_item_id, 1)..array_upper(v_old_g_item_id, 1) LOOP
v_flag := 0;
FOR j IN array_lower(p_old_g_item_id, 1)..array_upper(p_old_g_item_id, 1) LOOP
IF v_old_g_item_id[i]=p_old_g_item_id[j] THEN
v_flag :=1;
EXIT;
END IF;
END LOOP;
IF v_flag=0 THEN
DELETE FROM system.general_journal_item WHERE id=v_old_g_item_id[i];
END IF;
END LOOP;
ELSE
FOR i IN array_lower(v_old_g_item_id, 1)..array_upper(v_old_g_item_id, 1) LOOP
DELETE FROM system.general_journal_item WHERE id=v_old_g_item_id[i];
END LOOP;
END IF;
ELSE
IF array_upper(p_old_g_item_id, 1) IS NOT NULL THEN
FOR i IN array_lower(v_old_g_item_id, 1)..array_upper(v_old_g_item_id, 1) LOOP
v_flag := 0;
FOR j IN array_lower(p_old_g_item_id, 1)..array_upper(p_old_g_item_id, 1) LOOP
IF v_old_g_item_id[i]=p_old_g_item_id[j] THEN
v_flag :=1;
EXIT;
END IF;
END LOOP;
IF v_flag=0 THEN
DELETE FROM system.general_journal_item WHERE id=v_old_g_item_id[i];
END IF;
END LOOP;
ELSE
IF array_upper(v_old_item_id, 1) IS NOT NULL THEN
FOR i IN array_lower(v_old_item_id, 1)..array_upper(v_old_item_id, 1) LOOP
DELETE FROM system.general_journal_item WHERE id=v_old_item_id[i];
END Loop;
END IF;
END IF;
END IF;
IF array_upper(p_amount, 1) IS NOT NULL THEN
FOR i IN array_lower(p_amount, 1)..array_upper(p_amount, 1) LOOP
IF p_drcr[i] = 'CR' THEN
v_bal := v_bal + CAST(p_amount[i] AS NUMERIC);
ELSE
v_bal := v_bal - CAST(p_amount[i] AS NUMERIC);
END IF;
END LOOP;
FOR v_item IN SELECT drcr,amount FROM system.general_journal_item WHERE journal_id=v_journal_id LOOP
IF v_item.drcr='CR' THEN
v_bal := v_bal + v_item.amount;
ELSE
v_bal := v_bal - v_item.amount;
END IF;
END LOOP;
IF v_bal != 0 THEN
v_error = 30301;
RAISE EXCEPTION 'journal not balanced';
END IF;
END IF;
-- We are assuming that the GL items are being written to accounts that allow posting,
-- and that if there are subledger items, there is exactly one control account entry
-- equalling their sum. Ultimately, it would be good to verify these facts.
-- create the general journal items
IF array_upper(p_description, 1) IS NOT NULL THEN
FOR i IN array_lower(p_description, 1)..array_upper(p_description, 1) LOOP
EXECUTE 'INSERT INTO system.general_journal_item (journal_id, description, account_id, amount, drcr) VALUES (' || v_journal_id || ', ''' || p_description[i] || ''', ' || p_account_id[i] || ', ' || p_amount[i] || ', ''' || p_drcr[i] || ''')';
END LOOP;
END IF;
SELECT count(*) INTO v_num FROM system.general_journal_item WHERE journal_id=v_journal_id;
IF v_num=0 THEN
DELETE FROM system.journal WHERE id = v_journal_id;
END IF;
-- create the subledger journal items (if there are any)
IF p_subledger NOTNULL AND p_subledger<>'' THEN
v_num :=1;
--FOR v_item IN EXECUTE 'SELECT id FROM system. '|| p_subledger ||'_journal_item WHERE journal_id=v_journal_id' LOOP
FOR v_item IN EXECUTE 'SELECT id FROM system.'|| p_subledger ||'_journal_item WHERE journal_id = '|| v_journal_id LOOP
v_old_d_item_id[v_num] := v_item.id;
v_num := v_num+1;
END LOOP;
IF array_upper(p_old_d_item_id, 1) IS NOT NULL THEN
FOR i IN array_lower(v_old_d_item_id, 1)..array_upper(v_old_d_item_id, 1) LOOP
v_flag := 0;
FOR j IN array_lower(p_old_d_item_id, 1)..array_upper(p_old_d_item_id, 1) LOOP
IF v_old_d_item_id[i]=p_old_d_item_id[j] THEN
v_flag :=1;
EXIT;
END IF;
END LOOP;
IF v_flag=0 THEN
EXECUTE 'DELETE FROM system. '|| p_subledger ||'_journal_item WHERE id='||v_old_d_item_id[i]||' AND journal_id = '||v_journal_id;
END IF;
END LOOP;
ELSE
IF array_upper(v_old_d_item_id, 1) IS NOT NULL THEN
FOR i IN array_lower(v_old_d_item_id, 1)..array_upper(v_old_d_item_id, 1) LOOP
EXECUTE 'DELETE FROM system. '|| p_subledger ||'_journal_item WHERE id='||v_old_d_item_id[i]||' AND journal_id ='|| v_journal_id;
END LOOP;
END IF;
END IF;
IF array_upper(p_sl_description, 1) IS NOT NULL THEN
FOR i IN array_lower(p_sl_description, 1)..array_upper(p_sl_description, 1) LOOP
EXECUTE 'INSERT INTO system.' || p_subledger || '_journal_item (journal_id, description, account_id, amount, drcr) VALUES (' || v_journal_id || ', ''' || p_sl_description[i] || ''', ' || p_sl_account_id[i] || ', ' || p_sl_amount[i] || ', ''' || p_sl_drcr[i] || ''' )';
END LOOP;
END IF;
END IF;
-- post the journal (if directed)
IF p_post THEN
SELECT INTO v_error post_journal(v_journal_id);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
v_success_message := 30400;
END IF;
RETURN v_success_message;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 30399;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION post_journal (p_journal_id TEXT) RETURNS INT AS $$
BEGIN
UPDATE system.journal SET posted = 'NOW' WHERE id = p_journal_id;
RETURN 30400;
EXCEPTION
WHEN OTHERS THEN
RETURN 30499;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION bal(text) RETURNS NUMERIC AS $$
DECLARE
account RECORD;
account_type VARCHAR(2);
result NUMERIC;
BEGIN
EXECUTE 'SELECT COALESCE(SUM(cr), 0) - COALESCE(SUM(dr), 0) AS crbal FROM ledger.'|| quote_ident(regexp_replace($1, E'[0-9]*\\\\.0*', '')) INTO account;
result := account.crbal;
if split_part($1, '_', 1) = 'general' then
EXECUTE 'SELECT sum FROM system.account_type WHERE id = (SELECT account_type_id FROM ledger.general_chart_of_accounts WHERE id = ' || split_part($1, '_', 2) || ')' INTO account_type;
else
EXECUTE 'SELECT sum FROM system.account_type WHERE id = (SELECT account_type_id FROM ledger.general_chart_of_accounts WHERE id = ' || split_part(split_part($1, '_', 2), '.', 1) || ')' INTO account_type;
end if;
if account_type = 'DR' then
result := -result;
end if;
RETURN result;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION profit_bal(text,text,text) RETURNS NUMERIC AS $$
DECLARE
account RECORD;
result NUMERIC;
BEGIN
EXECUTE 'SELECT COALESCE(SUM(cr), 0) - COALESCE(SUM(dr), 0) AS crbal FROM ledger.' || quote_ident(regexp_replace($1, E'[0-9]*\\\\.0*', '')) || ' WHERE date BETWEEN to_date(''' || $2 || ''',''yyyymmdd'') AND to_date(''' || $3 || ''',''yyyymmdd'')' inTO account;
result := account.crbal;
RETURN result;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION tax_bal(text,text,text) RETURNS NUMERIC AS $$
DECLARE
account RECORD;
result NUMERIC;
BEGIN
EXECUTE 'SELECT COALESCE(SUM(cr), 0) - COALESCE(SUM(dr), 0) AS crbal FROM ledger.' || quote_ident(regexp_replace($1, E'[0-9]*\\\\.0*', '')) || ' WHERE date BETWEEN to_date(''' || $2 || ''',''yyyymmdd'') AND to_date(''' || $3 || ''',''yyyymmdd'')' inTO account;
result := account.crbal;
RETURN result;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION balance(
TEXT,
begindate TEXT,
enddte TEXT) RETURNS NUMERIC AS $$
DECLARE
account RECORD;
account_type VARCHAR(2);
result NUMERIC;
BEGIN
EXECUTE 'SELECT COALESCE(SUM(cr), 0) - COALESCE(SUM(dr), 0) AS crbal FROM ledger.'|| quote_ident(regexp_replace($1, E'[0-9]*\\\\.0*', ''))||' WHERE date BETWEEN '||to_date(COALESCE($2, '1970-01-01'),'YYYY-MM-DD')||' AND '|| to_date(COALESCE($3, '2100-01-01'),'YYYY-MM-DD') INTO account;
result := account.crbal;
if split_part($1, '_', 1) = 'general' then
EXECUTE 'SELECT sum FROM system.account_type WHERE id = (SELECT account_type_id FROM ledger.general_chart_of_accounts WHERE id = ' || split_part($1, '_', 2) || ')' INTO account_type;
else
EXECUTE 'SELECT sum FROM system.account_type WHERE id = (SELECT account_type_id FROM ledger.general_chart_of_accounts WHERE id = ' || split_part(split_part($1, '_', 2), '.', 1) || ')' INTO account_type;
end if;
if account_type = 'DR' then
result := -result;
end if;
RETURN result;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION link_object_id(text) RETURNS INT AS $$
DECLARE
result INT;
BEGIN
result := SPLIT_PART(SPLIT_PART($1, '#', 2), ':', 2);
RETURN result;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION link_object(text) RETURNS VARCHAR(20) AS $$
DECLARE
result VARCHAR(20);
BEGIN
result := SPLIT_PART(SPLIT_PART($1, '#', 2), ':', 1);
RETURN result;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION system.inv_item_tax (
p_invoice_item_id BIGINT,
p_tax_id INT) RETURNS NUMERIC AS $$
DECLARE
v_tax RECORD;
v_result NUMERIC;
BEGIN
SELECT INTO v_tax * FROM system.transaction_tax WHERE id = p_tax_id;
SELECT INTO v_result (qty * unit_price - system.inv_item_included_tax(p_invoice_item_id)) * COALESCE(v_tax.rate,0) / 100 FROM system.invoice_item WHERE id = p_invoice_item_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE OR REPLACE FUNCTION system.inv_item_included_tax (p_invoice_item_id BIGINT) RETURNS NUMERIC AS $$
DECLARE
v_included_tax_rate NUMERIC;
v_result NUMERIC;
BEGIN
SELECT INTO v_included_tax_rate COALESCE(sum(rate), 0) FROM system.transaction_tax WHERE id IN (SELECT transaction_tax_id FROM system.invoice_item_tax WHERE invoice_item_id = p_invoice_item_id AND included_in_unit_price);
SELECT INTO v_result qty * unit_price * v_included_tax_rate / (100 + v_included_tax_rate) FROM system.invoice_item WHERE id = p_invoice_item_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE OR REPLACE FUNCTION system.inv_item_combined_tax (p_invoice_item_id BIGINT) RETURNS NUMERIC AS $$
DECLARE
v_tax_rate NUMERIC;
v_result NUMERIC;
BEGIN
SELECT INTO v_tax_rate sum(rate) FROM system.transaction_tax WHERE id IN (SELECT transaction_tax_id FROM system.invoice_item_tax WHERE invoice_item_id = p_invoice_item_id);
SELECT INTO v_result (qty * unit_price - system.inv_item_included_tax(p_invoice_item_id)) * v_tax_rate / 100 FROM system.invoice_item WHERE id = p_invoice_item_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE VIEW system.invoice_tax_aggregation AS SELECT invoice_id, tt.shortname, round(sum(system.inv_item_tax(ii.id, tt.id)), 2) AS individual_tax_total FROM system.invoice_item ii, system.invoice_item_tax it, system.transaction_tax tt WHERE it.invoice_item_id = ii.id AND it.transaction_tax_id = tt.id GROUP BY invoice_id, shortname;
CREATE OR REPLACE FUNCTION system.invoice_total_ex_tax (p_invoice_id BIGINT) RETURNS NUMERIC as $$
DECLARE
v_result NUMERIC;
BEGIN
SELECT INTO v_result round(sum(item_total_ex_tax), 2) FROM (SELECT invoice_id, qty * unit_price - COALESCE(system.inv_item_included_tax(id),0) AS item_total_ex_tax FROM system.invoice_item ii WHERE invoice_id = p_invoice_id) AS totals WHERE invoice_id = p_invoice_id GROUP BY invoice_id;
RETURN v_result;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION system.invoice_tax (p_invoice_id BIGINT) RETURNS NUMERIC AS $$
DECLARE
v_result NUMERIC;
BEGIN
SELECT INTO v_result COALESCE(sum(individual_tax_total),round(0,2)) FROM system.invoice_tax_aggregation WHERE invoice_id = p_invoice_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE OR REPLACE FUNCTION system.invoice_total (p_invoice_id BIGINT) RETURNS NUMERIC as $$
DECLARE
v_result NUMERIC;
BEGIN
SELECT INTO v_result system.invoice_total_ex_tax(p_invoice_id) + system.invoice_tax(p_invoice_id);
RETURN v_result;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION create_invoice (
p_customer_id TEXT,
p_sales_agent_id TEXT,
p_invoice_id TEXT,
p_item_qty TEXT[],
p_item_description TEXT[],
p_item_unit_price TEXT[],
p_item_tax_ids TEXT[],
p_item_tax_inclusions TEXT[]
) RETURNS INT AS $$
DECLARE
v_invoice_id BIGINT;
v_journal_id BIGINT;
v_invoice_item_id BIGINT;
v_item_tax_ids TEXT[];
v_item_tax_inclusions TEXT[];
v_rec RECORD;
v_special_ac_sales_rev TEXT;
v_customer_ac INT;
v_comm_rec RECORD;
v_commission_tax NUMERIC:=0;
v_gl_descriptions TEXT[];
v_gl_account_ids TEXT[];
v_gl_amounts TEXT[];
v_gl_drcrs TEXT[];
v_sl_descriptions TEXT[];
v_sl_account_ids TEXT[];
v_sl_amounts TEXT[];
v_sl_drcrs TEXT[];
v_error INT;
BEGIN
-- create the invoice and get the id
IF p_customer_id IS NULL OR p_customer_id='' OR array_upper(p_item_description, 1) IS NULL THEN
RAISE EXCEPTION 'Not enough parameters';
END IF;
IF p_invoice_id IS NULL THEN
SELECT INTO v_invoice_id nextval('system.invoice_id_seq');
ELSE
v_invoice_id = p_invoice_id;
END IF;
INSERT INTO system.invoice (id, date, sales_agent_id) VALUES (v_invoice_id, 'NOW', CAST(p_sales_agent_id AS INT));
--COMMIT;
-- We are assuming that all the item arrays are the same length Ultimately,
-- it would be good to verify this fact.
-- create the invoice items (and tax records for each item - these are in a
-- separate table)
FOR i IN array_lower(p_item_qty, 1)..array_upper(p_item_qty, 1) LOOP
SELECT INTO v_invoice_item_id nextval('system.invoice_item_id_seq');
INSERT INTO system.invoice_item (id, invoice_id, qty, description, unit_price) VALUES (v_invoice_item_id, v_invoice_id, CAST(p_item_qty[i] AS INT), p_item_description[i], CAST(p_item_unit_price[i] AS NUMERIC));
v_item_tax_ids := string_to_array(p_item_tax_ids[i], ',');
v_item_tax_inclusions := string_to_array(p_item_tax_inclusions[i], ',');
IF v_item_tax_ids IS NOT NULL THEN
FOR t in array_lower(v_item_tax_ids, 1)..array_upper(v_item_tax_ids, 1) LOOP
EXECUTE 'INSERT INTO system.invoice_item_tax (invoice_item_id, transaction_tax_id, included_in_unit_price) VALUES (' || v_invoice_item_id || ', ' || v_item_tax_ids[t] || ', ''' || v_item_tax_inclusions[t] || ''')';
END LOOP;
END IF;
END LOOP;
-- prepare journal... AR control account
SELECT INTO v_rec id AS account_id FROM ledger.general_chart_of_accounts WHERE subsidiary_shortname = 'ar';
v_gl_descriptions[1] := 'Invoice #' || v_invoice_id;
v_gl_account_ids[1] := CAST(v_rec.account_id AS TEXT);
v_gl_amounts[1] := CAST(system.invoice_total(v_invoice_id) AS TEXT);
v_gl_drcrs[1] := CAST('DR'AS TEXT);
-- prepare journal... get the aggregated transaction taxes
FOR v_rec IN SELECT CASE WHEN position(shortname in coa.name) > 0 THEN 'Invoice #' || invoice_id ELSE shortname || ' on invoice #' || invoice_id END AS description, account_id, individual_tax_total AS amount FROM system.linked_account la, system.invoice_tax_aggregation ta, ledger.general_chart_of_accounts coa WHERE la.transaction_tax_shortname = ta.shortname AND la.account_id = coa.id AND lower(la.transaction_type) = 'retail sale' AND ta.invoice_id = v_invoice_id GROUP BY invoice_id, shortname, account_id, individual_tax_total, coa.name LOOP
-- We are assuming that taxes with rates of zero will not have a linked
-- account and therefore not appear in this result set. Ultimately, it
-- may be useful to explicitly ignore zero amounts.
v_gl_descriptions := v_gl_descriptions || v_rec.description;
v_gl_account_ids := v_gl_account_ids || CAST(v_rec.account_id AS TEXT);
v_gl_amounts := v_gl_amounts || CAST(v_rec.amount AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('CR' AS TEXT);
END LOOP;
-- prepare journal... book revenue
SELECT INTO v_special_ac_sales_rev code_value FROM system.sys_code WHERE code_id = 'special_ac_sales_rev';
v_gl_descriptions := v_gl_descriptions || CAST('Invoice #' || v_invoice_id AS TEXT);
v_gl_account_ids := v_gl_account_ids || v_special_ac_sales_rev;
v_gl_amounts := v_gl_amounts || CAST(system.invoice_total_ex_tax(v_invoice_id) AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('CR' AS TEXT);
-- prepare journal... AR ledger
SELECT INTO v_customer_ac id FROM ledger.ar_chart_of_accounts WHERE name = '#customer:' || p_customer_id;
v_sl_descriptions[1] := 'Invoice #' || v_invoice_id;
v_sl_account_ids[1] := CAST(v_customer_ac AS TEXT);
v_sl_amounts[1] := CAST(system.invoice_total(v_invoice_id) AS TEXT);
v_sl_drcrs[1] := CAST('DR' AS TEXT);
-- prepare journal... commission payable
IF p_sales_agent_id IS NOT NULL THEN
SELECT INTO v_comm_rec CASE WHEN position('commission' in lower(name)) > 0 THEN COALESCE(name, given_name || ' ' || surname) || ' - Invoice #' || v_invoice_id ELSE COALESCE(name, given_name || ' ' || surname) || ' commission - Invoice #' || v_invoice_id END AS description, code_value AS account_id, round(system.invoice_total(v_invoice_id) * commission / 100, 2) AS amount FROM sales_agent_info, system.sys_code WHERE code_id = 'special_ac_comm_pay' AND id = p_sales_agent_id;
v_gl_descriptions := v_gl_descriptions || v_comm_rec.description;
v_gl_account_ids := v_gl_account_ids || CAST(v_comm_rec.account_id AS TEXT);
v_gl_amounts := v_gl_amounts || CAST(v_comm_rec.amount AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('CR' AS TEXT);
--prepare journal... tax on commission
FOR v_rec IN SELECT CASE WHEN position(shortname in coa.name) > 0 THEN 'Invoice #' || v_invoice_id || ' commission' ELSE shortname || ' on commission for invoice #' || v_invoice_id END AS description, account_id, round(v_comm_rec.amount * rate / (100 + rate), 2) AS amount FROM system.transaction_tax tt, system.linked_account la, ledger.general_chart_of_accounts coa WHERE la.transaction_tax_shortname = tt.shortname AND la.account_id = coa.id AND lower(la.transaction_type) = 'retail purchase' LOOP
v_gl_descriptions := v_gl_descriptions || v_rec.description;
v_gl_account_ids := v_gl_account_ids || CAST(v_rec.account_id AS TEXT);
v_gl_amounts := v_gl_amounts || CAST(v_rec.amount AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
v_commission_tax := v_commission_tax + v_rec.amount;
END LOOP;
--prepare journal... commission expense
SELECT INTO v_rec CASE WHEN position('commission' in lower(name)) > 0 THEN 'Invoice #' || v_invoice_id ELSE 'Commission on invoice #' || v_invoice_id END AS description, code_value AS account_id FROM ledger.general_chart_of_accounts, system.sys_code WHERE code_id = 'special_ac_comm_exp' AND code_value = id;
v_gl_descriptions := v_gl_descriptions || v_rec.description;
v_gl_account_ids := v_gl_account_ids || CAST(v_rec.account_id AS TEXT);
v_gl_amounts := v_gl_amounts || CAST(v_comm_rec.amount - v_commission_tax AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
END IF;
SELECT INTO v_error create_ar_journal(v_gl_descriptions, v_gl_account_ids, v_gl_amounts, v_gl_drcrs, v_sl_descriptions, v_sl_account_ids, v_sl_amounts, v_sl_drcrs, TRUE);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
SELECT INTO v_journal_id currval('system.journal_id_seq');
UPDATE system.invoice SET journal_id = v_journal_id WHERE id = v_invoice_id;
RETURN 30200;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 30299;
END;
$$ LANGUAGE plpgsql;
CREATE VIEW system.invoice_item_info AS SELECT invoice_id, description, round(qty * unit_price - COALESCE(system.inv_item_included_tax(ii.id),0), 2) AS total_ex, round(COALESCE(system.inv_item_combined_tax(ii.id),0), 2) as combined_tax, round(qty * unit_price - COALESCE(system.inv_item_included_tax(ii.id),0) + COALESCE(system.inv_item_combined_tax(ii.id),0), 2) as total_inc FROM system.invoice_item ii ORDER BY id;
CREATE TABLE system.expense_report (id SERIAL PRIMARY KEY, journal_id BIGINT REFERENCES system.journal);
CREATE TABLE system.expense_report_item_tax (journal_item_id BIGINT REFERENCES system.general_journal_item, transaction_tax_id INT REFERENCES system.transaction_tax, amount NUMERIC, PRIMARY KEY (journal_item_id, transaction_tax_id));
CREATE OR REPLACE FUNCTION create_expense_report (
p_expense_report_id TEXT,
p_expenses_relate_to TEXT,
p_item_account_id TEXT[],
p_item_amount TEXT[],
p_item_description TEXT[],
p_item_tax_ids TEXT[],
p_item_tax_amounts TEXT[]) RETURNS INT AS $$
DECLARE
v_special_ac_cash TEXT;
v_expense_report_id INT;
v_expense_report_total NUMERIC:=0;
v_item_tax_ids TEXT[];
v_item_tax_amounts TEXT[];
v_tax_id TEXT[];
v_tax_amount NUMERIC[];
v_ind INT;
v_item_total_tax NUMERIC;
v_rec RECORD;
v_journal_id BIGINT;
v_journal_item_id BIGINT;
v_gl_descriptions TEXT[];
v_gl_account_ids TEXT[];
v_gl_amounts TEXT[];
v_gl_drcrs TEXT[];
v_error INT;
BEGIN
-- create the expense report and get the id
IF array_upper(p_item_description, 1) IS NULL THEN
RAISE EXCEPTION 'Nothing to expense';
END IF;
IF p_expense_report_id IS NULL THEN
SELECT INTO v_expense_report_id nextval('system.expense_report_id_seq');
ELSE
v_expense_report_id = p_expense_report_id;
END IF;
INSERT INTO system.expense_report (id) VALUES (v_expense_report_id);
-- We are assuming that all the item arrays are the same length. Ultimately,
-- it would be good to verify this fact.
-- prepare journal... Cash account
SELECT INTO v_special_ac_cash code_value FROM system.sys_code WHERE code_id = 'special_ac_cash';
FOR i IN array_lower(p_item_amount, 1)..array_upper(p_item_amount, 1) LOOP
v_expense_report_total := v_expense_report_total + CAST(p_item_amount[i] AS NUMERIC);
END LOOP;
v_gl_descriptions[1] := 'Expense report #' || v_expense_report_id || COALESCE(' - ' || p_expenses_relate_to, '');
v_gl_account_ids[1] := v_special_ac_cash;
v_gl_amounts[1] := CAST(v_expense_report_total AS TEXT);
v_gl_drcrs[1] := 'CR';
-- prepare journal... aggregate the transaction taxes
IF p_item_tax_ids IS NOT NULL THEN
FOR i IN array_lower(p_item_tax_ids, 1)..array_upper(p_item_tax_ids, 1) LOOP
v_item_tax_ids := string_to_array(p_item_tax_ids[i], ',');
v_item_tax_amounts := string_to_array(p_item_tax_amounts[i], ',');
FOR t IN array_lower(v_item_tax_ids, 1)..array_upper(v_item_tax_ids, 1) LOOP
IF v_item_tax_ids[t] = ANY(v_tax_id) THEN
v_ind := system.array_index(v_tax_id, v_item_tax_ids[t]);
v_tax_amount[v_ind] := v_tax_amount[v_ind] + CAST(v_item_tax_amounts[t] AS NUMERIC);
ELSE
v_tax_id := array_append(v_tax_id, v_item_tax_ids[t]);
v_tax_amount := array_append(v_tax_amount, CAST(v_item_tax_amounts[t] AS NUMERIC));
END IF;
END LOOP;
END LOOP;
FOR i IN array_lower(v_tax_id, 1)..array_upper(v_tax_id, 1) LOOP
SELECT INTO v_rec coa.id AS account_id, CASE WHEN position(shortname IN coa.name) > 0 THEN 'Expense report #' || er.id ELSE shortname || ' on expense report #' || er.id END AS description FROM ledger.general_chart_of_accounts coa, system.transaction_tax tt, system.linked_account la, system.expense_report er WHERE coa.id = account_id AND tt.shortname = transaction_tax_shortname AND tt.id = v_tax_id[i] AND er.id = v_expense_report_id AND transaction_type = 'retail purchase';
v_gl_descriptions := v_gl_descriptions || CAST(v_rec.description AS TEXT);
v_gl_account_ids := v_gl_account_ids || CAST(v_rec.account_id AS TEXT);
v_gl_amounts := v_gl_amounts || CAST(v_tax_amount[i] AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
END LOOP;
END IF;
-- prepare journal... line items (ex tax)
FOR i IN array_lower(p_item_description, 1)..array_upper(p_item_description, 1) LOOP
v_item_total_tax := 0;
IF p_item_tax_ids IS NOT NULL THEN
v_item_tax_ids := string_to_array(p_item_tax_ids[i], ',');
v_item_tax_amounts := string_to_array(p_item_tax_amounts[i], ',');
FOR t IN array_lower(v_item_tax_amounts, 1)..array_upper(v_item_tax_amounts, 1) LOOP
v_item_total_tax := v_item_total_tax + CAST(v_item_tax_amounts[t] AS NUMERIC);
END LOOP;
END IF;
v_gl_descriptions := v_gl_descriptions || p_item_description[i];
v_gl_account_ids := v_gl_account_ids || p_item_account_id[i];
v_gl_amounts := v_gl_amounts || CAST(CAST(p_item_amount[i] AS NUMERIC) - v_item_total_tax AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
END LOOP;
SELECT INTO v_error create_journal(v_gl_descriptions, v_gl_account_ids, v_gl_amounts, v_gl_drcrs, NULL, NULL, NULL, NULL, TRUE);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
SELECT INTO v_journal_id currval('system.journal_id_seq');
UPDATE system.expense_report SET journal_id = v_journal_id WHERE id = v_expense_report_id;
-- We are assuming the description/account_id combination is unique with the expense
-- report. This should be validated - probably both here and in the js.
-- store tax records for each item to facilitate regeneration of the expense report
IF p_item_tax_ids IS NOT NULL THEN
FOR i IN array_lower(p_item_account_id, 1)..array_upper(p_item_account_id, 1) LOOP
SELECT INTO v_journal_item_id id FROM system.general_journal_item WHERE journal_id = v_journal_id AND description = p_item_description[i] AND account_id = p_item_account_id[i];
v_item_tax_ids := string_to_array(p_item_tax_ids[i], ',');
v_item_tax_amounts := string_to_array(p_item_tax_amounts[i], ',');
FOR t IN array_lower(v_item_tax_ids, 1)..array_upper(v_item_tax_ids, 1) LOOP
INSERT INTO system.expense_report_item_tax (journal_item_id, transaction_tax_id, amount) VALUES (v_journal_item_id, CAST(v_item_tax_ids[t] AS INT), CAST(v_item_tax_amounts[t] AS NUMERIC));
END LOOP;
END LOOP;
END IF;
RETURN 31000;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 31099;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION generate_receipt (
p_receipt_id TEXT,
p_customer_id TEXT,
p_amount TEXT,
p_comment TEXT,
p_invoice_ids TEXT[]) RETURNS INT AS $$
DECLARE
v_receipt_id BIGINT;
v_special_ac_cash TEXT;
v_ar_account TEXT;
v_customer_ac INT;
v_journal_id BIGINT;
v_journal_item_id BIGINT;
v_gl_descriptions TEXT[];
v_gl_account_ids TEXT[];
v_gl_amounts TEXT[];
v_gl_drcrs TEXT[];
v_sl_descriptions TEXT[];
v_sl_account_ids TEXT[];
v_sl_amounts TEXT[];
v_sl_drcrs TEXT[];
v_error INT;
BEGIN
-- create the receipt and get the id
IF p_receipt_id IS NULL THEN
SELECT INTO v_receipt_id nextval('system.receipt_id_seq');
ELSE
v_receipt_id = p_receipt_id;
END IF;
INSERT INTO system.receipt VALUES (v_receipt_id, 'NOW', CAST(p_invoice_ids AS BIGINT[]), NULL);
-- prepare journal... Cash account
SELECT INTO v_special_ac_cash code_value FROM system.sys_code WHERE code_id = 'special_ac_cash';
v_gl_descriptions[1] := 'Receipt #' || v_receipt_id || COALESCE(' - ' || p_comment, '');
v_gl_account_ids[1] := v_special_ac_cash;
v_gl_amounts[1] := p_amount;
v_gl_drcrs[1] := CAST('DR' AS TEXT);
-- prepare journal... AR control account
SELECT INTO v_ar_account id FROM ledger.general_chart_of_accounts WHERE subsidiary_shortname = 'ar';
v_gl_descriptions := v_gl_descriptions || CAST('Receipt #' || v_receipt_id || COALESCE(' - ' || p_comment, '') AS TEXT);
v_gl_account_ids := v_gl_account_ids || v_ar_account;
v_gl_amounts := v_gl_amounts || CAST(p_amount AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('CR' AS TEXT);
-- prepare journal... AR ledger
SELECT INTO v_customer_ac id FROM ledger.ar_chart_of_accounts WHERE name = '#customer:' || p_customer_id;
v_sl_descriptions[1] := 'Receipt #' || v_receipt_id || COALESCE(' - ' || p_comment, '');
v_sl_account_ids[1] := CAST(v_customer_ac AS TEXT);
v_sl_amounts[1] := p_amount;
v_sl_drcrs[1] := CAST('CR' AS TEXT);
-- create the journal and stamp its id onto the receipt
SELECT INTO v_error create_ar_journal(v_gl_descriptions, v_gl_account_ids, v_gl_amounts, v_gl_drcrs, v_sl_descriptions, v_sl_account_ids, v_sl_amounts, v_sl_drcrs, TRUE);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
SELECT INTO v_journal_id currval('system.journal_id_seq');
UPDATE system.receipt SET journal_id = v_journal_id WHERE id = v_receipt_id;
RETURN 31100;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 31199;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION system.po_item_tax (
p_purchase_order_item_id BIGINT,
p_tax_id INT) RETURNS NUMERIC AS $$
DECLARE
v_tax RECORD;
v_result NUMERIC;
BEGIN
SELECT INTO v_tax * FROM system.transaction_tax WHERE id = p_tax_id;
SELECT INTO v_result (qty * unit_price - system.po_item_included_tax(p_purchase_order_item_id)) * COALESCE(v_tax.rate,0) / 100 FROM system.purchase_order_item WHERE id = p_purchase_order_item_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE OR REPLACE FUNCTION system.po_item_included_tax (p_purchase_order_item_id BIGINT) RETURNS NUMERIC AS $$
DECLARE
v_included_tax_rate NUMERIC;
v_result NUMERIC;
BEGIN
SELECT INTO v_included_tax_rate COALESCE(sum(rate), 0) FROM system.transaction_tax WHERE id IN (SELECT transaction_tax_id FROM system.purchase_item_tax WHERE purchase_order_item_id = p_purchase_order_item_id AND included_in_unit_price);
SELECT INTO v_result qty * unit_price * v_included_tax_rate / (100 + v_included_tax_rate) FROM system.purchase_order_item WHERE id = p_purchase_order_item_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE OR REPLACE FUNCTION system.po_item_combined_tax (p_purchase_order_item_id BIGINT) RETURNS NUMERIC AS $$
DECLARE
v_tax_rate NUMERIC;
v_result NUMERIC;
BEGIN
SELECT INTO v_tax_rate COALESCE(sum(rate),0) FROM system.transaction_tax WHERE id IN (SELECT transaction_tax_id FROM system.purchase_item_tax WHERE purchase_order_item_id = p_purchase_order_item_id);
SELECT INTO v_result (qty * unit_price - system.po_item_included_tax(p_purchase_order_item_id)) * v_tax_rate / 100 FROM system.purchase_order_item WHERE id = p_purchase_order_item_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE VIEW system.purchase_order_tax_aggregation AS SELECT purchase_order_id, tt.shortname, round(sum(system.po_item_tax(pi.id, tt.id)), 2) AS individual_tax_total FROM system.purchase_order_item pi, system.purchase_item_tax pt, system.transaction_tax tt WHERE pt.purchase_order_item_id = pi.id AND pt.transaction_tax_id = tt.id GROUP BY purchase_order_id, shortname;
CREATE OR REPLACE FUNCTION system.purchase_order_total_ex_tax (p_purchase_order_id BIGINT) RETURNS NUMERIC as $$
DECLARE
v_result NUMERIC;
BEGIN
SELECT INTO v_result round(sum(item_total_ex_tax), 2) FROM (SELECT purchase_order_id, qty * unit_price - COALESCE(system.po_item_included_tax(id),round(0,2)) AS item_total_ex_tax FROM system.purchase_order_item WHERE purchase_order_id = p_purchase_order_id) AS totals WHERE purchase_order_id = p_purchase_order_id GROUP BY purchase_order_id;
RETURN v_result;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION system.purchase_order_tax (p_purchase_order_id BIGINT) RETURNS NUMERIC AS $$
DECLARE
v_result NUMERIC;
BEGIN
SELECT INTO v_result COALESCE(sum(individual_tax_total),round(0,2)) FROM system.purchase_order_tax_aggregation WHERE purchase_order_id = p_purchase_order_id;
RETURN v_result;
END;
$$ language plpgsql;
CREATE OR REPLACE FUNCTION system.purchase_order_total (p_purchase_order_id BIGINT) RETURNS NUMERIC as $$
DECLARE
v_result NUMERIC;
BEGIN
SELECT INTO v_result system.purchase_order_total_ex_tax(p_purchase_order_id) + system.purchase_order_tax(p_purchase_order_id);
RETURN v_result;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION create_purchase_order (
p_supplier_id TEXT,
p_purchase_order_id TEXT,
p_delivery_location_id TEXT,
p_expense_account_id TEXT,
p_item_qty TEXT[],
p_item_description TEXT[],
p_item_unit_price TEXT[],
p_item_tax_ids TEXT[],
p_item_tax_inclusions TEXT[]) RETURNS INT AS $$
DECLARE
v_purchase_order_id BIGINT;
v_journal_id BIGINT;
v_purchase_order_item_id BIGINT;
v_item_tax_ids TEXT[];
v_item_tax_inclusions TEXT[];
v_error INT;
BEGIN
-- create the purchase order and get the id
IF p_supplier_id IS NULL OR p_delivery_location_id IS NULL OR array_upper(p_item_description, 1) IS NULL THEN
RAISE EXCEPTION 'Not enough parameters';
END IF;
IF p_purchase_order_id IS NULL THEN
SELECT INTO v_purchase_order_id nextval('system.purchase_order_id_seq');
ELSE
v_purchase_order_id = p_purchase_order_id;
END IF;
INSERT INTO system.purchase_order VALUES (v_purchase_order_id, 'NOW', CAST(p_supplier_id AS INT), p_expense_account_id,CAST(p_delivery_location_id AS INT));
-- We are assuming that all the item arrays are the same length. Ultimately,
-- it would be good to verify this fact.
-- create the purchase order items (and tax records for each item - these are in a
-- separate table)
FOR i IN array_lower(p_item_qty, 1)..array_upper(p_item_qty, 1) LOOP
SELECT INTO v_purchase_order_item_id nextval('system.purchase_order_item_id_seq');
INSERT INTO system.purchase_order_item (id, purchase_order_id, qty, description, unit_price) VALUES (v_purchase_order_item_id , v_purchase_order_id , CAST(p_item_qty[i] AS INT) , p_item_description[i] , CAST(p_item_unit_price[i] AS NUMERIC));
v_item_tax_ids := string_to_array(p_item_tax_ids[i], ',');
v_item_tax_inclusions := string_to_array(p_item_tax_inclusions[i], ',');
IF v_item_tax_ids IS NOT NULL THEN
FOR t in array_lower(v_item_tax_ids, 1)..array_upper(v_item_tax_ids, 1) LOOP
EXECUTE 'INSERT INTO system.purchase_item_tax (purchase_order_item_id, transaction_tax_id, included_in_unit_price) VALUES (' || v_purchase_order_item_id || ', ' || v_item_tax_ids[t] || ', ''' || v_item_tax_inclusions[t] || ''')';
END LOOP;
END IF;
END LOOP;
RETURN 20200;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 20299;
END;
$$ LANGUAGE plpgsql;
CREATE VIEW system.purchase_order_item_info AS SELECT purchase_order_id, description, round(qty * unit_price - COALESCE(system.po_item_included_tax(pi.id),0), 2) AS total_ex, round(COALESCE(system.po_item_combined_tax(pi.id),0), 2) as combined_tax, round(qty * unit_price - COALESCE(system.po_item_included_tax(pi.id),0) + COALESCE(system.po_item_combined_tax(pi.id),0), 2) as total_inc FROM system.purchase_order_item pi ORDER BY id;
CREATE OR REPLACE FUNCTION pay_bill (
p_supplier_id TEXT,
p_amount TEXT,
p_tax_id TEXT[],
p_tax_amount TEXT[],
p_comment TEXT,
p_adjustment_expense_account TEXT,
p_adjustment_comment TEXT,
p_purchase_order_ids TEXT[]) RETURNS INT AS $$
DECLARE
v_bill_payment_id BIGINT;
v_special_ac_cash TEXT;
v_ap_account TEXT;
v_journal_id BIGINT;
v_journal_item_id BIGINT;
v_supplier_ac INT;
v_rec RECORD;
v_purchase_order_amount NUMERIC;
v_total_purchase_orders NUMERIC:=0;
v_total_purchase_orders_ex_tax NUMERIC:=0;
v_bill_total_ex_tax NUMERIC;
v_gl_descriptions TEXT[];
v_gl_account_ids TEXT[];
v_gl_amounts TEXT[];
v_gl_drcrs TEXT[];
v_sl_descriptions TEXT[];
v_sl_account_ids TEXT[];
v_sl_amounts TEXT[];
v_sl_drcrs TEXT[];
v_error INT;
BEGIN
-- create the bill payment and get the id
SELECT INTO v_bill_payment_id nextval('system.bill_payment_id_seq');
INSERT INTO system.bill_payment VALUES (v_bill_payment_id, 'NOW', CAST(p_purchase_order_ids AS BIGINT[]), NULL);
-- prepare journal... Cash account
SELECT INTO v_special_ac_cash code_value FROM system.sys_code WHERE code_id = 'special_ac_cash';
v_gl_descriptions[1] := 'Bill payment #' || v_bill_payment_id || COALESCE(' - ' || p_comment, '');
v_gl_account_ids[1] := v_special_ac_cash;
v_gl_amounts[1] := CAST(p_amount AS TEXT);
v_gl_drcrs[1] := 'CR';
-- prepare journal... AP control account
SELECT INTO v_ap_account id FROM ledger.general_chart_of_accounts WHERE subsidiary_shortname = 'ap';
FOR i IN array_lower(p_purchase_order_ids, 1)..array_upper(p_purchase_order_ids, 1) LOOP
v_purchase_order_amount := system.purchase_order_total(CAST(p_purchase_order_ids[i] AS BIGINT));
v_gl_descriptions := v_gl_descriptions || CAST('Purchase order #' || p_purchase_order_ids[i] AS TEXT);
v_gl_account_ids := v_gl_account_ids || v_ap_account;
v_gl_amounts := v_gl_amounts || CAST(v_purchase_order_amount AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('CR' AS TEXT);
v_total_purchase_orders := v_total_purchase_orders + v_purchase_order_amount;
END LOOP;
-- adjustment
IF CAST(p_amount AS NUMERIC) != v_total_purchase_orders THEN
v_gl_descriptions := v_gl_descriptions || CAST('Bill payment #' || v_bill_payment_id || COALESCE(' - adjustment for ' || p_adjustment_comment, '') AS TEXT);
v_gl_account_ids := v_gl_account_ids || v_ap_account;
v_gl_amounts := v_gl_amounts || CAST(ABS(CAST(p_amount AS NUMERIC) - v_total_purchase_orders) AS TEXT);
IF CAST(p_amount AS NUMERIC) > v_total_purchase_orders THEN
v_gl_drcrs := v_gl_drcrs || CAST('CR' AS TEXT);
ELSE
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
END IF;
END IF;
-- payment
v_gl_descriptions := v_gl_descriptions || CAST('Payment on account - Bill #' || v_bill_payment_id AS TEXT);
v_gl_account_ids := v_gl_account_ids || v_ap_account;
v_gl_amounts := v_gl_amounts || CAST(p_amount AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
-- prepare journal... transaction taxes
v_bill_total_ex_tax := p_amount;
FOR i IN array_lower(p_tax_id, 1)..array_upper(p_tax_id, 1) LOOP
SELECT INTO v_rec CASE WHEN position(shortname in coa.name) > 0 THEN 'Bill payment #' || v_bill_payment_id ELSE shortname || ' on bill payment #' || v_bill_payment_id END AS description, account_id FROM system.linked_account la, ledger.general_chart_of_accounts coa, system.transaction_tax tt WHERE la.account_id = coa.id AND la.transaction_tax_shortname = tt.shortname AND lower(la.transaction_type) = 'retail purchase' AND tt.id = CAST(p_tax_id[i] AS INT);
IF CAST(p_tax_amount[i] AS NUMERIC) > 0 THEN
v_gl_descriptions := v_gl_descriptions || v_rec.description;
v_gl_account_ids := v_gl_account_ids || CAST(v_rec.account_id AS TEXT);
v_gl_amounts := v_gl_amounts || CAST(p_tax_amount[i] AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
v_bill_total_ex_tax := v_bill_total_ex_tax - CAST(p_tax_amount[i] AS NUMERIC);
END IF;
END LOOP;
-- prepare journal... book expenses
FOR i IN array_lower(p_purchase_order_ids, 1)..array_upper(p_purchase_order_ids, 1) LOOP
SELECT INTO v_rec system.purchase_order_total_ex_tax(CAST(p_purchase_order_ids[i] AS BIGINT)), expense_account_id FROM system.purchase_order WHERE id = CAST(p_purchase_order_ids[i] AS BIGINT);
v_gl_descriptions := v_gl_descriptions || CAST('Purchase order #' || p_purchase_order_ids[i] AS TEXT);
v_gl_account_ids := v_gl_account_ids || CAST(v_rec.expense_account_id AS TEXT);
v_gl_amounts := v_gl_amounts || CAST(v_rec.purchase_order_total_ex_tax AS TEXT);
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
v_total_purchase_orders_ex_tax := v_total_purchase_orders_ex_tax + v_rec.purchase_order_total_ex_tax;
END LOOP;
-- adjustment
IF v_bill_total_ex_tax != v_total_purchase_orders_ex_tax THEN
v_gl_descriptions := v_gl_descriptions || CAST('Bill payment #' || v_bill_payment_id || COALESCE(' - ' || p_adjustment_comment, '') AS TEXT);
v_gl_account_ids := v_gl_account_ids || p_adjustment_expense_account;
v_gl_amounts := v_gl_amounts || CAST(ABS(v_bill_total_ex_tax - v_total_purchase_orders_ex_tax) AS TEXT);
IF v_bill_total_ex_tax > v_total_purchase_orders_ex_tax THEN
v_gl_drcrs := v_gl_drcrs || CAST('DR' AS TEXT);
ELSE
v_gl_drcrs := v_gl_drcrs || CAST('CR' AS TEXT);
END IF;
END IF;
-- prepare journal... AP ledger
SELECT INTO v_supplier_ac id FROM ledger.ap_chart_of_accounts WHERE name = '#supplier:' || p_supplier_id;
FOR i in array_lower(p_purchase_order_ids, 1)..array_upper(p_purchase_order_ids, 1) LOOP
SELECT INTO v_rec system.purchase_order_total(CAST(p_purchase_order_ids[i] AS BIGINT));
IF i = 1 THEN
v_sl_descriptions[1] := 'Purchase order #' || p_purchase_order_ids[i];
v_sl_account_ids[1] := CAST(v_supplier_ac AS TEXT);
v_sl_amounts[1] := CAST(v_rec.purchase_order_total AS TEXT);
v_sl_drcrs[1] := 'CR';
ELSE
v_sl_descriptions := v_sl_descriptions || CAST('Purchase order #' || p_purchase_order_ids[i] AS TEXT);
v_sl_account_ids := v_sl_account_ids || CAST(v_supplier_ac AS TEXT);
v_sl_amounts := v_sl_amounts || CAST(v_rec.purchase_order_total AS TEXT);
v_sl_drcrs := v_sl_drcrs || CAST('CR' AS TEXT);
END IF;
END LOOP;
-- adjustment
IF CAST(p_amount AS NUMERIC) != v_total_purchase_orders THEN
v_sl_descriptions := v_sl_descriptions || CAST('Bill payment #' || v_bill_payment_id || COALESCE(' - adjustment for ' || p_adjustment_comment, '') AS TEXT);
v_sl_account_ids := v_sl_account_ids || CAST(v_supplier_ac AS TEXT);
v_sl_amounts := v_sl_amounts || CAST(ABS(CAST(p_amount AS NUMERIC) - v_total_purchase_orders) AS TEXT);
IF CAST(p_amount AS NUMERIC) > v_total_purchase_orders THEN
v_sl_drcrs := v_sl_drcrs || CAST('CR' AS TEXT);
ELSE
v_sl_drcrs := v_sl_drcrs || CAST('DR' AS TEXT);
END IF;
END IF;
-- payment
v_sl_descriptions := v_sl_descriptions || CAST('Payment on account - Bill #' || v_bill_payment_id AS TEXT);
v_sl_account_ids := v_sl_account_ids || CAST(v_supplier_ac AS TEXT);
v_sl_amounts := v_sl_amounts || CAST(p_amount AS TEXT);
v_sl_drcrs := v_sl_drcrs || CAST('DR' AS TEXT);
-- create the journal and stamp its id onto the bill payment
SELECT INTO v_error create_ap_journal(v_gl_descriptions, v_gl_account_ids, v_gl_amounts, v_gl_drcrs, v_sl_descriptions, v_sl_account_ids, v_sl_amounts, v_sl_drcrs, TRUE);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
SELECT INTO v_journal_id currval('system.journal_id_seq');
UPDATE system.bill_payment SET journal_id = v_journal_id WHERE id = v_bill_payment_id;
RETURN 20300;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 20399;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION create_contact(
p_surname VARCHAR(30),
p_given_name VARCHAR(30),
p_company_name VARCHAR(30),
p_position VARCHAR(30),
p_line1 VARCHAR(50),
p_line2 VARCHAR(50),
p_suburb VARCHAR(20),
p_region VARCHAR(20),
p_code VARCHAR(10),
p_country VARCHAR(20),
p_location_id INT,
p_loc_phone VARCHAR(20),
p_loc_fax VARCHAR(20),
p_phone VARCHAR(100),
p_fax VARCHAR(100),
p_email VARCHAR(100),
p_mobile VARCHAR(100),
p_sms VARCHAR(100),
p_company_id INT,
p_location_name VARCHAR(10),
p_entity_type VARCHAR(30)) RETURNS INT AS $$
DECLARE
v_person_id INT :=null;
v_company_id INT :=null;
v_address_id INT :=null;
v_location_id INT :=null;
v_phone VARCHAR(20) :=null;
v_fax VARCHAR(20) :=null;
v_location_name VARCHAR(20) :=null;
v_relation_type VARCHAR(10) :='employee';
v_type VARCHAR(30) :=null;
v_company_name VARCHAR(30) :=null;
v_entity_id INT :=null;
v_relationship_id INT :=null;
v_phone_id INT :=NULL;
v_fax_id INT :=NULL;
v_email_id INT :=NULL;
v_mobile_id INT :=NULL;
v_sms_id INT :=NULL;
v_position_id INT :=NULL;
v_flag INT := 0;
BEGIN
---create person and get the person''s id
IF p_surname IS NOT NULL AND p_surname<>'' AND p_given_name IS NOT NULL AND p_given_name<>'' THEN
v_type :='person';
INSERT INTO system.entity(id,type,name,given_name) VALUES(DEFAULT,v_type,p_surname,p_given_name);
SELECT CURRVAL('system.entity_id_seq') INTO v_person_id;
ELSE
RAISE EXCEPTION 'Can not create person,error occurs';
END IF;
---get the company''s id(direct or create) and create the address and the location
IF p_location_id IS NOT NULL THEN
v_location_id := p_location_id;
SELECT entity_id INTO v_company_id FROM system.location WHERE id = v_location_id;
ELSIF p_company_id IS NOT NULL THEN
v_company_id := p_company_id;
IF p_location_id IS NOT NULL THEN
v_location_id := p_location_id;
ELSIF p_location_name IS NOT NULL AND p_location_name<>'' AND p_line1 IS NOT NULL AND p_line1<>'' AND p_suburb IS NOT NULL AND p_suburb<>'' AND p_region IS NOT NULL AND p_region<>'' AND p_code IS NOT NULL AND p_code<>'' AND p_country IS NOT NULL AND p_country<>'' THEN
INSERT INTO system.address(line1,line2,suburb,region,code,country) VALUES(p_line1,p_line2,p_suburb,p_region,p_code,p_country);
SELECT CURRVAL('system.address_id_seq') INTO v_address_id;
v_location_name := p_location_name;
v_phone := p_loc_phone;
v_fax := p_loc_fax;
INSERT INTO system.location(entity_id, address_id, name,phone,fax) VALUES (v_company_id,v_address_id,v_location_name,v_phone,v_fax);
SELECT CURRVAL('system.location_id_seq') INTO v_location_id;
ELSE
v_flag := 2;
END IF;
ELSIF p_company_name IS NOT NULL AND p_company_name<>'' THEN
v_type :=p_entity_type;
v_company_name :=p_company_name;
INSERT INTO system.entity(type,name) VALUES(v_type,v_company_name);
SELECT CURRVAL('system.entity_id_seq') INTO v_company_id;
IF p_location_name IS NOT NULL AND p_location_name<>'' AND p_line1 IS NOT NULL AND p_line1<>'' AND p_suburb IS NOT NULL AND p_suburb<>'' AND p_region IS NOT NULL AND p_region<>'' AND p_code IS NOT NULL AND p_code<>'' AND p_country IS NOT NULL AND p_country<>'' THEN
INSERT INTO system.address(line1,line2,suburb,region,code,country) VALUES(p_line1,p_line2,p_suburb,p_region,p_code,p_country);
SELECT CURRVAL('system.address_id_seq') INTO v_address_id;
v_location_name := p_location_name;
v_phone := p_loc_phone;
v_fax := p_loc_fax;
INSERT INTO system.location(entity_id, address_id, name,phone,fax) VALUES (v_company_id,v_address_id,v_location_name,v_phone,v_fax);
SELECT CURRVAL('system.location_id_seq') INTO v_location_id;
ELSE
v_flag := 2;
END IF;
ELSIF p_line1 IS NOT NULL AND p_line1<>'' AND p_suburb IS NOT NULL AND p_suburb<>'' AND p_region IS NOT NULL AND p_region<>'' AND p_code IS NOT NULL AND p_code<>'' AND p_country IS NOT NULL AND p_country<>'' THEN
INSERT INTO system.address(line1,line2,suburb,region,code,country) VALUES(p_line1,p_line2,p_suburb,p_region,p_code,p_country);
SELECT CURRVAL('system.address_id_seq') INTO v_address_id;
v_location_name := 'work';
INSERT INTO system.location(entity_id, address_id, name) VALUES (v_person_id,v_address_id,v_location_name);
SELECT CURRVAL('system.location_id_seq') INTO v_location_id;
ELSE
v_flag := 1;
END IF;
--create relationship(the v_company_id and the v_person_id both exists)
IF v_flag<>1 AND v_company_id IS NOT NULL AND v_person_id IS NOT NULL THEN
IF v_flag=0 THEN
INSERT INTO system.relationship(entity_id,rel_entity_id,type,location_id) VALUES(v_person_id,v_company_id,v_relation_type,v_location_id);
ELSIF v_flag=2 THEN
INSERT INTO system.relationship(entity_id,rel_entity_id,type) VALUES(v_person_id,v_company_id,v_relation_type);
END IF;
SELECT CURRVAL('system.relationship_id_seq') INTO v_relationship_id;
END IF;
--create contanct detail
IF p_phone IS NOT NULL AND p_phone<>'' THEN
IF p_loc_phone IS NOT NULL AND p_loc_phone<>'' THEN
IF p_phone <> p_loc_phone THEN
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'phone',p_phone);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_phone_id;
END IF;
ELSE
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'phone',p_phone);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_phone_id;
END IF;
ELSE
RAISE NOTICE 'Can not create phone,doing nothing';
END IF;
IF p_fax IS NOT NULL AND p_fax<>''THEN
IF p_loc_fax IS NOT NULL AND p_loc_fax<>'' THEN
IF p_fax <> p_loc_fax THEN
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'fax',p_fax);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_fax_id;
END IF;
ELSE
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'fax',p_fax);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_fax_id;
END IF;
ELSE
RAISE NOTICE 'Can not create fax,doing nothing';
END IF;
IF p_email IS NOT NULL AND p_email<>'' THEN
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'email', p_email);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_email_id;
ELSE
RAISE NOTICE 'Can not create email,doing nothing';
END IF;
IF p_mobile IS NOT NULL AND p_mobile<>''THEN
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'mobile',p_mobile);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_mobile_id;
ELSE
RAISE NOTICE 'Can not create mobile,doing nothing';
END IF;
IF p_sms IS NOT NULL AND p_sms<>'' THEN
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'sms',p_sms);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_sms_id;
ELSE
RAISE NOTICE 'Can not create sms,doing nothing';
END IF;
IF p_position IS NOT NULL AND p_position<>'' THEN
INSERT INTO system.contact_detail(entity_id,type,detail) VALUES(v_person_id,'position',p_position);
SELECT CURRVAL('system.contact_detail_id_seq') INTO v_position_id;
ELSE
RAISE NOTICE 'Can not create position,doing nothing';
END IF;
RETURN 50100;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN 50101;
WHEN OTHERS THEN
RETURN 50199;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION delete_contact(person_id integer)
RETURNS integer AS
$$
DECLARE
v_iscustomer boolean := false;
v_issupplier boolean := false;
v_success integer := 50300;
v_error integer := 50399;
BEGIN
select into v_iscustomer true from customer where entity_id = person_id;
select into v_issupplier true from supplier where entity_id = person_id;
if v_iscustomer or v_issupplier then
update system.entity set status = 'DELETED' where id = person_id;
else
delete from system.contact_detail where entity_id = person_id;
delete from system.location where entity_id = person_id;
delete from system.relationship where entity_id = person_id;
delete from system.entity where id = person_id;
end if;
return v_success;
EXCEPTION
WHEN query_canceled THEN
return v_error;
WHEN others THEN
return v_error;
END;
$$
LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION merge_locations(p_person1_id integer, p_person2_id integer, p_location1 text[], p_location2 text[])
RETURNS INTEGER AS
$$
DECLARE
v_location1 TEXT;
v_location2 TEXT;
v_success INT := 50500;
v_error INT := 50599;
BEGIN
IF p_location1 is not null then
v_location1 := array_to_string(p_location1,',');
EXECUTE 'delete from system.location where entity_id = '||p_person1_id||' and id not in ('||v_location1||')';
ELSE
EXECUTE 'delete from system.location where entity_id = '||p_person1_id;
END IF;
IF p_location2 is not null then
v_location2 := array_to_string(p_location2,',');
EXECUTE 'insert into system.location(entity_id,name,phone,fax,address_id,deactivated) select '||p_person1_id||',name,phone,fax,address_id,deactivated from system.location where id in ('||v_location2||')';
END IF;
RETURN v_success;
EXCEPTION
WHEN query_canceled THEN
RETURN v_error;
WHEN others THEN
RETURN v_error;
end
$$
LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION merge_contact(p_person1_id integer, p_person2_id integer, p_field_names text[], p_new_values text[], p_locations text[], p_original_page_load timestamp without time zone)
RETURNS integer AS
$$
DECLARE
v_person1 RECORD;
v_person2 RECORD;
v_field_names TEXT[];
v_new_values TEXT[];
v_relationship1 TEXT[];
v_relationship2 TEXT[];
v_location TEXT[];
v_locations1 TEXT[];
v_locations2 TEXT[];
v_keep_person_id INT;
v_merge_person_id INT;
v_contact_status TEXT;
v_edit_message INT;
v_delete_message INT;
v_flag INT := 1;
v_returnum INT;
v_success INT := 50400;
v_error INT := 50499;
BEGIN
SELECT INTO v_person1 * FROM contact_info WHERE person_id = p_person1_id;
SELECT INTO v_person2 * FROM contact_info WHERE person_id = p_person2_id;
IF v_person1.iscustomer OR v_person1.issupplier THEN
v_keep_person_id := p_person1_id;
v_merge_person_id := p_person2_id;
IF v_person2.iscustomer OR v_person2.issupplier THEN
SELECT INTO v_edit_message edit_contact(p_person1_id,'','',p_field_names,p_new_values,p_original_page_load);
v_contact_status := 'MERGED';
ELSE
SELECT INTO v_edit_message edit_contact(p_person1_id,'','',p_field_names,p_new_values,p_original_page_load);
v_contact_status := 'DELETED';
END IF;
ELSE
IF v_person2.iscustomer OR v_person2.issupplier THEN
v_keep_person_id := p_person2_id;
v_merge_person_id := p_person1_id;
UPDATE system.entity SET given_name=v_person1.given_name, name = v_person1.surname
WHERE id = p_person2_id;
SELECT INTO v_edit_message edit_contact(p_person2_id,'','',p_field_names,p_new_values,p_original_page_load);
v_contact_status := 'DELETED';
ELSE
v_keep_person_id := p_person1_id;
v_merge_person_id := p_person2_id;
SELECT INTO v_edit_message edit_contact(p_person1_id,'','',p_field_names,p_new_values,p_original_page_load);
v_contact_status := 'DELETED';
END IF;
END IF;
FOR i IN array_lower(p_locations,1)..array_upper(p_locations,1) LOOP
v_location := string_to_array(p_locations[i],'_');
IF v_location[1] = 'c' THEN
IF v_location[3] = v_keep_person_id::TEXT THEN
v_flag := v_flag + 2;
v_relationship1 := v_location;
ELSE
v_flag := v_flag + 4;
v_relationship2 := v_location;
END IF;
ELSE
IF v_location[3] = v_keep_person_id::TEXT THEN
v_locations1 := array_append(v_locations1,v_location[4]);
ELSE
v_locations2 := array_append(v_locations2,v_location[4]);
END IF;
END IF;
END LOOP;
SELECT INTO v_returnum merge_locations(v_keep_person_id,v_merge_person_id,v_locations1,v_locations2);
IF v_flag = 1 THEN
IF v_person1.person_id = v_keep_person_id AND v_person1.company_id IS NOT NULL THEN
DELETE FROM system.relationship WHERE entity_id = v_keep_person_id AND rel_entity_id = v_person1.company_id;
ELSIF v_person2.person_id = v_keep_person_id AND v_person2.company_id IS NOT NULL THEN
DELETE FROM system.relationship WHERE entity_id = v_keep_person_id AND rel_entity_id = v_person2.company_id;
END IF;
ELSIF v_flag = 5 THEN
IF v_person1.person_id = v_keep_person_id AND v_person1.company_id IS NOT NULL THEN
DELETE FROM system.relationship WHERE entity_id = v_keep_person_id AND rel_entity_id = v_person1.company_id;
ELSIF v_person2.person_id = v_keep_person_id AND v_person2.company_id IS NOT NULL THEN
DELETE FROM system.relationship WHERE entity_id = v_keep_person_id AND rel_entity_id = v_person2.company_id;
END IF;
EXECUTE 'INSERT INTO system.relationship(entity_id, rel_entity_id, type, location_id) SELECT '||v_keep_person_id||', rel_entity_id, type, location_id FROM system.relationship WHERE entity_id = '||v_merge_person_id||' AND rel_entity_id = '||v_relationship2[2];
ELSIF v_flag = 7 THEN
EXECUTE 'INSERT INTO system.location(entity_id,name,phone,fax,address_id,deactivated) SELECT '||v_keep_person_id||',name,phone,fax,address_id,deactivated FROM system.location WHERE id = '||v_relationship2[4];
END IF;
IF v_contact_status = 'MERGED' THEN
UPDATE system.entity SET status = 'MERGED' WHERE id = v_merge_person_id;
ELSIF v_contact_status = 'DELETED' THEN
SELECT INTO v_returnum delete_contact(v_merge_person_id);
END IF;
RETURN v_success;
END
$$
LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION system.safe_update(
p_table_name TEXT,
p_where_cond TEXT,
p_set_string TEXT,
p_original_page_load TIMESTAMP) RETURNS INT AS $func$
DECLARE
v_delimited_set_string TEXT;
v_single_col_strings TEXT[];
v_rec RECORD;
v_has_recent_update BOOLEAN := FALSE;
v_col_name TEXT;
v_col_clash BOOLEAN;
v_set_string TEXT := '';
v_cols_updated TEXT := '';
v_success_message INT := 70100;
BEGIN
v_delimited_set_string := regexp_replace(p_set_string, '([^'',]*)?(''[^'']*'')?,', E'\\1\\2\\~:~', 'g'); --changes all commas not inside single quotes into ~:~
v_single_col_strings := string_to_array(v_delimited_set_string, '~:~');
FOR i IN array_lower(v_single_col_strings, 1)..array_upper(v_single_col_strings, 1) LOOP
v_col_name := trim(split_part(v_single_col_strings[i], '=', 1));
FOR v_rec IN EXECUTE 'SELECT * FROM system.row_update_log WHERE where_cond = '||quote_literal(p_where_cond)||' AND updated > '''||CAST(p_original_page_load AS TEXT)||'''' LOOP
v_has_recent_update := TRUE;
v_col_clash := FALSE;
IF v_col_name = ANY (v_rec.cols_updated) THEN
v_col_clash := TRUE;
END IF;
END LOOP;
IF NOT v_col_clash THEN
v_set_string = trim(', ' from v_set_string||', '||v_single_col_strings[i]);
v_cols_updated := trim('~:~' from v_cols_updated||'~:~'||v_col_name);
END IF;
END LOOP;
IF v_set_string = '' AND v_has_recent_update THEN
RAISE EXCEPTION '70101';
ELSIF v_set_string = '' THEN
v_set_string := p_set_string;
FOR i IN array_lower(v_single_col_strings, 1)..array_upper(v_single_col_strings, 1) LOOP
v_col_name := trim(split_part(v_single_col_strings[i], '=', 1));
v_cols_updated := trim('~:~' from v_cols_updated||'~:~'||v_col_name);
END LOOP;
ELSIF array_upper(v_single_col_strings, 1) != array_upper(string_to_array(v_cols_updated, '~:~'), 1) THEN
v_success_message := 70150;
END IF;
EXECUTE $$UPDATE $$||p_table_name||$$ SET $$||v_set_string||$$ WHERE $$||p_where_cond;
IF EXISTS (SELECT * FROM system.row_update_log WHERE table_name=p_table_name AND where_cond=p_where_cond) THEN
UPDATE system.row_update_log SET updated='NOW' WHERE table_name=p_table_name AND where_cond=p_where_cond;
ELSE
INSERT INTO system.row_update_log VALUES (p_table_name, p_where_cond, string_to_array(v_cols_updated, '~:~'), 'NOW');
END IF;
RETURN v_success_message;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN CAST(SQLERRM AS INT);
WHEN OTHERS THEN
RETURN 70199;
END;
$func$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION system.array_index (
p_array TEXT[],
p_search_string TEXT) RETURNS INT AS $$
DECLARE
array_string TEXT;
v_part_1 TEXT;
v_result INT;
BEGIN
array_string := array_to_string(p_array, '~delim~');
IF position(p_search_string in array_string) = 0 THEN
RETURN 0;
END IF;
v_part_1 := split_part(array_string, p_search_string, 1) || 'some terminating text';
v_result := array_upper(string_to_array(v_part_1, '~delim~'), 1);
RETURN v_result;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION edit_contact (
p_person_id INT,
p_surname TEXT,
p_given_name TEXT,
p_field_names TEXT[],
p_new_values TEXT[],
p_original_page_load TIMESTAMP) RETURNS INT AS $$
DECLARE
v_company_id INT;
v_address_id INT;
v_line2 TEXT;
v_location_type RECORD;
v_location_phone TEXT;
v_location_fax TEXT;
v_location_id INT;
v_old_location_id INT;
v_relationship_id INT;
v_detail_fields TEXT[];
v_new_value TEXT;
v_current_detail RECORD;
v_error INT;
v_success_message INT := 50200;
v_type VARCHAR(30);
BEGIN
-- update customer name if necessary
IF p_surname IS NOT NULL AND p_surname<>'' AND p_given_name IS NOT NULL AND p_given_name <>'' THEN
SELECT INTO v_error system.safe_update('system.entity', 'id = ' || p_person_id , 'name = ''' || p_surname || ''',given_name='''|| p_given_name ||'''', p_original_page_load);
IF v_error % 100 != 0 THEN
IF v_error % 50 != 0 THEN
RAISE EXCEPTION 'called function returned error';
ELSE
v_success_message := v_error;
END IF;
END IF;
END IF;
-- update contact details if necessary
v_detail_fields = '{position,phone,fax,mobile,email,sms}';
FOR i IN array_lower(v_detail_fields, 1)..array_upper(v_detail_fields, 1) LOOP
IF v_detail_fields[i] = ANY (p_field_names) THEN
v_new_value := p_new_values[system.array_index(p_field_names, v_detail_fields[i])];
SELECT INTO v_current_detail detail FROM system.contact_detail WHERE entity_id = p_person_id AND type = v_detail_fields[i];
IF NOT FOUND THEN
INSERT INTO system.contact_detail VALUES (DEFAULT, p_person_id, v_detail_fields[i], v_new_value);
ELSE
SELECT INTO v_error system.safe_update('system.contact_detail', 'entity_id = ' || p_person_id || ' AND type = ''' || v_detail_fields[i] || '''', 'detail = ''' || TRIM(v_new_value) || '''', p_original_page_load);
IF v_error % 100 != 0 THEN
IF v_error % 50 != 0 THEN
RAISE EXCEPTION 'called function returned error';
ELSE
v_success_message := v_error;
END IF;
END IF;
END IF;
END IF;
END LOOP;
-- update alt_location details (work, home, postal_address, etc) if necessary
FOR v_location_type IN SELECT * FROM system.sys_code WHERE code_id = 'alt_location_type' LOOP
IF v_location_type.code_value || '_line1' = ANY (p_field_names) THEN
IF v_location_type.code_value || '_phone' = ANY (p_field_names) THEN
v_location_phone := p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_phone')];
ELSE
v_location_phone := NULL;
END IF;
IF v_location_type.code_value || '_fax' = ANY (p_field_names) THEN
v_location_fax := p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_fax')];
ELSE
v_location_fax := NULL;
END IF;
IF v_location_type.code_value || '_line2' = ANY (p_field_names) THEN
v_line2 := p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_line2')];
ELSE
v_line2 := NULL;
END IF;
SELECT INTO v_address_id nextval('system.address_id_seq');
INSERT INTO system.address VALUES (v_address_id, p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_line1')], v_line2, p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_suburb')], p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_region')], p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_code')], p_new_values[system.array_index(p_field_names, v_location_type.code_value || '_country')]);
SELECT INTO v_location_id nextval('system.location_id_seq');
INSERT INTO system.location (id, entity_id, name, phone, fax, address_id) VALUES (v_location_id, p_person_id, v_location_type.code_value, v_location_phone, v_location_fax, v_address_id);
--tidy up the old location details
SELECT INTO v_old_location_id id FROM system.location WHERE entity_id = p_person_id AND name = v_location_type.code_value AND deactivated IS NULL AND id != v_location_id;
SELECT INTO v_error system.safe_update('system.location', 'id = ' || v_old_location_id, 'deactivated = ''NOW''', p_original_page_load);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
-- re-initialise v_location_id to avoid triggering a bogus relationship update
v_location_id := NULL;
END IF;
END LOOP;
-- add new alt_location details if necessary
IF 'alt_location_type' = ANY (p_field_names) THEN
IF 'alt_location_phone' = ANY (p_field_names) THEN
v_location_phone := p_new_values[system.array_index(p_field_names, 'alt_location_phone')];
ELSE
v_location_phone := NULL;
END IF;
IF 'location_fax' = ANY (p_field_names) THEN
v_location_fax := p_new_values[system.array_index(p_field_names, 'alt_location_fax')];
ELSE
v_location_fax := NULL;
END IF;
IF 'alt_location_line2' = ANY (p_field_names) THEN
v_line2 := p_new_values[system.array_index(p_field_names, 'alt_location_line2')];
ELSE
v_line2 := NULL;
END IF;
SELECT INTO v_address_id nextval('system.address_id_seq');
INSERT INTO system.address VALUES (v_address_id, p_new_values[system.array_index(p_field_names, 'alt_location_line1')], v_line2, p_new_values[system.array_index(p_field_names, 'alt_location_suburb')], p_new_values[system.array_index(p_field_names, 'alt_location_region')], p_new_values[system.array_index(p_field_names, 'alt_location_code')], p_new_values[system.array_index(p_field_names, 'alt_location_country')]);
SELECT INTO v_location_id nextval('system.location_id_seq');
INSERT INTO system.location (id, entity_id, name, phone, fax, address_id) VALUES (v_location_id, p_person_id, p_new_values[system.array_index(p_field_names, 'alt_location_type')], v_location_phone, v_location_fax, v_address_id);
-- re-initialise v_location_id to avoid triggering a bogus relationship update
v_location_id := NULL;
END IF;
-- add company if necessary
v_type := 'company';
IF 'entity_type' = ANY(p_field_names) THEN
v_type := p_new_values[system.array_index(p_field_names, 'entity_type')];
END IF;
IF 'company_name' = ANY (p_field_names) THEN
SELECT INTO v_company_id nextval('system.entity_id_seq');
INSERT INTO system.entity (id, type, name) VALUES (v_company_id, v_type, p_new_values[system.array_index(p_field_names, 'company_name')]);
END IF;
IF v_company_id IS NULL THEN
IF 'company_id' = ANY (p_field_names) THEN
v_company_id := p_new_values[system.array_index(p_field_names, 'company_id')];
END IF;
END IF;
-- add company location and address if necessary
IF 'location_name' = ANY (p_field_names) THEN
IF 'location_phone' = ANY (p_field_names) THEN
v_location_phone := p_new_values[system.array_index(p_field_names, 'location_phone')];
END IF;
IF 'location_fax' = ANY (p_field_names) THEN
v_location_fax := p_new_values[system.array_index(p_field_names, 'location_fax')];
END IF;
IF 'line2' = ANY (p_field_names) THEN
v_line2 := p_new_values[system.array_index(p_field_names, 'line2')];
END IF;
SELECT INTO v_address_id nextval('system.address_id_seq');
INSERT INTO system.address VALUES (v_address_id, p_new_values[system.array_index(p_field_names, 'line1')], v_line2, p_new_values[system.array_index(p_field_names, 'suburb')], p_new_values[system.array_index(p_field_names, 'region')], p_new_values[system.array_index(p_field_names, 'code')], p_new_values[system.array_index(p_field_names, 'country')]);
SELECT INTO v_location_id nextval('system.location_id_seq');
INSERT INTO system.location (id, entity_id, name, phone, fax, address_id) VALUES (v_location_id, v_company_id, p_new_values[system.array_index(p_field_names, 'location_name')], v_location_phone, v_location_fax, v_address_id);
END IF;
-- update or add relationship if necessary
IF v_location_id IS NULL AND 'location_id' = ANY (p_field_names) THEN
v_location_id := p_new_values[system.array_index(p_field_names, 'location_id')];
END IF;
IF v_location_id IS NOT NULL THEN
IF v_company_id IS NULL THEN
SELECT INTO v_company_id entity_id FROM system.location WHERE id = v_location_id;
END IF;
--obsolete the work location if it exists
SELECT INTO v_old_location_id id FROM system.location WHERE entity_id = p_person_id AND name = 'work' AND deactivated IS NULL;
IF FOUND THEN
SELECT INTO v_error system.safe_update('system.location', 'id = ' || v_old_location_id, 'deactivated = ''NOW''', p_original_page_load);
IF v_error % 100 != 0 THEN
RAISE EXCEPTION 'called function returned error';
END IF;
END IF;
END IF;
IF v_company_id IS NOT NULL THEN
SELECT INTO v_relationship_id id FROM system.relationship WHERE entity_id = p_person_id AND type = 'employee';
IF v_relationship_id IS NOT NULL THEN
IF v_location_id IS NULL THEN
SELECT INTO v_error system.safe_update('system.relationship', 'id = ' || v_relationship_id, 'rel_entity_id = ' || COALESCE(CAST(v_company_id AS TEXT), 'comp'), p_original_page_load);
ELSE
SELECT INTO v_error system.safe_update('system.relationship', 'id = ' || v_relationship_id, 'rel_entity_id = ' || COALESCE(CAST(v_company_id AS TEXT), 'comp') || ', location_id = ' || COALESCE(CAST(v_location_id AS TEXT), 'loc'), p_original_page_load);
END IF;
IF v_error % 100 != 0 THEN
IF v_error % 50 != 0 THEN
RAISE EXCEPTION 'called function returned error';
ELSE
v_success_message := v_error;
END IF;
END IF;
ELSE
SELECT INTO v_relationship_id nextval('system.relationship_id_seq');
INSERT INTO system.relationship (id, entity_id, rel_entity_id, type, location_id) VALUES (v_relationship_id, p_person_id, v_company_id, 'employee', v_location_id);
END IF;
END IF;
RETURN v_success_message;
EXCEPTION
WHEN RAISE_EXCEPTION THEN
RETURN v_error;
WHEN OTHERS THEN
RETURN 50299;
END;
$$ LANGUAGE plpgsql;
RETURN 0;
END;
$init_db$ LANGUAGE plpgsql;""" }
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
admin_action_map = {
'get_user_id': ''' select nextval('system.user_id_seq') ''',
'get_grant_id': ''' select nextval('system.grant_id_seq') ''',
'update_user_passwd': ''' update system.user set encrypted_password = '%s' where name = '%s' ''',
'get_person_name': '''select id, given_name||' '||name as personname from system.entity where type='person' ''',
'get_role': '''select id,name from system.role''',
'get_group': "SELECT id,name FROM system.group WHERE name<>'root'",
'get_user_info': "select name,encrypted_password from system.user where name = '%s'",
'create_db_user': ''' create user %s with login password '%s' ''',
'grant_db_user': ''' grant %s to %s ''',
'get_user_role': ''' select r.id,r.name from system.grant g,system.user u,system.role r where g.user_id = u.id and r.id = g.role_id and u.name = '%s' ''',
'get_sys_code': ''' select code_value,code_desc from system.sys_code where code_id = '%s' ''',
'get_country_code': '''SELECT * FROM system.iso_country_code WHERE name = UPPER('%s') OR UPPER('%s') = ANY(alias)''',
#'get_errors': "SELECT * FROM system.error ORDER BY id %s",
#'get_error_by_id': "SELECT * FROM system.error WHERE id = %s",
#'update_error': "UPDATE system.error SET name = '%s',description = '%s' WHERE id=%s",
#'delete_error': "DELETE FROM system.error WHERE id=%s",
}
app_admin_action_map = {
#-------------------------------------liang
'get_users': "SELECT * FROM system.user WHERE is_active='TRUE' ORDER BY id %s",
'get_company_roles': "SELECT * FROM system.grant ORDER BY user_id,company_id,role_id",
'app_get_user_company_by_id': "SELECT DISTINCT b.id,b.name FROM system.grant a, system.company b, system.user c WHERE a.user_id = c.id and a.company_id = b.id and c.id = %s",
'app_get_users_of_company': "SELECT a.*,b.name AS user_name,c.name AS group_name FROM system.affiliation a ,system.user b,system.group c WHERE a.user_id=b.id AND a.group_id=c.id AND a.company_id=%s ORDER BY a.user_id %s",
'app_get_user_affiliation':"SELECT a.*,b.name AS user_name,c.name AS company_name,d.name AS group_name FROM system.affiliation a LEFT JOIN system.user b ON a.user_id = b.id LEFT JOIN system.company c ON a.company_id = c.id LEFT JOIN system.group d ON a.group_id = d.id WHERE user_id=%d AND company_id=%d AND group_id=%d",
'delete_grants': "DELETE FROM system.grant WHERE user_id=%s AND company_id=%s",
'insert_grants': "INSERT INTO system.grant VALUES(%s,%s,%s)",
'delete_group': "DELETE FROM system.group WHERE id=%s",
'get_all_grant': "SELECT * FROM system.grant",
'delete_grant_of_group':"DELETE FROM system.grant WHERE group_id=%s",
'get_group_details': "SELECT * FROM system.group WHERE id=%s",
'get_group_grant_details': "SELECT group_id,role_id,ro.name AS role_name FROM system.grant gt LEFT JOIN system.role ro ON gt.role_id=ro.id WHERE gt.group_id=%s",
'check_group_grant': "SELECT DISTINCT id,count(role_id) AS grant_role FROM system.group gp LEFT JOIN system.grant gt ON gt.group_id=gp.id GROUP BY id",
'check_user_grant': "SELECT DISTINCT id,count(company_id) AS grant_role FROM system.user ur LEFT JOIN system.affiliation an ON ur.id=an.user_id GROUP BY id",
'get_user_rights': "SELECT a.user_id,u.name AS user_name,a.company_id,c.name AS company_name,a.group_id,g.name AS group_name FROM system.affiliation a LEFT JOIN system.user u ON a.user_id=u.id LEFT JOIN system.company c ON a.company_id=c.id LEFT JOIN system.group g ON a.group_id=g.id WHERE a.company_id<>0 %s and a.user_id not in (select id from system.user where is_active='FALSE') ORDER BY a.user_id,a.company_id,a.group_id %s",
'revoke_user': "DELETE FROM system.affiliation WHERE user_id=%d AND company_id=%d AND group_id=%d",
'delete_user': "UPDATE system.user SET is_active='FALSE' WHERE id=%s",
'remove_right_on_user': "DELETE FROM system.affiliation WHERE user_id=%s",
'edit_user_group':"UPDATE system.affiliation SET group_id=%s WHERE user_id=%s AND company_id=%s AND group_id=%s",
'get_user_group':"SELECT company_id,group_id FROM system.affiliation WHERE user_id=%s",
'change_skin':"UPDATE system.user SET skin='%s' WHERE id=%s",
#--------------------------liang
'app_get_user_role': ''' select c.name as companyname,d.name as rolename,c.db_conn_str from system.grant a, system.user b, system.company c, system.role d where a.user_id = b.id and a.company_id = c.id and a.role_id = d.id and b.name = '%s' and a.company_id = %s ''',
'app_get_user_role_cnd': ''' select b.name as username, c.name as companyname,d.name as rolename,c.db_conn_str,c.id from system.grant a, system.user b, system.company c, system.role d where a.user_id = b.id and a.company_id = c.id and a.role_id = d.id %s order by b.name,c.name,d.name limit %d offset %d ''',
'app_get_user_company': ''' select distinct b.id as company_id,b.name as company_name,b.db_conn_str from system.grant a, system.company b, system.user c where a.user_id = c.id and a.company_id = b.id and c.name = '%s' ''',
'app_get_user_info': ''' select * from system.user where name = '%s' ''' ,
'app_verify_user_passwd': ''' select name from system.user where name = '%s' and passwd = crypt('%s', passwd) ''',
'app_get_company_info': ''' select a.*,b.name as top_company from system.company a left join system.company b on a.top_id = b.id where a.id = %s order by id ''',
'app_get_all_company': ''' select * from system.company ''',
'app_get_company_entity_id': "SELECT code_value FROM system.sys_code WHERE code_id='this_entity_id'",
'app_get_company_address_id': "SELECT code_value FROM system.sys_code WHERE code_id='this_address_id'",
'app_get_abn_info': "SELECT detail FROM system.contact_detail WHERE entity_id=%s AND type='abn'",
'app_get_all_others_company': ''' select * from system.company where id <> %s''',
'app_is_company_exist': ''' select * from system.company where name = '%s' ''',
'app_get_id': ''' select nextval('%s') ''',
'app_update_user_passwd': ''' update system.user set passwd = crypt('%s',gen_salt('bf')) where name = '%s' ''',
'app_get_company_view': ''' select a.id,a.name,a.db_conn_str,b.name as top_company from system.company a left join system.company b on a.top_id = b.id order by id ''',
#-----------------------------rachel
'get_company_group': '''select company_id, group_id from system.affiliation as af, system.user as us where us.name='%s' and af.user_id=us.id order by user_id %s''',
'user_is_root': '''select MIN(id)=%d as is_root from system.user''',
## 'group_is_root': '''select lower(name)='root' as is_root from system.group where id = %d''', #hard code 'root'
'get_company_name': '''select name,logo_url,db_name from system.company where id = %d''',
'get_role_by_group': '''select ro.id,name from system.role as ro , system.grant as gr where gr.group_id = %d and ro.id = gr.role_id order by ro.id''',
'get_affiliation_info': '''select * from system.user as us, system.affiliation as af where us.name='%s' and af.user_id=us.id and af.company_id=%d and af.group_id=%d''',
'get_company_by_id': '''select id,name,db_ip,db_name,db_user,db_passwd, top_id ,logo_url from system.company where id=%d''',
'get_group_by_name': '''select * from system.group where name='%s' ''',
'get_all_company': '''select * from system.company order by id''',
'get_all_group': "select * from system.group order by id %s",
'get_all_role': '''select * from system.role order by id''',
'get_group_id': '''select nextval('system.group_id_seq') as id''',
'get_company_id': '''select nextval('system.company_id_seq') as id ''',
'get_system_user_id': '''select nextval('system.user_id_seq') as id''',
'insert_user': '''insert into system.user (id, name, passwd) values (%d, '%s', crypt('%s', gen_salt('bf'))) ''',
'insert_group': '''insert into system.group (id, name) values (%d, '%s')''',
'config_grant': '''insert into system.grant (group_id, role_id) values (%d, %d)''',
'assign_user': '''insert into system.affiliation (user_id, company_id, group_id) values (%d, %d, %d)''',
'active_user': "UPDATE system.user SET is_active='true',passwd=crypt('%s',gen_salt('bf')) WHERE id=%s",
'user_have_right': "SELECT * FROM system.affiliation WHERE user_id=%d AND company_id=%d",
'get_iso_country_code': '''select * from system.sys_code where code_id = 'iso_country_code' ''',
'get_tax_page_md5': '''select * from system.sys_code where code_id = 'tax_page_md5' ''',
'update_tax_page_md5': '''update system.sys_code set code_value='%s' where code_id='tax_page_md5' ''',
'get_current_tax_page_id': '''select MAX(tax_page_id) as current_tax_page_id from system.transaction_tax''',
'get_default_inv_terms': "SELECT * FROM system.sys_code WHERE code_id='default_inv_terms'",
'update_obsolete_tax': '''update system.transaction_tax set obsolete = 'NOW' where obsolete IS NULL AND tax_page_id != 0''',
'obsolete_user_input_tax': '''UPDATE system.transaction_tax SET obsolete = 'NOW' WHERE tax_page_id = 0 AND obsolete IS NULL AND shortname IN (SELECT shortname FROM (SELECT COUNT(shortname) AS count, shortname FROM system.transaction_tax WHERE obsolete IS NULL GROUP BY shortname) AS foo WHERE count != 1)''',
'insert_transaction_tax': '''insert into system.transaction_tax (shortname, name, tax_page_id, rate, included_in_unit_price_default, track_on_purchases) values ('%s', '%s', %d, %s, '%s', '%s')''',
'get_all_entities_not_sales_agent': '''SELECT id, type, CASE WHEN given_name IS NULL THEN name ELSE given_name||' '||name END AS name FROM system.entity WHERE type = '%s' AND id NOT IN (SELECT entity_id FROM sales_agent)''',
'insert_sales_agent': '''INSERT INTO sales_agent VALUES (DEFAULT, %d, %d)''',
'update_user_portal_order':"UPDATE system.user SET role_id='%s' WHERE id=%d",
}
crm_action_map = {
'get_place_of_business_info1': "SELECT * FROM system.company_location_info WHERE phone LIKE '%s%%'",
'get_place_of_business_info2': "SELECT * FROM system.company_location_info WHERE fax LIKE '%s%%'",
'get_place_of_business_info3': "SELECT * FROM system.company_location_info WHERE company_id = %s",
#'get_companies': "SELECT id, name FROM system.company ORDER BY name",
'get_companies': "SELECT id, name FROM system.entity WHERE type<>'person' ORDER BY name",
'get_c_entity_types': "SELECT * from system.entity_type WHERE id<>'person'",
#'get_pop_details': "SELECT phone, fax FROM system.place_of_business WHERE id=%s",
'get_pop_details': "SELECT phone, fax FROM system.location WHERE id=%s",
'insert_entity': "INSERT INTO system.entity (type) VALUES ('%s')",
'insert_person2': "INSERT INTO system.person (entity_id, place_of_business_id, %s) VALUES (%s, %s, '%s')",
'insert_company2': "INSERT INTO system.company (entity_id, name) VALUES (%s, '%s')",
#'get_company_id4': "SELECT id FROM system.company WHERE oid=%s",
#'get_pop_id1': "SELECT id FROM system.place_of_business WHERE oid=%s",
#'get_pop_id2': "SELECT id FROM system.place_of_business WHERE company_id = %s AND name = 'unknown'",
'get_pop_id2': "SELECT id FROM system.location WHERE entity_id = %s",
#'get_pop_details2': "SELECT phone, fax, name FROM system.place_of_business WHERE id=%s",
'get_pop_details2': "SELECT phone, fax, name FROM system.location WHERE id=%s",
'insert_person3': "INSERT INTO system.person (entity_id, %s) VALUES (%s,'', '%s')",
'insert_alt_location': "INSERT INTO system.alt_location (person_id, type, %s) VALUES (%s, 'work', '%s')",
#'get_person_id4': "SELECT id FROM system.person WHERE oid=%s",
#'get_company_info': "SELECT id,name FROM customer_info WHERE company_id=%s",
'get_customer_company_info': "SELECT id,name FROM customer_info WHERE company_id=%s",
#'get_company_info2': "SELECT name FROM system.company WHERE entity_id=%s",
'get_company_info2': "SELECT name FROM system.entity WHERE id=%s",
#'get_pop_info1': "SELECT * FROM system.place_of_business WHERE company_id=%s AND name <> 'unknown' LIMIT 2 OFFSET %s",
'get_pop_info1': "SELECT * FROM system.location WHERE entity_id=%s",
'get_address_info': "SELECT * FROM system.address WHERE id='%s'",
'get_person_id_list': "SELECT person_id FROM contact_info where company_id=%s",
'get_person_name2': "SELECT e.given_name||' '||e.name as person_name FROM system.entity e WHERE type='person' AND id=%s",
'get_log_entry': "SELECT entity_id, comment, filename, action FROM contact_log WHERE id=%s",
'get_customer_id2': "SELECT id FROM customer_info WHERE person_id=%s",
#'insert_contact_log': "INSERT INTO contact_log (id, person_id, comment, filename, action) VALUES (%i, %i, %s, %s, %s)",
'insert_contact_log': "INSERT INTO contact_log (id, entity_id, comment, filename, action) VALUES (%i, %i, '%s', '%s', '%s')",
'update_contact_log1': "UPDATE contact_log SET comment = '%s', action = '%s', closed = 'today' WHERE id = %s",
'update_contact_log2': "UPDATE contact_log SET comment = '%s', filename = '%s', action = '%s', closed = 'today' WHERE id = %s",
'update_contact_log3': "UPDATE contact_log SET comment = '%s', action = '%s' WHERE id = %s",
'update_contact_log4': "UPDATE contact_log SET comment = '%s', filename = '%s', action = '%s' WHERE id = %s",
#'get_contact_info': "SELECT * FROM contact_info WHERE person_id=%s",
'get_contact_info': "SELECT * FROM contact_info WHERE person_id=%s AND company_id %s",
#'get_person_info': "SELECT * FROM system.person WHERE id=%s",
'get_person_info': "SELECT e.id,e.given_name,e.name AS surname,c.position,c.email,c.mobile,c.sms FROM system.entity e,system.abn_info c WHERE e.id = %s AND e.id = c.entity_id",
'get_person_contact_info': "SELECT * FROM system.contact_detail WHERE entity_id = %s",
#'get_work_details': "SELECT * from system.alt_location WHERE type = 'work' AND person_id=%s",
'get_work_details': "SELECT * from system.location WHERE name = 'work' AND entity_id=%s AND deactivated IS NULL",
'get_pop_info2': "SELECT * FROM system.company_location_info WHERE id=%s",
'get_alt_locations': "SELECT * FROM system.person_location_info WHERE type NOT IN ('place of business', 'work') AND person_id=%s",
'get_locations_by_name': "SELECT * FROM system.person_location_info WHERE type='%s' AND person_id=%s",
#'get_alt_locations': "SELECT * FROM system.location WHERE name <> 'work' AND entity_id=%s",
#'get_locations_by_name': "SELECT * FROM system.location WHERE name='%s' AND entity_id=%s",
'get_contact_log_id': "SELECT NEXTVAL('contact_log_id_seq') as num",
'create_contact': "SELECT create_contact('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,'%s','%s','%s','%s','%s','%s','%s',%s,'%s','%s')",
'get_entity_by_id': "SELECT * FROM system.entity WHERE id = %s",
'edit_other_location': "SELECT edit_other_location(%s,'%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,%s,'%s')",
'create_other_location': "SELECT edit_other_location(%s,'%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,%s,'%s')",
'get_exist_alt_location_types': "SELECT DISTINCT name FROM system.location WHERE entity_id = %s",
'get_relation_ship': "SELECT * FROM system.relationship WHERE entity_id=%s AND rel_entity_id=%s",
'get_old_address_info': "SELECT * FROM system.address WHERE id=%s AND ver=%s",
'get_persons1': "select person_id, given_name, surname from contact_info where person_id <> %s",
'get_persons2': "select * from contact_info where person_id = %s",
'get_location_id': "select location_id from system.relationship where entity_id = %s and rel_entity_id = %s",
'get_person_locations1': "select id, entity_id, name, address_id, 'p_0'||'_'||%s||'_'||id as combination, ' ' as checked from system.location where entity_id = %s and deactivated is null" ,
'get_person_locations2': "select id, entity_id, name, address_id, 'c_'||entity_id||'_'||%s||'_'||id as combination, ' ' as checked from system.location where id = %s and deactivated is null union all select id, entity_id, name, address_id, 'p_0'||'_'||%s||'_'||id as combination, ' ' as checked from system.location where entity_id = %s and deactivated is null",
'get_person_locations3': "select id, entity_id, name, address_id, 'c_'||entity_id||'_'||%s||'_'||id as combination, ' ' as checked from system.location where id = %s and deactivated is null %s union all select id, entity_id, name, address_id, 'p_0'||'_'||%s||'_'||id as combination, ' ' as checked from system.location where entity_id = %s and deactivated is null",
}
finance_action_map = {
'get_link_candidates': "SELECT * FROM system.business_objects",
'get_link_objects': "SELECT * FROM system.%s",
'get_accounts': "SELECT id, name, bal('%s'||'_'||id) as s_id FROM ledger.%s_info",
'get_account_type': "SELECT * FROM system.account_type",
'get_same_account': "SELECT id,name FROM ledger.general_chart_of_accounts WHERE id='%s' OR name='%s'",
'get_same_type_accounts': "SELECT * FROM ledger.general_chart_of_accounts WHERE account_type_id = '%s'",
'get_same_type_taxes': "SELECT t.* FROM system.linked_account AS l, system.transaction_tax AS t WHERE l.transaction_type = '%s' AND t.shortname = l.transaction_tax_shortname AND t.obsolete IS NULL",
'insert_account': "INSERT INTO ledger.general_chart_of_accounts (id, name,account_type_id,shortname) values ('%s', '%s', '%s','%s')",
'default_tax_is_null': "SELECT code_value='' AS bool FROM system.sys_code WHERE code_id = 'default_tax'",
'update_default_tax': "UPDATE system.sys_code SET code_value = (SELECT shortname FROM system.transaction_tax ORDER BY id LIMIT 1) WHERE code_id = 'default_tax'",
'get_default_tax': "SELECT id AS default_tax_id, shortname, rate FROM system.transaction_tax WHERE shortname = (SELECT code_value FROM system.sys_code WHERE code_id = 'default_tax') AND obsolete IS NULL",
'get_tax': "SELECT * FROM system.transaction_tax WHERE obsolete IS NULL ORDER BY id",
'get_ptax': "SELECT tt.*,case when dt.code_value IS NULL then 'false' else 'true' end as default_flag,case when dt.code_value IS NULL then 'none' else 'block' end as isdefault FROM (select a.* from system.transaction_tax a,system.linked_account b where a.shortname=b.transaction_tax_shortname and a.obsolete is null and b.transaction_type='retail purchase') as tt left join (select * from system.sys_code where code_id = 'default_tax') dt on tt.shortname = dt.code_value",
'get_invoicer': "SELECT name, abn, line1, line2, suburb, region, code, country FROM system.abn_info c, system.entity e, system.address a, (SELECT CAST(ent.code_value AS INT) AS id, CAST(add.code_value AS INT) AS address_id FROM system.sys_code ent, system.sys_code add WHERE ent.code_id = 'this_entity_id' AND add.code_id = 'this_address_id') AS this WHERE c.entity_id = e.id AND e.id = this.id AND this.address_id = a.id",
'get_buyer': "SELECT name, abn, line1, line2, suburb, region, code, country FROM system.abn_info c, system.entity e, system.address a, (SELECT CAST(ent.code_value AS INT) AS id, CAST(add.code_value AS INT) AS address_id FROM system.sys_code ent, system.sys_code add WHERE ent.code_id = 'this_entity_id' AND add.code_id = 'this_address_id') AS this WHERE c.entity_id = e.id AND e.id = this.id AND this.address_id = a.id",
'get_invoicer_id': "SELECT NEXTVAL('system.invoice_id_seq') AS invoice_id",
'get_purchase_order_id': "SELECT NEXTVAL('system.purchase_order_id_seq') AS purchase_order_id",
'get_curr_invoicer_id': "SELECT CURRVAL('system.invoice_id_seq') AS invoice_id",
'get_invoices1': "SELECT * FROM system.invoice_info WHERE id = %d",
'get_invoices2': "SELECT * FROM system.invoice_info WHERE id >= %d",
'get_invoices3': "SELECT * FROM system.invoice_info WHERE id IN %s",
'get_purchase_orders1': "SELECT * FROM system.purchase_order_info WHERE id = %d",
'get_purchase_orders2': "SELECT * FROM system.purchase_order_info WHERE id >= %d",
'get_invoice_items_info': "SELECT * FROM system.invoice_item_info WHERE invoice_id = %d",
'get_purchase_order_items_info': "SELECT * FROM system.purchase_order_item_info WHERE purchase_order_id = %d",
'get_items': "SELECT ji.id, description, amount FROM system.ar_journal_item ji, ledger.ar_chart_of_accounts coa WHERE ji.account_id = coa.id AND ji.drcr = 'DR' AND ji.id NOT IN (SELECT journal_item_id FROM system.invoice_item) AND link_object_id(coa.name)=%s",
'get_remit_msg': "SELECT code_desc FROM system.sys_code WHERE code_id = 'remit_msg' ORDER BY code_value",
'get_candidates': "SELECT * FROM ledger.general_chart_of_accounts WHERE subsidiary_shortname IS NULL OR subsidiary_shortname=''",
'get_coa': "SELECT * FROM ledger.general_chart_of_accounts WHERE subsidiary_shortname IS NULL OR subsidiary_shortname='' ORDER BY id",
'get_coa2': "SELECT * FROM ledger.general_chart_of_accounts WHERE subsidiary_shortname = '%s'",
#'get_baccounts': "SELECT * FROM ledger.general_chart_of_accounts WHERE account_type_id = 'EXPENSE' AND subsidiary_shortname IS NULL",
'get_equip_account': "SELECT * FROM system.sys_code WHERE code_id = 'special_ac_equip'",
'get_scoa': "SELECT * FROM ledger.%s_info",
'get_accounts2': "SELECT id, name,subsidiary_shortname, bal('general_'||id) as gid,account_type_id as type FROM ledger.general_chart_of_accounts ORDER BY account_type_id,id",
'get_accounts_type': "SELECT id AS name FROM system.account_type WHERE id IN (SELECT DISTINCT account_type_id FROM ledger.general_chart_of_accounts) ORDER BY ord;",
'update_journal': "UPDATE system.journal SET posted = 'NOW' WHERE ID = %s",
'update_general_accounts': "UPDATE ledger.general_chart_of_accounts SET subsidiary_id = nextval('subsidiary_id_seq'), opening_balance = (SELECT bal('general_%s')) WHERE id='%s'",
'create_subledger': "SELECT create_subledger('%s','%s')",
'get_journals': "SELECT * FROM system.journal j WHERE ledger_shortname %s AND (SELECT SUM(amount) FROM system.general_journal_item ji WHERE ji.journal_id = j.id AND drcr = 'CR') - (SELECT SUM(amount) FROM system.general_journal_item ji WHERE ji.journal_id = j.id AND drcr = 'DR') = 0 AND posted IS NULL",
'insert_general_item': "INSERT INTO system.general_journal_item (id, journal_id, description, account_id, amount, drcr) values (DEFAULT, %s, '%s', '%s', %f, '%s')",
#TODO:sl is useless
'insert_sub_item': "INSERT INTO system.sl%s_journal_item (id, journal_id, description, account_id, amount, drcr) VALUES (DEFAULT, %s, '%s', %s, %s, '%s')",
'insert_journal': "INSERT INTO system.journal (id, date) VALUES (DEFAULT, '%s')",
'insert_journal2': "INSERT INTO system.journal (id, date, ledger_shortname, posted) VALUES (%s, '%s', '%s', '%s')",
'insert_journal3': "INSERT INTO system.journal (id, date, ledger_shortname) VALUES (%s, '%s', '%s')",
'get_curr_journal_id': "SELECT CURRVAL('system.journal_id_seq') AS journal_id",
'get_connections_to_bill': "SELECT cx.id, cx.site_id, cx.customer_id, b.fee, ac.id AS account_id FROM connection cx, billing_plan b, ledger.%s_chart_of_accounts ac , customer cust WHERE cx.billing_plan_id = b.id AND cx.customer_id = cust.id AND link_object_id(ac.name) = cust.id AND link_object(ac.name) = 'customer' AND b.fee_type = 'monthly'",
'get_same_billing_log': "SELECT id from billing_log where fee_type='%s' and billed_month_year=%s and billed_month=%s",
'get_next_journal_id': "SELECT NEXTVAL('system.journal_id_seq') AS journal_id",
'get_journal2': "SELECT * FROM system.journal WHERE id =%s",
'get_total': "SELECT SUM(amount) as total FROM system.ar_journal_item WHERE journal_id = %s",
'insert_billing_log': "INSERT INTO billing_log (id, log_date, fee_type, billed_month_year, billed_month) VALUES (%s, '%s', '%s', %s, %s)",
'insert_sub_account': "INSERT INTO ledger.%s_chart_of_accounts (name) values ('%s%s')",
'get_pk': "SELECT * FROM system.pk_lookup WHERE table_schema = '%s' and table_name = '%s'",
'get_accounts3': "SELECT id, name, bal('%s'||'_'||id) as s_id FROM ledger.%s_chart_of_accounts ORDER BY id",
'get_accounts_id': "SELECT id FROM ledger.ar_chart_of_accounts",
'get_items2': "SELECT ji.id, description, amount FROM system.ar_journal_item ji WHERE ji.drcr = 'DR' AND ji.id NOT IN (SELECT journal_item_id FROM system.invoice_item) AND ji.account_id=%s",
'insert_invoice': "INSERT INTO system.invoice (id, date,journal_id) VALUES (%d, '%s', %d)",
'get_invoice_id': "SELECT currval('system.invoice_id_seq') as id",
'get_invoice_item_id': "SELECT nextval('system.invoice_item_id_seq') as invoice_item_id",
'insert_invoice_item_tax': "INSERT INTO system.invoice_item_tax (invoice_item_id, transaction_tax_id) VALUES (%d, %d)",
'insert_invoice_item': "INSERT INTO system.invoice_item (id, invoice_id, qty, description, unit_price, tax_included) VALUES (%d, %d, %d, '%s', %f, '%s')",
'get_purchase_item_id': "SELECT NEXTVAL('system.purchase_order_item_id_seq') as purchase_item_id",
'insert_purchase_item': "INSERT INTO system.purchase_order_item (id,purchase_order_id,qty,unit_price,tax_included) VALUES (%i,%i,%i,%f,%s)",
'insert_purchase_item_tax': "INSERT INTO system.purchase_item_tax(purchase_order_item_id,transaction_tax_id) VALUES(%i,%i)",
'get_next_ap_journal_id': "SELECT NEXTVAL('system.ap_journal_item_id_seq') AS ap_journal_id",
'get_customers': "SELECT * FROM customer_info",
#'get_suppliers': "SELECT * FROM supplier_info where id in(select split_part(ac.name,':',2)::integer from ledger.ap_info ai,ledger.ap_chart_of_accounts ac where ac.id = split_part(ai.id,'.',2)::integer) %s",
'get_suppliers': "SELECT * FROM supplier_info",
'get_delivery_address': "select b.id AS location_id,a.id,a.line1,a.line2,a.suburb,a.region,a.code,a.country,b.name,b.phone,b.fax from system.address a,system.location b where a.id = b.address_id and b.entity_id = %s",
'get_items3': "SELECT ji.id, 0 as state FROM system.ar_journal_item ji WHERE ji.drcr = 'DR' AND ji.id NOT IN (SELECT journal_item_id FROM system.invoice_item) AND ji.id IN (%s)",
'get_table_name': "SELECT find_name('%s')",
'get_control_account_id': "SELECT id FROM ledger.general_chart_of_accounts WHERE subsidiary_shortname ='%s'",
'get_journals2': "SELECT * FROM system.journal j WHERE ledger_shortname IS NULL AND posted IS NULL",
'get_account2': "SELECT * FROM ledger.%s_chart_of_accounts WHERE id = %s",
'get_sub_account_name': "SELECT * FROM ledger.%s_chart_of_accounts WHERE name = '%s'",
'get_account': "SELECT * FROM ledger.general_chart_of_accounts WHERE id='%s'",
'get_journal_items': "SELECT * FROM system.general_journal_item WHERE journal_id = %i ORDER BY account_id",
'get_sub_journal_items': "SELECT * FROM system.%s_journal_item WHERE journal_id = %s",
'get_sl_account_id': "SELECT * FROM ledger.%s_info WHERE name = '%s'",
'get_gen_account_id': "SELECT * FROM ledger.general_chart_of_accounts WHERE lower(subsidiary_shortname) = lower('%s')",
'insert_sl_journal_item': "INSERT INTO system.%s_journal_item (id,journal_id, description, account_id, amount, drcr) VALUES (%i, %i, '%s', %i, %f, '%s')",
'get_curr_sl_journal_id': "SELECT CURRVAL('system.%s_journal_item_id_seq') AS sl_journal_id",
'create_account': "SELECT create_account('%s','%s','%s','%s','%s')",
'post_journal': "SELECT post_journal(%s)",
'create_journal': "SELECT create_journal('%s','{%s}','{%s}','{%s}','{%s}','{%s}','{%s}','{%s}','{%s}','%s')",
'edit_journal': "SELECT edit_journal(%s,'{%s}',%s,'%s','{%s}','{%s}','{%s}','{%s}','{%s}','%s','{%s}','{%s}','{%s}','{%s}','%s')",
'create_invoice': "SELECT create_invoice('%s','%s','%s','%s','{%s}',E'{%s}','{%s}','{%s}','{%s}')",
'get_invoices': "SELECT i.id,i.date FROM system.journal j,system.invoice i WHERE i.journal_id = j.id AND j.ledger_shortname = 'ar'",
'get_delivery_invoices': "SELECT * FROM system.invoice_delivery_report ORDER BY invoice_id,date",
'get_purchase_orders': "SELECT id,date FROM system.purchase_order",
'delete_journal': "DELETE FROM system.journal WHERE id=%s",
'create_purchase_order': "SELECT create_purchase_order('%s','%s','%s','%s','%s','{%s}',E'{%s}','{%s}','{%s}','{%s}')",
'get_next_expense_report_id': "SELECT MAX(id)+1 AS id FROM system.expense_report",
'create_expense_report': "SELECT create_expense_report('%s', '%s', '%s', '{%s}', '{%s}', '{%s}', '%s', '%s')",
'generate_receipt': "SELECT generate_receipt('%s', '%s', '%s', '%s', '%s', '{%s}')",
'get_linked_account_details': "SELECT la.* FROM system.linked_account la,system.transaction_tax tt WHERE la.transaction_tax_shortname = tt.shortname AND tt.obsolete IS NULL ORDER BY transaction_tax_shortname",
'get_linked_account_of_tax': "SELECT * FROM system.linked_account WHERE transaction_tax_shortname='%s' AND transaction_type='%s'",
'insert_linked_account': "INSERT INTO system.linked_account(transaction_tax_shortname,transaction_type,account_id) VALUES('%s','%s','%s')",
'update_linked_account': "UPDATE system.linked_account SET account_id = '%s' WHERE transaction_tax_shortname = '%s' AND transaction_type = '%s'",
'delete_linked_account': "DELETE FROM system.linked_account WHERE transaction_tax_shortname = '%s' AND transaction_type = '%s'",
'exist_special_params_len': "SELECT count(*) AS special_params_len FROM (SELECT code_id FROM system.sys_code WHERE code_id IN %s GROUP BY code_id) AS sys_code",
'check_special_params': "SELECT * FROM system.sys_code WHERE code_id='%s' AND code_desc='%s'",
'check_special_params2': "SELECT * FROM system.sys_code WHERE code_id='%s' AND code_desc IS NULL",
'get_special_params_details': "SELECT * FROM system.sys_code WHERE code_id IN %s",
'check_sys_code': "SELECT * FROM system.sys_code WHERE code_id='%s' AND code_desc='%s'",
'update_sys_code': "UPDATE system.sys_code SET code_value='%s' WHERE code_id='%s' AND code_desc='%s'",
'insert_sys_code': "INSERT INTO system.sys_code VALUES('%s','%s','%s')",
'delete_sys_code': "DELETE FROM system.sys_code WHERE code_id='%s' AND code_desc='%s'",
'get_accounts_by_type_without_sub':"SELECT * FROM ledger.general_chart_of_accounts WHERE account_type_id = '%s' AND subsidiary_shortname IS NULL",
}
operations_action_map = {
'get_entity_types': 'SELECT id FROM system.entity_type',
#'get_company_entities': "SELECT c.id||':'||TRIM(COALESCE(abn, ' ')) as id, name FROM system.company c, system.entity e WHERE c.entity_id = e.id AND type = '%s' ORDER BY name",
'get_company_entities': "SELECT id||':'||TRIM(COALESCE(abn, ' ')) as id, name FROM system.entity e LEFT JOIN system.abn_info c ON c.entity_id = e.id WHERE e.type = '%s' ORDER BY name",
#'get_person_entities': "SELECT p.id||':'||TRIM(COALESCE(abn, ' ')) as id, given_name||' '||surname as name FROM system.person p, system.entity e WHERE p.entity_id = e.id ORDER BY surname, given_name",
'get_person_entities': "SELECT id||':'||TRIM(COALESCE(abn, ' ')) as id, given_name||' '||name as name FROM system.entity e LEFT JOIN system.abn_info c ON c.entity_id = e.id WHERE type='%s' ORDER BY name, given_name",
'get_salesagents': "SELECT id, COALESCE(name, given_name||' '||surname) as name FROM sales_agent_info",
'get_sales_agents': "select sa.id, sa.name, sa.given_name, sa.surname, sa.commission, case when cu.id IS NULL then -1 else cu.id end as customer_id from sales_agent_info sa left join customer cu on cu.sales_agent_id = sa.id",
'get_alt_location_types': "SELECT code_value FROM system.sys_code WHERE code_id = 'alt_location_type'",
#'get_person_entity_id': "SELECT entity_id FROM system.person WHERE id=%s",
#'get_person_entity_id': "SELECT id FROM system.entity WHERE id=%s",
#'get_company_entity_id': "SELECT entity_id FROM system.company WHERE entity_id=%s",
#'get_company_entity_id': "SELECT id FROM system.entity WHERE id=%s",
'get_if_exist_abn': "SELECT * FROM system.contact_detail WHERE entity_id=%s AND type='abn'",
#'update_abn': "UPDATE system.entity SET abn='%s' WHERE id=%s",
'update_abn': "UPDATE system.contact_detail SET detail='%s' WHERE entity_id=%s AND type='abn'",
#'insert_abn1': "INSERT INTO system.entity (type, abn) VALUES ('%s','%s')",
'insert_abn': "INSERT INTO system.contact_detail(entity_id,type,detail) VALUES ('%s','abn','%s')",
#'insert_person': "INSERT INTO system.person (surname, given_name, entity_id) VALUES ('%s', '%s', %s)",
'insert_person': "INSERT INTO system.entity (name, given_name,type) VALUES ('%s', '%s', '%s')",
#'insert_company': "INSERT INTO system.company (name, entity_id) VALUES ('%s', %s)",
'insert_company': "INSERT INTO system.entity (name, type) VALUES ('%s','%s')",
#'get_oid': "SELECT id FROM system.entity WHERE oid=%s",
'get_entity_id': "SELECT CURRVAL('system.entity_id_seq') AS id",
'get_entity_id2': "SELECT entity_id FROM customer cu WHERE cu.id=%s",
'get_person_id': "SELECT id FROM system.person WHERE entity_id=%s",
#'get_company_id': "SELECT id FROM system.company WHERE entity_id=%s",
#'get_pob_id': "SELECT place_of_business_id FROM system.person WHERE id=%s",
'get_pob_id': "SELECT location_id FROM system.relationship WHERE type='employee' AND entity_id=%s AND rel_entity_id=%s",
#'get_address_id1': "SELECT address_id FROM system.place_of_business WHERE id=%s",
#'get_address_id3': "SELECT address_id FROM system.alt_location WHERE id=%s",
'insert_address1': "INSERT INTO system.address (line1, line2, suburb, region, code, country) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
'get_address_id': "SELECT address_id FROM system.location WHERE id='%s'",
'insert_address2': "INSERT INTO system.address (line1, suburb, region, code, country) VALUES ('%s', '%s', '%s', '%s', '%s')",
#'get_address_id4': "SELECT id FROM system.address WHERE oid=%s",
'get_address_id4': "SELECT CURRVAL('system.address_id_seq') AS id",
#'insert_address3': "INSERT INTO system.place_of_business (company_id, address_id, %s) VALUES (%s, %s, '%s')",
'insert_address3': "INSERT INTO system.location(entity_id, address_id, %s) VALUES (%s, %s, '%s')",
#'insert_address4': "INSERT INTO system.alt_location (person_id, address_id, %s) VALUES (%s, %s, '%s')",
#'insert_address4': "INSERT INTO system.location(entity_id, address_id, %s) VALUES (%s, %s, '%s')",
#'insert_address5': "INSERT INTO system.alt_location (person_id, address_id,type) VALUES (%s, %s, 'postal_address')",
'insert_address5': "INSERT INTO system.location(entity_id, address_id,name) VALUES (%s, %s, 'postal_address')",
'insert_customer1': "INSERT INTO customer (entity_id, sales_agent_id, billing_method, address_id) VALUES (%s, %s, '%s', %s)",
'insert_customer2': "INSERT INTO customer (entity_id, billing_method, address_id) VALUES (%s, '%s', %s)",
'insert_customer3': "INSERT INTO customer (entity_id, sales_agent_id, billing_method) VALUES (%s, %s, '%s')",
'insert_customer4': "INSERT INTO customer (entity_id, billing_method) VALUES (%s, '%s')",
'insert_supplier': "INSERT INTO supplier (entity_id, address_id) VALUES (%s,%s)",
#'get_customer_id': "SELECT id FROM customer WHERE oid=%s",
'get_customer_id': "SELECT CURRVAL('customer_id_seq') AS id",
#'get_supplier_id': "SELECT id FROM supplier WHERE oid=%s",
'get_supplier_id': "SELECT CURRVAL('supplier_id_seq') AS id",
'get_next_ar_seq': "SELECT NEXTVAL('ledger.ar_chart_of_accounts_id_seq') AS id",
'get_next_ap_seq': "SELECT NEXTVAL('ledger.ap_chart_of_accounts_id_seq') AS id",
#'insert_ledger_ar_chart_of_accounts': "INSERT INTO ledger.ar_chart_of_accounts (name) values ('#customer:%s')",
'insert_ledger_ar_chart_of_accounts': "SELECT create_account('ar','%s','#customer:%s','','')",
'insert_ledger_ap_chart_of_accounts': "SELECT create_account('ap','%s','#supplier:%s','','')",
'get_customer_billing_info': "SELECT id,customer_name,billing_method,line1,line2,suburb,region,code,country,COALESCE(name, given_name||' '||surname) AS sales_agent,entity_id FROM customer_billing_info where id=%d",
#'get_rscount': "SELECT count(customer_id) FROM system.invoice_info where customer_id=%d group by customer_id",
'get_rscount': "SELECT count(%s) FROM %s %s",
'get_supplier_billing_info': "SELECT id,supplier_name,line1,line2,suburb,region,code,country FROM supplier_billing_info where id=%d",
'get_invoices_info': "SELECT * FROM system.invoice_info where customer_id=%d ORDER BY id %s",
'get_all_invoices': "select * from system.invoice_info where id NOT IN (select i.id from system.invoice i, system.receipt r where i.id = ANY(r.invoice_id))",
'get_all_purchase_orders': "select * from system.purchase_order_info where id NOT IN (select p.id from system.purchase_order p, system.bill_payment b where p.id = ANY(b.purchase_order_id))",
'get_purchase_orders_info': "SELECT * FROM system.purchase_order_info where supplier_id=%d ORDER BY id %s",
'get_customer_info': "SELECT * FROM customer_info",
'get_entity_type': "SELECT type FROM customer_info WHERE id=%s",
#'get_person_id2': "SELECT p.id FROM system.person p, system.entity e, customer cu WHERE cu.entity_id = e.id AND p.entity_id = e.id AND cu.id=%s",
'get_person_id2': "SELECT e.id FROM system.entity e,customer cu WHERE e.type = 'person' AND cu.entity_id = e.id AND cu.id=%s",
#'get_company_id2': "SELECT c.id FROM system.company c, system.entity e, customer cu WHERE cu.entity_id = e.id AND c.entity_id = e.id AND cu.id=%s",
'get_company_id2': "SELECT e.id FROM system.entity e, customer cu WHERE e.type = 'company' AND cu.entity_id = e.id AND cu.id=%s",
'get_site_id': "SELECT site_id FROM connection",
'get_billing_plan': "SELECT id, name FROM billing_plan",
'get_address_id2': "SELECT address_id FROM system.place_of_business pob, system.person p WHERE p.place_of_business_id = pob.id AND p.id=%s",
'get_person_id3': "SELECT person_id FROM customer_info WHERE id=%s",
'get_company_id3': "SELECT company_id FROM customer_info WHERE id=%s",
'insert_connection': "INSERT INTO connection (site_id, customer_id, address_id, billing_plan_id) VALUES (%s, %s, %s, %s)",
'get_company_ids_from_customer': "SELECT company_id FROM customer_info",
'get_person_ids_from_customer': "SELECT person_id FROM customer_info",
'get_company_ids_from_supplier': "SELECT company_id FROM supplier_info",
'get_person_ids_from_supplier': "SELECT person_id FROM supplier_info",
'get_all_purchase_tax_aggregation': "SELECT * FROM system.purchase_order_tax_aggregation",
'insert_contact_detail': "INSERT INTO system.contact_detail VALUES(default,%s,'%s','%s')",
'get_billing_methods':"SELECT code_value AS name FROM system.sys_code WHERE code_id='billing_method'",
'get_customer_billing_details':"SELECT detail FROM system.contact_detail WHERE entity_id=%s AND type='%s'",
#'get_customer_by_invoice_id':"SELECT c.* FROM customer c,system.invoice_info ii WHERE c.id=ii.customer_id AND ii.id=%s",
'insert_invoice_delivery_report1':"INSERT INTO system.invoice_delivery_report VALUES(default,%s,default,'%s',%s)",
'insert_invoice_delivery_report2':"INSERT INTO system.invoice_delivery_report (invoice_id,method,detail)VALUES(%s,'%s','%s')",
'get_customer_by_id':"SELECT * FROM customer WHERE id=%s",
'pay_bill': "SELECT pay_bill('%s','%s','%s', '{%s}','{%s}','%s','%s','%s','{%s}')",
'get_invoice_tax_aggregation': "SELECT * FROM system.invoice_tax_aggregation WHERE invoice_id = %d",
'get_po_tax_aggregation': "SELECT * FROM system.purchase_order_tax_aggregation WHERE purchase_order_id = %d",
'get_delivery_address_info':"SELECT a.*,l.name FROM system.location l,system.address a WHERE l.address_id=a.id AND l.id=%s",
}
report_action_map = {
## 'get_report_info': "SELECT * FROM system.report WHERE id = %i",
## 'get_system_report_detail': "SELECT rd.id AS detail_id, rd.section_id AS section_id, se.name AS section_name, rd.item_id AS item_id, it.name AS item_name, rd.params AS params FROM system.report_detail AS rd, system.report_section AS se, system.report_item AS it WHERE rd.report_id = %i AND it.flag = 0 AND se.id = rd.section_id AND it.id = rd.item_id ORDER BY detail_id",
## 'get_user_report_detail': "SELECT rd.id AS detail_id, rd.section_id AS section_id, se.name AS section_name, rd.item_id AS item_id, it.name AS item_name, rd.params AS params FROM system.report_detail AS rd, system.report_section AS se, system.report_item AS it WHERE rd.report_id = %i AND it.flag = 1 AND se.id = rd.section_id AND it.id = rd.item_id ORDER BY detail_id",
## 'get_section': "SELECT se.id AS section_id, se.name AS section_name,se.f_id FROM system.report_detail AS rd, system.report_section AS se WHERE rd.report_id=%i AND se.id=rd.section_id GROUP BY se.id, se.name,se.f_id",
## #---------------liang
## 'insert_report_item': "INSERT INTO system.report_item (id,name,flag) VALUES (Default,'%s',1)",
## 'get_item_id': "SELECT currval('system.report_item_id_seq') AS id",
## 'insert_report_detail': "INSERT INTO system.report_detail(id,report_id,section_id,item_id,params) VALUES(Default,%s,%s,%s,'%s')",
## 'get_simple_report_details': "SELECT s.id as section_id,s.name AS section_name,i.name AS item_name,i.flag,d.params FROM system.report_detail AS d,system.report_section AS s,system.report_item AS i WHERE d.report_id = %s AND d.section_id = s.id AND d.item_id = i.id ORDER BY d.section_id,d.item_id",
## 'get_sum': "SELECT bal('general_'||id) AS sumamount FROM ledger.general_chart_of_accounts %s ORDER BY id",
## 'get_sum2': "SELECT profit_bal('general_'||id) AS sumamount FROM ledger.general_chart_of_accounts %s ORDER BY id",
## 'update_report_detail': "UPDATE system.report_detail SET params='%s' WHERE report_id=%s AND section_id=%s AND item_id=%s",
## 'get_report_item_by_name': "SELECT * FROM system.report_item WHERE name='%s'",
## 'escape_repeat_details': "SELECT id FROM system.report_detail WHERE report_id=%s AND section_id=%s AND item_id=%s",
## #-------------liang
'get_report_detail': "SELECT * FROM system.report_detail WHERE report_id=%s order by order_num",
'get_report_info': "SELECT * FROM system.report WHERE id=%s",
'get_report_sections': "SELECT * FROM system.report_section WHERE report_id=%s and insert_position_id > 0",
'update_params': "UPDATE system.report_detail SET params='%s' WHERE name||id='%s'" ,
'get_max_id': "SELECT max(id) as max_id FROM system.report_detail WHERE report_id=%s",
'get_insert_position1': "SELECT order_num FROM system.report_detail WHERE id = (SELECT insert_position_id FROM system.report_section WHERE report_id=%s AND id=%s)",
'get_insert_position2': "SELECT max(order_num) as order_num FROM system.report_detail WHERE report_id=%s",
'update_order_num': "UPDATE system.report_detail SET order_num=order_num+1 WHERE order_num>%s and report_id=%s",
'insert_new_item': "insert into system.report_detail values(default,%s,%s,'%s','%s',1,%s,%s)",
'del_report_preresult': "delete from system.report_result where report_id=%s",
'get_item_info1': "select a.*,b.formula from system.report_detail a,system.report_formula b where a.report_formula_id = b.id and params <>'' and a.report_id=%s",
'get_item_info2': "select a.*,b.formula from system.report_detail a,system.report_formula b where a.report_formula_id = b.id and item_flag=2 and a.report_id=%s",
'get_item_info0': "select a.* from system.report_detail a where item_flag=0 and a.report_id=%s and section_id in(%s)" ,
'insert_result': "insert into system.report_result values(%s,%s,%s)",
'display_report': "select name,value,item_flag from system.report_detail rd,system.report_result rr where rd.id = rr.item_id and rd.report_id = %s order by order_num"
}
tax_action_map = {
'get_tax_by_id': ''' select a.id,b.formula as cal_formula,c.formula as cond_formula from system.tax_class a, system.tax_formula b,system.tax_formula c where a.calc_formula_id = b.id and a.cond_formula_id = c.id and a.id = %s and ( a.effect_date = '19700101' or to_date('%s','YYYYMMDD') > a.effect_date ) and ( a.expire_date = '21000101' or to_date('%s','YYYYMMDD') < a.expire_date ) ''',
}
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import app_sql
import start_sql
class ActionExistError(Exception):
pass
def register_action( name, action ):
if action_map.has_key( name ):
raise ActionExistError,'ActionExistError %s' % name
else:
action_map[name]=action
action_map = {}
for action_name in app_sql.operations_action_map.keys():
register_action(action_name,app_sql.operations_action_map[action_name])
for action_name in app_sql.crm_action_map.keys():
register_action(action_name,app_sql.crm_action_map[action_name])
for action_name in app_sql.admin_action_map.keys():
register_action(action_name,app_sql.admin_action_map[action_name])
for action_name in app_sql.finance_action_map.keys():
register_action(action_name,app_sql.finance_action_map[action_name])
for action_name in app_sql.tax_action_map.keys():
register_action(action_name,app_sql.tax_action_map[action_name])
for action_name in app_sql.app_admin_action_map.keys():
register_action(action_name,app_sql.app_admin_action_map[action_name])
for action_name in app_sql.report_action_map.keys():
register_action(action_name,app_sql.report_action_map[action_name])
for action_name in start_sql.start_sql_map.keys():
register_action(action_name,start_sql.start_sql_map[action_name])
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from phunc.logger import logger
from phunc.exception import GeneralBusinessErr
session_timeout = 1800
RESET_TIME_LIMIT = 1200 #reset session time limit
ROOT_PATH = ''
#COMPANY_LOGO_PATH = 'company/'
COMPANY_ROOT_PATH = '/var/fivedash/logos/'
COMPANY_VIRTUAL_PATH = '/company/'
JS_TEMP_PATH = '/var/fivedash/js_tmp/'
#sys_code code_id
BILLING_METHOD = 'billing_method'
CONTACT_TYPE = 'contact_type'
SMTP_SERVER = 'smtp_server'
SMTP_USER = 'smtp_user'
SMTP_PASS = 'smtp_pass'
THIS_EMAIL = 'this_email'
BUSINESS_NUM_LABEL = 'business_num_label'
ALT_LOCATION_TYPE = 'alt_location_type'
#billing method
BILLING_METHOD_ONE = 'hard copy'
BILLING_METHOD_TWO = 'email'
BILLING_METHOD_THREE = 'fax'
#billing method
#contact type
CONTACT_TYPE_EMAIL = 'email'
CONTACT_TYPE_FAX = 'fax'
CONTACT_TYPE_PHONE = 'phone'
CONTACT_TYPE_MOBILE = 'mobile'
CONTACT_TYPE_SMS = 'sms'
CONTACT_TYPE_POSITION = 'position'
#contact_type
#entity type
ENTITY_TYPE_PERSON = 'person'
ENTITY_TYPE_COMPANY = 'company'
ENTITY_TYPE_GOVERNMENT_DEPARTMENT = 'government department'
ENTITY_TYPE_NON_PROFIT_ORG = 'non-profit org'
#entity type
#alt location type
ALT_LOCATION_TYPE_COURIER_ADDRESS='courier_address'
ALT_LOCATION_TYPE_HOME='home'
ALT_LOCATION_TYPE_POSTAL_ADDRESS='postal address'
ALT_LOCATION_TYPE_WORK='work'
ALT_LOCATION_TYPE_OTHER='other'
#alt location type
#special account short name
ACCOUNTS_RECEIVABLE = 'ar'
ACCOUNTS_PAYABLE = 'ap'
ISO_COUNTRY_CODE_AUSTRALIA='AU'
BUSINESS_NUM_LABEL_AUSTRALIA = 'ABN'
BUSINESS_NUM_LABEL_OTHER = 'Business Number'
def getTemplateDir( req ):
template_dir = req.document_root()
template_dir = template_dir[:template_dir.rindex('skins')]+ 'templates/'
return template_dir
def getDocumentRootPath( req ):
return req.document_root()
#--------------------------------------------------#
# base information from form
#--------------------------------------------------#
query_string = '?1=1'
t = ''
v = ''
page = 0
page_string = ''
##a=''
##sl=''
##j=''
##def loadBaseInfo( form ):
## global query_string
## global t
## global v
## global page
## global page_string
## global a
## global sl
## global j
## if form.has_key('j'):
## j = form['j']
## if form.has_key('sl'):
## sl = form['sl']
## if form.has_key('a'):
## a = form['a']
## if form.has_key('sys') and form['sys'] != 'bde':
## sys = form['sys']
## syslabel = 'BDE (' + sys.lower() + ')'
## query_string = '?sys=' + sys
## instance = sys
## if form.has_key('t'):
## t = form['t']
## if form.has_key('v'):
## v = form['v']
## if form.has_key('page'):
## page = int(form['page'])
## else:
## page = 1
## page_string = ' LIMIT 20 OFFSET ' + str((page - 1) * 20)
#----------------------base info----------------
basic_save_path = "/var/fivedash/upload/crm"
INVOICE_FILE_PATH = 'invoice'
tp_index_path = "/usr/local/fivedash/cgi/phunc/tp_index"
tp_save_path = "/var/fivedash/upload/taxpage"
tp_server = "http://tps.obolsoftware.com/"
LOCAL_TP_INDEX_LOCK = tp_save_path + "/TPindex.py.lock"
LOCAL_TP_INDEX = tp_index_path + "/TPindex.py"
LOCAL_TP = tp_save_path + "/tp.ods"
TP_INDEX_ONLINE = tp_server + "TPindex.txt"
TP_INDEX_MD5_ONLINE = tp_server + "TPindex.txt.md5"
accounts_save_path = '/var/fivedash/upload/accounts'
ACCOUNTS_FILE = accounts_save_path + '/accounts.ods'
invalid_start_date ='19000101'
invalid_end_date = '21000101'
employee_code_prefix = 'employee_code_prefix'
salary_tax = 'salary_tax'
#----------------login info--------------------
main_menu = {'operations': ''' <div class="link-panel"><a href="/bin/operations.py">Operations</a></div> ''',
'crm':''' <div class="link-panel"><a href="/bin/crm.py">CRM</a></div> ''',
'finance':''' <div class="link-panel"><a href="/bin/finance.py">Finance</a></div> ''',
'admin':''' <div class="link-panel"><a href="/bin/admin.py">Admin</a></div> ''',
}
admin_menu = [''' <li><a href="/bin/appadmin/auc.py">Create New User</a></li> ''',
''' <li><a href="/bin/appadmin/auu.py">Change Admin Password</a></li> ''',
''' <li><a href="/bin/appadmin/acm.py">Company Management</a></li> ''',
''' <li><a href="/bin/appadmin/get_right.py">Grant User rights</a></li> ''',
''' <li><a href="/bin/appadmin/init_db.py">Create DB Script</a></li> ''',
''' <li><a href="/bin/appadmin/right_tree.py">Display Company Organization</a></li> ''',
]
page_count = 20
def _set_autocommit(connection):
"Make sure a connection is in autocommit mode."
if hasattr(connection, "autocommit"):
connection.autocommit(True)
elif hasattr(connection, "set_isolation_level"):
connection.set_isolation_level(0)
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from phunc.template import Template as Template
from phunc.logger import logger
##def form_text(
## label = None,
## id = None,
## name = None,
## classid = None,
## style = None,
## value = None,
## disabled = False,
## ):
## pass
##def form_textarea(
## label = None,
## id = None,
## name = None,
## classid = None,
## style = None,
## value = None,
## disabled = False,
## ):
## pass
##def form_select(
## label = None,
## id = None,
## name = None,
## classid = None,
## style = None,
## onchange = None,
## option = [{}],
## option_value = {'split':None,'items':['id'],'default_value':''},
## option_text = {'split':None,'items':['name'],'default_text':'-- Please select --'},
## selected_type = 1,#1:equal default_value 2:option value equal selected value 3:['id'](from the result set) equal selected value
## selected_value = '',
## selected_key = None,#if selected_type==3,set the key value
## ):
## pass
##def form_hidden(
## id = None,
## name = None,
## value = None,
## ):
## pass
##def form_button(
## id = None,
## name = None,
## classid = None,
## style = None,
## value = None,
## onclick = None,
## ):pass
##def form_submit(
## label = None,
## id = None,
## name = None,
## value = None,
## classid = None,
## style = None,
## ):
## pass
##def form_reset(
## label = None,
## id = None,
## name = None,
## value = None,
## ):
## pass
##def form_checkbox(
## checkbox_type = 1,#1:default create one by one; 2:loop auto create;
## checkbox_value = [{}],
## whole_label = None,
## prefix = False,
## prefix_text = None,
## label = None,#{'type':1,'format':'give the label'}{'type':2,'format':'loop,a key in the value,maybe have a prefix'}
## id = None,#{'type':1,'format':'give the id'}{'type':2,'format':'loop,a key in the value'}
## name = None,#give the name
## value = None,#{'type':1,'format':'give the id'}{'type':2,'format':'loop,a key in the value'}{'type':2,'format':'loop,a key in the value'}
## format = 1,#1:horizontal;2:vertical;3:vertical,no whole_label;4:vertical,no whole_label,no label.just description(a key in the value);
## ):
## pass
##def form_radio(
## radio_type = 1,#1:default create one by one; 2:loop auto create;
## radio_value = [{}],
## whole_label = None,
## label = None,#{'type':1,'format':'give the label'}{'type':2,'format':'loop,a key in the value'}
## id = None,#{'type':1,'format':'give the id'}{'type':2,'format':'loop,a key in the value'}
## name = None,#give the name
## value = None,#{'type':1,'format':'give the id'}{'type':2,'format':'loop,a key in the value'}
## format = 1,#1:horizontal;2:vertical
## ):
## pass
##def form_file(
## id = None,
## name = None,
## label = None,
## value = None,
## ):pass
##def form_div(
## id = None,
## name = None,
## classid = None,
## style = None,
## ):
## pass
##def textNode(
## label = None,
## flag = 1,#0:None;1:<span>value</span>;2:<div>value</div>;3:<p>value</p>
## classid = None,
## value = None,
##):
## pass
##def line(
## classid=None,
## flag=0,#0:<hr />;1:other,may be <div class="lin1"> </div>
##):
## pass
def user_form(
form_type = 1,#1:default;2:complex
id = None,
classid = None,#class
style = None,
action = None,
method = 'post',
enctype = None,
onsubmit = None,
onreset = None,
fieldsets = [],
form_bottom = {'type':'div','id':None,'classid':'bottom input','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Create'},{'type':'hidden','id':None,'name':None,'value':''}]},
template_dir = '',
):
for fieldset in fieldsets:#fieldset list fieldset
for item in fieldset['items']:#element list item
#select
if item['type'] == 'select':
option_list = []
if item['option_value'].has_key('default_value'):
option_map = {}
option_map['value'] = item['option_value']['default_value']
option_map['text'] = item['option_text']['default_text']
option_list.append(option_map)
if item['option']:
for option_item in item['option']:#create option
option_map = {}
option_value = None
option_text = None
if item['option_value']['split']:
option_value = []
for subitem in item['option_value']['items']:#option value item
option_value.append(str(option_item[subitem]))
option_value = item['option_value']['split'].join(option_value)
else:
option_value = option_item[item['option_value']['items'][0]]
if item['option_text']['split']:
option_text = []
for subitem in item['option_text']['items']:#option value item
option_text.append(option_item[subitem])
option_text = item['option_text']['split'].join(option_text)
else:
option_text = option_item[item['option_text']['items'][0]]
option_map['text'] = option_text
option_map['value'] = option_value
if item['selected_type'] == 3:
option_map['selected'] = option_item[selected_key]
option_list.append(option_map)
item['option_list'] = option_list
#checkbox
content = {
'id':id,
'classid':classid,
'style':style,
'action':action,
'method':method,
'enctype':enctype,
'onsubmit':onsubmit,
'onreset':onreset,
'fieldsets':fieldsets,
'form_bottom':form_bottom,
}
template = Template()
template.parseFile( template_dir + 'form.opt' )
## if form_type==1:
## template.parseFile( template_dir + 'form.opt' )
## elif form_type==2:
## template.parseFile( template_dir + 'form.opt' )
html = template.render( content )
return html
def user_div(
id = None,
name = None,
classid = None,#class
template_dir = '',
list=None,
style=None,
isfo=None,
title1=None,
key=None,
main=None,
detail=None,
item=None,
devide=None,
a_img=None,
a_script =None,
a_value=None,
list_type=1, #default type
img_offdate=None,
img_edit=None,
skin=None,
isi_div1=None,
input=None,
isi=None,
):
content = {
'id':id,
'name':name,
'classid':classid,
'style':style,
'list':list,
'isfo':isfo,
'title1':title1,
'key':key,
'main':main,
'detail':detail,
'item':item,
'devide':devide,
'a_img':a_img,
'a_script':a_script,
'a_value':a_value,
'img_offdate':img_offdate,
'img_edit':img_edit,
'skin':skin,
'isi_div1':isi_div1,
'input':input,
'isi':isi,
}
template = Template()
if list_type ==1:
template.parseFile( template_dir + 'div.opt' )
else:
template.parseFile( template_dir + 'div2.opt' )
html = template.render( content )
return html
| Python |
#!/usr/bin/python
"""
Obol Hub
Copyright, license, etc notice..
"""
class BaseElement:
def __init__( self ):
self.name = ''
self.id = ''
self.child = []
def __setitem__( self,name,value ):
if name == 'name':
self.name = value
if name == 'id':
self.id = value
def __getitem__( self, name ):
if name == 'name':
return self.name
if name == 'id':
return self.id
def rander( self, tabsize = 0) :
tabspace = '' * tabsize
html = tabspace + self.begin()
for c in self.child:
if isinstance(c,str):
html = html + c
else:
html = html + c.rander()
html = html + tabspace + self.end()
return html
def begin( self ):
pass
def end( self ):
pass
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
common_list = '''
<div class="title title2 hr-title ">
<dl class="hr-tit">
{% for list_colname in list_colnames %}
<dd class="{% if list_colname.find(' ')>0 %}{{str(list_colname.split(' ',1)[1]).lower()}}{% else %}{{list_colname.lower()}}{% endif %}">{{list_colname}}</dd>
{% endfor %}
<dt>Actions</dt>
</dl>
{% for element in results %}
{% if (results.index(element))%2!=0 %}
<dl class="list-bg2">
{% else %}
<dl>
{% endif %}
{% for db_colname in db_colnames %}
<dd class="{% if db_colname.find('_')>0 %}{{str(db_colname.split('_',1)[1]).lower()}}{% else %}{{db_colname.lower()}}{% endif %}">{{element[db_colname]}}</dd>
{% endfor %}
<dt>
{% if element['edit_url'] %}
<a href="{{element['edit_url']}}"><img src="/{{skin}}/{{element['edit']}}.gif" /></a>
<a href="{{element['del_url']}}"><img src="/{{skin}}/{{element['del']}}.gif" /></a>
{% else %}
{% endif %}
</dt>
</dl>
{% endfor %}
</div>
<div class="img-line"> </div>
<div class="bottom input">
<input name="add" type="button" value="Add entity" onClick="javascript:location.href='{{add_url}}';" />
</div>
'''
common_search = '''<div class="list-bg"> </div>
<form id="search" action="/bin/hr.py/search_employee_salary_details" enctype="multipart/form-data" method="post">
<fieldset class="form">
<label>Enter employee's code : </label>
<input type="text" name="employee_code"/>
<input type="button" name="search" onClick="check_submit('search')" value="search" class="button2"/>
</fieldset>
</form>
<div class="list-bg"> </div>
<script type="text/javascript">
function check_submit(id)
{
var form=document.getElementById(id);
form.submit();
}
</script>
'''
common_edit = '''
{% if len(employee)>0 %}
<form id="edit" action="/bin/hr.py/edit_employee_salary?employee_id={{employee['employee_id']}}" enctype="multipart/form-data" method="post">
<div class="title title2">Edit salary</div>
<fieldset class="form">
<div class="new-oth">{{employee['given_name']}} {{employee['surname']}}</div><br/><br/>
<label>employee code:</label>{{employee['employee_code']}}<br/><br/>
<label>nation:</label>{{employee['nation']}}<br/><br/>
{% for section in employee_sections %}
<label>{{section['name']}}:</label>
<input type="text" name="amount{{section['section_id']}}" value="{{section['amount']}}"/><br/><br/>
{% endfor %}
<label>reason:</label>
<input type="text" name="reason" maxlength="80"/><br/><br/>
<div class=" bottom input"><input type="submit" name="submit" value="edit"/></div>
</fieldset>
</form>
{% endif %}
'''
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
def address(validation_class):
if validation_class == 'required':
line2_class = ''
indicator_color = 'red'
else:
line2_class = ' validate-optional-or-none'
indicator_color = 'pink'
html = ''' <label for="line1">Address line 1 <span class="''' + indicator_color + '''">*</span></label>
<input name="line1" id="line1" type="text" onblur="if(!Validation.get('IsEmpty').test(this.value)&&this.value.toLowerCase().indexOf(' box ')<0&&this.value.toLowerCase().indexOf(' bag ')<0){elem=document.getElementById('address_type');elem.checked=true;hideUnhide(elem, 'location-fields')}" class=" ''' + validation_class + ''' validate-chars3" /><br /><br/>
<label for="line2">line 2</label>
<input name="line2" id="line2" type="text" class="''' + line2_class + ''' validate-chars3" /><br /><br/>
<label for="suburb">Suburb <span class="''' + indicator_color + ''' bold">*</span></label>
<input name="suburb" id="suburb" type="text" class=" ''' + validation_class + ''' validate-chars4" /><br /><br/>
<label for="region">Region <span class="''' + indicator_color + ''' bold">*</span></label>
<input name="region" id="region" type="text" class=" ''' + validation_class + ''' validate-chars4" /><br /><br/>
<label for="code">Postal/Zip Code <span class="''' + indicator_color + ''' bold">*</span></label>
<input name="code" id="code" type="text" class=" ''' + validation_class + ''' validate-chars6" /><br /><br/>
<label for="country">Country <span class="''' + indicator_color + ''' bold">*</span></label>
<input name="country" id="country" type="text" class=" ''' + validation_class + ''' validate-chars4" /><br /><br />
'''
return html
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import phunc.info as info
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger
##def cryptPasswd( passwd,oldpasswd = None ):
## """
## Encrypt the passwd.
## """
## hashCode='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
## import random
## import crypt
## if oldpasswd == None:
## hashedPasswd = random.choice( hashCode ) + random.choice( hashCode )
## else:
## hashedPasswd = oldpasswd[:2]
## return crypt.crypt( passwd , hashedPasswd )
def createUser( conn, name, passwd ):
"""
Create a user, return an error if name exists
"""
cursor = conn.cursor()
broadcast_message = None
logger .debug('name:%s passwd:%s' % (name,passwd) )
isUserExist = db_tools.exec_action( cursor,'app_get_user_info',[name])
if not isUserExist:
userid = int(db_tools.exec_action(cursor, 'get_system_user_id')[0]['id'])
db_tools.exec_action( cursor,'insert_user',[userid,name,passwd])
broadcast_message = "User '%s' created successfully. "%name
else:
if not isUserExist[0]['is_active']:
db_tools.exec_action( cursor,'active_user',[ passwd, isUserExist[0]['id']])
broadcast_message = "User '%s' created successfully. "%name
else:
broadcast_message = "User '%s' alread exists. "%name
userid = int(isUserExist[0]['id'])
conn.commit()
return (userid, broadcast_message)
def grantUser( conn, user_id, company_id, group_id ):
"""
Assign company, group to user.
"""
cursor = conn.cursor()
isAffiliationExist = db_tools.exec_action( cursor,'app_get_user_affiliation',[user_id,company_id,group_id])
if not isAffiliationExist:
same_rights = db_tools.exec_action(cursor, 'user_have_right', [user_id,int(company_id)])
if same_rights:
company_name = db_tools.exec_action(cursor, 'get_company_name', [int(company_id)])[0]['name']
broadcast_message ="'%s' can not have more than one role on '%s'!"%(name,company_name)
return broadcast_message
db_tools.exec_action(cursor,'assign_user',[user_id,company_id,group_id])
affiliation = db_tools.exec_action( cursor,'app_get_user_affiliation',[user_id,company_id,group_id])
broadcast_message = "'%s' as '%s' on '%s' authorize successfully"%(affiliation[0]['user_name'],affiliation[0]['group_name'],affiliation[0]['company_name'])
else:
broadcast_message = "'%s' as '%s' on '%s' had been authorized already"%(isAffiliationExist[0]['user_name'],isAffiliationExist[0]['group_name'],isAffiliationExist[0]['company_name'])
conn.commit()
return broadcast_message
def changePasswd( cursor, name, oldPasswd, newPasswd ):
"""
Change a user's password, returning appropriate errors
"""
broadcast_message = None
user_list = db_tools.exec_action( cursor,'app_get_user_info',[name])
isUserExist = len( user_list ) > 0
if isUserExist:
if len(db_tools.exec_action(cursor, 'app_verify_user_passwd',[name,oldPasswd])) > 0:
db_tools.exec_action(cursor, 'app_update_user_passwd',(newPasswd, name) )
broadcast_message = "User '%s' password changed"%name
else:
broadcast_message = 'Old Password not correct'
else:
broadcast_message = "User '%s' is not exist"%name
return broadcast_message
def getUserAccess( cursor, user, company_id ):
'''
get user's role
'''
retset = db_tools.exec_action( cursor,'app_get_user_role',[user,company_id])
roleset = []
if len( retset ) > 0 :
for r in retset:
roleset.append( r['rolename'] )
return roleset
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
err_msg_map = {
'user_not_login':'User not login in',
'user_not_exist':'User not exist',
'access_forbit':'You have not enough to access this url',
'error_password':'error password',
'db_conn_str_err':'DB Connection String error.Please check it',
'company_not_exist':'Company not exist',
'user_no_grant':"User has no right on any company.Please contact System Administator",
'usergroup_no_right':"The UserGroup has no right.Please contact System Administator",
#---------hr-----------------------
'employee_not_exist':'Employee %s not exist',
'period_not_exist':'Period %s not exist',
#--------operations-----------------
'customer_not_exist':'Customer not exist',
'SYSTEM_ERROR':'Web site error,Please contact system Administator',
'ADDRESS_NOT_EXISTS':'Address not exist',
'BILLING_METHOD_ERROR':"There is not a billing addrss or it is a wrong addrss,Please contact system Administator and reset it",
'SMTP_ERROR':"The SMTP Server Settings error,Please set it before you use it!",
'LINKED_ACCOUNTS_ERROR':"The linked accounts have not set,Please set them before you create invoice!",
}
class GeneralBusinessErr( Exception ):
def __init__( self, msg = '',url = '', msgParam = [] ):
Exception.__init__( self )
self.msg = msg
self.url = url
self.msgParam = msgParam
def getURL(self):
return self.url
def getErrMsg( self ):
if len( self.msgParam ) == 0:
return err_msg_map[self.msg]
else:
return err_msg_map[self.msg] % tuple( self.msgParam )
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
#path
#COMPANY_LOGO_PATH = 'company/'
COMPANY_ROOT_PATH = '/var/fivedash/logos/'
#sys_code code_id
BILLING_METHOD = 'billing_method'
CONTACT_TYPE = 'contact_type'
SMTP_SERVER = 'smtp_server'
SMTP_USER = 'smtp_user'
SMTP_PASS = 'smtp_pass'
THIS_EMAIL = 'this_email'
#billing method
BILLING_METHOD_ONE = 'hard copy'
BILLING_METHOD_TWO = 'email'
BILLING_METHOD_THREE = 'fax'
#contact type
CONTACT_TYPE_EMAIL = 'email'
CONTACT_TYPE_FAX = 'fax'
CONTACT_TYPE_PHONE = 'phone'
CONTACT_TYPE_MOBILE = 'mobile'
CONTACT_TYPE_SMS = 'sms'
CONTACT_TYPE_POSITION = 'position'
#entity type
ENTITY_TYPE_PERSON = 'person'
ENTITY_TYPE_COMPANY = 'company'
ENTITY_TYPE_GOVERNMENT_DEPARTMENT = 'government department'
ENTITY_TYPE_NON_PROFIT_ORG = 'non-profit org'
#special account short name
ACCOUNTS_RECEIVABLE = 'ar'
ACCOUNTS_PAYABLE = 'ap'
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
from mod_python import apache
from mod_python import Session
from mod_python import util
from phunc.template import Template as Template
def genErrorPage(errmsg = '10002: Error generating error page', errurl = '/bin/login.py/login_out',err_code=None):
if err_code:
errmsg=showErr(int(err_code))
content = {
'error_msg':errmsg,
'error_url':errurl,
}
template = Template()
template.parseString(err_page)
page = template.render(content)
return page
err_page = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style type="text/css">
body{
font-family:Arial,sans-serif,DejaVuSans;
font-size:12px;
line-height:18px;
margin:135px auto;
padding:0pt;
width:750px;
}
.error{
width:100%;
background:url(/error.gif) no-repeat left 0;
}
.error a{
color:#fe0000;
}
.error a:link,.error a:visited{
text-decoration:underline;
}
.error a:hover,.error a:active {
text-decoration:none;
}
.error div{
margin-left:113px;
}
.line-d{
font-weight:bold;
font-size:13px;
border-bottom:1px solid #8D8D8D;
padding-bottom:15px;
margin-bottom:15px;
width:95%;
}
.line-r{
border:2px solid #fe0000;
padding:14px;
margin:22px 0;
color:#ff0000;
}
</style>
<title>Fivedash</title>
</head>
<body>
<div class="error">
<div class="line-d">Error</div>
<div class="line-r">{{error_msg}}</div>
<div><img src="/error02.gif" align="middle" /><a href="{{error_url}}">Continue</a></div>
</div>
</body>
</html>
'''
error_map={
10000: 'Application',
10001: 'User not logged in',
10002: 'Error generating error page',
10003: 'User has no right on any company.Please contact system Administator',
10004: 'The UserGroup has no right.Please contact system Administator',
10005: 'You have not enough to access this url',
20000: 'Operations portal',
20100: 'Customer created',
20199: 'Error creating customer',
20200: 'Purchase order created',
20299: 'Error creating purchase order',
20300: 'Payment recorded',
20399: 'Error recording bill payment',
30000: 'Finance portal',
30100: 'Account created',
30101: 'Duplicate account name or id',
30199: 'Error creating account',
30200: 'Invoice created',
30299: 'Error creating invoice',
30300: 'Journal created',
30301: 'Journal does not balance',
30302: 'Journal does not exist',
30399: 'Error creating journal',
30400: 'Journal posted',
30499: 'Error posting journal',
30500: 'Journal updated',
30599: 'Error updating journal',
30600: 'Subledger created',
30699: 'Error creating subledger',
30900: 'Invoices printed',
30999: 'Error printing invoices',
31000: 'Expense report created',
31099: 'Error creating expense report',
31100: 'Receipt created',
31199: 'Error creating receipt',
40000: 'HR portal',
50000: 'CRM portal',
50100: 'Contact created',
50199: 'Error creating contact',
50200: 'Contact updated',
50299: 'Error updating contact',
50300: 'Contact deleted',
50399: 'Error deleting contact',
50400: 'Contact merged',
50499: 'Error merging contact',
60000: 'Admin portal',
70000: 'Database',
80000: 'Server',
99999: 'Unknown Error',
}
def showErr(id):
if error_map.has_key(id):
return str(id) + ': ' + error_map[id]
else:
return str(id) + ': Unlisted error (no description available)'
| Python |
#!/usr/bin/python
"""
Obol Hub
Copyright, license, etc notice..
"""
class BaseElement:
def __init__( self ):
self.name = ''
self.id = ''
self.child = []
def __setitem__( self,name,value ):
if name == 'name':
self.name = value
if name == 'id':
self.id = value
def __getitem__( self, name ):
if name == 'name':
return self.name
if name == 'id':
return self.id
def rander( self, tabsize = 0) :
tabspace = '' * tabsize
html = tabspace + self.begin()
for c in self.child:
if isinstance(c,str):
html = html + c
else:
html = html + c.rander()
html = html + tabspace + self.end()
return html
def begin( self ):
pass
def end( self ):
pass
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import datetime
from mod_python import apache
from mod_python import Session
from mod_python import util
from phunc import *
from phunc.cx_wrapper import db_tools
from phunc.logger import logger
# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage, showErr = error.genErrorPage, error.showErr
jtable , sljtable = table.jtable, table.sljtable
def check_special_params(cursor):
"""
#TODO: put a comment here
Returns a tuple of 2 lists
"""
special_params = [{'param_id':'special_ac_cash','param_name':'CASH','param_desc':'CASH'},{'param_id':'special_ac_equip','param_name':'Capital Equipment','param_desc':'Capital Equipment'},{'param_id':'special_ac_comm_pay','param_name':'Commissions Payable','param_desc':'Commissions Payable'},{'param_id':'special_ac_sales_rev','param_name':'Sales Revenue','param_desc':'Sales Revenue'},{'param_id':'special_ac_comm_exp','param_name':'Commissions','param_desc':'Commissions'}]
leave_params = []
set_params = []
for param in special_params:
exist_special_params = None
if param['param_desc']:
exist_special_params = db_tools.exec_action(cursor, 'check_special_params', [param['param_id'],param['param_desc']])
else:
exist_special_params = db_tools.exec_action(cursor, 'check_special_params2', [param['param_id']])
if exist_special_params:
set_params.append(param)
else:
leave_params.append(param)
return set_params,leave_params
def index( req, **params ):
"""displays the GL account list with balances and links"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
accounts = db_tools.exec_action(dbc,'get_accounts2')
accounts_type = db_tools.exec_action(dbc,'get_accounts_type')
slink_list=[]
for account in accounts:
slink_dict={}
if account['subsidiary_shortname'] is None:
slink = ''
else:
slink = '<a href="/bin/finance.py/sub_account_index?sl=%s%s">detail</a>' % (account['subsidiary_shortname'], info.query_string.replace('?', '&'))
slink_dict['id']=account['id']
slink_dict['slink']=slink
slink_list.append(slink_dict)
page.content = {
'accounts':accounts,
'info_query_string':info.query_string.replace('?','&'),
'slink_list':slink_list,
'accounts_type':accounts_type,
}
page.setup = {
'breadcrumbs':['Finance'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account','special','linked', 'subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':'Chart of Accounts',
'broadcast_message':broadcast_message,
'template':'finance/f.opt',
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def sub_account_index( req,**params ):
"""displays a subledger account list with balances and links"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
accounts = db_tools.exec_action(dbc,'get_accounts',[params['sl'],params['sl']])
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
page.content = {
'accounts':accounts,
'info_sl':params['sl'],
'info_query_string':info.query_string.replace('?','&'),
'ledger':ledger
}
page.setup = {
'breadcrumbs':['finance', ledger],
'menu_title':'<dl class="ledger"><dd title="'+ledger+'">' + ledger + '</dd><dt> Ledger</dt></dl>',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount','spacer','subjournal','editsubjournal','postsubjournal'],
'content_title':'Chart of Accounts',
'broadcast_message':broadcast_message,
'template':'finance/f-sl.opt'
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl']
}
return page.render(debug=True)
def insert_sub_account1( req,**params ):
"""display form 1 of 2 for creating an account in the current subledger"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
link_candidates = db_tools.exec_action(dbc,'get_link_candidates')
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
page.content = {
'link_candidates':link_candidates,
'info_sl':params['sl']
}
page.setup = {
'breadcrumbs':['finance', 'subledger', 'New Account'],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount!','spacer','subjournal','editsubjournal','postsubjournal'],
'content_title':'Create Account',
'template':'finance/fac1-sl.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl'],
}
return page.render()
def insert_sub_account2( req,**params ):
"""display form 1 of 2 for creating an account in the current subledger"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
params_list={}
for field in params.keys():
params_list[field]=params[field]
if params.has_key('link_candidate') and params['link_candidate']!='':
page.content = {
'submit':False,
'link_candidate':params['link_candidate'].capitalize(),
'link_objects':db_tools.exec_action(dbc,'get_link_objects',[params['link_candidate']]),
'params_name':params.keys(),
'params_list':params
}
else:
page.content = {
'submit':True,
'params_name':params.keys(),
'params_list':params
}
page.setup = {
'breadcrumbs':['finance', 'subledger', 'New Account'],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount!','spacer','subjournal','editsubjournal','postsubjournal'],
'content_title':'Create Account',
'template':'finance/fac2-sl.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl'],
}
return page.render()
def create_account( req,**params ):
"""actually creates a GL account, redirects to finance index page (GL)"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map={'p_ledger':'','p_id':'','p_name':'','p_account_type_id':'','p_subsidiary_shortname':''}
account_name = params['name']
account_id = params['id']
account_type = params['account_type_id']
var_map['p_id'] = account_id
var_map['p_name'] = account_name
var_map['p_account_type_id'] = account_type
if params.has_key('has_subledger'):
subledger_name = params['short_name']
import re
p=re.compile(r'[a-zA-Z]+[a-zA-Z0-9_]*[a-zA-Z0-9]')
v=p.match(subledger_name)
if not v:
broadcast_message="Subledger shortname must start with a letter and contain only alphanumeric characters"
util.redirect(req,'/bin/finance.py?broadcast_message=%s'%broadcast_message)
else:
var_map['p_subsidiary_shortname'] = subledger_name
result = db_tools.exec_action(dbc,'create_account',[var_map['p_ledger'],var_map['p_id'],var_map['p_name'],var_map['p_account_type_id'],var_map['p_subsidiary_shortname']])[0]['create_account']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py?broadcast_message=%s'%broadcast_message)
def create_sub_account(req,**params):
"""actually creates a subledger account -- redirects to subledger"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
result = 'null'
if params.has_key('name') and params['name']!='':
same_view = db_tools.exec_action(dbc,'get_sub_account_name',[params['sl'],params['name']])
if len(same_view)==0:
result = db_tools.exec_action(dbc,'create_account',[params['sl'],'',params['name'],'',''])[0]['create_account']
else:
same_view = db_tools.exec_action(dbc,'get_sub_account_name',[params['sl'],'#'+params['link_candidate']+':'+params['link_object_id']])
if len(same_view)==0:
result = db_tools.exec_action(dbc,'create_account',[params['sl'],'','#'+params['link_candidate']+':'+params['link_object_id'],'',''])[0]['create_account']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/finance.py/sub_account_index?broadcast_message=%s&sl=%s"%(broadcast_message,params['sl']))
def insert_account(req,**params):
"""displays a form for createing a GL account"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page.content = {
'actypes':db_tools.exec_action(dbc,'get_account_type')
}
page.setup = {
'breadcrumbs':['finance','Create an Account'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account!', 'special','linked','subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':'Create an Account',
'template':'finance/fac.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def show_account_details(req,**params):
"""display t-account view of a GL account"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
account=''
if params.has_key('sl') and params['sl']:
account = db_tools.exec_action(dbc,'get_account2',[params['sl'],params['a']])
if len(account)==0:
account = db_tools.exec_action(dbc,'get_account',[params['a']])
if account:
account=account[0]['name']
page.content = {
'no_render':table.atable(dbc, 'general_' + params['a'], info.query_string)
}
page.setup = {
'window_title' :'A' + params['a'],
'breadcrumbs':['finance',params['a']],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account','special','linked', 'subledger','spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':account,
'template':'no_render.opt',
}
page.info = {
'query_string':info.query_string,
'a':params['a']
}
return page.render()
def show_sub_account_details(req,**params):
"""displays t-account view of a subledger account"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
account_name = db_tools.exec_action(dbc,'get_account2',[params['sl'],params['a']])[0]['name']
if account_name.find(':',0)>=0 and account_name.find('#',0)>=0:
account_name = db_tools.exec_action(dbc,'get_table_name',[account_name])[0]['find_name']
control_account_id = db_tools.exec_action(dbc,'get_control_account_id',[params['sl']])[0]['id']
account_id = '0000' + params['a']
formatted_account_id = str(control_account_id) + '.' + account_id[-5:]
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
page.content = {
'no_render':table.atable(dbc, params['sl'] + '_' + params['a'], info.query_string)
}
page.setup = {
'window_title':'A' + formatted_account_id,
'breadcrumbs':['finance','subledger',formatted_account_id],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount','spacer','subjournal','editsubjournal','postsubjournal'],
'content_title':account_name,
'template':'no_render.opt'
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl'],
'a':params['a']
}
return page.render()
def insert_journal(req,**params):
"""displays a form for creating a GL journal"""
page = Page(req, company_db=True)
page.content = {
'date_time':datetime.date.today().strftime('%d %b %Y'),
'operator_name':page.session['login_user_name'],
'coa':db_tools.exec_action(page.company_db.cursor(),'get_coa'),
'skin':page.session['skin']
}
page.setup = {
'breadcrumbs':['finance','Write a Journal'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked','subledger', 'spacer', 'journal!', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':'Write a Journal',
'template':'finance/fjc.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def insert_sub_journal(req,**params):
"""displays a form for creating a subledger journal"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
d_coa = db_tools.exec_action(dbc,'get_scoa',[params['sl']])
for ac in d_coa:
ac['sid'] = int(ac['id'].split('.')[1])
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
page.content = {
'd_coa':d_coa,
'g_coa':db_tools.exec_action(dbc,'get_coa'),
'datetime_time':datetime.date.today().strftime('%d %b %Y'),
'info_sl':params['sl'],
'g_account_id':control['id'],
'operator_name':page.session['login_user_name'],
'skin':page.session['skin']
}
page.setup = {
'breadcrumbs':['finance','subledger','New Journal'],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount','spacer','subjournal!','editsubjournal','postsubjournal'],
'content_title':'Create Journal',
'template':'finance/fjc-sl.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl']
}
return page.render()
def list_journal(req,**params):
"""displays a list of completed GL journals, with some links"""
page = Page(req, company_db=True)
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
journals = db_tools.exec_action(page.company_db.cursor(),'get_journals2')
for journal in journals:
journal['label'] = '<a href="/bin/finance.py/edit_journal?j=%s%s">%s\' \'%s</a>'%(str(journal['id']),info.query_string.replace('?', '&'),str(journal['id']),str(journal['date']))
form_setup={
'id':'journals',
'action':'/bin/finance.py/delete_journal',
'fieldsets':[{
'id':None,
'classid':'form fin-label',
'legend':'Completed Journals',
'items':[
{'type':'checkbox','checkbox_type':2,'checkbox_value':journals,'whole_label':None,'label':'label','id':'id','name':'journalId','value':'id','format':4},
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {'type':'div','id':None,'classid':'bottom input','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Delete selected'}]},
}
page.content = {
'journals':journals,
'info_query_string':info.query_string.replace('?', '&'),
'uform':form.user_form(**form_setup)
}
page.setup = {
'breadcrumbs':['finance','Edit or Delete Journals'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked','subledger', 'spacer', 'journal', 'editjournal!', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':'Edit or Delete Journals',
'broadcast_message':broadcast_message,
'template':'finance/fjd.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def list_sub_journal(req, **params):
"""displays a list of completed subledger journals, with some links"""
page = Page(req, company_db=True)
dbc=page.company_db.cursor()
ledger = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]['name']
page.content = {
'journals':db_tools.exec_action(page.company_db.cursor(),'get_journals',['=\'%s\''%params['sl']]),
'info_query_string':info.query_string.replace('?', '&'),
'info_sl':params['sl']
}
page.setup = {
'breadcrumbs':['finance','subledger','Journals'],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount','spacer','subjournal','editsubjournal!','postsubjournal'],
'content_title':'Edit or Delete Unposted Journals',
'template':'finance/fjd-sl.opt',
'form':True,
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or '',
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl'],
}
return page.render()
def edit_journal(req,**params):
"""displays a form for editing an unposted journal"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
page.content = {
'coa':db_tools.exec_action(dbc,'get_coa'),
'info_j':params['j'],
'date':db_tools.exec_action(dbc,'get_journal2',[params['j']])[0]['date'],
'journals':db_tools.exec_action(dbc,'get_journals2'),
'operator_name':page.session['login_user_name'],
'journal_items':db_tools.exec_action(dbc, 'get_journal_items', [int(params['j'])]),
'skin':page.session['skin']
}
page.setup = {
'breadcrumbs':['finance','journals','Edit J' + params['j']],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked','subledger', 'spacer', 'journal', 'editjournal!', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':'Edit Journal ' + params['j'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or '',
'template':'finance/fje.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
'j':params['j']
}
return page.render()
def edit_sub_journal(req,**params):
"""displays a form for editing an unposted journal"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
d_coa = db_tools.exec_action(dbc,'get_scoa',[params['sl']])
for ac in d_coa:
ac['sid'] = int(ac['id'].split('.')[1])
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
journal_items = db_tools.exec_action(dbc, 'get_journal_items', [int(params['j'])])
page.content = {
'd_coa':d_coa,
'g_coa':db_tools.exec_action(dbc,'get_coa'),
'g_account_id':control['id'],
'operator_name':page.session['login_user_name'],
'info_j':params['j'],
'info_sl':params['sl'],
'datetime_time':db_tools.exec_action(dbc,'get_journal2',[params['j']])[0]['date'],
'journals':db_tools.exec_action(dbc,'get_journals',['=\'%s\''%params['sl']]),
'sub_journal_items':db_tools.exec_action(dbc, 'get_sub_journal_items', [params['sl'],params['j']]),
'journal_items':journal_items,
'has_input_DR':'false',
'has_input_CR':'false',
'skin':page.session['skin']
}
for item in journal_items:
if item['account_id'] == control['id']:
if item['drcr']=='DR':
page.content['has_input_DR'] = 'true'
else:
page.content['has_input_CR'] = 'true'
break
page.setup = {
'breadcrumbs':['finance','subledger','subjournals','Edit J' + params['j']],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount','spacer','subjournal','editsubjournal!','postsubjournal'],
'content_title':'Edit Journal ' + params['j'],
'broadcast_message':broadcast_message,
'template':'finance/fje-sl.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl'],
}
return page.render()
def create_sub_journal(req, **params):
"""actually creates a subledger journal -- redirects to post subledger journals page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map={'p_description':'','p_account_id':'','p_amount':'','p_drcr':'','p_subledger':'','p_sl_description':'','p_sl_account_id':'','p_sl_amount':'','p_sl_drcr':'','p_post':'false'}
if type(params['g_accountId']) == type([]):
for i in xrange(len(params['g_accountId'])):
var_map['p_account_id'] += '"'+params['g_accountId'][i]+'",'
var_map['p_description'] += '"'+params['g_description'][i]+'",'
if params['g_DRamount'][i] != '':
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_DRamount'][i])+'",'
var_map['p_drcr'] += '"DR",'
else:
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_CRamount'][i])+'",'
var_map['p_drcr'] += '"CR",'
var_map['p_account_id'] = var_map['p_account_id'][:-1]
var_map['p_description'] = var_map['p_description'][:-1]
var_map['p_amount'] = var_map['p_amount'][:-1]
var_map['p_drcr'] = var_map['p_drcr'][:-1]
else:
var_map['p_account_id'] += '"'+params['g_accountId']+'"'
var_map['p_description'] += '"'+params['g_description']+'"'
if params['DRamount'] != '':
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_DRamount'])+'"'
var_map['p_drcr'] += '"DR"'
else:
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_CRamount'])+'"'
var_map['p_drcr'] += '"CR"'
var_map['p_subledger'] += params['sl']
if type(params['d_accountId']) == type([]):
for i in xrange(len(params['d_accountId'])):
var_map['p_sl_account_id'] += '"'+params['d_accountId'][i]+'",'
var_map['p_sl_description'] += '"'+params['d_description'][i]+'",'
if params['d_DRamount'][i] != '':
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_DRamount'][i])+'",'
var_map['p_sl_drcr'] += '"DR",'
else:
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_CRamount'][i])+'",'
var_map['p_sl_drcr'] += '"CR",'
var_map['p_sl_account_id'] = var_map['p_sl_account_id'][:-1]
var_map['p_sl_description'] = var_map['p_sl_description'][:-1]
var_map['p_sl_amount'] = var_map['p_sl_amount'][:-1]
var_map['p_sl_drcr'] = var_map['p_sl_drcr'][:-1]
else:
var_map['p_sl_account_id'] += '"'+params['d_accountId']+'"'
var_map['p_sl_description'] += '"'+params['d_description']+'"'
if params['d_DRamount'] != '':
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_DRamount'])+'"'
var_map['p_sl_drcr'] += '"DR"'
else:
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_CRamount'])+'"'
var_map['p_sl_drcr'] += '"CR"'
#this next line can't possibly work - it should be going to a special function for that subledger
result = db_tools.exec_action(dbc,'create_journal',[params['date'], var_map['p_description'],var_map['p_account_id'],var_map['p_amount'],var_map['p_drcr'],var_map['p_sl_description'],var_map['p_sl_account_id'],var_map['p_sl_amount'],var_map['p_sl_drcr'],var_map['p_post']])[0]['create_journal']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/finance.py/list_sub_post_journal?broadcast_message=%s&sl=%s"%(broadcast_message,params['sl']))
def edit_sub_journal_complete( req,**params ):
"""actaully updates a subledger journal -- redirects to edit subledger journals page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map={'p_journal_id':'null','p_old_d_item_id':'','p_old_g_item_id':'','p_description':'','p_account_id':'','p_amount':'','p_drcr':'','p_subledger':'','p_sl_description':'','p_sl_account_id':'','p_sl_amount':'','p_sl_drcr':'','p_post':'false','p_old_g_amount':'','p_old_g_description':''}
if params.has_key('old_d_accountId'):
old_accountset = params['old_d_accountId']
if type(old_accountset) == type([]):
for i in xrange(len(params['old_d_accountId'])):
var_map['p_old_d_item_id'] += params['old_d_accountId'][i]+','
var_map['p_old_d_item_id'] = var_map['p_old_d_item_id'][:-1]
else:
var_map['p_old_d_item_id'] += params['old_d_accountId']
if params.has_key('old_g_accountId'):
if params['old_g_DRamount']!='':
var_map['p_old_g_amount'] = utils.escape_comma_in_number(params['old_g_DRamount'])
else:
var_map['p_old_g_amount'] = utils.escape_comma_in_number(params['old_g_CRamount'])
var_map['p_old_g_description'] = params['old_g_description']
old_accountset = params['old_g_accountId']
if type(old_accountset) == type([]):
for i in xrange(len(params['old_g_accountId'])):
var_map['p_old_g_item_id'] += params['old_g_accountId'][i]+','
var_map['p_old_g_item_id'] = var_map['p_old_g_item_id'][:-1]
else:
var_map['p_old_g_item_id'] += params['old_g_accountId']
var_map['p_journal_id'] = params['j']
if params.has_key('g_accountId'):
if type(params['g_accountId']) == type([]):
for i in xrange(len(params['g_accountId'])):
var_map['p_account_id'] += '"'+params['g_accountId'][i]+'",'
var_map['p_description'] += '"'+params['g_description'][i]+'",'
if params['g_DRamount'][i] != '':
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_DRamount'][i])+'",'
var_map['p_drcr'] += '"DR",'
else:
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_CRamount'][i])+'",'
var_map['p_drcr'] += '"CR",'
var_map['p_account_id'] = var_map['p_account_id'][:-1]
var_map['p_description'] = var_map['p_description'][:-1]
var_map['p_amount'] = var_map['p_amount'][:-1]
var_map['p_drcr'] = var_map['p_drcr'][:-1]
else:
var_map['p_account_id'] += '"'+params['g_accountId']+'"'
var_map['p_description'] += '"'+params['g_description']+'"'
if params['g_DRamount'] != '':
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_DRamount'])+'"'
var_map['p_drcr'] += '"DR"'
else:
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['g_CRamount'])+'"'
var_map['p_drcr'] += '"CR"'
var_map['p_subledger'] = params['sl']
if params.has_key('d_accountId'):
if type(params['d_accountId']) == type([]):
for i in xrange(len(params['d_accountId'])):
var_map['p_sl_account_id'] += '"'+params['d_accountId'][i]+'",'
var_map['p_sl_description'] += '"'+params['d_description'][i]+'",'
if params['d_DRamount'][i] != '':
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_DRamount'][i])+'",'
var_map['p_sl_drcr'] += '"DR",'
else:
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_CRamount'][i])+'",'
var_map['p_sl_drcr'] += '"CR",'
var_map['p_sl_account_id'] = var_map['p_sl_account_id'][:-1]
var_map['p_sl_description'] = var_map['p_sl_description'][:-1]
var_map['p_sl_amount'] = var_map['p_sl_amount'][:-1]
var_map['p_sl_drcr'] = var_map['p_sl_drcr'][:-1]
else:
var_map['p_sl_account_id'] += '"'+params['d_accountId']+'"'
var_map['p_sl_description'] += '"'+params['d_description']+'"'
if params['d_DRamount'] != '':
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_DRamount'])+'"'
var_map['p_sl_drcr'] += '"DR"'
else:
var_map['p_sl_amount'] += '"'+utils.escape_comma_in_number(params['d_CRamount'])+'"'
var_map['p_sl_drcr'] += '"CR"'
logger.debug(params['j'])
result = db_tools.exec_action(dbc,'edit_journal',[var_map['p_journal_id'],var_map['p_old_g_item_id'],var_map['p_old_g_amount'],var_map['p_old_g_description'],var_map['p_old_d_item_id'],var_map['p_description'],var_map['p_account_id'],var_map['p_amount'],var_map['p_drcr'],var_map['p_sl_description'],var_map['p_sl_account_id'],var_map['p_sl_amount'],var_map['p_sl_drcr'],var_map['p_post']])[0]['edit_journal']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/finance.py/edit_sub_journal?broadcast_message=%s&sl=%s&j=%s"%(broadcast_message,params['sl'],params['j']))
def post_journal( req,**params ):
"""actually posts a GL journal -- redirects to finance index page (GL)"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
result = ''
if params.has_key('journalId'):
if type(params['journalId']) == type([]):
for journalid in params['journalId']:
result = db_tools.exec_action(dbc,'post_journal',[journalid])[0]['post_journal']
if result % 100 !=0:
break
else:
result = db_tools.exec_action(dbc,'post_journal',[params['journalId']])[0]['post_journal']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
else:
broadcast_message = 'No journals selected'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py?broadcast_message=%s'%broadcast_message)
def post_sub_journal( req,**params ):
"""actually posts a subledger journal -- redirects to subledger index page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
result = ''
if params.has_key('journalId'):
if type(params['journalId']) == type([]):
for journalid in params['journalId']:
result = db_tools.exec_action(dbc,'post_journal',[journalid])[0]['post_journal']
if result % 100 !=0:
break
else:
result = db_tools.exec_action(dbc,'post_journal',[params['journalId']])[0]['post_journal']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
else:
broadcast_message = 'No journals selected'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py/sub_account_index?sl=%s&broadcast_message=%s'%(params['sl'],broadcast_message))
def list_post_journal( req,**params ):
"""displays a list of postable GL journals, with links"""
page = Page(req, company_db=True)
journals = db_tools.exec_action(page.company_db.cursor(),'get_journals',['is NULL'])
for journal in journals:
journal['label'] = '<a href="/bin/finance.py/journal_details?j=%s%s">%s\' \'%s</a>'%(str(journal['id']),info.query_string.replace('?', '&'),str(journal['id']),str(journal['date']))
form_setup={
'id':'journals',
'action':'/bin/finance.py/post_journal',
'fieldsets':[{
'id':None,
'classid':'form fin-label',
'legend':'Completed Journals',
'items':[
{'type':'checkbox','checkbox_type':2,'checkbox_value':journals,'whole_label':None,'label':'label','id':'id','name':'journalId','value':'id','format':4},
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {'type':'div','id':None,'classid':'bottom input','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Post selected to ledger'}]},
}
page.content = {
'journals':journals,
'info_query_string':info.query_string.replace('?', '&'),
'uform':form.user_form(**form_setup)
}
page.setup = {
'breadcrumbs':['finance','Post Journals'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked', 'subledger','spacer', 'journal', 'editjournal', 'postjournal!','spacer', 'balsheet','pl','taxreport'],
'content_title':'Post Journals',
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or '',
'template':'finance/fjp.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def list_sub_post_journal( req,**params ):
"""displays a list of postable subledger journals, with links"""
page = Page(req, company_db=True)
dbc=page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
journals = db_tools.exec_action(page.company_db.cursor(),'get_journals',['=\'%s\''%params['sl']])
ledger = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]['name']
page.content = {
'journals':journals,
'info_query_string':info.query_string.replace('?', '&'),
'info_sl':params['sl']
}
page.setup = {
'breadcrumbs':['finance','subledger','Journals'],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount','spacer','subjournal','editsubjournal','postsubjournal!'],
'content_title':'Unposted Journals',
'broadcast_message':broadcast_message,
'template':'finance/fjp-sl.opt',
'form':True
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl']
}
return page.render()
def journal_details( req,**params ):
"""displays a GL journal"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
jdate = db_tools.exec_action(dbc,'get_journal2',[params['j']])[0]['id']
page.content = {
'no_render':jtable(dbc, params['j'], info.query_string)
}
page.setup = {
'window_title':'J' + params['j'],
'breadcrumbs':['finance','Journal #' + params['j']],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked', 'subledger','spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':'Journal #' + str(jdate),
'template':'no_render.opt'
}
page.info = {
'query_string':info.query_string,
'j':params['j']
}
return page.render()
def sub_journal_details( req,**params ):
"""displays a GL journal"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]
ledger = control['name']
jdate = db_tools.exec_action(dbc,'get_journal2',[params['j']])[0]['id']
page.content = {
'no_render':sljtable(dbc, params['j'], params['sl'], control['id'], info.query_string)
}
page.setup = {
'window_title':'J' + params['j'],
'breadcrumbs':['finance','subledger','J' + params['j']],
'menu_title':ledger + ' Ledger',
'menu':(params['sl']=='ar' or params['sl']=='ap') and ['spacer'] or ['subaccount','spacer','subjournal','editsubjournal','postsubjournal'],
'content_title':jdate,
'template':'no_render.opt'
}
page.info = {
'query_string':info.query_string,
'ledger':ledger,
'sl':params['sl'],
'j':params['j']
}
return page.render()
def create_sub_ledger(req, **params):
"""actually creates a subledger -- redirects to finance index page (GL)"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
control_account_id = params['control_id']
subledger_name = params['short_name']
import re
p=re.compile(r'[a-zA-Z]+[a-zA-Z0-9_]*[a-zA-Z0-9]')
v=p.match(subledger_name)
if not v:
broadcast_message="Subledger shortname must start with a letter and consist of only alphanumeric characters"
util.redirect(req,'/bin/finance.py?broadcast_message=%s'%broadcast_message)
else:
result = db_tools.exec_action(dbc,'create_subledger',[subledger_name,control_account_id])[0]['create_subledger']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py?broadcast_message=%s'%broadcast_message)
def insert_sub_ledger(req,**params):
"""displays a form for creating a subledger"""
page = Page(req, company_db=True)
page.content = {
'candidates':db_tools.exec_action(page.company_db.cursor(),'get_candidates')
}
page.setup = {
'breadcrumbs':['finance','Create a Subsidiary Ledger'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked', 'subledger!','spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'content_title':'Create a Subsidiary Ledger',
'template':'finance/flc.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_journal( req,**params ):
"""actually creates a GL journal -- redirects to post journals page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
var_map={'p_description':'','p_account_id':'','p_amount':'','p_drcr':'','p_subledger':'','p_sl_description':'','p_sl_account_id':'','p_sl_amount':'','p_sl_drcr':'','p_post':'false'}
var_map['p_description'] = ''
var_map['p_account_id'] = ''
var_map['p_amount'] = ''
var_map['p_drcr'] = ''
if type(params['account_id']) == type([]):
for i in xrange(len(params['account_id'])):
var_map['p_account_id'] += '"'+params['account_id'][i]+'",'
var_map['p_description'] += '"'+params['description'][i]+'",'
if params['dr_amount'][i] != '':
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['dr_amount'][i])+'",'
var_map['p_drcr'] += '"DR",'
else:
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['cr_amount'][i])+'",'
var_map['p_drcr'] += '"CR",'
var_map['p_account_id'] = var_map['p_account_id'][:-1]
var_map['p_description'] = var_map['p_description'][:-1]
var_map['p_amount'] = var_map['p_amount'][:-1]
var_map['p_drcr'] = var_map['p_drcr'][:-1]
else:
var_map['p_account_id'] += '"'+params['account_id']+'"'
var_map['p_description'] += '"'+params['description']+'"'
if params['dr_amount'] != '':
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['dr_amount'])+'"'
var_map['p_drcr'] += '"DR"'
else:
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['cr_amount'])+'"'
var_map['p_drcr'] += '"CR"'
result = db_tools.exec_action(dbc,'create_journal',[params['journal_date'],var_map['p_description'],var_map['p_account_id'],var_map['p_amount'],var_map['p_drcr'],var_map['p_sl_description'],var_map['p_sl_account_id'],var_map['p_sl_amount'],var_map['p_sl_drcr'],var_map['p_post']])[0]['create_journal']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py/list_post_journal?broadcast_message=%s'%broadcast_message)
def edit_journal_complete( req,**params ):
"""actually updates a GL journal -- redirects to post journals page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
var_map={'p_journal_id':'null','p_old_d_item_id':'','p_old_g_item_id':'','p_description':'','p_account_id':'','p_amount':'','p_drcr':'','p_subledger':'','p_sl_description':'','p_sl_account_id':'','p_sl_amount':'','p_sl_drcr':'','p_post':'false','p_old_g_amount':'null','p_old_g_description':''}
var_map['p_description'] = ''
var_map['p_account_id'] = ''
var_map['p_amount'] = ''
var_map['p_drcr'] = ''
if params.has_key('old_accountId'):
old_accountset = params['old_accountId']
if type(old_accountset) == type([]):
for i in xrange(len(params['old_accountId'])):
var_map['p_old_g_item_id'] += params['old_accountId'][i]+','
var_map['p_old_g_item_id'] = var_map['p_old_g_item_id'][:-1]
else:
var_map['p_old_g_item_id'] += params['old_accountId']
var_map['p_journal_id'] = params['j']
if params.has_key('accountId'):
if type(params['accountId']) == type([]):
for i in xrange(len(params['accountId'])):
var_map['p_account_id'] += '"'+params['accountId'][i]+'",'
var_map['p_description'] += '"'+params['description'][i]+'",'
if params['DRamount'][i] != '':
var_map['p_amount'] += '"'+params['DRamount'][i]+'",'
var_map['p_drcr'] += '"DR",'
else:
var_map['p_amount'] += '"'+params['CRamount'][i]+'",'
var_map['p_drcr'] += '"CR",'
var_map['p_account_id'] = var_map['p_account_id'][:-1]
var_map['p_description'] = var_map['p_description'][:-1]
var_map['p_amount'] = var_map['p_amount'][:-1]
var_map['p_drcr'] = var_map['p_drcr'][:-1]
else:
var_map['p_account_id'] += '"'+params['accountId']+'"'
var_map['p_description'] += '"'+params['description']+'"'
if params['DRamount'] != '':
var_map['p_amount'] += '"'+params['DRamount']+'"'
var_map['p_drcr'] += '"DR"'
else:
var_map['p_amount'] += '"'+params['CRamount']+'"'
var_map['p_drcr'] += '"CR"'
result = db_tools.exec_action(dbc,'edit_journal',[var_map['p_journal_id'],var_map['p_old_g_item_id'],var_map['p_old_g_amount'],var_map['p_old_g_description'],var_map['p_old_d_item_id'],var_map['p_description'],var_map['p_account_id'],var_map['p_amount'],var_map['p_drcr'],var_map['p_subledger'],var_map['p_sl_description'],var_map['p_sl_account_id'],var_map['p_sl_amount'],var_map['p_sl_drcr'],var_map['p_post']])[0]['edit_journal']
conn.commit()
result_desc = showErr(int(result))
broadcast_message = result_desc
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py/list_post_journal?broadcast_message=%s'%(params['j'],broadcast_message))
def delete_journal( req,**params ):
"""actually deletes a GL journal -- redirects to journal list page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
if params.has_key('journalId'):
journalset = params['journalId']
if type(journalset)==type([]):
for journal_id in journalset:
db_tools.exec_action(dbc,'delete_journal',[journal_id])
else:
db_tools.exec_action(dbc,'delete_journal',[journalset])
conn.commit()
broadcast_message = 'Deleted'
else:
broadcast_message = 'No journal selected!'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/finance.py/list_journal?broadcast_message=%s"%broadcast_message)
def delete_sub_journal( req,**params ):
"""actually deletes a subledger journal -- redirects to journal list page"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
broadcast_message = ''
if params.has_key('journalId'):
journalset = params['journalId']
if type(journalset)==type([]):
for journal_id in journalset:
db_tools.exec_action(dbc,'delete_journal',[journal_id])
else:
db_tools.exec_action(dbc,'delete_journal',[journalset])
conn.commit()
broadcast_message = 'Deleted'
else:
broadcast_message = 'No journal selected!'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/finance.py/list_sub_journal?broadcast_message=%s&sl=%s"%(broadcast_message,params['sl']))
def insert_expenses( req,**params ):
"""displays a form for recording expenses"""
import datetime
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
all_expense_taxes = db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail purchase'])
page.content = {
'expense_accounts':db_tools.exec_action(dbc,'get_same_type_accounts', ['EXPENSE']),
'skin':page.session['skin'],
'today':datetime.date.today().isoformat(),
'all_expense_taxes':[],
'last_expense_taxes':[]
}
if len(all_expense_taxes)>0:
for i in range(len(all_expense_taxes)-1):
page.content['all_expense_taxes'].append(all_expense_taxes[i])
page.content['last_expense_taxes'].append(all_expense_taxes[-1])
page.setup = {
'breadcrumbs':['finance','Record Expenses'],
'menu_title':'General Ledger',
'menu':['recordexp!', 'spacer', 'account', 'special','linked','subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Record Expenses',
'template':'finance/fer.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_expenses_report( req,**params ):
"""actually creates an expense report -- redirects to expense report form"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
all_expense_taxes = db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail purchase'])
#TODO:add string escape (",) and add a function to translate None to NULL.
var_map = {'p_report_id':'', 'p_expenses_relate_to':'','p_account_id':'','p_amount':'','p_description':'','p_tax_ids':'', 'p_tax_amounts':''}
var_map['p_expenses_relate_to'] = utils.escape_quotes_in_sql(params['relate_to'])
if type(params['accountId']) == list:
for i in xrange(len(params['accountId'])):
var_map['p_account_id'] += '"'+params['accountId'][i]+'",'
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['DRamount'][i])+'",'
var_map['p_description'] += '"'+utils.escape_quotes_in_procedure(params['description'][i])+'",'
tax_id_temp, tax_amount_temp = '', ''
for tax in all_expense_taxes:
tax_id_temp += str(tax['id']) +','
tax_amount_temp += utils.escape_comma_in_number(params[tax['shortname']][i]) + ','
tax_id_temp = '"'+tax_id_temp[:-1]+'"'
tax_amount_temp = '"'+tax_amount_temp[:-1]+'"'
var_map['p_tax_ids'] += tax_id_temp + ','
var_map['p_tax_amounts'] += tax_amount_temp + ','
var_map['p_account_id'] = var_map['p_account_id'][:-1]
var_map['p_amount'] = var_map['p_amount'][:-1]
var_map['p_description'] = var_map['p_description'][:-1]
var_map['p_tax_ids'] = '{'+var_map['p_tax_ids'][:-1]+'}'
var_map['p_tax_amounts'] = '{'+var_map['p_tax_amounts'][:-1]+'}'
else:
var_map['p_account_id'] += '"'+params['accountId']+'"'
var_map['p_amount'] += '"'+utils.escape_comma_in_number(params['DRamount'])+'"'
var_map['p_description'] += '"'+utils.escape_quotes_in_procedure(params['description'])+'"'
tax_id_temp, tax_amount_temp = '', ''
for tax in all_expense_taxes:
tax_id_temp += str(tax['id']) +','
tax_amount_temp += utils.escape_comma_in_number(params[tax['shortname']]) + ','
var_map['p_tax_ids'] = '{"'+tax_id_temp[:-1]+'"}'
var_map['p_tax_amounts'] = '{"'+tax_amount_temp[:-1]+'"}'
if len(all_expense_taxes) == 0:
result = db_tools.exec_action(dbc, 'create_expense_report', [var_map['p_report_id'],params['expense_report_date'],var_map['p_expenses_relate_to'],var_map['p_account_id'], var_map['p_amount'], var_map['p_description'], 'None', 'None'], nullify = True, escaped = True)[0]['create_expense_report']
else:
result = db_tools.exec_action(dbc,'create_expense_report', [var_map['p_report_id'],var_map['p_expenses_relate_to'],params['expense_report_date'],var_map['p_account_id'], var_map['p_amount'], var_map['p_description'], var_map['p_tax_ids'], var_map['p_tax_amounts']], nullify = True, escaped = True)[0]['create_expense_report']
conn.commit()
broadcast_message = showErr(int(result))
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py/insert_expenses?broadcast_message=%s'% broadcast_message)
def special_params_setting_page(req,**params):
"""displays a form for setting special account flags"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
set_params,leave_params = check_special_params(dbc)
special_params = [{'param_id':'special_ac_cash','param_name':'CASH','param_desc':'CASH'},{'param_id':'special_ac_equip','param_name':'Capital Equipment','param_desc':'Capital Equipment'},{'param_id':'special_ac_comm_pay','param_name':'Commissions Payable','param_desc':'Commissions Payable'},{'param_id':'special_ac_sales_rev','param_name':'Sales Revenue','param_desc':'Sales Revenue'},{'param_id':'special_ac_comm_exp','param_name':'Commissions','param_desc':'Commissions'}]
special_params_details = db_tools.exec_action(dbc, 'get_special_params_details', [tuple([a['param_id'] for a in special_params])])
revenueAccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['REVENUE'])
expenseAccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['EXPENSE'])
liabilityAccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['LIABILITY'])
assetAccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['ASSET'])
for param in special_params:
if param['param_id']=='special_ac_cash':
flag=False
if assetAccounts:
for asset in assetAccounts:
if special_params_details:
for specialParams in special_params_details:
if specialParams['code_id']==param['param_id'] and specialParams['code_value']==asset['id']:
specialParams['seted']=True
flag=True
break
if not flag:
for asset in assetAccounts:
if 'cash' in asset['name'].lower():
specialParams={}
specialParams['code_id'] = param['param_id']
specialParams['code_value'] = asset['id']
specialParams['seted'] = False
special_params_details.append(specialParams)
break
if param['param_id']=='special_ac_equip':
flag=False
if assetAccounts:
for asset in assetAccounts:
if special_params_details:
for specialParams in special_params_details:
if specialParams['code_id']==param['param_id'] and specialParams['code_value']==asset['id']:
specialParams['seted']=True
flag=True
break
if not flag:
for asset in assetAccounts:
if 'equipment' in asset['name'].lower():
specialParams={}
specialParams['code_id'] = param['param_id']
specialParams['code_value'] = asset['id']
specialParams['seted'] = False
special_params_details.append(specialParams)
break
if param['param_id']=='special_ac_comm_pay':
flag=False
if liabilityAccounts:
for liability in liabilityAccounts:
if special_params_details:
for specialParams in special_params_details:
if specialParams['code_id']==param['param_id'] and specialParams['code_value']==liability['id']:
specialParams['seted']=True
flag=True
break
if not flag:
for liability in liabilityAccounts:
if 'commission' in liability['name'].lower():
specialParams={}
specialParams['code_id'] = param['param_id']
specialParams['code_value'] = liability['id']
specialParams['seted'] = False
special_params_details.append(specialParams)
break
if param['param_id']=='special_ac_sales_rev':
flag=False
if revenueAccounts:
for rev in revenueAccounts:
if special_params_details:
for specialParams in special_params_details:
if specialParams['code_id']==param['param_id'] and specialParams['code_value']==rev['id']:
specialParams['seted']=True
flag=True
break
if not flag:
for rev in revenueAccounts:
if 'sales' in rev['name'].lower():
specialParams={}
specialParams['code_id'] = param['param_id']
specialParams['code_value'] = rev['id']
specialParams['seted'] = False
special_params_details.append(specialParams)
break
if param['param_id']=='special_ac_comm_exp':
flag=False
if expenseAccounts:
for exp in expenseAccounts:
if special_params_details:
for specialParams in special_params_details:
if specialParams['code_id']==param['param_id'] and specialParams['code_value']==exp['id']:
specialParams['seted']=True
flag=True
break
if not flag:
for exp in expenseAccounts:
if 'commission' in exp['name'].lower():
specialParams={}
specialParams['code_id'] = param['param_id']
specialParams['code_value'] = exp['id']
specialParams['seted'] = False
special_params_details.append(specialParams)
break
#return special_params_details,len(special_params_details)
page.content = {
'set_params':set_params,
'leave_params':leave_params,
'special_params':special_params,
'special_params_details':special_params_details,
'revenueAccounts':revenueAccounts,
'expenseAccounts':expenseAccounts,
'liabilityAccounts':liabilityAccounts,
'assetAccounts':assetAccounts,
#'redirect_url':'/bin/'+page.session['user_access'].split(',')[0]+'.py'
'redirect_url':'/bin/'+page.session['user_access'].values()[0]+'.py'
}
page.setup = {
'breadcrumbs':['finance','Set Special Accounts'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special!','linked','subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Set Special Accounts',
'template':'finance/special_params_setting.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def special_params_setting_submit(req,**params):
"""actually sets the special account flags -- redirects to special accounts form"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
special_params = [{'param_id':'special_ac_cash','param_name':'CASH','param_desc':'CASH'},{'param_id':'special_ac_equip','param_name':'Capital Equipment','param_desc':'Capital Equipment'},{'param_id':'special_ac_comm_pay','param_name':'Commissions Payable','param_desc':'Commissions Payable'},{'param_id':'special_ac_sales_rev','param_name':'Sales Revenue','param_desc':'Sales Revenue'},{'param_id':'special_ac_comm_exp','param_name':'Commissions','param_desc':'Commissions'}]
for param in special_params:
if params.has_key(param['param_id']):
logger.debug('***** exist Code *******')
logger.debug(param['param_desc'])
existCode = db_tools.exec_action(dbc, 'check_sys_code', [param['param_id'],param['param_desc']])
if params[param['param_id']].strip():
if existCode:
db_tools.exec_action(dbc, 'update_sys_code', [params[param['param_id']],param['param_id'],param['param_desc']])
else:
db_tools.exec_action(dbc, 'insert_sys_code', [param['param_id'],params[param['param_id']],param['param_desc']])
else:
if existCode:
db_tools.exec_action(dbc, 'delete_sys_code', [param['param_id'],param['param_desc']])
conn.commit()
broadcast_message = 'Special accounts have been flagged'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,"/bin/finance.py/special_params_setting_page")
def linked_account_setting_page( req,**params ):
"""displays a form for setting linked accounts (for transaction taxes)"""
page = Page(req, company_db=True)
dbc = page.company_db.cursor()
taxSets = db_tools.exec_action(dbc,'get_tax')
liabilityAccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['LIABILITY'])
assetAccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['ASSET'])
linkedAccountDetails = db_tools.exec_action(dbc,'get_linked_account_details')
for tax in taxSets:
flag=False
if liabilityAccounts:
for liability in liabilityAccounts:
for linkedAccount in linkedAccountDetails:
if linkedAccount['transaction_tax_shortname']==tax['shortname'] and linkedAccount['account_id']==liability['id']:
linkedAccount['seted'] = True
flag=True
break
if not flag:
for liability in liabilityAccounts:
if tax['shortname'].lower() in liability['name'].lower():
linkedAccount={}
linkedAccount['transaction_tax_shortname']=tax['shortname']
linkedAccount['account_id']=liability['id']
linkedAccount['seted']=False
linkedAccountDetails.append(linkedAccount)
flag=True
break
if not flag:
for liability in liabilityAccounts:
if 'tax' in liability['name'].lower():
linkedAccount={}
linkedAccount['transaction_tax_shortname']=tax['shortname']
linkedAccount['account_id']=liability['id']
linkedAccount['seted']=False
linkedAccountDetails.append(linkedAccount)
break
if tax['track_on_purchases']:
flag=False
if assetAccounts:
for asset in assetAccounts:
for linkedAccount in linkedAccountDetails:
if linkedAccount['transaction_tax_shortname']==tax['shortname'] and linkedAccount['account_id']==asset['id']:
linkedAccount['seted'] = True
flag=True
break
if not flag:
for asset in assetAccounts:
if tax['shortname'].lower() in asset['name'].lower():
linkedAccount={}
linkedAccount['transaction_tax_shortname']=tax['shortname']
linkedAccount['account_id']=asset['id']
linkedAccount['seted']=False
linkedAccountDetails.append(linkedAccount)
flag=True
break
if not flag:
for asset in assetAccounts:
if 'tax' in asset['name'].lower():
linkedAccount={}
linkedAccount['transaction_tax_shortname']=tax['shortname']
linkedAccount['account_id']=asset['id']
linkedAccount['seted']=False
linkedAccountDetails.append(linkedAccount)
break
page.content = {
'taxSets':taxSets,
'liabilityAccounts':liabilityAccounts,
'assetAccounts':assetAccounts,
'linkedAccountDetails':linkedAccountDetails
}
page.setup = {
'breadcrumbs':['finance','Set Tax Accounts'],
'menu_title':'General Ledger',
'menu':['recordexp', 'spacer', 'account', 'special','linked!','subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer', 'balsheet','pl','taxreport'],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
'content_title':'Set Tax Accounts',
'template':'finance/olas.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def linked_account_setting_submit(req,**params):
"""actually sets the linked accounts -- redirects to linked accounts form"""
try:
session = Session.Session(req)
check_access(req,session, req.uri)
conn = get_connection(session)
dbc = conn.cursor()
RETAIL_SALE = {'suffix':'_retail_sale','value':'retail sale'}
RETAIL_PURCHASE = {'suffix':'_retail_purchase','value':'retail purchase'}
taxSets = db_tools.exec_action(dbc,'get_tax')
for tax in taxSets:
if params.has_key(tax['shortname']+RETAIL_SALE['suffix']):
existLinkedAccount = db_tools.exec_action(dbc,'get_linked_account_of_tax',[tax['shortname'],RETAIL_SALE['value']])
if params[tax['shortname']+RETAIL_SALE['suffix']].strip():
if existLinkedAccount:
db_tools.exec_action(dbc,'update_linked_account',[params[tax['shortname']+RETAIL_SALE['suffix']],tax['shortname'],RETAIL_SALE['value']])
else:
db_tools.exec_action(dbc,'insert_linked_account',[tax['shortname'],RETAIL_SALE['value'],params[tax['shortname']+RETAIL_SALE['suffix']]])
else:
if existLinkedAccount:
db_tools.exec_action(dbc,'delete_linked_account',[tax['shortname'],RETAIL_SALE['value']])
if params.has_key(tax['shortname']+RETAIL_PURCHASE['suffix']):
existLinkedAccount = db_tools.exec_action(dbc,'get_linked_account_of_tax',[tax['shortname'],RETAIL_PURCHASE['value']])
if params[tax['shortname']+RETAIL_PURCHASE['suffix']].strip():
if existLinkedAccount:
db_tools.exec_action(dbc,'update_linked_account',[params[tax['shortname']+RETAIL_PURCHASE['suffix']],tax['shortname'],RETAIL_PURCHASE['value']])
else:
db_tools.exec_action(dbc,'insert_linked_account',[tax['shortname'],RETAIL_PURCHASE['value'],params[tax['shortname']+RETAIL_PURCHASE['suffix']]])
else:
if existLinkedAccount:
db_tools.exec_action(dbc,'delete_linked_account',[tax['shortname'],RETAIL_PURCHASE['value']])
conn.commit()
broadcast_message = 'Linked accounts set'
except GeneralBusinessErr,e:
broadcast_message = e.getErrMsg()
except Exception,e:
errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
except:
broadcast_message = 'An undefined error occurred'
finally:
util.redirect(req,'/bin/finance.py/linked_account_setting_page?broadcast_message=%s'%broadcast_message)
| Python |
"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008 Obol Software Pty Ltd
This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt
"""
import datetime
from mod_python import apache
from mod_python import Session
from mod_python import util
from phunc import *
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger
# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage = error.genErrorPage
##def sessionise_user_portals(access_portals,session):
## """
## Stamps user portals onto session
## Returns nothing
## """
## portals = []
## for portal in access_portals:
## portals.append(portal['name'])
## session['user_access'] = ','.join(portals)
## session.save()
class CountryCodeErr(Exception):
pass
class DataBaseErr(Exception):
pass
def sessionise_user_portals(access_portals,session):
"""
Stamps user portals onto session
Returns nothing
"""
portals = {}
for portal in access_portals:
portals[portal['id']]=portal['name']
session['user_access'] = portals
session.save()
def company_group_affiliation(cursor, user_name, company_id, group_id):
"""
Checks affiliation to company and group
Returns a boolean
"""
return len(db_tools.exec_action(cursor, 'get_affiliation_info',[user_name, int(company_id), int(group_id)])) > 0
def group_exists(cursor, name):
"""
Checks if group exists
Returns a boolean
"""
return len(db_tools.exec_action(cursor, 'get_group_by_name', [name])) > 0
def tax_page_updated_today(company_id):
"""
Checks if tax page server has been interrogated for updates (stamps date if not - since it is about to be)
Returns a boolean
"""
import datetime
try:
have_updated = utils.read_file_content_local(info.LOCAL_TP_INDEX_LOCK+'_'+str(company_id)) == str(datetime.date.today())
except IOError, e:
have_updated = False
if not have_updated:
utils.save_upload_file(info.tp_save_path, info.LOCAL_TP_INDEX_LOCK+'_'+str(company_id), str(datetime.date.today()))
return have_updated
#XML namespace for open document table tags
OD_TABLE_NS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
def get_text(node):
"""
Gets content from an xml element
Returns a string
"""
text = ''
for child in node.childNodes:
if child.nodeType == child.ELEMENT_NODE:
text = text + get_text(child)
elif child.nodeType == child.TEXT_NODE:
text = text + child.data
return text
def get_float(node):
"""
Gets the office:value attribute from an ods table-cell node
NOTE: text formatted cells do not have an office:value attribute
Returns a string
"""
return node.getAttribute('office:value')
def update_transaction_tax_page(cx):
tax_page_changed = False
dbc = cx.cursor()
country_code = db_tools.exec_action(dbc, 'get_iso_country_code')[0]['code_value']
current_tax_page_md5 = db_tools.exec_action(dbc, 'get_tax_page_md5')[0]['code_value']
current_tax_page_id = len(db_tools.exec_action(dbc, 'get_current_tax_page_id')) != 0 and db_tools.exec_action(dbc, 'get_current_tax_page_id')[0]['current_tax_page_id'] or -1
import zipfile
import xml.dom.minidom
if current_tax_page_md5 != utils.read_file_content_online(info.TP_INDEX_MD5_ONLINE).split(' ')[0]:
db_tools.exec_action(dbc, 'update_tax_page_md5', [utils.read_file_content_online(info.TP_INDEX_MD5_ONLINE).split(' ')[0]])
utils.save_upload_file(info.tp_index_path, info.LOCAL_TP_INDEX, utils.read_file_content_online(info.TP_INDEX_ONLINE))
import phunc.tp_index.TPindex as tp_index
tax_page_id_list = tp_index.index[country_code].keys()
tax_page_id_list.sort()
if int(current_tax_page_id) < int(tax_page_id_list[-1]):
utils.save_upload_file(info.tp_save_path, info.LOCAL_TP, utils.read_file_content_online(info.tp_server+tp_index.index[country_code][tax_page_id_list[-1]]))
zip_data = zipfile.ZipFile(info.LOCAL_TP, 'r')
content = zip_data.read('content.xml')
content = xml.dom.minidom.parseString(content)
sheet_list = content.getElementsByTagNameNS(OD_TABLE_NS, 'table')
for sheet in sheet_list:
sheet_name = sheet.getAttributeNS(OD_TABLE_NS, 'name')
rows = sheet.getElementsByTagNameNS(OD_TABLE_NS, 'table-row')
if len(rows) >= 3:
db_tools.exec_action(dbc, 'update_obsolete_tax')
for i in xrange(2, len(rows)):
cells = rows[i].getElementsByTagNameNS(OD_TABLE_NS, 'table-cell')
if len(cells) >= 5:
if get_text(cells[4]) == '':
db_tools.exec_action(dbc, 'insert_transaction_tax', [get_text(cells[0]), get_text(cells[1]), int(tax_page_id_list[-1]), get_float(cells[2]),get_text(cells[3]),get_text(cells[3])])
else:
db_tools.exec_action(dbc, 'insert_transaction_tax', [get_text(cells[0]), get_text(cells[1]), int(tax_page_id_list[-1]), get_float(cells[2]),get_text(cells[3]),get_text(cells[4])])
tax_page_changed = True
db_tools.exec_action(dbc, 'obsolete_user_input_tax')
#TODO:need a place to let user can change the default tax.
if db_tools.exec_action(dbc, 'default_tax_is_null')[0]['bool']:
db_tools.exec_action(dbc,'update_default_tax')
zip_data.close()
cx.commit()
return tax_page_changed
def get_sql_suffix_and_page_num(result, page_num = 1, page_size = 5):
"""
#TODO: put a comment here
Returns a dictionary
"""
result_dic = {}
total_result_num = len(result)
if total_result_num % page_size == 0:
result_dic['total_page_num'] = total_result_num / page_size
else:
result_dic['total_page_num'] = total_result_num / page_size + 1
if page_num == '' or int(page_num) < 0:
result_dic['curr_page_num'] = 1
elif int(page_num) > int(result_dic['total_page_num']):
result_dic['curr_page_num'] = int(result_dic['total_page_num'])
else:
result_dic['curr_page_num'] = int(page_num)
result_dic['page_string'] = " LIMIT %d OFFSET %d" % (int(page_size), (result_dic['curr_page_num']-1)*page_size)
return result_dic
def file_is_ods_type(file):
return file.type == 'application/vnd.oasis.opendocument.spreadsheet' or file.type =='application/octet-stream'
def create_account_use_file(cx, file):
"""
Reads an ods file with inital ledger accounts info, creates ledger accounts as directed
Returns nothing
"""
import zipfile
import xml.dom.minidom
utils.save_upload_file((info.accounts_save_path), info.ACCOUNTS_FILE, file.file.read())
zip_data = zipfile.ZipFile(info.ACCOUNTS_FILE, 'r')
content = zip_data.read('content.xml')
content = xml.dom.minidom.parseString(content)
# It is important to search using namespace
sheet_list = content.getElementsByTagNameNS(OD_TABLE_NS, 'table')
dbc = cx.cursor()
for sheet in sheet_list:
sheet_name = sheet.getAttributeNS(OD_TABLE_NS, 'name')
rows = sheet.getElementsByTagNameNS(OD_TABLE_NS, 'table-row')
for row in rows:
cells = row.getElementsByTagNameNS(OD_TABLE_NS, 'table-cell')
if len(cells) == 3:
db_tools.exec_action(dbc,'create_account',['',get_text(cells[0]),get_text(cells[1]),get_text(cells[2]),''])
elif len(cells) == 4:
db_tools.exec_action(dbc,'create_account',['',get_text(cells[0]),get_text(cells[1]),get_text(cells[2]),get_text(cells[3])])
cx.commit()
zip_data.close()
def printCompany(map,companyN):
"""
#TODO: put a comment here and change function name to standard form
Returns a string
"""
if map.has_key(companyN['id']):
s="<li><a href='/bin/root.py/display_company_details?company_id=%s'>%s</a>\n"%(companyN['id'],companyN['name'])
s+="<ul>\n"
for company in map[companyN['id']]:
s+=printCompany(map,company)
s+="</ul>\n"
s+="</li>"
else:
s="<li><a href='/bin/root.py/display_company_details?company_id=%s'>%s</a></li>\n"%(companyN['id'],companyN['name'])
return s
def access_forbit(req,**params):
return genErrorPage(err_code=10005)
#**************************************************page function start**************************************************
def loginpage(req, **params):
"""displays link tiles for companies to which the user has access (redirects to company if there is only one)"""
page = Page(req, is_root_page=True)
cursor = get_app_connection().cursor()
company_group_list = db_tools.exec_action(cursor, 'get_company_group', [page.session['login_user_name'], ''])
if user_is_root(page.session, cursor) or len(company_group_list)>0:
page.session['company_group_list'] = company_group_list
else:
#raise GeneralBusinessErr('user_no_grant','/bin/login.py/login_out')
return genErrorPage(err_code=10003)
page.session['logo_url'] = None
page.session['company_name'] = None
page.session.save()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
if not (user_is_root(page.session, cursor) or len(page.session['company_group_list']) > 1):
util.redirect(req, '/bin/root.py/company?company_id=%d&group_id=%d&broadcast_message=%s' % (int(page.session['company_group_list'][0]['company_id']), int(page.session['company_group_list'][0]['group_id']), broadcast_message))
page.content['skin'] = page.session['skin']
page.content['group'] = None
page.content['company_list'] = []
if user_is_root(page.session, cursor):
page.content['group'] = 'root'
#page split start
pagesize=6
page_params={}
page_num = params.has_key('page') and params['page'] and int(params['page']) or 1
sql_str = "select company_id, group_id from system.affiliation as af, system.user as us where us.name='%s' and af.user_id=us.id order by user_id" % page.session['login_user_name']
page_split_setup={
'cursor':cursor,
'sql':sql_str,
'skin':page.session['skin'],
'page':page_num,
'pagesize':pagesize,
'url':"/bin/root.py/loginpage",
'params':page_params,
'flag':1,
}
company_groups = table.ControlPage(**page_split_setup)
company_group_subset = company_groups.result
page.content['page_split'] = company_groups.createHtml()
#page split end
for item in company_group_subset:
company_detail = db_tools.exec_action(cursor, 'get_company_name', [int(item['company_id'])])
if len(company_detail[0]['name']) >20:
item['company_name'] = company_detail[0]['db_name']
else:
item['company_name'] = company_detail[0]['name']
item['company_logo'] = company_detail[0]['logo_url']
page.content['company_list'].append(item)
#prepare page dictionaries
page.setup = {
'breadcrumbs':[page.content['group'] == 'root' and 'Root Menu' or 'Global Menu'],
'menu_title':page.content['group'] == 'root' and 'Root Menu' or 'Global Menu',
'menu':page.content['group']=='root' and ['users','groups','grants','spacer','companies'] or None,
'content_title':'Companies',
'broadcast_message':broadcast_message,
'template':'login_company.opt',
}
page.info = {
'query_string':info.query_string,
'group':page.content['group']
}
page.session.save()
logger.debug(page.session)
return page.render(debug=True)
def company(req, **params):
"""downloads tax page if necessary, redirects to additional settings page if necessary, otherwise a portal to which the user has access"""
try:
page = Page(req,is_root_page=True,app_db=True)
#session = Session.Session(req)
#check_session(req,session)
session=page.session
cursor = page.app_db.cursor()
# 'log in' to the chosen company
if not company_group_affiliation(cursor, session['login_user_name'], params['company_id'], params['group_id']):
raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
session['login_company'] = params['company_id']
session['login_group'] = params['group_id']
company_db_info = db_tools.exec_action(cursor, 'get_company_by_id', [int(params['company_id'])])[0]
session['company_name'] = str(company_db_info['name'])
session['company_db_ip'] = str(company_db_info['db_ip'])
session['company_db_name'] = str(company_db_info['db_name'])
session['company_db_user'] = str(company_db_info['db_user'])
session['company_db_passwd'] = str(app_db_passwd)
session['logo_url'] = company_db_info['logo_url']
access_portals = db_tools.exec_action(cursor, 'get_role_by_group', [int(params['group_id'])])
if len(access_portals) == 0:
raise GeneralBusinessErr('usergroup_no_right','/bin/login.py/login_out')
sessionise_user_portals(access_portals, session)
session.save()
# check and update tax page
broadcast_message = ''
company_db = get_connection(session)
dbc = company_db.cursor()
#if 'finance' in session['user_access'].split(','):
if 'finance' in session['user_access'].values():
if not tax_page_updated_today(params['company_id']):
try:
if update_transaction_tax_page(company_db):
broadcast_message = 'New tax page found. Transaction taxes for ' +str(session['company_name'])+' have changed'
except Exception, e:
broadcast_message = "Tax page not found. Your jurisdiction may not have a tax page, or the tax page server may be unreachable"
# check for special accounts
special_params = [{'param_id':'special_ac_cash','param_name':'CASH','param_desc':'CASH'},{'param_id':'special_ac_equip','param_name':'Capital Equipment','param_desc':'Capital Equipment'},{'param_id':'special_ac_comm_pay','param_name':'Commissions Payable','param_desc':'Commissions Payable'},{'param_id':'special_ac_sales_rev','param_name':'Sales Revenue','param_desc':'Sales Revenue'},{'param_id':'special_ac_comm_exp','param_name':'Commissions','param_desc':'Commissions'}]
special_params_len = len(special_params)
exist_special_params_len = db_tools.exec_action(dbc, 'exist_special_params_len', [tuple([a['param_id'] for a in special_params])])[0]['special_params_len']
if special_params_len!=exist_special_params_len or broadcast_message != '':
util.redirect(req, '/bin/admin.py/additional_setup?broadcast_message=%s' % broadcast_message)
# check for transaction taxes
#if 'admin' in session['user_access'].split(','):
if 'admin' in session['user_access'].values():
dbc.execute('SELECT * FROM system.transaction_tax')
if dbc.rowcount == 0:
util.redirect(req, '/bin/admin.py/additional_setup')
# if set the portal order
for order in session['portal_order']:
for portal in access_portals:
if portal['id']==order:
util.redirect(req, '/bin/' + portal['name'] + '.py?broadcast_message=%s' % broadcast_message)
# proceed to first accessible portal
util.redirect(req, '/bin/' + access_portals[0]['name'] + '.py?broadcast_message=%s' % broadcast_message)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def create_company_page(req, **params):
"""display a form to create a managed company"""
page = Page(req, is_root_page=True, superuser_only=True)
page.setup = {
'breadcrumbs':['root','Create New Company'],
'menu_title':'Root Menu',
'menu':['users','groups','grants','spacer','companies'],
'content_title':'Create New Company',
'form' :True,
'template':'create_company.opt',
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def create_company_delivery_address(req, **params):
"""display a form to create a managed company"""
try:
page = Page(req, is_root_page=True, superuser_only=True)
session = page.session
app_db = page.app_db
cursor = app_db.cursor()
root_path = req.document_root()
logo_url = None
if params.has_key('logo') and params['logo']!='':
import os
fileext = os.path.splitext(params['logo'].filename)[1]
filevalue = params['logo'].file.read()
refilename = utils.shorten(params['company_name'])+'_logo'+fileext
filepath = info.COMPANY_ROOT_PATH + refilename
utils.save_upload_file(info.COMPANY_ROOT_PATH,filepath,filevalue)
logo_url = os.path.join(info.COMPANY_VIRTUAL_PATH,refilename)
del(params['logo'])
session['company_info'] = params
session['logo_url'] = logo_url
session.save()
if params.has_key('address_type'):
util.redirect(req,'/bin/root.py/create_company')
page.setup = {
'breadcrumbs':['root','Create New Company'],
'menu_title':'Root Menu',
'menu':['users','groups','grants','spacer','companies'],
'content_title':'Delivery address',
'form' :True,
'template':'create_delivery_address.opt',
}
page.info = {
'query_string':info.query_string,
}
return page.render()
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def create_company(req, **params):
"""actually create a managed company - redirects to loginpage"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
## session = Session.Session(req)
## check_session(req,session)
## app_db = get_app_connection()
## cursor = app_db.cursor()
## if not user_is_root(session,cursor):
## raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
session = page.session
app_db = page.app_db
cursor = app_db.cursor()
params['short_name'] = session['company_info']['short_name']
params['company_name'] = session['company_info']['company_name']
params['business_reg_no'] = session['company_info']['business_reg_no']
params['line1'] = session['company_info']['line1']
params['line2'] = session['company_info']['line2']
params['suburb'] = session['company_info']['suburb']
params['region'] = session['company_info']['region']
params['code'] = session['company_info']['code']
params['country'] = session['company_info']['country']
logo_url = session['logo_url']
if session['company_info'].has_key('address_type'):
params['pob_name'] = session['company_info']['pob_name']
params['pob_phone'] = session['company_info']['pob_phone']
params['pob_fax'] = session['company_info']['pob_fax']
temp_dic = {}
info._set_autocommit(app_db)
try:
cursor.execute("CREATE DATABASE %s" % utils.escape_quotes_in_sql(utils.shorten(params['short_name'])))
company_id = int(db_tools.exec_action(cursor, 'get_company_id')[0]['id'])
if logo_url:
cursor.execute("INSERT INTO system.company (id, name, db_ip, db_name, db_user, db_passwd,logo_url) VALUES (%d, '%s', '%s','%s','%s',encrypt('%s','','bf'),'%s')" % (company_id, utils.escape_quotes_in_sql(params['company_name']), 'localhost', utils.escape_quotes_in_sql(utils.shorten(params['short_name'])), app_db_user, app_db_passwd,logo_url))
else:
cursor.execute("INSERT INTO system.company (id, name, db_ip, db_name, db_user, db_passwd) VALUES (%d, '%s', '%s','%s','%s',encrypt('%s','','bf' ))" % (company_id, utils.escape_quotes_in_sql(params['company_name']), 'localhost', utils.escape_quotes_in_sql(utils.shorten(params['short_name'])), app_db_user, app_db_passwd))
cursor.execute("INSERT INTO system.affiliation VALUES (%d, %d, (SELECT id FROM system.group WHERE name = 'root'))" % (int(session['login_user_id']), int(company_id)))
country_code = db_tools.exec_action(cursor, 'get_country_code', [params['country'],params['country']])
if country_code:
country_code = country_code[0]['code']
else:
raise CountryCodeErr
except CountryCodeErr,e:
broadcast_message="Create company '%s' failed.The country does not exist!"%utils.shorten(params['short_name'])
try:
cursor.execute("DROP DATABASE %s" % utils.shorten(params['short_name']))
if company_id:
cursor.execute("DELETE FROM system.company WHERE id= %s" %str(company_id))
cursor.execute("DELETE FROM system.affiliation WHERE user_id= %s AND company_id=%s AND group_id=(SELECT id FROM system.group WHERE name = 'root')" % (session['login_user_id'],company_id))
except:
app_db.close()
util.redirect(req,'/bin/root.py/loginpage?broadcast_message=%s'%broadcast_message)
except Exception,e:
broadcast_message="Create company '%s' failed.Database error,please contact System Administator"%utils.shorten(params['short_name'])
try:
cursor.execute("DROP DATABASE %s" % utils.shorten(params['short_name']))
if company_id:
cursor.execute("DELETE FROM system.company WHERE id= %s" %str(company_id))
cursor.execute("DELETE FROM system.affiliation WHERE user_id= %s AND company_id=%s AND group_id=(SELECT id FROM system.group WHERE name = 'root')" % (session['login_user_id'],company_id))
except:
app_db.close()
util.redirect(req,'/bin/root.py/loginpage?broadcast_message=%s'%broadcast_message)
finally:
app_db.close()
#operate company
try:
new_db_conn = get_app_connection(dbname=utils.shorten(params['short_name']))
new_db_cursor = new_db_conn.cursor()
somevoidthing = db_tools.exec_action(new_db_cursor, 'create_init_db_func')
new_db_cursor.execute("SELECT init_db()")
new_db_cursor.execute("INSERT INTO system.entity (type, name) VALUES ('company', '%s')" % utils.escape_quotes_in_sql(params['company_name']))
if params.has_key('business_reg_no') and params['business_reg_no']:
new_db_cursor.execute("INSERT INTO system.contact_detail (entity_id, type, detail) VALUES (1, 'abn', '%s')" % utils.escape_quotes_in_sql(params['business_reg_no']))
if country_code==info.ISO_COUNTRY_CODE_AUSTRALIA:
new_db_cursor.execute("INSERT INTO system.sys_code (code_id, code_value) VALUES ('%s', '%s')" % (info.BUSINESS_NUM_LABEL,info.BUSINESS_NUM_LABEL_AUSTRALIA))
else:
new_db_cursor.execute("INSERT INTO system.sys_code (code_id, code_value) VALUES ('%s', '%s')" %(info.BUSINESS_NUM_LABEL,info.BUSINESS_NUM_LABEL_OTHER))
if params.has_key('line2'):
new_db_cursor.execute("INSERT INTO system.address (line1, line2, suburb, region, code, country) VALUES ('%s','%s','%s','%s','%s','%s')" % (utils.escape_quotes_in_sql(params['line1']), utils.escape_quotes_in_sql(params['line2']), utils.escape_quotes_in_sql(params['suburb']), utils.escape_quotes_in_sql(params['region']), params['code'], params['country']))
else:
new_db_cursor.execute("INSERT INTO system.address (line1, suburb, region, code, country) VALUES ('%s','%s','%s','%s','%s')" % (utils.escape_quotes_in_sql(params['line1']), utils.escape_quotes_in_sql(params['suburb']), utils.escape_quotes_in_sql(params['region']), params['code'], params['country']))
if session['company_info'].has_key('address_type'):
new_db_cursor.execute("INSERT INTO system.location(entity_id,name,phone,fax,address_id) VALUES(1,'%s','%s','%s',1)"%(utils.escape_quotes_in_sql(params['pob_name']),params['pob_phone'],params['pob_fax']))
else:
if params.has_key('line2'):
new_db_cursor.execute("INSERT INTO system.address (line1, line2, suburb, region, code, country) VALUES ('%s','%s','%s','%s','%s','%s')" % (utils.escape_quotes_in_sql(params['l_line1']), utils.escape_quotes_in_sql(params['l_line2']), utils.escape_quotes_in_sql(params['l_suburb']), utils.escape_quotes_in_sql(params['l_region']), params['l_code'], params['l_country']))
else:
new_db_cursor.execute("INSERT INTO system.address (line1, suburb, region, code, country) VALUES ('%s','%s','%s','%s','%s')" % (utils.escape_quotes_in_sql(params['l_line1']), utils.escape_quotes_in_sql(params['l_suburb']), utils.escape_quotes_in_sql(params['l_region']), params['l_code'], params['l_country']))
new_db_cursor.execute("INSERT INTO system.location(entity_id,name,phone,fax,address_id) VALUES(1,'%s','%s','%s',2)"%(utils.escape_quotes_in_sql(params['pob_name']),params['pob_phone'],params['pob_fax']))
new_db_cursor.execute("INSERT INTO system.sys_code (code_id, code_value) VALUES ('this_entity_id', '1')")
new_db_cursor.execute("INSERT INTO system.sys_code (code_id, code_value) VALUES ('this_address_id', '1')")
new_db_cursor.execute("INSERT INTO system.sys_code (code_id, code_value) VALUES ('iso_country_code', '%s')" % country_code)
new_db_cursor.execute("DROP FUNCTION init_db()")
new_db_conn.commit()
new_db_conn.close()
except DataBaseConnErr,e:
broadcast_message="Create company '%s' failed.Can't connect to the database."%utils.shorten(params['short_name'])
try:
app_db = get_app_connection()
cursor = app_db.cursor()
info._set_autocommit(app_db)
cursor.execute("DROP DATABASE %s" % utils.shorten(params['short_name']))
cursor.execute("DELETE FROM system.company WHERE id= %s" %str(company_id))
cursor.execute("DELETE FROM system.affiliation WHERE user_id= %s AND company_id=%s AND group_id=(SELECT id FROM system.group WHERE name = 'root')" % (session['login_user_id'],company_id))
app_db.close()
except DataBaseConnErr,e:
pass
except Exception,e:
app_db.close()
util.redirect(req,'/bin/root.py/loginpage?broadcast_message=%s'%broadcast_message)
except Exception,e:
broadcast_message="Create company '%s' failed.Database error,please contact System Administator"%utils.shorten(params['short_name'])
try:
app_db = get_app_connection()
cursor = app_db.cursor()
info._set_autocommit(app_db)
cursor.execute("DROP DATABASE %s" % utils.shorten(params['short_name']))
cursor.execute("DELETE FROM system.company WHERE id= %s" %str(company_id))
cursor.execute("DELETE FROM system.affiliation WHERE user_id= %s AND company_id=%s AND group_id=(SELECT id FROM system.group WHERE name = 'root')" % (session['login_user_id'],company_id))
app_db.close()
new_db_conn.close()
except DataBaseConnErr,e:
new_db_conn.close()
except Exception,e:
app_db.close()
new_db_conn.close()
util.redirect(req,'/bin/root.py/loginpage?broadcast_message=%s'%broadcast_message)
temp_dic['company_id'] = company_id
temp_dic['group_id'] = 1
session['company_group_list'].append(temp_dic)
session['company_db_ip'] = str(app_db_ip)
session['company_db_name'] = str(utils.shorten(params['short_name']))
session['company_db_user'] = str(app_db_user)
session['company_db_passwd'] = str(app_db_passwd)
session.save()
util.redirect(req, '/bin/root.py/upload_accounts_file_page?company_id=%d' % company_id)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def upload_accounts_file_page(req, **params):
"""display a form for uploading an initial chart of accounts"""
page = Page(req, company_db=True, is_root_page=True, superuser_only=True)
company_cursor = page.company_db.cursor()
page.content = {
'company_id':params['company_id'],
'iso_country_code':db_tools.exec_action(company_cursor, 'get_iso_country_code')[0]['code_value'],
'sample_files':[],
'generic_sample_files':[],
'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or 'Company created'
}
import os, re
pattern = '.*[.](?=ods$).*$'
try:
for li in os.listdir(req.document_root()[:req.document_root().rindex('skins')] +'samples/'+ str(page.content['iso_country_code']) + '/'):
if re.search(pattern, li):
page.content['sample_files'].append(li)
except:
pass
finally:
for li in os.listdir(req.document_root()[:req.document_root().rindex('skins')] +'samples/generic/'):
if re.search(pattern, li):
page.content['generic_sample_files'].append(li)
page.setup = {
'breadcrumbs':['root','Create New Company - Step 2'],
'menu_title':'Root Menu',
'menu':['users','groups','grants','spacer','companies'],
'content_title':'Create New Company - Step 2',
'broadcast_message':page.content['broadcast_message'],
'template':'upload_accounts_file.opt',
'form':True,
}
page.info = {
'query_string':info.query_string
}
return page.render()
def create_accounts(req, **params):
"""actually create accounts from an uploaded file - redirects to loginpage"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
session = page.session
enzhun_conn = page.app_db
enzhun_cursor = enzhun_conn.cursor()
if not user_is_root(session,enzhun_cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
company_db_info = db_tools.exec_action(enzhun_cursor, 'get_company_by_id', [int(params['company_id'])])[0]
enzhun_conn.close()
#company_conn = psycopg2.connect('host=%s dbname=%s user=%s password=%s' %(str(company_db_info['db_ip']), str(company_db_info['db_name']), app_db_user,app_db_passwd))
company_conn = get_app_connection(host=str(company_db_info['db_ip']),dbname=str(company_db_info['db_name']))
if not file_is_ods_type(params['file']):
broadcast_message = 'File was the wrong type. Please upload an open document spreadsheet (.ods) file'
util.redirect(req, '/bin/root.py/upload_accounts_file_page?company_id=%s&broadcast_message=%s' % (params['company_id'],broadcast_message))
return
else:
create_account_use_file(company_conn,params['file'])
broadcast_message = 'Company created'
company_conn.close()
util.redirect(req, '/bin/root.py/loginpage?broadcast_message=%s&from=create_company' % broadcast_message)
except GeneralBusinessErr,e:
return genErrorPage( errmsg = "%s" % e.getErrMsg() )
except Exception,e:
return genErrorPage( errmsg = "%s" % str(e.args) )
except:
return genErrorPage()
def create_user(req, **params):
"""actually creates a user - redirects to login page"""
try:
page =Page(req, app_db=True, superuser_only=True,is_root_page=True)
conn = page.app_db
import phunc.user as user
user_id, broadcast_message = user.createUser(conn, params['user_name'], params['user_pwd'])
util.redirect(req, "/bin/root.py/user_management?broadcast_message=%s. You need to <a href='/bin/root.py/grant_right_page?user_id=%s'>grant rights</a> to set the user's access" % (broadcast_message,user_id))
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
## try:
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection( )
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
## user_id, broadcast_message = user.createUser(conn, params['user_name'], params['user_pwd'])
## util.redirect(req, "/bin/login.py/user_management?broadcast_message=%s. You need to <a href='/bin/login.py/grant_right_page?user_id=%s'>grant rights</a> to set the user's access" % (broadcast_message,user_id))
## except GeneralBusinessErr,e:
## return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
## except Exception,e:
## return genErrorPage( errmsg = "%s" % e.args )
## except:
## return genErrorPage()
def create_group(req, **params):
# """actually creates a group - redirects to login page"""
page = Page(req, is_root_page=True, superuser_only=True)
conn = page.app_db
cursor = conn.cursor()
if group_exists(cursor, params['group_name']):
util.redirect(req, "/bin/root.py/group_management?broadcast_message=this group name '%s' already exists!"%params['group_name'])
group_id = int(db_tools.exec_action(cursor, 'get_group_id')[0]['id'])
db_tools.exec_action(cursor, 'insert_group', [group_id, params['group_name']])
if type(params['role_id']) == type([]):
for role_id in params['role_id']:
db_tools.exec_action(cursor, 'config_grant', [group_id, int(role_id)])
else:
db_tools.exec_action(cursor, 'config_grant', [group_id, int(params['role_id'])])
conn.commit()
util.redirect(req, "/bin/root.py/group_management?broadcast_message=Group '%s' Created"%params['group_name'])
## try:
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection()
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
## if group_exists(cursor, params['group_name']):
## util.redirect(req, "/bin/login.py/group_management?broadcast_message=this group name '%s' already exists!"%params['group_name'])
## group_id = int(db_tools.exec_action(cursor, 'get_group_id')[0]['id'])
## db_tools.exec_action(cursor, 'insert_group', [group_id, params['group_name']])
## if type(params['role_id']) == type([]):
## for role_id in params['role_id']:
## db_tools.exec_action(cursor, 'config_grant', [group_id, int(role_id)])
## else:
## db_tools.exec_action(cursor, 'config_grant', [group_id, int(params['role_id'])])
## conn.commit()
## util.redirect(req, "/bin/login.py/group_management?broadcast_message=Group '%s' Created"%params['group_name'])
# except GeneralBusinessErr,e:
# return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
# except Exception,e:
# return genErrorPage( errmsg = "%s" % e.args )
# except:
# return genErrorPage()
def user_management(req, **params):
"""display a form for adding/deleting/editing users"""
page = Page(req, is_root_page=True, superuser_only=True)
cursor = page.app_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
check_users = db_tools.exec_action(cursor, 'check_user_grant')
pagesize=6
page_num = params.has_key('page') and params['page'] and int(params['page']) or 1
sql_str = "SELECT * FROM system.user WHERE is_active='TRUE' ORDER BY id"
page_split_setup={
'cursor':cursor,
'sql':sql_str,
'skin':page.session['skin'],
'page':page_num,
'pagesize':pagesize,
'url':"/bin/root.py/user_management",
'params':{},
}
users = table.ControlPage(**page_split_setup)
for user in users.result:
if utils.is_root_user(user['id'], cursor):
user['is_root']=True
else:
user['is_root']=False
user_list = users.result
page_split = users.createHtml()
form_setup={
'id':'user_details',
'action':'/bin/root.py/create_user',
'onsubmit':'check_form()',
'fieldsets':[{
'id':None,
'legend':'New User Details',
'classid':'form',
'items':[
{'type':'text','label':'User Name','id':'user_name','name':'user_name','classid':'required validate-chars1'},
{'type':'password','label':'User Password','id':'user_pwd','name':'user_pwd','classid':'required validate-chars1'},
{'type':'password','label':'Retype User Password','id':'config_user_pwd','name':'config_user_pwd','classid':'required validate-chars1'}
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {'type':'div','id':None,'classid':'submit','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Create'}]}
}
uform = form.user_form(**form_setup)
page.content = {
'check_users':check_users,
'user_list':user_list,
'uform':uform,
'page_split':page_split,
'page':page,
'broadcast_message':broadcast_message
}
page.setup = {
'breadcrumbs':['root','Manage Users'],
'menu_title':'Root Menu',
'menu':['users!','groups','grants','spacer','companies'],
'content_title':'Manage Users',
'broadcast_message':broadcast_message,
'template':'user_manage.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def edit_group_page(req, **params):
"""displays a form for editing a group"""
page = Page(req, is_root_page=True, superuser_only=True)
cursor = page.app_db.cursor()
group_details = db_tools.exec_action(cursor, 'get_group_details', [params['group_id']])[0] #this may not be necessary - check it
page.content = {
'group_id':params['group_id'],
'role_list':db_tools.exec_action(cursor, 'get_all_role'),
'grant_list':db_tools.exec_action(cursor, 'get_all_grant'),
'group_list':db_tools.exec_action(cursor, 'get_all_group', [''])
}
page.setup = {
'breadcrumbs':['root','groups',group_details['name'].capitalize()+ ' - Edit'],
'menu_title':'Root Menu',
'menu':['users','groups!','grants','spacer','companies'],
'content_title':group_details['name'].capitalize(),
'template':'edit_group.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def edit_group(req,**params):
"""actually updates group details, redirects to group management page"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
session=page.session
conn=page.app_db
cursor=conn.cursor()
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection( )
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
group_id,group_name = params['group_id'].split(':')
db_tools.exec_action(cursor, 'delete_grant_of_group', [group_id])
if type(params['role_id']) == type([]):
for role_id in params['role_id']:
db_tools.exec_action(cursor, 'config_grant', [int(group_id), int(role_id)])
else:
db_tools.exec_action(cursor, 'config_grant', [int(group_id), int(params['role_id'])])
conn.commit()
util.redirect(req, "/bin/root.py/group_management?broadcast_message=Group '%s' Edited"%group_name)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def display_group_details(req,**params):
"""displays a detail page for a single group"""
page = Page(req, is_root_page=True, superuser_only=True)
cursor = page.app_db.cursor()
group_id = params['group_id']
group_grant_details = db_tools.exec_action(cursor, 'get_group_grant_details', [group_id])
grant_str = ''
if group_grant_details:
for grant in group_grant_details:
grant_str += grant['role_name']+' , '
grant_str = grant_str[:-2]
page.content = {
'grant_str':grant_str,
'group_details':db_tools.exec_action(cursor, 'get_group_details', [group_id])[0],
}
list_setup={
'classid':{'main':'title title2','detail':'table'},
'template_dir':info.getTemplateDir(req),
'detail':{'title':['Group Id','Group Name','Group Roles'],'value':[page.content['group_details']['id'],page.content['group_details']['name'],grant_str]},
'main':' ' # space required for formatting
}
ulist = form.user_div(**list_setup)
page.content['ulist']=ulist
page.setup = {
'breadcrumbs':['root','groups',page.content['group_details']['name'].capitalize() + ' - Details'],
'menu_title':'Root Menu',
'menu':['users','groups!','grants','spacer','companies'],
'content_title':page.content['group_details']['name'].capitalize() + ' - Details',
'template':'group_details.opt'
}
page.info = {
'query_string':info.query_string
}
return page.render()
def group_management(req, **params):
"""displays a group list and form for adding a new group"""
page = Page(req, is_root_page=True, superuser_only=True)
cursor = page.app_db.cursor()
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
check_groups = db_tools.exec_action(cursor, 'check_group_grant')
page_num = params.has_key('page') and params['page'] and int(params['page']) or 1
page_split_setup={
'cursor':cursor,
'sql':"select * from system.group order by id",
'skin':page.session['skin'],
'page':page_num,
'pagesize':6,
'url':"/bin/root.py/group_management",
'params':{}
}
groups = table.ControlPage(**page_split_setup)
group_list = groups.result
page_split = groups.createHtml()
role_list = db_tools.exec_action(cursor, 'get_all_role')
form_setup={
'id':'group_details',
'action':'/bin/root.py/create_group',
'onsubmit':'check_right()',
'fieldsets':[{
'id':None,
'legend':'Create New Group',
'classid':'form',
'items':[
{'type':'text','label':'Group Name','id':'group_name','name':'group_name','classid':'required validate-chars1'},
{'type':'checkbox','checkbox_type':2,'checkbox_value':role_list,'whole_label':'Roles','label':'name','id':'id','name':'role_id','value':'id','format':1,'prefix':True,'prefix_text':'role_'},
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {'type':'div','id':None,'classid':'bottom input','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Create'}]}
}
uform = form.user_form(**form_setup)
page.content = {
'uform':uform,
'group_list':group_list,
'role_list':role_list,
'page_split':page_split,
'page':page_num,
'broadcast_message':broadcast_message,
'check_groups':check_groups
}
page.setup = {
'breadcrumbs':['root','Manage Groups'],
'menu_title':'Root Menu',
'menu':['users','groups!','grants','spacer','companies'],
'content_title':'Manage Groups',
'broadcast_message':broadcast_message,
'template':'group_manage.opt',
'form':True,
'javascript':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def delete_group(req,**params):
"""actually deletes a group, redirects to group management page"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
## session = Session.Session(req)
## check_session(req,session)
## conn = info.getAppConnection( )
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
broadcast_message = ''
group_id = params['group_id']
group_name = params['group_name']
if group_name.lower()!='root':
db_tools.exec_action(page.app_db.cursor(), 'delete_group', [params['group_id']])
page.app_db.commit()
broadcast_message = "group '%s' deleted"%params['group_name']
else:
broadcast_message = "root can't be deleted"
util.redirect(req,"/bin/root.py/group_management?broadcast_message=%s"%broadcast_message)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def grant_right_page(req, **params):
"displays a user list and form for granting rights"""
page = Page(req, is_root_page=True, superuser_only=True)
cursor = page.app_db.cursor()
user_id = None
if params.has_key('user_id') and params['user_id']:
user_id = int(params['user_id'])
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
page_num = params.has_key('page') and params['page'] and int(params['page']) or 1
sql_str = "SELECT a.user_id,u.name AS user_name,a.company_id,c.name AS company_name,a.group_id,g.name AS group_name FROM system.affiliation a LEFT JOIN system.user u ON a.user_id=u.id LEFT JOIN system.company c ON a.company_id=c.id LEFT JOIN system.group g ON a.group_id=g.id WHERE a.company_id<>0 and a.user_id not in (select id from system.user where is_active='FALSE') ORDER BY a.user_id,a.company_id,a.group_id"
page_split_setup={
'cursor':cursor,
'sql':sql_str,
'skin':page.session['skin'],
'page':page_num,
'pagesize':8,
'url':"/bin/root.py/grant_right_page",
'params':{}
}
user_rights = table.ControlPage(**page_split_setup)
user_rights_list = user_rights.result
page_split = user_rights.createHtml()
user_list = db_tools.exec_action(cursor, 'get_users', [''])
for user in user_list:
if utils.is_root_user(user['id'], cursor):
user['is_root']=True
else:
user['is_root']=False
company_list = db_tools.exec_action(cursor, 'get_all_company')
group_list = db_tools.exec_action(cursor, 'get_all_group', [''])
form_setup={
'id':'grant_right',
'action':'/bin/root.py/grant_right',
'fieldsets':[{
'id':None,
'legend':'Grant Details',
'classid':'form',
'items':[
{'type':'select','label':'User Name','id':'user_id','name':'user_id','classid':'required','option':user_list,'option_value':{'split':':','items':['id','name'],'default_value':''},'option_text':{'split':None,'items':['name'],'default_text':'-- Please select --'},'selected_type':1,'selected_value':'','selected_key':None},
{'type':'select','label':'Company Name','id':'company_id','name':'company_id','classid':'required','option':company_list,'option_value':{'split':':','items':['id','name'],'default_value':''},'option_text':{'split':None,'items':['name'],'default_text':'-- Please select --'},'selected_type':1,'selected_value':'','selected_key':None},
{'type':'select','label':'Group Name','id':'group_id','name':'group_id','classid':'required','option':group_list,'option_value':{'split':':','items':['id','name'],'default_value':''},'option_text':{'split':None,'items':['name'],'default_text':'-- Please select --'},'selected_type':1,'selected_value':'','selected_key':None},
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {'type':'div','id':None,'classid':'submit','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Add'}]},
}
uform = form.user_form(**form_setup)
page.content = {
'uform':uform,
'user_id':user_id,
'user_rights_list':user_rights_list,
'user_list':user_list,
'company_list':company_list,
'group_list':group_list,
'page_split':page_split,
'page':page_num,
'broadcast_message':broadcast_message
}
page.setup = {
'breadcrumbs':['root','Grant User Rights'],
'menu_title':'Root Menu',
'menu':['users','groups','grants!','spacer','companies'],
'content_title':'Grant User Rights',
'broadcast_message':broadcast_message,
'template':'grant_right.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def grant_right(req, **params):
"""actually grants rights to a user, redirects to grant rights page"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
conn=page.app_db
cursor=conn.cursor()
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection()
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
broadcast_message = ''
user_id,user_name = params['user_id'].split(':')
company_id,company_name = params['company_id'].split(':')
group_id,group_name = params['group_id'].split(':')
same_rights = db_tools.exec_action(cursor, 'user_have_right', [int(user_id), int(company_id)])
if same_rights:
broadcast_message="error:%s's can not have more than one role on '%s'!"%(user_name,company_name)
else:
db_tools.exec_action(cursor, 'assign_user', [int(user_id), int(company_id), int(group_id)])
conn.commit()
broadcast_message="Right: %s granted to %s on %s"%(group_name,user_name,company_name)
util.redirect(req,"/bin/root.py/grant_right_page?broadcast_message=%s"%broadcast_message)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def remove_right(req, **params):
"""actually removes the specified rights, redirects to grant rights page"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
conn=page.app_db
cursor=conn.cursor()
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection()
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
broadcast_message = ''
user_id = params['user_id']
user_name = params['user_name']
company_id = params['company_id']
company_name = params['company_name']
group_id = params['group_id']
group_name = params['group_name']
if not utils.is_root_user(user_id, cursor):
db_tools.exec_action(cursor, 'revoke_user', [int(user_id), int(company_id), int(group_id)])
conn.commit()
broadcast_message="removes %s's '%s' rights for company '%s'" % (user_name, group_name,company_name)
else:
broadcast_message = "root privileges can't be removed"
util.redirect(req,"/bin/root.py/grant_right_page?broadcast_message=%s"%broadcast_message)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def delete_user(req, **params):
"""actually deletes a user, redirects to user management page"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
conn=page.app_db
cursor=conn.cursor()
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection()
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
broadcast_message = ''
user_id = params['user_id']
user_name = params['user_name']
if not utils.is_root_user(user_id, cursor):
db_tools.exec_action(cursor, 'remove_right_on_user', [user_id])
db_tools.exec_action(cursor, 'delete_user', [user_id])
conn.commit()
broadcast_message="User '%s' has been removed!"%user_name
else:
broadcast_message = "root user can't be deleted"
util.redirect(req,"/bin/root.py/user_management?broadcast_message=%s"%broadcast_message)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def display_user_details(req,**params):
"""displays a page of details for a single user"""
page = Page(req, is_root_page=True, superuser_only=True)
user_id = params['user_id']
user_name = params['user_name']
user_right_list = db_tools.exec_action(page.app_db.cursor(), 'get_user_rights', ['AND a.user_id=%s'%user_id,''])
user_right_str = ''
if user_right_list:
for user_right in user_right_list:
user_right_str += "<a href='/bin/root.py/display_company_details?company_id="+str(user_right['company_id'])+"'>"+user_right['company_name']+"</a> | <a href='/bin/root.py/display_group_details?group_id="+str(user_right['group_id'])+"'>"+user_right['group_name']+'</a><br/><br/>'
page.content = {
'user_right_str':user_right_str,
'user_name':user_name,
'user_id':user_id
}
list_setup={
'classid':{'main':'title title2','detail':'table'},
'template_dir':info.getTemplateDir(req),
'detail':{'title':['User Id','User Name','User Rights'],'value':[page.content['user_id'],page.content['user_name'],page.content['user_right_str'] ]},
'main':' ', #space required for formatting
}
ulist = form.user_div(**list_setup)
page.content['ulist']=ulist
page.setup = {
'breadcrumbs':['root','users',user_name.capitalize() + ' - Details'],
'menu_title':'Root Menu',
'menu':['users!','groups','grants','spacer','companies'],
'content_title':user_name.capitalize() + ' - Details',
'template':'user_details.opt'
}
page.info = {
'query_string':info.query_string,
}
return page.render()
def company_management(req,**params):
"""displays a list of managed companies, with some links"""
page = Page(req, is_root_page=True, superuser_only=True)
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
companyset=db_tools.exec_action(page.app_db.cursor(),'app_get_all_company')
companymap={}
for company in companyset:
if companymap.has_key(company['top_id']):
companymap[company['top_id']].append(company)
else:
companymap[company['top_id']]=[]
companymap[company['top_id']].append(company)
tree=""
for company in companymap[0]:
tree+=printCompany(companymap,company)
page.content = {
'tree':tree,
'broadcast_message':broadcast_message
}
page.setup = {
'breadcrumbs':['root','Modify Company Details'],
'menu_title':'Root Menu',
'menu':['users','groups','grants','spacer','companies!'],
'content_title':'Modify Company Details',
'broadcast_message':broadcast_message,
'template':'company_manage.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def display_company_details(req,**params):
"""displays details for a single managed company"""
page = Page(req, is_root_page=True, superuser_only=True)
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
company_id = params['company_id']
company_details = db_tools.exec_action(page.app_db.cursor(),'app_get_company_info',[company_id])
if not company_details:
util.redirect(req,"/bin/root.py/company_management?broadcast_message=No data for this company")
company_details = company_details[0]
#dbconn = psycopg2.connect('host=%s dbname=%s user=%s password=%s' %(company_details['db_ip'], company_details['db_name'], app_db_user,app_db_passwd))
dbconn = get_app_connection(host=company_details['db_ip'],dbname=company_details['db_name'])
dbc = dbconn.cursor()
this_entity_id = db_tools.exec_action(dbc,'app_get_company_entity_id')[0]['code_value']
this_address_id = db_tools.exec_action(dbc,'app_get_company_address_id')[0]['code_value']
abn = db_tools.exec_action(dbc,'app_get_abn_info',[this_entity_id])
if abn:
abn = abn[0]['detail']
else:
abn=''
abn_label = db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value']
address_details = db_tools.exec_action(dbc,'get_address_info',[this_address_id])[0]
address_details = utils.get_formatted_address(address_details)
logo_url=None
if company_details['logo_url']:
logo_url = company_details['logo_url']
dbconn.close()
page.content = {
'abn':abn,
'abn_label': abn_label,
'company_details':company_details,
'address_details':address_details,
'broadcast_message':broadcast_message,
'logo_url':logo_url
}
page.setup = {
'breadcrumbs':['root','companies',company_details['name'] + ' - Details'],
'menu_title':'Root Menu',
'menu':['users','groups','grants','spacer','companies!'],
'content_title':company_details['name'] + ' - Details',
'broadcast_message':broadcast_message,
'template':'company_details.opt'
}
page.info = {
'query_string':info.query_string
}
return page.render()
def edit_company_details_page(req,**params):
"""displays a form for editing a managed company's details"""
page = Page(req, is_root_page=True, superuser_only=True)
company_id = params['company_id']
company_details = db_tools.exec_action(page.app_db.cursor(),'app_get_company_info',[company_id])
if not company_details:
util.redirect(req,"/bin/root.py/company_management?broadcast_message=no this company!")
company_details = company_details[0]
#dbconn = psycopg2.connect('host=%s dbname=%s user=%s password=%s' %(company_details['db_ip'], company_details['db_name'], app_db_user,app_db_passwd))
dbconn = get_app_connection(host=company_details['db_ip'],dbname=company_details['db_name'])
dbc = dbconn.cursor()
this_entity_id = db_tools.exec_action(dbc,'app_get_company_entity_id')[0]['code_value']
this_address_id = db_tools.exec_action(dbc,'app_get_company_address_id')[0]['code_value']
abn = db_tools.exec_action(dbc,'app_get_abn_info',[this_entity_id])
if abn:
abn = abn[0]['detail']
else:
abn = ''
abn_label = db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value']
address_details = db_tools.exec_action(dbc,'get_address_info',[this_address_id])[0]
logo_url=None
inv_terms=db_tools.exec_action(dbc,'get_default_inv_terms')[0]['code_value']
if company_details['logo_url']:
logo_url = company_details['logo_url']
dbconn.close()
page.content = {
'abn':abn,
'abn_label': abn_label,
'company_details':company_details,
'address_details':address_details,
'original_page_load':datetime.datetime.today(),
'logo_url':logo_url,
'inv_terms':inv_terms
}
page.setup = {
'breadcrumbs':['root','companies',company_details['name'] + ' - Edit'],
'menu_title':'Root Menu',
'menu':['users','groups','grants','spacer','companies!'],
'content_title':company_details['name'] + ' - Edit',
'template':'edit_company_details.opt',
'form':True
}
page.info = {
'query_string':info.query_string
}
return page.render()
def edit_company_details(req,**params):
"""actually updates a managed company's details, redirects to company details page"""
try:
page=Page(req,is_root_page=True,superuser_only=True,app_db=True)
conn=page.app_db
cursor=conn.cursor()
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection( )
## cursor = conn.cursor()
## if not user_is_root(session,cursor): raise GeneralBusinessErr('access_forbit','/bin/login.py/login_out')
company_id = params['company_id']
default_inv_terms=params['inv_terms']
company_details = db_tools.exec_action(cursor,'app_get_company_info',[company_id])
if not company_details:
util.redirect(req,"/bin/root.py/display_company_details?company_id=%s&broadcast_message=Couldn't retrieve details for company %s. Nothing was updated" % (company_id,company_details['name']))
company_details = company_details[0]
#dbconn = psycopg2.connect('host=%s dbname=%s user=%s password=%s' %(company_details['db_ip'], company_details['db_name'], app_db_user,app_db_passwd))
dbconn = get_app_connection(host=company_details['db_ip'],dbname=company_details['db_name'])
dbc = dbconn.cursor()
root_path = req.document_root()
logo_url = None
if params.has_key('logo') and params['logo']!='':
import os
fileext = os.path.splitext(params['logo'].filename)[1]
filevalue = params['logo'].file.read()
refilename = utils.shorten(company_details['name'])+'_logo'+fileext
filepath = info.COMPANY_ROOT_PATH + refilename
utils.save_upload_file(info.COMPANY_ROOT_PATH,filepath,filevalue)
logo_url = os.path.join(info.COMPANY_VIRTUAL_PATH,refilename)
if logo_url:
cursor.execute("UPDATE system.company SET logo_url='%s',name='%s' WHERE id=%s"%(logo_url,params['company_name'],company_id))
else:
cursor.execute("UPDATE system.company SET name='%s' WHERE id=%s"%(params['company_name'],company_id))
conn.commit()
conn.close()
this_entity_id = db_tools.exec_action(dbc,'app_get_company_entity_id')[0]['code_value']
this_address_id = db_tools.exec_action(dbc,'app_get_company_address_id')[0]['code_value']
dbc.execute("SELECT system.safe_update('system.contact_detail', 'type = ''abn'' AND entity_id = %s', 'detail=''%s''', '%s')"% (this_entity_id, params['business_reg_no'],params['original_page_load']))
if params['line2'].strip():
dbc.execute("SELECT system.safe_update('system.address', 'id = %s', 'line1=''%s'',line2=''%s'',suburb=''%s'',region=''%s'',code=''%s'',country=''%s''', '%s')" % (this_address_id,params['line1'],params['line2'],params['suburb'],params['region'],params['code'],params['country'],params['original_page_load']))
else:
dbc.execute("SELECT system.safe_update('system.address', 'id = %s', 'line1=''%s'',line2=null,suburb=''%s'',region=''%s'',code=''%s'',country=''%s''', '%s')" % (this_address_id,params['line1'],params['suburb'],params['region'],params['code'],params['country'],params['original_page_load']))
inv_terms=db_tools.exec_action(dbc,'get_default_inv_terms')[0]['code_value']
if default_inv_terms !='' and inv_terms!=default_inv_terms:
dbc.execute("SELECT system.safe_update('system.sys_code','code_id=''default_inv_terms''','code_value=''%s''','%s')"%(default_inv_terms,params['original_page_load']))
dbconn.commit()
dbconn.close()
util.redirect(req,"/bin/root.py/display_company_details?company_id=%s&broadcast_message=Company details updated" % company_id)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def mypage(req,**params):
"""displays the my preferences page, which doesn't have a lot on it at present"""
page = Page(req, is_root_page=True)
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page['is_root_page']=False
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
page.content = {
'user_name':page.session['login_user_name'],
'user_skin':page.session['skin'],
'user_right_list':db_tools.exec_action(page.app_db.cursor(), 'get_user_rights', ['AND a.user_id=%s' % page.session['login_user_id'],''])
}
list_setup={
'classid':{'main':'title title2','detail':'table'},
'template_dir':info.getTemplateDir(req),
'detail':{'title':['Login User','User Skin'],'value':[page.content['user_name'] ,page.content['user_skin']]},
'main':'My Details',
}
ulist=form.user_div(**list_setup)
page.content['ulist']=ulist
page.setup = {
'breadcrumbs':['root','My Prefs'],
'menu_title':'User Config',
'menu':['passwd','skin','portal'],
'content_title':'My Preferences',
'broadcast_message':broadcast_message,
'template':'mypage.opt'
}
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page.setup['breadcrumbs']=['My Prefs']
page.info = {
'query_string':info.query_string,
}
return page.render()
def change_password_page(req,**params):
"""displays a form for changing the current user's password"""
page = Page(req, is_root_page=True)
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page['is_root_page']=False
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
user_id = page.session['login_user_id']
user_name = page.session['login_user_name']
form_setup={
'id':'user_details',
'action':'/bin/root.py/change_password',
'onsubmit':'check_form()',
'fieldsets':[{
'id':None,
'legend':'User Details',
'classid':'form',
'items':[
{'type':'password','label':'Old Password','id':'old_user_pwd','name':'old_user_pwd','classid':'required'},
{'type':'password','label':'New Password','id':'user_pwd','name':'user_pwd','classid':'required'},
{'type':'password','label':'Retype Password','id':'config_user_pwd','name':'config_user_pwd','classid':'required'}
]
}],
'template_dir':info.getTemplateDir(req),
'form_bottom': {'type':'div','id':None,'classid':'submit','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Change'},{'type':'hidden','name':'user_name','value':user_name},{'type':'hidden','name':'user_id','value':user_id}]},
}
uform = form.user_form(**form_setup)
page.content = {
'uform':uform,
'user_id':user_id,
'user_name':user_name,
}
page.setup = {
'breadcrumbs':['root','myprefs','Change Password'],
'menu_title':'User Config',
'menu':['passwd!','skin','portal'],
'content_title':'Change Password',
'broadcast_message':broadcast_message,
'template':'mypage_change_pwd.opt',
'form':True,
'javascript':True
}
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page.setup['breadcrumbs']=['root','Change Password']
page.info = {
'query_string':info.query_string
}
return page.render()
def change_password(req,**params):
"""actually changes the current user's password, redirects to my preferences page"""
import phunc.user as user
try:
page=Page(req,is_root_page=True,app_db=True)
## session = Session.Session(req)
## check_session(req,session)
## conn = get_app_connection()
## cursor = conn.cursor()
## if not (params.has_key('user_id') and params['user_id'].strip() and params.has_key('user_name') and params['user_name'].strip()):
## raise GeneralBusinessErr('user_not_login','/bin/login.py/login_out')
user_id = params['user_id']
user_name = params['user_name']
broadcast_message = user.changePasswd(page.app_db.cursor(),user_name,params['old_user_pwd'],params['user_pwd'])
page.app_db.commit()
util.redirect(req,"/bin/root.py/mypage?broadcast_message=%s"%broadcast_message)
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def change_skin_page(req,**params):
"""displays a simple form for changing the current users's skin preference"""
page = Page(req, is_root_page=True)
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page['is_root_page']=False
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
user_id = page.session['login_user_id']
user_skin = page.session['skin']
page.content = {
'user_id':user_id,
'user_skin':user_skin
}
page.setup = {
'breadcrumbs':['root','myprefs','Change Skin'],
'menu_title':'User Config',
'menu':['passwd','skin!','portal'],
'content_title' :'Change Skin',
'broadcast_message':broadcast_message,
'template':'mypage_change_skin.opt',
'form':True
}
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page.setup['breadcrumbs']=['root','Change Skin']
page.info = {
'query_string':info.query_string
}
return page.render()
def change_skin(req,**params):
"""actually change the current user's skin preference, redirects to my preferences page"""
try:
page=Page(req,is_root_page=True,app_db=True)
user_id = params['user_id']
user_skin = params['skin']
db_tools.exec_action(page.app_db.cursor(), 'change_skin', [user_skin,user_id])
page.session['skin'] = params['skin']
page.session.save()
page.app_db.commit()
util.redirect(req,"/bin/root.py/change_skin_page?broadcast_message=Skin preference updated")
except GeneralBusinessErr,e:
return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
except Exception,e:
return genErrorPage( errmsg = "%s" % e.args )
except:
return genErrorPage()
def change_default_portal_page(req,**params):
"""displays a simple form for changing the current users's default login portal preference"""
page = Page(req, is_root_page=True)
portal_list=[]
for company in page.session['company_group_list']:
access_portals = db_tools.exec_action(page.app_db.cursor(), 'get_role_by_group', [int(company['group_id'])])
for portal in access_portals:
if portal not in portal_list and portal['name']!='report':
portal_list.append(portal)
default_orders = page.session['portal_order']
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page['is_root_page']=False
broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
page.content = {
'user_id':page.session['login_user_id'],
'portal_list':portal_list,
'order_list':[i+1 for i in range(len(portal_list))],
'default_orders':default_orders,
}
page.setup = {
'breadcrumbs':['root','myprefs','Change Default Portal'],
'menu_title':'User Config',
'menu':['passwd','skin','portal!'],
'content_title' :'Change Portal Order',
'broadcast_message':broadcast_message,
'template':'mypage_change_portal.opt',
'form':True,
'javascript':True
}
if len(page.session['company_group_list'])<=1 and not user_is_root(page.session, page.app_db.cursor()):
page.setup['breadcrumbs']=['root','Change Default Portal']
page.info = {
'query_string':info.query_string
}
return page.render()
def change_portal(req,**params):
"""displays a simple form for changing the current users's default login portal preference"""
page = Page(req, is_root_page=True)
portal_list=[]
for company in page.session['company_group_list']:
access_portals = db_tools.exec_action(page.app_db.cursor(), 'get_role_by_group', [int(company['group_id'])])
for portal in access_portals:
if portal not in portal_list and portal['name']!='report':
portal_list.append(portal)
portal_order_str=''
for i in [i+1 for i in range(len(portal_list))]:
for portal in portal_list:
if int(params[portal['name']].split('-')[1])==i:
portal_order_str += str(portal['id'])+','
if portal_order_str:
portal_order_str=portal_order_str[:-1]
db_tools.exec_action(page.app_db.cursor(), 'update_user_portal_order', ['{'+portal_order_str+'}',page.session['login_user_id']])
page.app_db.commit()
page.session['portal_order'] = tuple([int(i) for i in portal_order_str.split(',')])
page.session.save()
broadcast_message = "The Portal order defined"
util.redirect(req,"/bin/root.py/change_default_portal_page?broadcast_message=%s"%broadcast_message)
| Python |
#!/usr/local/bin/python
import xml.parsers.expat
import httplib
import tempfile
import subprocess
class XMLNode:
def __init__(self, parent, name, attrs):
self.parent = parent
self.name = name
self.attrs = attrs
self.children = {}
self.data = ''
def addData(self, data):
self.data += data
def add(self, name, attrs):
if name not in self.children:
self.children[name] = []
node = XMLNode(self, name, attrs)
self.children[name].append(node)
return node
def __str__(self):
s = ''
for name in self.children:
if s != '':
s += ', '
c = ''
for child in self.children[name]:
if c != '':
c += ', '
c += str(child)
s += name + '[' + c + ']'
return "XMLNode(" + self.name + ", " + str(self.attrs) + ', "' \
+ self.data + '", ' + s + ')'
def getChild(self, name):
return self.children[name]
def getOneChildData(self, name):
children = self.getChild(name)
assert len(children) == 1
return children[0].data
class TrustAnchorParser:
def __init__(self, anchors):
parser = xml.parsers.expat.ParserCreate()
parser.StartElementHandler = self.startElement;
parser.EndElementHandler = self.endElement
parser.CharacterDataHandler = self.charData
self._current = None
parser.Parse(anchors)
def push(self, name, attrs):
if self._current is None:
self._parsed = self._current = XMLNode(None, name, attrs)
else:
self._current = self._current.add(name, attrs)
def pop(self, name):
assert self._current.name == name
self._current = self._current.parent
def dump(self):
print self._parsed
def startElement(self, name, attrs):
# print "start", name, attrs
self.push(name, attrs)
def endElement(self, name):
# print "end", name
self.pop(name)
def charData(self, data):
# print "data", data
if data != '\n':
self._current.addData(data)
def getOneChild(self, name):
return self._parsed.getOneChildData(name)
def keys(self):
self.dump()
assert self._parsed.name == 'TrustAnchor'
zone = self.getOneChild('Zone')
assert zone == '.'
digests = self._parsed.getChild('KeyDigest')
out = ''
for digest in digests:
keyTag = digest.getOneChildData('KeyTag')
algorithm = digest.getOneChildData('Algorithm')
digestType = digest.getOneChildData('DigestType')
digest = digest.getOneChildData('Digest')
out += zone + ' 300 IN DS ' + keyTag + ' ' +algorithm + ' ' \
+ digestType + ' ' + digest + '\n'
return out
iana = httplib.HTTPConnection('data.iana.org')
iana.request('GET', '/root-anchors/root-anchors.xml')
res = iana.getresponse()
assert res.status == 200
xml2 = res.read()
xmlfile = tempfile.NamedTemporaryFile()
print xmlfile.name
xmlfile.write(xml2)
xmlfile.flush()
iana.request('GET', '/root-anchors/root-anchors.asc')
res = iana.getresponse()
assert res.status == 200
sig = res.read()
sigfile = tempfile.NamedTemporaryFile()
print sigfile.name
sigfile.write(sig)
sigfile.flush()
subprocess.check_call([ 'gpg', '--no-default-keyring', '--keyring',
'./icann.pgp', '--verify', sigfile.name, xmlfile.name ])
parser = TrustAnchorParser(xml2)
keys = parser.keys()
print keys,
keyfile = open('keys', 'w')
keyfile.write(keys)
print "Root keys retrieved and verified"
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.8.2',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = []
def addPossibleError(pos_err):
Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err)
addPossibleError = staticmethod(addPossibleError)
def getPossibleErrors():
return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS)
getPossibleErrors = staticmethod(getPossibleErrors)
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 8
FLAGPOLL_PATCH_VERSION = 2
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig",
"/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string += str(item)
list_string += " "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE = 0
INFO = 1
WARN = 2
ERROR = 3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n")
errs = Utils.getPossibleErrors()
if len(errs) > 0:
sys.stderr.write("Possible culprits:\n")
for pos_err in errs:
sys.stderr.write( " " + str(pos_err) + "\n" )
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x,v=arch_list: x in v)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.INFO, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber += 1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber += 1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'),
lhs.getVariable('Version')))
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFiltersChanged = True
self.mCheckDepends = True
self.mAgentDependList = []
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v)
elif req_string_list[i+1] == ">":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v)
elif req_string_list[i+1] == "<":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v)
else:
i += 1
else:
i += 1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self, packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
# Make depend list if we are supposed to
self.updateFilters()
self.makeDependList()
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter",
"Filter %s" % self.mName + " on %s." % filter.getVarName())
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
flagDBG().out(flagDBG.INFO, "PkgAgent.update",
"%s" % self.mName)
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters",
"%s has " % self.mName + str(len(self.mViablePackageList)) + " left")
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
for f in self.mFilterList:
Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName()))
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def getVarName(self):
return self.mVarName
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
ret_pkg_list.append(pkg)
else:
flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
# Now sort
ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName),
lhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--verbose-debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.INFO)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x,v=exact_version: x == v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show debug information"
print " --verbose-debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
print ""
print "extending search path"
print " FLAGPOLL_PATH environment variable that can be set to"
print " extend the search path for .fpc/.pc files"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.8.2',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = []
def addPossibleError(pos_err):
Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err)
addPossibleError = staticmethod(addPossibleError)
def getPossibleErrors():
return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS)
getPossibleErrors = staticmethod(getPossibleErrors)
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 8
FLAGPOLL_PATCH_VERSION = 2
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig",
"/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string += str(item)
list_string += " "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE = 0
INFO = 1
WARN = 2
ERROR = 3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n")
errs = Utils.getPossibleErrors()
if len(errs) > 0:
sys.stderr.write("Possible culprits:\n")
for pos_err in errs:
sys.stderr.write( " " + str(pos_err) + "\n" )
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x,v=arch_list: x in v)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.INFO, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber += 1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber += 1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'),
lhs.getVariable('Version')))
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFiltersChanged = True
self.mCheckDepends = True
self.mAgentDependList = []
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v)
elif req_string_list[i+1] == ">":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v)
elif req_string_list[i+1] == "<":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v)
else:
i += 1
else:
i += 1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self, packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
# Make depend list if we are supposed to
self.updateFilters()
self.makeDependList()
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter",
"Filter %s" % self.mName + " on %s." % filter.getVarName())
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
flagDBG().out(flagDBG.INFO, "PkgAgent.update",
"%s" % self.mName)
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters",
"%s has " % self.mName + str(len(self.mViablePackageList)) + " left")
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
for f in self.mFilterList:
Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName()))
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def getVarName(self):
return self.mVarName
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
ret_pkg_list.append(pkg)
else:
flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
# Now sort
ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName),
lhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--verbose-debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.INFO)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x,v=exact_version: x == v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show debug information"
print " --verbose-debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
print ""
print "extending search path"
print " FLAGPOLL_PATH environment variable that can be set to"
print " extend the search path for .fpc/.pc files"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
from distutils.core import setup
try:
import py2exe
except:
pass
setup(
name='flagpoll',
version='0.9.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
console=['flagpoll'],
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
def tokenize(val, split_char):
val = val.strip()
results = []
while len(val) > 0:
sn = val.find(split_char)
qn = val.find('"')
#print " -> val: %s Len: %s" % (val, len(val))
# If we find a quote first, then find the space after the next quote.
if qn < sn:
#print " -> Found a quote first:", qn
# Find next quote.
qn2 = val.find('"', qn+1)
#print " -> Found second quote:", qn2
sn = val.find(split_char, qn2+1)
#print " -> Found next space:", sn
if sn < 0:
results.append(val[:])
val = ""
else:
results.append(val[:sn])
val = val[sn:]
val = val.strip()
return results
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = []
def addPossibleError(pos_err):
Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err)
addPossibleError = staticmethod(addPossibleError)
def getPossibleErrors():
return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS)
getPossibleErrors = staticmethod(getPossibleErrors)
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 9
FLAGPOLL_PATCH_VERSION = 1
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = extra_paths
path_list.extend(flg_cfg_dir)
path_list.extend(pkg_cfg_dir)
path_list.extend(ld_path)
default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')]
default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list]
default_path_flg = [pj(p,'flagpoll') for p in default_path_list]
path_list.extend(default_path_pkg)
path_list.extend(default_path_flg)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
list_len = len(gen_list)
i = 0
while i < list_len:
item = gen_list[i].strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item == '-framework':
item = '%s %s' % (item, gen_list[i + 1])
i += 1
if item not in new_list:
if len(item) > 0:
new_list.append(item)
i += 1
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
list_len = len(flag_list)
i = 0
while i < list_len:
flg = flag_list[i].strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R") or \
flg.startswith("-F") or flg.startswith("/libpath") or \
flg.startswith("-libpath"):
dir_list.append(flg)
else:
if flg == "-framework":
flg = "%s %s" % (flg, flag_list[i + 1])
i += 1
lib_list.append(flg)
i += 1
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I") and not flg.startswith("/I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l") or flg.endswith(".lib"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
upper_flg = flg.upper()
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R")\
and not upper_flg.startswith("/LIBPATH") and not upper_flg.startswith("-LIBPATH")\
and not flg.endswith(".lib"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R") or flg.startswith("/libpath")\
or flg.startswith("-libpath"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string += str(item)
list_string += " "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE = 0
INFO = 1
WARN = 2
ERROR = 3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n")
errs = Utils.getPossibleErrors()
if len(errs) > 0:
sys.stderr.write("Possible culprits:\n")
for pos_err in errs:
sys.stderr.write( " " + str(pos_err) + "\n" )
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x,v=arch_list: x in v)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.INFO, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber += 1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber += 1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'),
lhs.getVariable('Version')))
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFiltersChanged = True
self.mCheckDepends = True
self.mAgentDependList = []
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v)
elif req_string_list[i+1] == ">":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v)
elif req_string_list[i+1] == "<":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v)
else:
i += 1
else:
i += 1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self, packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
# Make depend list if we are supposed to
self.updateFilters()
self.makeDependList()
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter",
"Filter %s" % self.mName + " on %s." % filter.getVarName())
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
flagDBG().out(flagDBG.INFO, "PkgAgent.update",
"%s" % self.mName)
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters",
"%s has " % self.mName + str(len(self.mViablePackageList)) + " left")
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
for f in self.mFilterList:
Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName()))
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def getVarName(self):
return self.mVarName
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
ret_pkg_list.append(pkg)
else:
flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
# Now sort
ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName),
lhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
def getSplitChar(self):
self.evaluate()
split_char = self.mVariableDict.get("SplitCharacter", ' ')
if split_char == "":
split_char = ' '
return split_char
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--verbose-debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.INFO)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x,v=exact_version: x == v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
if len(listedAgentNames) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package")
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show debug information"
print " --verbose-debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
print ""
print "extending search path"
print " FLAGPOLL_PATH environment variable that can be set to"
print " extend the search path for .fpc/.pc files"
print ""
print ""
print "Send bug reports and/or feedback to flagpoll-users@vrsource.org"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
try:
import py2exe
except:
pass
setup(
name='flagpoll',
version='0.9.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
console=['flagpoll'],
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
def tokenize(val, split_char):
val = val.strip()
results = []
while len(val) > 0:
sn = val.find(split_char)
qn = val.find('"')
#print " -> val: %s Len: %s" % (val, len(val))
# If we find a quote first, then find the space after the next quote.
if qn < sn:
#print " -> Found a quote first:", qn
# Find next quote.
qn2 = val.find('"', qn+1)
#print " -> Found second quote:", qn2
sn = val.find(split_char, qn2+1)
#print " -> Found next space:", sn
if sn < 0:
results.append(val[:])
val = ""
else:
results.append(val[:sn])
val = val[sn:]
val = val.strip()
return results
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = []
def addPossibleError(pos_err):
Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err)
addPossibleError = staticmethod(addPossibleError)
def getPossibleErrors():
return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS)
getPossibleErrors = staticmethod(getPossibleErrors)
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 9
FLAGPOLL_PATCH_VERSION = 1
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = extra_paths
path_list.extend(flg_cfg_dir)
path_list.extend(pkg_cfg_dir)
path_list.extend(ld_path)
default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')]
default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list]
default_path_flg = [pj(p,'flagpoll') for p in default_path_list]
path_list.extend(default_path_pkg)
path_list.extend(default_path_flg)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
list_len = len(gen_list)
i = 0
while i < list_len:
item = gen_list[i].strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item == '-framework':
item = '%s %s' % (item, gen_list[i + 1])
i += 1
if item not in new_list:
if len(item) > 0:
new_list.append(item)
i += 1
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
list_len = len(flag_list)
i = 0
while i < list_len:
flg = flag_list[i].strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R") or \
flg.startswith("-F") or flg.startswith("/libpath") or \
flg.startswith("-libpath"):
dir_list.append(flg)
else:
if flg == "-framework":
flg = "%s %s" % (flg, flag_list[i + 1])
i += 1
lib_list.append(flg)
i += 1
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I") and not flg.startswith("/I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l") or flg.endswith(".lib"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
upper_flg = flg.upper()
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R")\
and not upper_flg.startswith("/LIBPATH") and not upper_flg.startswith("-LIBPATH")\
and not flg.endswith(".lib"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R") or flg.startswith("/libpath")\
or flg.startswith("-libpath"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string += str(item)
list_string += " "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE = 0
INFO = 1
WARN = 2
ERROR = 3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n")
errs = Utils.getPossibleErrors()
if len(errs) > 0:
sys.stderr.write("Possible culprits:\n")
for pos_err in errs:
sys.stderr.write( " " + str(pos_err) + "\n" )
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x,v=arch_list: x in v)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.INFO, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber += 1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber += 1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'),
lhs.getVariable('Version')))
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFiltersChanged = True
self.mCheckDepends = True
self.mAgentDependList = []
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v)
elif req_string_list[i+1] == ">":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v)
elif req_string_list[i+1] == "<":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v)
else:
i += 1
else:
i += 1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self, packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
# Make depend list if we are supposed to
self.updateFilters()
self.makeDependList()
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter",
"Filter %s" % self.mName + " on %s." % filter.getVarName())
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
flagDBG().out(flagDBG.INFO, "PkgAgent.update",
"%s" % self.mName)
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters",
"%s has " % self.mName + str(len(self.mViablePackageList)) + " left")
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
for f in self.mFilterList:
Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName()))
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def getVarName(self):
return self.mVarName
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
ret_pkg_list.append(pkg)
else:
flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
# Now sort
ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName),
lhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
def getSplitChar(self):
self.evaluate()
split_char = self.mVariableDict.get("SplitCharacter", ' ')
if split_char == "":
split_char = ' '
return split_char
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--verbose-debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.INFO)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x,v=exact_version: x == v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
if len(listedAgentNames) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package")
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show debug information"
print " --verbose-debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
print ""
print "extending search path"
print " FLAGPOLL_PATH environment variable that can be set to"
print " extend the search path for .fpc/.pc files"
print ""
print ""
print "Send bug reports and/or feedback to flagpoll-users@vrsource.org"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.6.2',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 7
FLAGPOLL_PATCH_VERSION = 0
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig",
"/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
#self.mOptParser = self.GetOptionParser()
#self.mOptParser.print_help()
if len(sys.argv) < 2:
self.printHelp()
#(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
#if self.mOptions.version:
# print "%s.%s.%s" % Utils.getFlagpollVersion()
# sys.exit(0)
#if len(self.mArgs) < 1:
# self.mOptParser.print_help()
# sys.exit(1)
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.6.2',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 7
FLAGPOLL_PATCH_VERSION = 0
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig",
"/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
#self.mOptParser = self.GetOptionParser()
#self.mOptParser.print_help()
if len(sys.argv) < 2:
self.printHelp()
#(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
#if self.mOptions.version:
# print "%s.%s.%s" % Utils.getFlagpollVersion()
# sys.exit(0)
#if len(self.mArgs) < 1:
# self.mOptParser.print_help()
# sys.exit(1)
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.3.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 3
FLAGPOLL_PATCH_VERSION = 1
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_DIR"):
pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("FLG_CONFIG_DIR"):
flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("LD_LIBRARY_PATH"):
ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep)
ld_path = [pj(p,'pkgconfig') for p in ld_path]
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
lokals = {}
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
fvars["XXFlagpollFilenameXX"] = filename
fvars["fp_file_cwd"] = str(filename[:- len(os.path.basename(filename))])
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
#self.mOptParser = self.GetOptionParser()
#self.mOptParser.print_help()
if len(sys.argv) < 2:
self.printHelp()
#(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
#if self.mOptions.version:
# print "%s.%s.%s" % Utils.getFlagpollVersion()
# sys.exit(0)
#if len(self.mArgs) < 1:
# self.mOptParser.print_help()
# sys.exit(1)
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--info"):
output_options.append(("info", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--list-all"):
curr_arg = curr_arg + 1
PkgDB().printAllPackages()
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
#flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
print " --info show information for packages"
print " --print-provides print which packages the package provides"
print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.3.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 3
FLAGPOLL_PATCH_VERSION = 1
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_DIR"):
pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("FLG_CONFIG_DIR"):
flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("LD_LIBRARY_PATH"):
ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep)
ld_path = [pj(p,'pkgconfig') for p in ld_path]
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
lokals = {}
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
fvars["XXFlagpollFilenameXX"] = filename
fvars["fp_file_cwd"] = str(filename[:- len(os.path.basename(filename))])
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
#self.mOptParser = self.GetOptionParser()
#self.mOptParser.print_help()
if len(sys.argv) < 2:
self.printHelp()
#(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
#if self.mOptions.version:
# print "%s.%s.%s" % Utils.getFlagpollVersion()
# sys.exit(0)
#if len(self.mArgs) < 1:
# self.mOptParser.print_help()
# sys.exit(1)
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--info"):
output_options.append(("info", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--list-all"):
curr_arg = curr_arg + 1
PkgDB().printAllPackages()
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
if agent is not None:
agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
#flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
print " --info show information for packages"
print " --print-provides print which packages the package provides"
print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.1.6',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name: var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name= %s\n" %(name))
fpc.write("Description= %s\n" %(description))
fpc.write("URL= %s\n" %(url))
fpc.write("Version= %s\n" %(version))
fpc.write("Provides= %s\n" %(provides))
fpc.write("Requires= %s\n" %(requires))
fpc.write("Arch= %s\n" %(architecture))
fpc.write("Libs= %s\n" %(libs))
fpc.write("Libs.private= %s\n" %(staticLib))
fpc.write("Cflags= %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 1
FLAGPOLL_PATCH_VERSION = 6
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_DIR"):
pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("FLG_CONFIG_DIR"):
flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("LD_LIBRARY_PATH"):
ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep)
ld_path = [pj(p,'pkgconfig') for p in ld_path if os.path.exists(p)]
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
extra_paths = [p for p in extra_paths if os.path.exists(p)]
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"]
path_list = [p for p in path_list if os.path.exists(p)]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
return path_list
getPathList = staticmethod(getPathList)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in lib_list and flg not in dir_list:
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return new_list
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in inc_list and flg not in extra_list:
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return new_list
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in inc_list:
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return inc_list
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in extra_list:
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return extra_list
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in lib_list:
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return lib_list
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in other_list:
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flag.startswith("-R"):
other_list.append(flg)
return other_list
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in dir_list:
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return dir_list
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
vars = {}
locals = {}
for line in lines:
line = line.strip()
if not line:
continue
elif ':' in line: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(locals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName)
vars[name] = val
elif '=' in line: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(locals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName)
locals[name] = val
return vars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
if level == self.ERROR:
sys.exit(1)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
DepResolutionSystem().addNewAgent(self)
self.mFilterList = DepResolutionSystem().getFilters()
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
self.makeDependList()
self.mFiltersChanged = True
def getName(self):
return self.mName
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but is not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = self.mBaseFilters
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, files[0], "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for file in list_to_add:
var_dict = Utils.parsePcFile(file)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Provides" % str(file))
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Arch" % str(file))
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, file, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
self.mOptParser = self.GetOptionParser()
(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
if self.mOptions.version:
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
if len(self.mArgs) < 1:
self.mOptParser.print_help()
sys.exit(1)
def evaluateArgs(self):
if self.mOptions.extra_paths:
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + self.mOptions.extra_paths
if self.mOptions.debug:
flagDBG().setLevel(flagDBG.VERBOSE)
Utils.printList(PkgDB().getInfo(self.mArgs[0]))
if self.mOptions.require:
DepResolutionSystem().makeRequireFilter(self.mOptions.require)
if self.mOptions.exists:
print PkgDB().exists(self.mArgs[0])
if self.mOptions.info:
for pkg in self.mArgs:
Utils.printList(PkgDB().getInfo(pkg))
if self.mOptions.variable:
Utils.printList(Utils.stripDupInList(PkgDB().getVariablesAndDeps(self.mArgs, [self.mOptions.variable])))
if self.mOptions.static:
DepResolutionSystem().setPrivateRequires(True)
if self.mOptions.atleast_version:
atleast_version = self.mOptions.atleast_version
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
DepResolutionSystem().addResolveAgentFilter(atleast_filter)
if self.mOptions.max_release:
max_release = self.mOptions.max_release
max_filter = Filter("Version", lambda x: x.startswith(max_release))
DepResolutionSystem().addResolveAgentFilter(max_filter)
if self.mOptions.exact_version:
exact_version = self.mOptions.exact_version
exact_filter = Filter("Version", lambda x: x == exact_version)
DepResolutionSystem().addResolveAgentFilter(exact_filter)
if self.mOptions.modversion:
print PkgDB().getVariables(self.mArgs[0], ["Version"])
if self.mOptions.libs:
Utils.printList(Utils.stripDupLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.libs_only_l:
Utils.printList(Utils.libsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.libs_only_L:
Utils.printList(Utils.libDirsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.libs_only_other:
Utils.printList(Utils.libsOnlyOtherLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.cflags:
Utils.printList(Utils.stripDupIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"])))
if self.mOptions.cflags_only_I:
Utils.printList(Utils.cflagsOnlyDirIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"])))
if self.mOptions.cflags_only_other:
Utils.printList(Utils.cflagsOnlyOtherIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"])))
# if not self.mOptions.list_all:
# print PkgDB().getPkgList
def GetOptionParser(self):
parser = OptionParser()
parser.add_option("--modversion", action="store_true", dest="modversion",
help="output version for package")
parser.add_option("--version", action="store_true", dest="version",
help="output version of pkg-config")
parser.add_option("--require", dest="require",
help="adds additional requirements for packages ex. 32/64")
parser.add_option("--libs", action="store_true", dest="libs",
help="output all linker flags")
parser.add_option("--static", action="store_true", dest="static",
help="output linker flags for static linking")
#parser.add_option("--short-errors", action="store_true", dest="short_errors",
# help="print short errors")
parser.add_option("--libs-only-l", action="store_true", dest="libs_only_l",
help="output -l flags")
parser.add_option("--libs-only-other", action="store_true", dest="libs_only_other",
help="output other libs (e.g. -pthread)")
parser.add_option("--libs-only-L", action="store_true", dest="libs_only_L",
help="output -L flags")
parser.add_option("--cflags", action="store_true", dest="cflags",
help="output all pre-processor and compiler flags")
parser.add_option("--cflags-only-I", action="store_true", dest="cflags_only_I",
help="output -I flags")
parser.add_option("--cflags-only-other ", action="store_true", dest="cflags_only_other",
help="output cflags not covered by the cflags-only-I option")
parser.add_option("--exists", action="store_true", dest="exists",
help="return 0 if the module(s) exist")
#parser.add_option("--list-all", action="store_true", dest="list_all",
# help="list all known packages")
parser.add_option("--debug", action="store_true", dest="debug",
help="show verbose debug information")
parser.add_option("--info", action="store_true", dest="info",
help="show information for packages")
parser.add_option("--extra-paths", dest="extra_paths",
help="extra paths for flagpoll to search for meta-data files")
#parser.add_option("--print-errors", action="store_true", dest="print_errors",
# help="show verbose information about missing or conflicting packages")
#parser.add_option("--silence-errors", action="store_true", dest="silence_errors",
# help="show no information about missing or conflicting packages")
#parser.add_option("--uninstalled", action="store_true", dest="uninstalled",
# help="return 0 if the uninstalled version of one or more module(s) or their dependencies will be used")
#parser.add_option("--errors-to-stdout", action="store_true", dest="errors_to_stdout",
# help="print errors from --print-errors to stdout not stderr")
#parser.add_option("--print-provides", action="store_true", dest="print_provides",
# help="print which packages the package provides")
#parser.add_option("--print-requires", action="store_true", dest="print_requires",
# help="print which packages the package requires")
parser.add_option("--atleast-version", dest="atleast_version",
help="return 0 if the module is at least version ATLEAST_VERSION")
parser.add_option("--exact-version", dest="exact_version",
help="return 0 if the module is exactly version EXACT_VERSION")
parser.add_option("--max-release", dest="max_release",
help="return 0 if the module has a release that has a version of MAX_RELEASE and will return the max")
#parser.add_option("--atleast-pkgconfig-version=VERSION", dest="atleast_pkgconfig_version",
# help="require given version of pkg-config")
parser.add_option("--variable", dest="variable",
help="get the value of a variable")
#parser.add_option("--define-variable", dest="define_variable",
# help="set the value of a variable")
return parser
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs()
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.1.6',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 1
FLAGPOLL_PATCH_VERSION = 6
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_DIR"):
pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("FLG_CONFIG_DIR"):
flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep)
if os.environ.has_key("LD_LIBRARY_PATH"):
ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep)
ld_path = [pj(p,'pkgconfig') for p in ld_path if os.path.exists(p)]
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
extra_paths = [p for p in extra_paths if os.path.exists(p)]
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"]
path_list = [p for p in path_list if os.path.exists(p)]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
return path_list
getPathList = staticmethod(getPathList)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in lib_list and flg not in dir_list:
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return new_list
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in inc_list and flg not in extra_list:
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return new_list
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in inc_list:
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return inc_list
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in extra_list:
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return extra_list
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in lib_list:
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return lib_list
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in other_list:
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flag.startswith("-R"):
other_list.append(flg)
return other_list
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if flg not in dir_list:
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return dir_list
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
vars = {}
locals = {}
for line in lines:
line = line.strip()
if not line:
continue
elif ':' in line: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(locals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName)
vars[name] = val
elif '=' in line: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(locals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName)
locals[name] = val
return vars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
if level == self.ERROR:
sys.exit(1)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
DepResolutionSystem().addNewAgent(self)
self.mFilterList = DepResolutionSystem().getFilters()
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
self.makeDependList()
self.mFiltersChanged = True
def getName(self):
return self.mName
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but is not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = self.mBaseFilters
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, files[0], "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for file in list_to_add:
var_dict = Utils.parsePcFile(file)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Provides" % str(file))
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Arch" % str(file))
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, file, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
self.mOptParser = self.GetOptionParser()
(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
if self.mOptions.version:
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
if len(self.mArgs) < 1:
self.mOptParser.print_help()
sys.exit(1)
def evaluateArgs(self):
if self.mOptions.extra_paths:
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + self.mOptions.extra_paths
if self.mOptions.debug:
flagDBG().setLevel(flagDBG.VERBOSE)
Utils.printList(PkgDB().getInfo(self.mArgs[0]))
if self.mOptions.require:
DepResolutionSystem().makeRequireFilter(self.mOptions.require)
if self.mOptions.exists:
print PkgDB().exists(self.mArgs[0])
if self.mOptions.info:
for pkg in self.mArgs:
Utils.printList(PkgDB().getInfo(pkg))
if self.mOptions.variable:
Utils.printList(Utils.stripDupInList(PkgDB().getVariablesAndDeps(self.mArgs, [self.mOptions.variable])))
if self.mOptions.static:
DepResolutionSystem().setPrivateRequires(True)
if self.mOptions.atleast_version:
atleast_version = self.mOptions.atleast_version
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
DepResolutionSystem().addResolveAgentFilter(atleast_filter)
if self.mOptions.max_release:
max_release = self.mOptions.max_release
max_filter = Filter("Version", lambda x: x.startswith(max_release))
DepResolutionSystem().addResolveAgentFilter(max_filter)
if self.mOptions.exact_version:
exact_version = self.mOptions.exact_version
exact_filter = Filter("Version", lambda x: x == exact_version)
DepResolutionSystem().addResolveAgentFilter(exact_filter)
if self.mOptions.modversion:
print PkgDB().getVariables(self.mArgs[0], ["Version"])
if self.mOptions.libs:
Utils.printList(Utils.stripDupLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.libs_only_l:
Utils.printList(Utils.libsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.libs_only_L:
Utils.printList(Utils.libDirsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.libs_only_other:
Utils.printList(Utils.libsOnlyOtherLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"])))
if self.mOptions.cflags:
Utils.printList(Utils.stripDupIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"])))
if self.mOptions.cflags_only_I:
Utils.printList(Utils.cflagsOnlyDirIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"])))
if self.mOptions.cflags_only_other:
Utils.printList(Utils.cflagsOnlyOtherIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"])))
# if not self.mOptions.list_all:
# print PkgDB().getPkgList
def GetOptionParser(self):
parser = OptionParser()
parser.add_option("--modversion", action="store_true", dest="modversion",
help="output version for package")
parser.add_option("--version", action="store_true", dest="version",
help="output version of pkg-config")
parser.add_option("--require", dest="require",
help="adds additional requirements for packages ex. 32/64")
parser.add_option("--libs", action="store_true", dest="libs",
help="output all linker flags")
parser.add_option("--static", action="store_true", dest="static",
help="output linker flags for static linking")
#parser.add_option("--short-errors", action="store_true", dest="short_errors",
# help="print short errors")
parser.add_option("--libs-only-l", action="store_true", dest="libs_only_l",
help="output -l flags")
parser.add_option("--libs-only-other", action="store_true", dest="libs_only_other",
help="output other libs (e.g. -pthread)")
parser.add_option("--libs-only-L", action="store_true", dest="libs_only_L",
help="output -L flags")
parser.add_option("--cflags", action="store_true", dest="cflags",
help="output all pre-processor and compiler flags")
parser.add_option("--cflags-only-I", action="store_true", dest="cflags_only_I",
help="output -I flags")
parser.add_option("--cflags-only-other ", action="store_true", dest="cflags_only_other",
help="output cflags not covered by the cflags-only-I option")
parser.add_option("--exists", action="store_true", dest="exists",
help="return 0 if the module(s) exist")
#parser.add_option("--list-all", action="store_true", dest="list_all",
# help="list all known packages")
parser.add_option("--debug", action="store_true", dest="debug",
help="show verbose debug information")
parser.add_option("--info", action="store_true", dest="info",
help="show information for packages")
parser.add_option("--extra-paths", dest="extra_paths",
help="extra paths for flagpoll to search for meta-data files")
#parser.add_option("--print-errors", action="store_true", dest="print_errors",
# help="show verbose information about missing or conflicting packages")
#parser.add_option("--silence-errors", action="store_true", dest="silence_errors",
# help="show no information about missing or conflicting packages")
#parser.add_option("--uninstalled", action="store_true", dest="uninstalled",
# help="return 0 if the uninstalled version of one or more module(s) or their dependencies will be used")
#parser.add_option("--errors-to-stdout", action="store_true", dest="errors_to_stdout",
# help="print errors from --print-errors to stdout not stderr")
#parser.add_option("--print-provides", action="store_true", dest="print_provides",
# help="print which packages the package provides")
#parser.add_option("--print-requires", action="store_true", dest="print_requires",
# help="print which packages the package requires")
parser.add_option("--atleast-version", dest="atleast_version",
help="return 0 if the module is at least version ATLEAST_VERSION")
parser.add_option("--exact-version", dest="exact_version",
help="return 0 if the module is exactly version EXACT_VERSION")
parser.add_option("--max-release", dest="max_release",
help="return 0 if the module has a release that has a version of MAX_RELEASE and will return the max")
#parser.add_option("--atleast-pkgconfig-version=VERSION", dest="atleast_pkgconfig_version",
# help="require given version of pkg-config")
parser.add_option("--variable", dest="variable",
help="get the value of a variable")
#parser.add_option("--define-variable", dest="define_variable",
# help="set the value of a variable")
return parser
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs()
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name: var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name= %s\n" %(name))
fpc.write("Description= %s\n" %(description))
fpc.write("URL= %s\n" %(url))
fpc.write("Version= %s\n" %(version))
fpc.write("Provides= %s\n" %(provides))
fpc.write("Requires= %s\n" %(requires))
fpc.write("Arch= %s\n" %(architecture))
fpc.write("Libs= %s\n" %(libs))
fpc.write("Libs.private= %s\n" %(staticLib))
fpc.write("Cflags= %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.4.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 4
FLAGPOLL_PATCH_VERSION = 1
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLG_CONFIG_PATH"):
flg_cfg_dir = os.environ["FLG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("LD_LIBRARY_PATH"):
ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep)
ld_path = [pj(p,'pkgconfig') for p in ld_path]
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["XXFlagpollFilenameXX"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
#self.mOptParser = self.GetOptionParser()
#self.mOptParser.print_help()
if len(sys.argv) < 2:
self.printHelp()
#(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
#if self.mOptions.version:
# print "%s.%s.%s" % Utils.getFlagpollVersion()
# sys.exit(0)
#if len(self.mArgs) < 1:
# self.mOptParser.print_help()
# sys.exit(1)
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
#flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
#MAKE PRETTY
print pkg.getInfo()
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.4.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
from optparse import OptionParser
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 4
FLAGPOLL_PATCH_VERSION = 1
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLG_CONFIG_PATH"):
flg_cfg_dir = os.environ["FLG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("LD_LIBRARY_PATH"):
ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep)
ld_path = [pj(p,'pkgconfig') for p in ld_path]
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["XXFlagpollFilenameXX"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
#self.mOptParser = self.GetOptionParser()
#self.mOptParser.print_help()
if len(sys.argv) < 2:
self.printHelp()
#(self.mOptions, self.mArgs) = self.mOptParser.parse_args()
#if self.mOptions.version:
# print "%s.%s.%s" % Utils.getFlagpollVersion()
# sys.exit(0)
#if len(self.mArgs) < 1:
# self.mOptParser.print_help()
# sys.exit(1)
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
#flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
#MAKE PRETTY
print pkg.getInfo()
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
from distutils.core import setup
try:
import py2exe
except:
pass
setup(
name='flagpoll',
version='0.9.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
console=['flagpoll'],
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
def tokenize(val, split_char):
val = val.strip()
results = []
while len(val) > 0:
sn = val.find(split_char)
qn = val.find('"')
#print " -> val: %s Len: %s" % (val, len(val))
# If we find a quote first, then find the space after the next quote.
if qn < sn:
#print " -> Found a quote first:", qn
# Find next quote.
qn2 = val.find('"', qn+1)
#print " -> Found second quote:", qn2
sn = val.find(split_char, qn2+1)
#print " -> Found next space:", sn
if sn < 0:
results.append(val[:])
val = ""
else:
results.append(val[:sn])
val = val[sn:]
val = val.strip()
return results
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = []
def addPossibleError(pos_err):
Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err)
addPossibleError = staticmethod(addPossibleError)
def getPossibleErrors():
return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS)
getPossibleErrors = staticmethod(getPossibleErrors)
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 9
FLAGPOLL_PATCH_VERSION = 3
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = extra_paths
path_list.extend(flg_cfg_dir)
path_list.extend(pkg_cfg_dir)
path_list.extend(ld_path)
default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')]
default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list]
default_path_flg = [pj(p,'flagpoll') for p in default_path_list]
path_list.extend(default_path_pkg)
path_list.extend(default_path_flg)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
clean_path_list = []
for p in path_list:
if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list:
clean_path_list.append(p)
path_list = clean_path_list
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
list_len = len(gen_list)
i = 0
while i < list_len:
item = gen_list[i].strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item in ('-framework', '-arch', '-isysroot'):
item = '%s %s' % (item, gen_list[i + 1])
i += 1
if item not in new_list:
if len(item) > 0:
new_list.append(item)
i += 1
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
list_len = len(flag_list)
i = 0
vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I)
other_linker_flag_re = _re.compile(r'^-[LRF]')
while i < list_len:
flg = flag_list[i].strip()
if len(flg) > 0:
if (other_linker_flag_re.match(flg) is not None\
or vc_linker_flag_re.match(flg) is not None):
dir_list.append(flg)
else:
if flg in ("-framework", "-arch", "-isysroot"):
flg = "%s %s" % (flg, flag_list[i + 1])
i += 1
lib_list.append(flg)
i += 1
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
list_len = len(flag_list)
i = 0
while i < list_len:
flg = flag_list[i].strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
elif flg in ("-arch", "-isysroot"):
extra_list.append("%s %s" % (flg, flag_list[i + 1]))
i += 1
else:
extra_list.append(flg)
i += 1
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I") and not flg.startswith("/I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l") or flg.endswith(".lib"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
upper_flg = flg.upper()
if not flg.startswith("-l") \
and not flg.startswith("-L")\
and not flg.startswith("-R")\
and not upper_flg.startswith("/LIBPATH")\
and not upper_flg.startswith("-LIBPATH")\
and not flg.endswith(".lib"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I)
other_linker_flag_re = _re.compile(r'^-[LRF]')
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if (other_linker_flag_re.match(flg) is not None or
vc_linker_flag_re.match(flg) is not None):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string += str(item)
list_string += " "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE = 0
INFO = 1
WARN = 2
ERROR = 3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n")
errs = Utils.getPossibleErrors()
if len(errs) > 0:
sys.stderr.write("Possible culprits:\n")
for pos_err in errs:
sys.stderr.write( " " + str(pos_err) + "\n" )
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
arch_list.append("x64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x,v=arch_list: x in v)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.INFO, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber += 1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber += 1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'),
lhs.getVariable('Version')))
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFiltersChanged = True
self.mCheckDepends = True
self.mAgentDependList = []
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v)
elif req_string_list[i+1] == ">":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v)
elif req_string_list[i+1] == "<":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v)
else:
i += 1
else:
i += 1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self, packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
# Make depend list if we are supposed to
self.updateFilters()
self.makeDependList()
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter",
"Filter %s" % self.mName + " on %s." % filter.getVarName())
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
flagDBG().out(flagDBG.INFO, "PkgAgent.update",
"%s" % self.mName)
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters",
"%s has " % self.mName + str(len(self.mViablePackageList)) + " left")
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
for f in self.mFilterList:
Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName()))
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def getVarName(self):
return self.mVarName
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
ret_pkg_list.append(pkg)
else:
flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
# Now sort
ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName),
lhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
def getSplitChar(self):
self.evaluate()
split_char = self.mVariableDict.get("SplitCharacter", ' ')
if split_char == "":
split_char = ' '
return split_char
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--verbose-debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.INFO)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x,v=exact_version: x == v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
if len(listedAgentNames) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator",
"Must specify at least one package")
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator",
"No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator",
"No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show debug information"
print " --verbose-debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
print ""
print "extending search path"
print " FLAGPOLL_PATH environment variable that can be set to"
print " extend the search path for .fpc/.pc files"
print ""
print ""
print "Send bug reports and/or feedback to flagpoll-users@vrsource.org"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
try:
import py2exe
except:
pass
setup(
name='flagpoll',
version='0.9.1',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
console=['flagpoll'],
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
def tokenize(val, split_char):
val = val.strip()
results = []
while len(val) > 0:
sn = val.find(split_char)
qn = val.find('"')
#print " -> val: %s Len: %s" % (val, len(val))
# If we find a quote first, then find the space after the next quote.
if qn < sn:
#print " -> Found a quote first:", qn
# Find next quote.
qn2 = val.find('"', qn+1)
#print " -> Found second quote:", qn2
sn = val.find(split_char, qn2+1)
#print " -> Found next space:", sn
if sn < 0:
results.append(val[:])
val = ""
else:
results.append(val[:sn])
val = val[sn:]
val = val.strip()
return results
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = []
def addPossibleError(pos_err):
Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err)
addPossibleError = staticmethod(addPossibleError)
def getPossibleErrors():
return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS)
getPossibleErrors = staticmethod(getPossibleErrors)
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 9
FLAGPOLL_PATCH_VERSION = 3
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = extra_paths
path_list.extend(flg_cfg_dir)
path_list.extend(pkg_cfg_dir)
path_list.extend(ld_path)
default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')]
default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list]
default_path_flg = [pj(p,'flagpoll') for p in default_path_list]
path_list.extend(default_path_pkg)
path_list.extend(default_path_flg)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
clean_path_list = []
for p in path_list:
if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list:
clean_path_list.append(p)
path_list = clean_path_list
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
list_len = len(gen_list)
i = 0
while i < list_len:
item = gen_list[i].strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item in ('-framework', '-arch', '-isysroot'):
item = '%s %s' % (item, gen_list[i + 1])
i += 1
if item not in new_list:
if len(item) > 0:
new_list.append(item)
i += 1
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
list_len = len(flag_list)
i = 0
vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I)
other_linker_flag_re = _re.compile(r'^-[LRF]')
while i < list_len:
flg = flag_list[i].strip()
if len(flg) > 0:
if (other_linker_flag_re.match(flg) is not None\
or vc_linker_flag_re.match(flg) is not None):
dir_list.append(flg)
else:
if flg in ("-framework", "-arch", "-isysroot"):
flg = "%s %s" % (flg, flag_list[i + 1])
i += 1
lib_list.append(flg)
i += 1
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
list_len = len(flag_list)
i = 0
while i < list_len:
flg = flag_list[i].strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
elif flg in ("-arch", "-isysroot"):
extra_list.append("%s %s" % (flg, flag_list[i + 1]))
i += 1
else:
extra_list.append(flg)
i += 1
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I") or flg.startswith("/I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I") and not flg.startswith("/I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l") or flg.endswith(".lib"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
upper_flg = flg.upper()
if not flg.startswith("-l") \
and not flg.startswith("-L")\
and not flg.startswith("-R")\
and not upper_flg.startswith("/LIBPATH")\
and not upper_flg.startswith("-LIBPATH")\
and not flg.endswith(".lib"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I)
other_linker_flag_re = _re.compile(r'^-[LRF]')
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if (other_linker_flag_re.match(flg) is not None or
vc_linker_flag_re.match(flg) is not None):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string += str(item)
list_string += " "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE = 0
INFO = 1
WARN = 2
ERROR = 3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n")
errs = Utils.getPossibleErrors()
if len(errs) > 0:
sys.stderr.write("Possible culprits:\n")
for pos_err in errs:
sys.stderr.write( " " + str(pos_err) + "\n" )
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
arch_list.append("x64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x,v=arch_list: x in v)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.INFO, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
self.resolveHelper()
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber += 1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber += 1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'),
lhs.getVariable('Version')))
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFiltersChanged = True
self.mCheckDepends = True
self.mAgentDependList = []
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v)
elif req_string_list[i+1] == ">":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v)
elif req_string_list[i+1] == "<":
ver_to_filt = req_string_list[i+2].strip()
new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v)
else:
i += 1
else:
i += 1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self, packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
# Make depend list if we are supposed to
self.updateFilters()
self.makeDependList()
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter",
"Filter %s" % self.mName + " on %s." % filter.getVarName())
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
flagDBG().out(flagDBG.INFO, "PkgAgent.update",
"%s" % self.mName)
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters",
"%s has " % self.mName + str(len(self.mViablePackageList)) + " left")
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
for f in self.mFilterList:
Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName()))
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def getVarName(self):
return self.mVarName
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
ret_pkg_list.append(pkg)
else:
flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() +
" %s is " % self.mVarName + str(var))
# Now sort
ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName),
lhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key, []).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
def getSplitChar(self):
self.evaluate()
split_char = self.mVariableDict.get("SplitCharacter", ' ')
if split_char == "":
split_char = ' '
return split_char
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--verbose-debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.INFO)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x,v=exact_version: x == v)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x <= v)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x,v=req_val: x >= v)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x > v)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x < v)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x,v=req_val: x == v)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
if len(listedAgentNames) == 0:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator",
"Must specify at least one package")
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator",
"No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator",
"No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar()))
for extra_var in ext_vars:
var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar()))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show debug information"
print " --verbose-debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
print ""
print "extending search path"
print " FLAGPOLL_PATH environment variable that can be set to"
print " extend the search path for .fpc/.pc files"
print ""
print ""
print "Send bug reports and/or feedback to flagpoll-users@vrsource.org"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.8.0',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 8
FLAGPOLL_PATCH_VERSION = 0
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig",
"/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='flagpoll',
version='0.8.0',
description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.',
author='Daniel E. Shipton',
author_email='dshipton@infiscape.com',
license='GPL',
url='https://realityforge.vrsource.org/view/FlagPoll/WebHome',
download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads',
scripts=['flagpoll'],
long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.",
data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])]
)
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flagpoll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flagpoll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
import sys, os, glob, os.path, copy, platform
pj = os.path.join
####################################################################
# SNAGGED FROM PYTHON 2.4 for versions under 2.4
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % val
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % mapping[named]
except KeyError:
return self.delimiter + named
braced = mo.group('braced')
if braced is not None:
try:
return '%s' % mapping[braced]
except KeyError:
return self.delimiter + '{' + braced + '}'
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return self.delimiter
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# End Snagging
####################################################################
class Utils:
# Holds collection of small utility functions
EXTRA_FLAGPOLL_SEARCH_PATHS = ""
EXTRA_FLAGPOLL_FILES = ""
path_list_cache = None # Cache of found path lists. (only calcuate once)
KEEP_DUPS = False
def getFlagpollVersion():
FLAGPOLL_MAJOR_VERSION = 0
FLAGPOLL_MINOR_VERSION = 8
FLAGPOLL_PATCH_VERSION = 0
return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION )
getFlagpollVersion = staticmethod(getFlagpollVersion)
def getPathList():
if None != Utils.path_list_cache:
return Utils.path_list_cache
#TODO: expand LD_LIBRARY_PATH to 64/32/etc???
pkg_cfg_dir = []
flg_cfg_dir = []
ld_path = []
if os.environ.has_key("PKG_CONFIG_PATH"):
pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep)
if os.environ.has_key("FLAGPOLL_PATH"):
flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep)
ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
for d in ld_dirs:
if os.environ.has_key(d):
cur_path = os.environ[d].split(os.pathsep)
ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path]
ld_path_flg = [pj(p,'flagpoll') for p in cur_path]
ld_path.extend(ld_path_pkg)
ld_path.extend(ld_path_flg)
extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep)
path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig",
"/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]
path_list.extend(pkg_cfg_dir)
path_list.extend(flg_cfg_dir)
path_list.extend(extra_paths)
path_list.extend(ld_path)
flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList",
"Potential path list: " + str(path_list))
path_list = [p for p in path_list if os.path.exists(p)]
flagDBG().out(flagDBG.INFO, "Utils.getPathList",
"Using path list: " + str(path_list))
Utils.path_list_cache = path_list
return path_list
getPathList = staticmethod(getPathList)
def getFileList():
flist = Utils.EXTRA_FLAGPOLL_FILES.split(":")
filelist = []
for f in flist:
if os.path.isfile(f):
filelist.append(f)
return filelist
getFileList = staticmethod(getFileList)
def setKeepDups(keep_dups):
Utils.KEEP_DUPS = keep_dups
setKeepDups = staticmethod(setKeepDups)
def stripDupInList(gen_list):
new_list = []
for item in gen_list:
item = item.strip()
if Utils.KEEP_DUPS:
if len(item) > 0:
new_list.append(item)
continue
if item not in new_list:
if len(item) > 0:
new_list.append(item)
return new_list
stripDupInList = staticmethod(stripDupInList)
def stripDupLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
else:
lib_list.append(flg)
new_list = dir_list + lib_list
return Utils.stripDupInList(new_list)
stripDupLinkerFlags = staticmethod(stripDupLinkerFlags)
def stripDupIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
else:
extra_list.append(flg)
extra_list.sort()
new_list = inc_list + extra_list
return Utils.stripDupInList(new_list)
stripDupIncludeFlags = staticmethod(stripDupIncludeFlags)
def cflagsOnlyDirIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
inc_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-I"):
inc_list.append(flg)
return Utils.stripDupInList(inc_list)
cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags)
def cflagsOnlyOtherIncludeFlags(flag_list):
# List is constructed as such ("-I/inc", "-fno-static-blah")
# We do slightly dumb stripping though
extra_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-I"):
extra_list.append(flg)
return Utils.stripDupInList(extra_list)
cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags)
def libsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
lib_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-l"):
lib_list.append(flg)
return Utils.stripDupInList(lib_list)
libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags)
def libsOnlyOtherLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
other_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"):
other_list.append(flg)
return Utils.stripDupInList(other_list)
libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags)
def libDirsOnlyLinkerFlags(flag_list):
# List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg")
# We do slightly dumb stripping though
dir_list = []
for flg in flag_list:
flg = flg.strip()
if len(flg) > 0:
if flg.startswith("-L") or flg.startswith("-R"):
dir_list.append(flg)
return Utils.stripDupInList(dir_list)
libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags)
def printList(gen_list):
list_string = ""
for item in gen_list:
if len(item) > 0:
list_string+=str(item)
list_string+=" "
print list_string.strip()
printList = staticmethod(printList)
def parsePcFile(filename):
lines = open(filename).readlines()
fvars = {}
fvars["FlagpollFilename"] = filename
lokals = {}
lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))])
lines.append("prefix: ${prefix}")
append_next = False
append_dict = {}
append_key = ""
for line in lines:
line = line.strip()
if not line:
continue
if append_next:
tmp = append_dict[append_key]
tmp = tmp[:-1] + " " + line
append_dict[append_key] = tmp
if tmp[-1:] == "\\":
append_next = True
else:
append_next = False
continue
if line.startswith("#"):
continue
eq_pos = line.find('=')
col_pos = line.find(':')
if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable
name, val = line.split('=', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
lokals[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = lokals
append_key = name
continue
if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable
name, val = line.split(':', 1)
name = name.strip()
val = val.strip()
if '$' in val:
try:
val = Template(val).safe_substitute(lokals)
except ValueError:
flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename)
fvars[name] = val
if val[-1:] == "\\":
append_next = True
append_dict = fvars
append_key = name
return fvars
parsePcFile = staticmethod(parsePcFile)
class flagDBG(object):
# Logging class is really easy to use
# Levels:
# 0 - VERBOSE
# 1 - INFO
# 2 - WARN
# 3 - ERROR
VERBOSE=0
INFO=1
WARN=2
ERROR=3
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if flagDBG.__initialized:
return
flagDBG.__initialized = True
self.mLevel = self.WARN
self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"]
def setLevel(self, level):
if level <= 3:
self.mLevel = level
def out(self, level, obj, message):
if level == self.ERROR:
if self.mLevel == self.VERBOSE:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
else:
print self.mLevelList[level] + ": " + str(message)
sys.exit(1)
if level >= self.mLevel:
print self.mLevelList[level] + ":" + str(obj) + ": " + str(message)
class DepResolutionSystem(object):
""" You add PkgAgents with Filters into system and call resolve()
you can check for succes by depsSatisfied() and get the list
of packages that work back by calling getPackages()
"""
__initialized = False
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def __init__(self):
if DepResolutionSystem.__initialized:
return
DepResolutionSystem.__initialized = True
self.mResolveAgents = []
self.mAgentDict = {}
self.mFilters = []
self.mResolveAgentFilters = []
self.mInvalidPackageList = []
self.mSatisfied = False
self.mAgentChangeList = [] # list of those responsible for adding Filters
# to agents in higher in the chain than them
# these are the first agents to ask that they pick
# the next best package of them
self.mAgentsVisitedList = [] # list of Agents that have been visited
self.mResolvedPackageList = [] # list that is generated when deps are satified
self.mCheckPrivateRequires = False
self.mMadeDependList = False
def getFilters(self):
return self.mFilters
def addFilter(self, filter):
self.mFilters.append(filter)
def addResolveAgentFilter(self, filter):
self.mResolveAgentFilters.append(filter)
def makeRequireFilter(self, requires):
arch_list = []
arch_list.append("no_arch")
arch_list.append("")
if platform.system() == "Linux":
if requires == "64":
arch_list.append("x86_64")
if requires == "32":
arch_list.append("i386")
arch_list.append("i486")
arch_list.append("i586")
arch_list.append("i686")
if platform.system() == "Darwin":
if requires == "64":
arch_list.append("ppc64")
if requires == "32":
arch_list.append("ppc")
if platform.system().startswith("IRIX"):
arch_list.append(requires)
new_filter = Filter("Arch", lambda x: x in arch_list)
self.addFilter(new_filter)
def createAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name)
self.addNewAgent(agent)
return agent
def createResolveAgent(self, name):
if self.checkAgentExists(name):
return self.getAgent(name)
else:
agent = PkgAgent(name)
flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name)
self.addResolveAgent(agent)
return agent
def setPrivateRequires( self, req ):
self.mCheckPrivateRequires = req
def checkPrivateRequires(self):
return self.mCheckPrivateRequires
def checkAgentExists(self, name):
return self.mAgentDict.has_key(name)
def getAgent(self, name):
if self.mAgentDict.has_key(name):
return self.mAgentDict[name]
else:
flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name)
def addNewAgent(self, agent):
if not self.checkAgentExists(agent):
self.mAgentDict[agent.getName()] = agent
def addResolveAgent(self, agent):
if agent not in self.mResolveAgents:
self.mResolveAgents.append(agent)
for filt in self.mResolveAgentFilters:
agent.addFilter(filt)
def isSatisfied(self):
return self.mSatisfied
def updateResolvedPackages(self):
pkg_list = []
agent_list = []
for agent in self.mResolveAgents:
list_of_pkgs = agent.getCurrentPackageList(agent_list)
pkg_list.extend(list_of_pkgs)
self.mResolvedPackageList = pkg_list
def getPackages(self):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages",
"Generating list of valid packages ")
#str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList]))
# If this comes back empty then there isn't a valid set of packages to use
self.updateResolvedPackages()
return self.mResolvedPackageList
def checkFiltersChanged(self):
list_to_use = []
return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents]
def resolveHelper(self):
self.resolveAgentsChanged = True
while self.resolveAgentsChanged:
for agent in self.mResolveAgents:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper",
"Updating " + agent.getName())
agent.update(self.mAgentsVisitedList, self.mAgentChangeList)
self.resolveAgentsChanged = self.checkFiltersChanged()
# Ask mResolveAgents if they are done(they ask sub people) unless they are
# really above you in the walk
# If there were changes...run update on mResolveAgents again
# at the end ask for pkglist..if it comes back empty then we don't
# have a usable configuration for those packages
def resolveDeps(self):
if not self.mMadeDependList:
for agent in self.mResolveAgents:
agent.makeDependList()
self.mMadeDependList = True
self.resolveHelper()
self.updateResolvedPackages()
# Check if the first round through we found something
# Otherwise we need to start removing packages that aren't viable
# during the loop
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
# remove top of packages that added Filters.
# then move on to resolving again
# remove more if neccesary
agentChangeNumber = 0
while not self.mResolvedPackageList:
if(self.mAgentChangeList[agentChangeNumber]):
if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList:
agentChangeNumber+=1
else:
if(self.mAgentChangeList[agentChangeNumber].getViablePackages()):
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"Removing bad pkg from " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage())
else:
flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps",
"No combinations.. Resetting " +
self.mAgentChangeList[agentChangeNumber].getName())
self.mAgentChangeList[agentChangeNumber].reset()
agentChangeNumber+=1
self.resolveHelper()
self.updateResolvedPackages()
self.mSatisfied = (len(self.mResolvedPackageList) != 0)
return
class PkgAgent:
""" Agent that keeps track of the versions for a package given some filters
and the addition of Filters
"""
# Makes a PkgAgent that finds its current package with the version reqs
def __init__(self, name):
if DepResolutionSystem().checkAgentExists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName)
self.mName = name
flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName))
if not PkgDB().exists(name):
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName)
#XXX Doesn't keep filters added for a redo...
DepResolutionSystem().addNewAgent(self)
self.mFilterList = []
self.mFilterList.extend(DepResolutionSystem().getFilters())
self.mBasePackageList = PkgDB().getPkgInfos(name)
for filt in self.mFilterList:
self.mBasePackageList = filt.filter(self.mBasePackageList)
if len(self.mBasePackageList) == 0:
flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName)
self.mViablePackageList = copy.deepcopy(self.mBasePackageList)
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mAgentDependList = [] # Agents that it depends on/needs to update
#self.makeDependList()
self.mFiltersChanged = True
self.mCheckDepends = True
def getName(self):
return self.mName
def setCheckDepends(self, tf):
self.mCheckDepends = tf
#Filter("Version", lambda x: x == "4.5")
def makeDependList(self):
if not self.mCheckDepends:
self.mAgentDependList = []
return
dep_list = []
if self.mCurrentPackage:
req_string = self.mCurrentPackage.getVariable("Requires")
if DepResolutionSystem().checkPrivateRequires():
req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private")
req_string = req_string.strip()
if req_string == "":
return
req_string = req_string.replace(',', ' ')
req_string = req_string.replace('(', ' ')
req_string = req_string.replace(')', ' ')
space_req_string_list = req_string.split(' ')
req_string_list = []
for entry in space_req_string_list:
if len(entry) > 0:
req_string_list.append(entry)
i = 0
flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList",
self.mCurrentPackage.getName() + " requires: " + str(req_string_list))
while len(req_string_list) > i:
if PkgDB().exists(req_string_list[i]):
new_filter = []
new_agent = DepResolutionSystem().createAgent(req_string_list[i])
if len(req_string_list) > i+1:
if req_string_list[i+1] == "=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x == ver_to_filt)
elif req_string_list[i+1] == "<=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x <= ver_to_filt)
elif req_string_list[i+1] == ">=":
ver_to_filt = req_string_list[i+2]
new_filter = Filter("Version", lambda x: x >= ver_to_filt)
else:
i+=1
else:
i+=1
dep_list.append(new_agent)
if new_filter:
i+=3
new_agent.addFilter(new_filter)
else:
flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList",
"Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i])))
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList",
"List is:" + str([pkg.getName() for pkg in dep_list]))
self.mAgentDependList = dep_list
def filtersChanged(self,packageList):
tf_list = [self.mFiltersChanged]
if self.mName not in packageList:
packageList.append(self.mName)
for pkg in self.mAgentDependList:
tf_list.append(pkg.filtersChanged(packageList))
return True in tf_list
def getCurrentPackageList(self, packageList):
pkgs = []
if self.mName not in packageList:
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList",
"Package: %s" % self.mName)
pkgs.append(self.mCurrentPackage)
packageList.append(self.mName)
for pkg in self.mAgentDependList:
pkgs.extend(pkg.getCurrentPackageList(packageList))
return pkgs
# current pkginfo for me
def getCurrentPkgInfo(self):
return self.mCurrentPackage
# Someone else usually places these on me
# I keep track of those separately
def addFilter(self, filter):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter",
"Adding a Filter to %s" % self.mName)
self.mFiltersChanged = True
self.mFilterList.append(filter)
def removeCurrentPackage(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage",
"Removing current package of %s" % self.mName)
if self.mViablePackageList:
ret_val = self.mViablePackageList[0] in self.mBasePackageList
del self.mViablePackageList[0]
if self.mViablePackageList:
self.mCurrentPackage = self.mViablePackageList[0]
return ret_val
def update(self, agentVisitedList, agentChangeList):
if self.mName in agentVisitedList:
return
agentVisitedList.append(self.mName)
if self.mFiltersChanged:
self.mFiltersChanged = False
self.updateFilters()
# TODO: checkFilters and add them
# if a pkg is in visitedList then add yourself to agentChangeList
for pkg in self.mAgentDependList:
pkg.update(agentVisitedList, agentChangeList)
return
def updateFilters(self):
for filt in self.mFilterList:
self.mViablePackageList = filt.filter(self.mViablePackageList)
if len(self.mViablePackageList) > 0:
self.mCurrentPackage = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
def reset(self):
flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName)
self.mViablePackageList = self.mBasePackageList
if self.mViablePackageList:
self.mCurrentPacakge = self.mViablePackageList[0]
else:
self.mCurrentPackage = []
self.mFilterList = DepResolutionSystem().getFilters()
self.mAgentDependList = []
self.mFiltersChanged = True
return
class Filter:
""" A single Filter that knows how to filter the list it recieves
Will be inheireted....?..?
"""
def __init__(self, variableName, testCallable):
self.mVarName = variableName
self.mTestCallable = testCallable
def filter(self, pkg_info_list):
ret_pkg_list = []
# Filter first
for pkg in pkg_info_list:
var = pkg.getVariable(self.mVarName)
if self.mTestCallable(var):
ret_pkg_list.append(pkg)
# Now sort
ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName),
rhs.getVariable(self.mVarName)))
return ret_pkg_list
#requires: qt == 4.5
#Filter("Version", lambda x: x <= "4.5")
#Filter("Version", lambda x: x <= "4.5")
class PkgDB(object):
""" Holds all the neccesary information to evaluate itself when needed.
Is in charge of holding a list of PkgInfo's that contain info
about the package.
"""
__initialized = False
def __init__(self):
if self.__initialized:
return
self.__initialized = True
self.mPkgInfos = {} # {pkg_name: List of package infos}
self.populatePkgInfoDBPcFiles()
self.populatePkgInfoDBFpcFiles()
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def printAllPackages(self):
list_of_package_names = []
for pkg in self.mPkgInfos:
list_of_package_names.append(pkg)
for name in list_of_package_names:
print name
sys.exit(0)
def getVariables(self, name, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariable",
"Finding " + str(variable_list) + " in " + str(name))
ret_list = []
for var in variable_list:
if self.mPkgInfos.has_key(name):
ret_list.extend(self.mPkgInfos[name][0].getVariable(var))
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name)
return ret_list
def checkPackage(self, name):
flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage",
"Finding " + str(name))
if self.mPkgInfos.has_key(name):
return True
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name)
return False
def getVariablesAndDeps(self, pkg_list, variable_list):
flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps",
"Finding " + str(variable_list) + " in " + str(pkg_list))
if DepResolutionSystem().checkPrivateRequires():
temp_var_list = []
for var in variable_list:
temp_var_list.append(var.join(".private"))
variable_list = variable_list + temp_var_list
for name in pkg_list:
if self.mPkgInfos.has_key(name):
agent = DepResolutionSystem().createAgent(name)
DepResolutionSystem().addResolveAgent(agent)
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name)
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
var_list = []
for pkg in pkgs:
if pkg:
for var in variable_list:
var_list.extend(pkg.getVariable(var).split(' '))
return var_list
def getPkgInfos(self, name):
if self.mPkgInfos.has_key(name):
return self.mPkgInfos[name]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name)
def exists(self, name):
return self.mPkgInfos.has_key(name)
def getInfo(self, name):
if self.mPkgInfos.has_key(name):
return [pkg.getInfo() for pkg in self.mPkgInfos[name]]
else:
flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name)
def buildPcFileDict(self):
""" Builds up a dictionary of {name: list of files for name} """
pc_dict = {}
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these pc files: %s" % str(glob_list))
for g in glob_list: # Get key name and add file to value list in dictionary
key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(g)
for f in Utils.getFileList():
if f.endswith(".pc"):
key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky
pc_dict.setdefault(key,[]).append(f)
return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] }
def populatePkgInfoDBPcFiles(self):
dict_to_pop_from = self.buildPcFileDict()
for (pkg,files) in dict_to_pop_from.iteritems():
for f in files:
self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc"))
def buildFpcFileList(self):
""" Builds up a dictionary of {name: list of files for name} """
file_list = []
for p in Utils.getPathList():
glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory
flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict",
"Process these fpc files: %s" % str(glob_list))
for g in glob_list:
file_list.append(g)
for f in Utils.getFileList():
if f.endswith(".fpc"):
file_list.append(f)
return file_list # [ "list", "of", "fpc", "files"]
def populatePkgInfoDBFpcFiles(self):
list_to_add = self.buildFpcFileList()
for filename in list_to_add:
var_dict = Utils.parsePcFile(filename)
if not var_dict.has_key("Provides"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename))
continue
if not var_dict.has_key("Arch"):
flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename))
continue
provides_string = var_dict["Provides"]
provides_string = provides_string.replace(',', ' ')
provides_string = provides_string.replace('(', ' ')
provides_string = provides_string.replace(')', ' ')
for key in provides_string.split(" "):
if len(key) > 0:
self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict))
class PkgInfo:
""" Holds the information for a package file on the system. These however
are evaluated when the need arises.
"""
def __init__(self, name, file, type, varDict={}):
self.mName = name
self.mFile = file
self.mIsEvaluated = False
self.mType = type
self.mVariableDict = varDict
if self.mType == "fpc":
self.mIsEvaluated = True
def getVariable(self, variable):
self.evaluate()
return self.mVariableDict.get(variable,"")
def getName(self):
return self.mName
def evaluate(self):
if not self.mIsEvaluated:
flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName)
self.mVariableDict= Utils.parsePcFile(self.mFile)
self.mIsEvaluated = True
def getInfo(self):
self.evaluate()
return self.mVariableDict
class OptionsEvaluator:
def __init__(self):
if len(sys.argv) < 2:
self.printHelp()
# This is only the args....(first arg is stripped)
def evaluateArgs(self, args):
# Catch any args that need to be tended to immediately
# Process args in the order that they were recieved. Some options are not
# shown below because they are sub-options of an option below (--strip-dups)
for option in args:
if option.startswith("--debug"):
flagDBG().setLevel(flagDBG.VERBOSE)
elif option.startswith("--from-file"):
val_start = option.find('=') + 1
file = option[val_start:]
Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file
elif option.startswith("--help"):
self.printHelp()
sys.exit(0)
elif option.startswith("--version"):
print "%s.%s.%s" % Utils.getFlagpollVersion()
sys.exit(0)
elif option.startswith("--list-all"):
PkgDB().printAllPackages()
continue
listedAgentNames = []
agent = None
num_args = len(args)
curr_arg = 0
output_options = [] # (option, name/"")
important_options = [] # ones that need special attention
while curr_arg < num_args:
if args[curr_arg].startswith("--atleast-version"):
val_start = args[curr_arg].find('=') + 1
atleast_version = args[curr_arg][val_start:]
atleast_filter = Filter("Version", lambda x: x >= atleast_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(atleast_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version")
continue
if args[curr_arg].startswith("--cflags-only-I"):
output_options.append(("cflags-only-I", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--cflags-only-other"):
output_options.append(("cflags-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
#For clarity of course...
if args[curr_arg].startswith("--cflags"):
output_options.append(("cflags", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--extra-paths"):
val_start = args[curr_arg].find('=') + 1
paths = args[curr_arg][val_start:]
Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--exact-version"):
val_start = args[curr_arg].find('=') + 1
exact_version = args[curr_arg][val_start:]
exact_filter = Filter("Version", lambda x: x == exact_version)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(exact_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version")
continue
if args[curr_arg].startswith("--exists"):
important_options.append("exists")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--from-file"):
val_start = args[curr_arg].find('=') + 1
file = args[curr_arg][val_start:]
file_filter = Filter("FlagpollFilename", lambda x: x == file)
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(file_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file")
continue
if args[curr_arg].startswith("--info"):
important_options.append("info")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--print-pkg-options"):
important_options.append("print-pkg-options")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--keep-dups"):
Utils.setKeepDups(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-l"):
output_options.append(("libs-only-l", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-L"):
output_options.append(("libs-only-L", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--libs-only-other"):
output_options.append(("libs-only-other", ""))
curr_arg = curr_arg + 1
continue
#This could be the catch all for the above ones to and then filter based on what is asked...
if args[curr_arg].startswith("--libs"):
output_options.append(("libs", ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require-all"):
rlen = len("--require-all")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
DepResolutionSystem().addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
DepResolutionSystem().addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--require-"):
rlen = len("--require-")
req_string = args[curr_arg][rlen:]
req_string = req_string.replace('-','_')
curr_arg = curr_arg + 1
if agent is None:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require")
if req_string.find("<=") != -1:
op_start = req_string.find("<=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x <= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">=") != -1:
op_start = req_string.find(">=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 2:]
new_filter = Filter(req_var, lambda x: x >= req_val)
agent.addFilter(new_filter)
continue
if req_string.find(">") != -1:
op_start = req_string.find(">")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x > req_val)
agent.addFilter(new_filter)
continue
if req_string.find("<") != -1:
op_start = req_string.find("<")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x < req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") != -1:
op_start = req_string.find("=")
req_var = req_string[:op_start]
req_val = req_string[op_start + 1:]
new_filter = Filter(req_var, lambda x: x == req_val)
agent.addFilter(new_filter)
continue
if req_string.find("=") == -1:
new_filter = Filter(req_string, lambda x: len(x) > 0)
agent.addFilter(new_filter)
continue
continue
if args[curr_arg].startswith("--no-deps"):
if agent is not None:
agent.setCheckDepends(False)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--require="):
val_start = args[curr_arg].find('=') + 1
req_var = args[curr_arg][val_start:]
curr_arg = curr_arg + 1
DepResolutionSystem().makeRequireFilter(req_var)
continue
if args[curr_arg].startswith("--modversion"):
if agent is not None:
output_options.append(("Version", agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--max-release"):
val_start = args[curr_arg].find('=') + 1
max_release = args[curr_arg][val_start:]
max_filter = Filter("Version", lambda x: x.startswith(max_release))
curr_arg = curr_arg + 1
if agent is not None:
agent.addFilter(max_filter)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release")
continue
if args[curr_arg].startswith("--static"):
DepResolutionSystem().setPrivateRequires(True)
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--variable"):
val_start = args[curr_arg].find('=') + 1
fetch_var = args[curr_arg][val_start:]
if agent is not None:
output_options.append((fetch_var, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get-all"):
rlen = len("--get-all-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
output_options.append((get_string, ""))
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--get"):
rlen = len("--get-")
get_string = args[curr_arg][rlen:]
get_string = get_string.replace('-','_')
if agent is not None:
output_options.append((get_string, agent.getName()))
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get")
curr_arg = curr_arg + 1
continue
if args[curr_arg].startswith("--concat"):
important_options.append("concat")
curr_arg = curr_arg + 1
continue
if not args[curr_arg].startswith("--"):
name = args[curr_arg]
curr_arg = curr_arg + 1
if PkgDB().checkPackage(name):
agent = DepResolutionSystem().createResolveAgent(name)
listedAgentNames.append(name)
else:
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name)
sys.exit(1)
continue
if args[curr_arg] != "--debug":
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg])
curr_arg = curr_arg + 1
DepResolutionSystem().resolveDeps()
pkgs = DepResolutionSystem().getPackages()
for p in pkgs:
if not p:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
if len(pkgs) == 0:
for option in important_options:
if option == "exists":
print "no"
sys.exit(1)
flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found")
sys.exit(1)
concat = False
for option in important_options:
if option == "exists":
print "yes"
return sys.exit(0) # already checked for none above
if option == "concat":
concat = True
if option == "info":
pkg_info_list = []
for pkg in pkgs:
if pkg.getName() in listedAgentNames:
print pkg.getName()
pkg_info = pkg.getInfo()
for key in pkg_info.keys():
print " %s : %s" % (key, pkg_info[key])
if option == "print-pkg-options":
print ""
print "All options below would start with (--get-/--get-all-/--require-/--require-all-)"
print "NOTE: this list does not include the standard variables that are exported."
print ""
for pkg in pkgs:
if pkg.getName() not in listedAgentNames:
continue
print "Package: " + pkg.getName()
for key in pkg.getInfo().keys():
if key not in [ "Name", "Description", "URL", "Version",
"Requires", "Requires.private", "Conflicts",
"Libs", "Libs.private", "Cflags", "Provides",
"Arch", "FlagpollFilename", "prefix" ]:
print " " + key.replace('_','-')
#print output_options
#output_options = []
#output_single = []
#Process options here..............
concat_list = []
if concat:
print_option = lambda x: concat_list.extend(x)
else:
print_option = lambda x: Utils.printList(x)
for option in output_options:
if option[0] == "cflags":
print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-I":
print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "cflags-only-other":
print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1])))
elif option[0] == "libs-only-l":
print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-L":
print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs-only-other":
print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
elif option[0] == "libs":
print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1])))
else:
print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1])))
if concat:
Utils.printList(Utils.stripDupInList(concat_list))
def getVarFromPkgs(self, var, pkgs, pkg_name=""):
var_list = []
ext_vars = []
if var == "Libs":
if DepResolutionSystem().checkPrivateRequires:
ext_vars.append("Libs.private")
if pkg_name == "":
for pkg in pkgs:
if pkg:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
else:
for pkg in pkgs:
if pkg:
if pkg.getName() == pkg_name:
var_list.extend(pkg.getVariable(var).split(' '))
for extra_var in ext_vars:
var_list.extend(pkg.getVariable(extra_var).split(' '))
return var_list
def printHelp(self):
print "usage: flagpoll pkg options [pkg options] [generic options]"
print " "
print "generic options:"
print " --help show this help message and exit"
print " --version output version of flagpoll"
print " --list-all list all known packages"
print " --debug show verbose debug information"
print " --extra-paths=EXTRA_PATHS"
print " extra paths for flagpoll to search for meta-data files"
print " --concat concatenate all output and output as one line"
print " --keep-dups do not strip out all duplicate info from options"
print " --info show information for packages"
print " --print-pkg-options show pkg specific options"
print " "
print "options:"
print " --modversion output version for package"
print " --require=REQUIRE adds additional requirements for packages ex. 32/64"
print " --libs output all linker flags"
print " --static output linker flags for static linking"
print " --libs-only-l output -l flags"
print " --libs-only-other output other libs (e.g. -pthread)"
print " --libs-only-L output -L flags"
print " --cflags output all pre-processor and compiler flags"
print " --cflags-only-I output -I flags"
print " --cflags-only-other output cflags not covered by the cflags-only-I option"
print " --exists return 0 if the module(s) exist"
print " --from-file=FILE use the specified FILE for the package"
#print " --print-provides print which packages the package provides"
#print " --print-requires print which packages the package requires"
print " --no-deps do not lookup dependencies for the package"
print " --atleast-version=ATLEAST_VERSION"
print " return 0 if the module is at least version"
print " ATLEAST_VERSION"
print " --exact-version=EXACT_VERSION"
print " return 0 if the module is exactly version"
print " EXACT_VERSION"
print " --max-release=MAX_RELEASE"
print " return 0 if the module has a release that has a"
print " version of MAX_RELEASE and will return the max"
print " --variable=VARIABLE get the value of a variable"
print " "
print "dynamic options(replace VAR with a variable you want to get/filter on)"
print " NOTE: replace underscores with dashes in VAR"
print " NOTE: quotes are needed around <,>,= combinations"
print " --get-VAR get VAR from package"
print " --get-all-VAR get VAR from package and its deps"
print " --require-VAR[<,>,=VAL]"
print " require that a var is defined for a package"
print " or optionally use equality operators against VAL"
print " --require-all-VAR[<,>,=VAL]"
print " require that a var is defined for all packages"
print " or optionally use equality operators against VAL"
sys.exit(0)
def main():
# GO!
# Initialize singletons and the start evaluating
#print sys.argv[1:]
my_dbg = flagDBG()
my_dep_system = DepResolutionSystem()
opt_evaluator = OptionsEvaluator()
opt_evaluator.evaluateArgs(sys.argv[1:])
sys.exit(0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# -----------------------------------------------------------------
#
# Flag Poll: A tool to extract flags from installed applications
# for compiling, settting variables, etc.
#
# Original Authors:
# Daniel E. Shipton <dshipton@gmail.com>
#
# Flag Poll is Copyright (C) 2006 by Daniel E. Shipton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
# Free SoftwareFoundation, Inc.
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# -----------------------------------------------------------------
"""Makes a flagpole .fpc file from user input.
v0.9 coded by Jeff Groves"""
import os
import sys
import getopt
##String prompts for the input
varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \
""" empty line when done)"""
namePrompt = "Formal Name"
descriptionPrompt = "Description"
urlPrompt = "URL"
providesPrompt = "One or more names to look package up by: (Provides)"
versionPrompt = "Version (x.y.z)"
architecturePrompt = "Architecture"
requirePrompt = "Requires"
libPrompt = "Linker Flags (-lfoo -L/usr/lib)"
staticLibPrompt = "Static Linking Flags/Libs (extra private libs)"
compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)"
fileNamePrompt = "FPC File's Name"
def usage():
"""Prints a list of acceptable arguments for fpcmaker.py."""
print """
Fpcmaker.py Options:
-n, --name= : Sets %s
-d, --description= : Sets %s
-u, --url= : Sets %s
-p, --provides= : Sets %s
-v, --version= : Sets %s
-a, --architecture= : Sets %s
-r, --requires= : Sets %s
-l, --libs= : Sets %s
-c, --cflags= : Sets %s
-s, --static= : Sets %s
-f, --file= : Sets %s
""" %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt,
versionPrompt, architecturePrompt,
requirePrompt, libPrompt, compileFlagsPrompt,
staticLibPrompt, fileNamePrompt)
return
def checkFileName(fileName):
"""Checks if the fpc file name's blank, contains slashes, or exists."""
nameCleared = False
writeFile = True
confirms = ['y', 'Y', 'yes', 'Yes']
##Loops until the name clears or writing the file's aborted.
while(not nameCleared and writeFile):
##If it's blank, give the option of aborting the program.
if fileName == "":
choice = raw_input("Do you want to abort writing the" +
" .fpc file? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
writeFile = False
##If it contains slashes, ask for another name.
elif '/' in fileName or '\\' in fileName:
print "I can't write to %s because it contains slashes."%(fileName)
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
##If it already exists, ask if they want to overwrite.
##If not, ask for another name.
elif os.path.exists(fileName):
choice = raw_input("The file %s already exists." %(fileName) +
" Do you want to overwrite it? (Y/N): ")
if choice not in confirms:
fileName = raw_input("Please enter a different name for the" +
" .fpc file: ")
else:
nameCleared = True
else:
nameCleared = True
return [fileName, writeFile]
##Booleans for whether that argument was sent in the command line
varSet = False
providesSet = False
nameSet = False
descriptionSet = False
urlSet = False
architectureSet = False
versionSet = False
requiresSet = False
libsSet = False
compileFlagsSet = False
staticLibSet = False
fileNameSet = False
##Get the options & arguments sent.
arguments = sys.argv[1:]
try:
opts, args = getopt.getopt(arguments,
"p:n:u:d:a:r:v:l:c:s:f:",
["provides=", "name=", "url=", "description=",
"architecture=", "requires=", "version=",
"libs=", "cflags=", "static=", "file="])
##Send them usage info if they enter a wrong argument
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--provides'):
providesSet = True
provides = arg
elif opt in ('-n', '--name'):
nameSet = True
name = arg
elif opt in ('-v', '--version'):
versionSet = True
version = arg
elif opt in ('-u', '--url'):
urlSet = True
url = arg
elif opt in ('-d', '--description'):
descriptionSet = True
description = arg
elif opt in ('-a', '--architecture'):
architectureSet = True
architecture = arg
elif opt in ('-r', '--requires'):
requiresSet = True
requires = arg
elif opt in ('-l', '--libs'):
libsSet = True
libs = arg
elif opt in ('-c', '--cflags'):
compileFlagsSet = True
compileFlags = arg
elif opt in ('-s', '--static'):
staticLibSet = True
staticLib = arg
elif opt in ('-f', '--file'):
fileNameSet = True
fileName = arg
##Grab any input not passed in the arguments from the user.
if not varSet:
varLine = None
variables = ""
print "%s:" %(varPrompt)
while(varLine != ""):
varLine = raw_input("")
variables = variables + "%s\n" %(varLine)
if not nameSet:
name = raw_input("%s: " %(namePrompt))
if not descriptionSet:
description = raw_input("%s: " %(descriptionPrompt))
if not urlSet:
url = raw_input("%s: " %(urlPrompt))
if not versionSet:
version = raw_input("%s: " %(versionPrompt))
if not providesSet:
provides = raw_input("%s: " %(providesPrompt))
if not requiresSet:
requires = raw_input("%s: " %(requirePrompt))
if not architectureSet:
architecture = raw_input("%s: " %(architecturePrompt))
if not libsSet:
libs = raw_input("%s: " %(libPrompt))
if not staticLibSet:
staticLib = raw_input("%s: " %(staticLibPrompt))
if not compileFlagsSet:
compileFlags = raw_input("%s: " %(compileFlagsPrompt))
if not fileNameSet:
fileName = raw_input("%s: " %(fileNamePrompt))
##Check the file's name.
fileName, writeFile = checkFileName(fileName)
##If they chose not to overwrite, write the file.
if writeFile:
fpc = open(fileName, 'w')
fpc.write("%s" %(variables))
fpc.write("Name: %s\n" %(name))
fpc.write("Description: %s\n" %(description))
fpc.write("URL: %s\n" %(url))
fpc.write("Version: %s\n" %(version))
fpc.write("Provides: %s\n" %(provides))
fpc.write("Requires: %s\n" %(requires))
fpc.write("Arch: %s\n" %(architecture))
fpc.write("Libs: %s\n" %(libs))
fpc.write("Libs.private: %s\n" %(staticLib))
fpc.write("Cflags: %s\n" %(compileFlags))
fpc.close()
##TESTER: Print the file out.
fpc = open(fileName, 'r') ##TESTER
print fpc.read() ##TESTER
fpc.close ##TESTER
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.