code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python # # Copyright (C) 2012 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. __author__ = 'afshar@google.com (Ali Afshar)' import os import httplib2 import sessions from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build_from_document from apiclient.http import MediaUpload from oauth2client import client from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json APIS_BASE = 'https://www.googleapis.com' ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') CODE_PARAMETER = 'code' STATE_PARAMETER = 'state' SESSION_SECRET = open('session.secret').read() DRIVE_DISCOVERY_DOC = open('drive.json').read() USERS_DISCOVERY_DOC = open('users.json').read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials.""" credentials = CredentialsProperty() def CreateOAuthFlow(request): """Create OAuth2.0 flow controller Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = client.flow_from_clientsecrets('client-debug.json', scope='') flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/') return flow def GetCodeCredentials(request): """Create OAuth2.0 credentials by extracting a code and performing OAuth2.0. Args: request: HTTP request used for extracting an authorization code. Returns: OAuth2.0 credentials suitable for authorizing clients. """ code = request.get(CODE_PARAMETER) if code: oauth_flow = CreateOAuthFlow(request) creds = oauth_flow.step2_exchange(code) users_service = CreateService(USERS_DISCOVERY_DOC, creds) userid = users_service.userinfo().get().execute().get('id') request.session.set_secure_cookie(name='userid', value=userid) StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(request): """Get OAuth2.0 credentials for an HTTP session. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ userid = request.session.get_secure_cookie(name='userid') if userid: creds = StorageByKeyName(Credentials, userid, 'credentials').get() if creds and not creds.invalid: return creds def CreateService(discovery_doc, creds): """Create a Google API service. Args: discovery_doc: Discovery doc used to configure service. creds: Credentials used to authorize service. Returns: Authorized Google API service. """ http = httplib2.Http() creds.authorize(http) return build_from_document(discovery_doc, APIS_BASE, http=http) def RedirectAuth(handler): """Redirect a handler to an authorization page. Args: handler: webapp.RequestHandler to redirect. """ flow = CreateOAuthFlow(handler.request) flow.scope = ALL_SCOPES uri = flow.step1_get_authorize_url(flow.redirect_uri) handler.redirect(uri) def CreateDrive(handler): """Create a fully authorized drive service for this handler. Args: handler: RequestHandler from which drive service is generated. Returns: Authorized drive service, generated from the handler request. """ request = handler.request request.session = sessions.LilCookies(handler, SESSION_SECRET) creds = GetCodeCredentials(request) or GetSessionCredentials(request) if creds: return CreateService(DRIVE_DISCOVERY_DOC, creds) else: RedirectAuth(handler) def ServiceEnabled(view): """Decorator to inject an authorized service into an HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) response_data = view(handler, service) handler.response.headers['Content-Type'] = 'text/html' handler.response.out.write(response_data) return ServiceDecoratedView def ServiceEnabledJson(view): """Decorator to inject an authorized service into a JSON HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) if handler.request.body: data = json.loads(handler.request.body) else: data = None response_data = json.dumps(view(handler, service, data)) handler.response.headers['Content-Type'] = 'application/json' handler.response.out.write(response_data) return ServiceDecoratedView class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): self.ParseState(state) @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get(STATE_PARAMETER)) def ParseState(self, state): """Parse a state parameter and set internal values. Args: state: State parameter to parse. """ if state.startswith('{'): self.ParseJsonState(state) else: self.ParsePlainState(state) def ParseJsonState(self, state): """Parse a state parameter that is JSON. Args: state: State parameter to parse """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) def ParsePlainState(self, state): """Parse a state parameter that is a plain resource id or missing. Args: state: State parameter to parse """ if state: self.action = 'open' self.ids = [state] else: self.action = 'create' self.ids = [] class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] def RenderTemplate(name, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ return template.render(name, context)
Python
#!/usr/bin/python # # Copyright (C) 2012 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. __author__ = 'afshar@google.com (Ali Afshar)' # Add the library location to the path import sys sys.path.insert(0, 'lib') import os import httplib2 import sessions from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build from apiclient.http import MediaUpload from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.client import AccessTokenRefreshError from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') def SibPath(name): """Generate a path that is a sibling of this file. Args: name: Name of sibling file. Returns: Path to sibling file. """ return os.path.join(os.path.dirname(__file__), name) # Load the secret that is used for client side sessions # Create one of these for yourself with, for example: # python -c "import os; print os.urandom(64)" > session-secret SESSION_SECRET = open(SibPath('session.secret')).read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials. The CredentialsProperty is provided by the Google API Python Client, and is used by the Storage classes to store OAuth 2.0 credentials in the data store.""" credentials = CredentialsProperty() def CreateService(service, version, creds): """Create a Google API service. Load an API service from a discovery document and authorize it with the provided credentials. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). creds: Credentials used to authorize service. Returns: Authorized Google API service. """ # Instantiate an Http instance http = httplib2.Http() # Authorize the Http instance with the passed credentials creds.authorize(http) # Build a service from the passed discovery document path return build(service, version, http=http) class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ if state: state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) else: self.action = 'create' self.ids = [] @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get('state')) class BaseDriveHandler(webapp.RequestHandler): """Base request handler for drive applications. Adds Authorization support for Drive. """ def CreateOAuthFlow(self): """Create OAuth2.0 flow controller This controller can be used to perform all parts of the OAuth 2.0 dance including exchanging an Authorization code. Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = flow_from_clientsecrets('client.json', scope='') # Dynamically set the redirect_uri based on the request URL. This is extremely # convenient for debugging to an alternative host without manually setting the # redirect URI. flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0] return flow def GetCodeCredentials(self): """Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0. The authorization code is extracted form the URI parameters. If it is absent, None is returned immediately. Otherwise, if it is present, it is used to perform step 2 of the OAuth 2.0 web server flow. Once a token is received, the user information is fetched from the userinfo service and stored in the session. The token is saved in the datastore against the user ID received from the userinfo service. Args: request: HTTP request used for extracting an authorization code and the session information. Returns: OAuth2.0 credentials suitable for authorizing clients or None if Authorization could not take place. """ # Other frameworks use different API to get a query parameter. code = self.request.get('code') if not code: # returns None to indicate that no code was passed from Google Drive. return None # Auth flow is a controller that is loaded with the client information, # including client_id, client_secret, redirect_uri etc oauth_flow = self.CreateOAuthFlow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None # Create an API service that can use the userinfo API. Authorize it with our # credentials that we gained from the code exchange. users_service = CreateService('oauth2', 'v2', creds) # Make a call against the userinfo service to retrieve the user's information. # In this case we are interested in the user's "id" field. userid = users_service.userinfo().get().execute().get('id') # Store the user id in the user's cookie-based session. session = sessions.LilCookies(self, SESSION_SECRET) session.set_secure_cookie(name='userid', value=userid) # Store the credentials in the data store using the userid as the key. StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(self): """Get OAuth 2.0 credentials for an HTTP session. If the user has a user id stored in their cookie session, extract that value and use it to load that user's credentials from the data store. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ # Try to load the user id from the session session = sessions.LilCookies(self, SESSION_SECRET) userid = session.get_secure_cookie(name='userid') if not userid: # return None to indicate that no credentials could be loaded from the # session. return None # Load the credentials from the data store, using the userid as a key. creds = StorageByKeyName(Credentials, userid, 'credentials').get() # if the credentials are invalid, return None to indicate that the credentials # cannot be used. if creds and creds.invalid: return None return creds def RedirectAuth(self): """Redirect a handler to an authorization page. Used when a handler fails to fetch credentials suitable for making Drive API requests. The request is redirected to an OAuth 2.0 authorization approval page and on approval, are returned to application. Args: handler: webapp.RequestHandler to redirect. """ flow = self.CreateOAuthFlow() # Manually add the required scopes. Since this redirect does not originate # from the Google Drive UI, which authomatically sets the scopes that are # listed in the API Console. flow.scope = ALL_SCOPES # Create the redirect URI by performing step 1 of the OAuth 2.0 web server # flow. uri = flow.step1_get_authorize_url(flow.redirect_uri) # Perform the redirect. self.redirect(uri) class MainPage(BaseDriveHandler): """Web handler for the main page. Handles requests and returns the user interface for Open With and Create cases. Responsible for parsing the state provided from the Drive UI and acting appropriately. """ def get(self): """Handle GET for Create New and Open With. This creates an authorized client, and checks whether a resource id has been passed or not. If a resource ID has been passed, this is the Open With use-case, otherwise it is the Create New use-case. """ # Fetch the credentials by extracting an OAuth 2.0 authorization code from # the request URL. If the code is not present, redirect to the OAuth 2.0 # authorization URL. creds = self.GetCodeCredentials() if not creds: return self.RedirectAuth() # Extract the numerical portion of the client_id from the stored value in # the OAuth flow. You could also store this value as a separate variable # somewhere. client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0] # Generate a state instance for the request, this includes the action, and # the file id(s) that have been sent from the Drive user interface. drive_state = DriveState.FromRequest(self.request) if drive_state.action == 'open': file_ids = [str(i) for i in drive_state.ids] else: file_ids = [''] self.RenderTemplate(file_ids=file_ids, client_id=client_id) def RenderTemplate(self, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ self.response.headers['Content-Type'] = 'text/html' self.response.out.write(template.render('index.html', context)) class ServiceHandler(BaseDriveHandler): """Web handler for the service to read and write to Drive.""" def post(self): """Called when HTTP POST requests are received by the web application. The POST body is JSON which is deserialized and used as values to create a new file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() # Create a new file data structure. resource = { 'title': data['title'], 'description': data['description'], 'mimeType': data['mimeType'], } try: # Make an insert request to create a new file. A MediaInMemoryUpload # instance is used to upload the file body. resource = service.files().insert( body=resource, media_body=MediaInMemoryUpload(data.get('content', ''), data['mimeType']), ).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def get(self): """Called when HTTP GET requests are received by the web application. Use the query parameter file_id to fetch the required file's metadata then content and return it as a JSON object. Since DrEdit deals with text files, it is safe to dump the content directly into JSON, but this is not the case with binary files, where something like Base64 encoding is more appropriate. """ # Create a Drive service service = self.CreateDrive() if service is None: return try: # Requests are expected to pass the file_id query parameter. file_id = self.request.get('file_id') if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(id=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: resp, f['content'] = service._http.request(downloadUrl) else: f['content'] = '' else: f = None # Generate a JSON response with the file data and return to the client. self.RespondJSON(f) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() def put(self): """Called when HTTP PUT requests are received by the web application. The PUT body is JSON which is deserialized and used as values to update a file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() try: # Create a new file data structure. resource = { 'title': data['title'] or 'Untitled Document', 'description': data['description'], 'mimeType': data['mimeType'], } # Make an update request to update the file. A MediaInMemoryUpload # instance is used to upload the file body. Because of a limitation, this # request must be made in two parts, the first to update the metadata, and # the second to update the body. resource = service.files().update( id=data['resource_id'], newRevision=False, body=resource, media_body=None, ).execute() resource = service.files().update( id=data['resource_id'], newRevision=True, body=None, media_body=MediaInMemoryUpload(data.get('content', ''), data['mimeType']), ).execute() # Respond with the updated file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def CreateDrive(self): """Create a drive client instance. The service can only ever retrieve the credentials from the session. """ # For the service, the session holds the credentials creds = self.GetSessionCredentials() if creds: # If the session contains credentials, use them to create a Drive service # instance. return CreateService('drive', 'v1', creds) else: # If no credentials could be loaded from the session, redirect the user to # the authorization page. self.RedirectAuth() def RedirectAuth(self): """Redirect a handler to an authorization page. Used when a handler fails to fetch credentials suitable for making Drive API requests. The request is redirected to an OAuth 2.0 authorization approval page and on approval, are returned to application. Args: handler: webapp.RequestHandler to redirect. """ flow = self.CreateOAuthFlow() # Manually add the required scopes. Since this redirect does not originate # from the Google Drive UI, which authomatically sets the scopes that are # listed in the API Console. flow.scope = ALL_SCOPES # Create the redirect URI by performing step 1 of the OAuth 2.0 web server # flow. uri = flow.step1_get_authorize_url(flow.redirect_uri) # Perform the redirect. self.RespondJSON({'redirect': uri}) def RespondJSON(self, data): """Generate a JSON response and return it to the client. Args: data: The data that will be converted to JSON to return. """ self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(data)) def RequestJSON(self): """Load the request body as JSON. Returns: Request body loaded as JSON or None if there is no request body. """ if self.request.body: return json.loads(self.request.body) class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] # Create an WSGI application suitable for running on App Engine application = webapp.WSGIApplication( [('/', MainPage), ('/svc', ServiceHandler)], # XXX Set to False in production. debug=True ) def main(): """Main entry point for executing a request with this handler.""" run_wsgi_app(application) if __name__ == "__main__": main()
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&#904;' 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/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
# 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. """Utilities for Google App Engine Utilities for making it easier to use OAuth 2.0 on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import httplib2 import logging import pickle import time 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 import clientsecrets from client import AccessTokenRefreshError from client import AssertionCredentials from client import Credentials from client import Flow from client import OAuth2WebServerFlow from client import Storage from google.appengine.api import memcache from google.appengine.api import users from google.appengine.api.app_identity import app_identity from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp.util import login_required from google.appengine.ext.webapp.util import run_wsgi_app OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' class InvalidClientSecretsError(Exception): """The client_secrets.json file is malformed or missing required fields.""" pass class AppAssertionCredentials(AssertionCredentials): """Credentials object for App Engine Assertion Grants This object will allow an App Engine application to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the App Engine application itself. The algorithm used for generating the assertion is the Signed JSON Web Token (JWT) algorithm. Additional details can be found at the following link: http://self-issued.info/docs/draft-jones-json-web-token.html This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ def __init__(self, scope, audience='https://accounts.google.com/o/oauth2/token', assertion_type='http://oauth.net/grant_type/jwt/1.0/bearer', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for AppAssertionCredentials Args: scope: string, scope of the credentials being requested. audience: string, The audience, or verifier of the assertion. For convenience defaults to Google's audience. assertion_type: string, Type name that will identify the format of the assertion string. For convience, defaults to the JSON Web Token (JWT) assertion type string. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. """ self.scope = scope self.audience = audience self.app_name = app_identity.get_service_account_name() super(AppAssertionCredentials, self).__init__( assertion_type, None, token_uri) @classmethod def from_json(cls, json): data = simplejson.loads(json) retval = AccessTokenCredentials( data['scope'], data['audience'], data['assertion_type'], data['token_uri']) return retval def _generate_assertion(self): header = { 'typ': 'JWT', 'alg': 'RS256', } now = int(time.time()) claims = { 'aud': self.audience, 'scope': self.scope, 'iat': now, 'exp': now + 3600, 'iss': self.app_name, } jwt_components = [base64.b64encode(simplejson.dumps(seg)) for seg in [header, claims]] base_str = ".".join(jwt_components) key_name, signature = app_identity.sign_blob(base_str) jwt_components.append(base64.b64encode(signature)) return ".".join(jwt_components) class FlowProperty(db.Property): """App Engine datastore Property for Flow. Utility property that allows easy storage and retreival of an oauth2client.Flow""" # Tell what the user type is. data_type = Flow # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, Flow): raise db.BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowProperty, self).validate(value) def empty(self, value): return not value class CredentialsProperty(db.Property): """App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of oath2client.Credentials """ # Tell what the user type is. data_type = Credentials # For writing to datastore. def get_value_for_datastore(self, model_instance): logging.info("get: Got type " + str(type(model_instance))) cred = super(CredentialsProperty, self).get_value_for_datastore(model_instance) if cred is None: cred = '' else: cred = cred.to_json() return db.Blob(cred) # For reading from datastore. def make_value_from_datastore(self, value): logging.info("make: Got type " + str(type(value))) if value is None: return None if len(value) == 0: return None try: credentials = Credentials.new_from_json(value) except ValueError: credentials = None return credentials def validate(self, value): value = super(CredentialsProperty, self).validate(value) logging.info("validate: Got type " + str(type(value))) if value is not None and not isinstance(value, Credentials): raise db.BadValueError('Property %s must be convertible ' 'to a Credentials instance (%s)' % (self.name, value)) #if value is not None and not isinstance(value, Credentials): # return None return value class StorageByKeyName(Storage): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name, cache=None): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty cache: memcache, a write-through cache to put in front of the datastore """ self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ if self._cache: json = self._cache.get(self._key_name) if json: return Credentials.new_from_json(json) credential = None entity = self._model.get_by_key_name(self._key_name) if entity is not None: credential = getattr(entity, self._property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) if self._cache: self._cache.set(self._key_name, credentials.to_json()) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json()) class CredentialsModel(db.Model): """Storage for OAuth 2.0 Credentials Storage of the model is keyed by the user.user_id(). """ credentials = CredentialsProperty() class OAuth2Decorator(object): """Utility for making OAuth 2.0 easier. Instantiate and then use with oauth_required or oauth_aware as decorators on webapp.RequestHandler methods. Example: decorator = OAuth2Decorator( client_id='837...ent.com', client_secret='Qh...wwI', scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, client_id, client_secret, scope, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', message=None): """Constructor for OAuth2Decorator Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. message: Message to display if there are problems with the OAuth 2.0 configuration. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. """ self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, None, auth_uri, token_uri) self.credentials = None self._request_handler = None self._message = message self._in_error = False def _display_error_message(self, request_handler): request_handler.response.out.write('<html><body>') request_handler.response.out.write(self._message) request_handler.response.out.write('</body></html>') def oauth_required(self, method): """Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def check_oauth(request_handler, *args): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return # Store the request URI in 'state' so we can use it later self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: method(request_handler, *args) except AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) return check_oauth def oauth_aware(self, method): """Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def setup_oauth(request_handler, *args): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() method(request_handler, *args) return setup_oauth def has_credentials(self): """True if for the logged in user there are valid access Credentials. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ return self.credentials is not None and not self.credentials.invalid def authorize_url(self): """Returns the URL to start the OAuth dance. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ callback = self._request_handler.request.relative_url('/oauth2callback') url = self.flow.step1_get_authorize_url(callback) user = users.get_current_user() memcache.set(user.user_id(), pickle.dumps(self.flow), namespace=OAUTH2CLIENT_NAMESPACE) return url def http(self): """Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. """ return self.credentials.authorize(httplib2.Http()) class OAuth2DecoratorFromClientSecrets(OAuth2Decorator): """An OAuth2Decorator that builds from a clientsecrets file. Uses a clientsecrets file as the source for all the information when constructing an OAuth2Decorator. Example: decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json') scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, filename, scope, message=None): """Constructor Args: filename: string, File name of client secrets. scope: string, Space separated list of scopes. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.') super(OAuth2DecoratorFromClientSecrets, self).__init__( client_info['client_id'], client_info['client_secret'], scope, client_info['auth_uri'], client_info['token_uri'], message) except clientsecrets.InvalidClientSecretsError: self._in_error = True if message is not None: self._message = message else: self._message = "Please configure your application for OAuth 2.0" def oauth2decorator_from_clientsecrets(filename, scope, message=None): """Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string, Space separated list of scopes. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. Returns: An OAuth2Decorator """ return OAuth2DecoratorFromClientSecrets(filename, scope, message) class OAuth2Handler(webapp.RequestHandler): """Handler for the redirect_uri of the OAuth 2.0 dance.""" @login_required def get(self): error = self.request.get('error') if error: errormsg = self.request.get('error_description', error) self.response.out.write( 'The authorization request failed: %s' % errormsg) else: user = users.get_current_user() flow = pickle.loads(memcache.get(user.user_id(), namespace=OAUTH2CLIENT_NAMESPACE)) # This code should be ammended with application specific error # handling. The following cases should be considered: # 1. What if the flow doesn't exist in memcache? Or is corrupt? # 2. What if the step2_exchange fails? if flow: credentials = flow.step2_exchange(self.request.params) StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').put(credentials) self.redirect(str(self.request.get('state'))) else: # TODO Add error handling here. pass application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler)]) def main(): run_wsgi_app(application)
Python
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright (C) 2011 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. import base64 import hashlib import logging import time from OpenSSL import crypto 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 CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds class AppIdentityError(Exception): pass class Verifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey, OpenSSL.crypto.PKey, The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string, The message to verify. signature: string, The signature on the message. Returns: True if message was singed by the private key associated with the public key that this object was constructed with. """ try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except: return False @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return Verifier(pubkey) class Signer(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey, The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return crypto.sign(self._key, message, 'sha256') @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in P12 format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ pkey = crypto.load_pkcs12(key, password).get_privatekey() return Signer(pkey) def _urlsafe_b64encode(raw_bytes): return base64.urlsafe_b64encode(raw_bytes).rstrip('=') def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _json_encode(data): return simplejson.dumps(data, separators = (',', ':')) def make_signed_jwt(signer, payload): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} segments = [ _urlsafe_b64encode(_json_encode(header)), _urlsafe_b64encode(_json_encode(payload)), ] signing_input = '.'.join(segments) signature = signer.sign(signing_input) segments.append(_urlsafe_b64encode(signature)) logging.debug(str(segments)) return '.'.join(segments) def verify_signed_jwt_with_certs(jwt, certs, audience): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError if any checks are failed. """ segments = jwt.split('.') if (len(segments) != 3): raise AppIdentityError( 'Wrong number of segments in token: %s' % jwt) signed = '%s.%s' % (segments[0], segments[1]) signature = _urlsafe_b64decode(segments[2]) # Parse token. json_body = _urlsafe_b64decode(segments[1]) try: parsed = simplejson.loads(json_body) except: raise AppIdentityError('Can\'t parse token: %s' % json_body) # Check signature. verified = False for (keyname, pem) in certs.items(): verifier = Verifier.from_string(pem, True) if (verifier.verify(signed, signature)): verified = True break if not verified: raise AppIdentityError('Invalid token signature: %s' % jwt) # Check creation timestamp. iat = parsed.get('iat') if iat is None: raise AppIdentityError('No iat field in token: %s' % json_body) earliest = iat - CLOCK_SKEW_SECS # Check expiration timestamp. now = long(time.time()) exp = parsed.get('exp') if exp is None: raise AppIdentityError('No exp field in token: %s' % json_body) if exp >= now + MAX_TOKEN_LIFETIME_SECS: raise AppIdentityError( 'exp field too far in future: %s' % json_body) latest = exp + CLOCK_SKEW_SECS if now < earliest: raise AppIdentityError('Token used too early, %d < %d: %s' % (now, earliest, json_body)) if now > latest: raise AppIdentityError('Token used too late, %d > %d: %s' % (now, latest, json_body)) # Check audience. if audience is not None: aud = parsed.get('aud') if aud is None: raise AppIdentityError('No aud field in token: %s' % json_body) if aud != audience: raise AppIdentityError('Wrong recipient, %s != %s: %s' % (aud, audience, json_body)) return parsed
Python
# Copyright 2011 Google Inc. All Rights Reserved. """Multi-credential file store with lock support. This module implements a JSON credential store where multiple credentials can be stored in one file. That file supports locking both in a single process and across processes. The credential themselves are keyed off of: * client_id * user_agent * scope The format of the stored data is like so: { 'file_version': 1, 'data': [ { 'key': { 'clientId': '<client id>', 'userAgent': '<user agent>', 'scope': '<scope>' }, 'credential': { # JSON serialized Credentials. } } ] } """ __author__ = 'jbeda@google.com (Joe Beda)' import base64 import fcntl import logging import os import threading 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 from client import Storage as BaseStorage from client import Credentials logger = logging.getLogger(__name__) # A dict from 'filename'->_MultiStore instances _multistores = {} _multistores_lock = threading.Lock() class Error(Exception): """Base error for this module.""" pass class NewerCredentialStoreError(Error): """The credential store is a newer version that supported.""" pass def get_credential_storage(filename, client_id, user_agent, scope, warn_on_readonly=True): """Get a Storage instance for a credential. Args: filename: The JSON file storing a set of credentials client_id: The client_id for the credential user_agent: The user agent for the credential scope: string or list of strings, Scope(s) being requested warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ filename = os.path.realpath(os.path.expanduser(filename)) _multistores_lock.acquire() try: multistore = _multistores.setdefault( filename, _MultiStore(filename, warn_on_readonly)) finally: _multistores_lock.release() if type(scope) is list: scope = ' '.join(scope) return multistore._get_storage(client_id, user_agent, scope) class _MultiStore(object): """A file backed store for multiple credentials.""" def __init__(self, filename, warn_on_readonly=True): """Initialize the class. This will create the file if necessary. """ self._filename = filename self._thread_lock = threading.Lock() self._file_handle = None self._read_only = False self._warn_on_readonly = warn_on_readonly self._create_file_if_needed() # Cache of deserialized store. This is only valid after the # _MultiStore is locked or _refresh_data_cache is called. This is # of the form of: # # (client_id, user_agent, scope) -> OAuth2Credential # # If this is None, then the store hasn't been read yet. self._data = None class _Storage(BaseStorage): """A Storage object that knows how to read/write a single credential.""" def __init__(self, multistore, client_id, user_agent, scope): self._multistore = multistore self._client_id = client_id self._user_agent = user_agent self._scope = scope def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ self._multistore._lock() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._multistore._unlock() def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ credential = self._multistore._get_credential( self._client_id, self._user_agent, self._scope) if credential: credential.set_store(self) return credential def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._update_credential(credentials, self._scope) def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._filename): old_umask = os.umask(0177) try: open(self._filename, 'a+').close() finally: os.umask(old_umask) def _lock(self): """Lock the entire multistore.""" self._thread_lock.acquire() # Check to see if the file is writeable. if os.access(self._filename, os.W_OK): self._file_handle = open(self._filename, 'r+') fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_EX) else: # Cannot open in read/write mode. Open only in read mode. self._file_handle = open(self._filename, 'r') self._read_only = True if self._warn_on_readonly: logger.warn('The credentials file (%s) is not writable. Opening in ' 'read-only mode. Any refreshed credentials will only be ' 'valid for this run.' % self._filename) if os.path.getsize(self._filename) == 0: logger.debug('Initializing empty multistore file') # The multistore is empty so write out an empty file. self._data = {} self._write() elif not self._read_only or self._data is None: # Only refresh the data if we are read/write or we haven't # cached the data yet. If we are readonly, we assume is isn't # changing out from under us and that we only have to read it # once. This prevents us from whacking any new access keys that # we have cached in memory but were unable to write out. self._refresh_data_cache() def _unlock(self): """Release the lock on the multistore.""" if not self._read_only: fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_UN) self._file_handle.close() self._thread_lock.release() def _locked_json_read(self): """Get the raw content of the multistore file. The multistore must be locked when this is called. Returns: The contents of the multistore decoded as JSON. """ assert self._thread_lock.locked() self._file_handle.seek(0) return simplejson.load(self._file_handle) def _locked_json_write(self, data): """Write a JSON serializable data structure to the multistore. The multistore must be locked when this is called. Args: data: The data to be serialized and written. """ assert self._thread_lock.locked() if self._read_only: return self._file_handle.seek(0) simplejson.dump(data, self._file_handle, sort_keys=True, indent=2) self._file_handle.truncate() def _refresh_data_cache(self): """Refresh the contents of the multistore. The multistore must be locked when this is called. Raises: NewerCredentialStoreError: Raised when a newer client has written the store. """ self._data = {} try: raw_data = self._locked_json_read() except Exception: logger.warn('Credential data store could not be loaded. ' 'Will ignore and overwrite.') return version = 0 try: version = raw_data['file_version'] except Exception: logger.warn('Missing version for credential data store. It may be ' 'corrupt or an old version. Overwriting.') if version > 1: raise NewerCredentialStoreError( 'Credential file has file_version of %d. ' 'Only file_version of 1 is supported.' % version) credentials = [] try: credentials = raw_data['data'] except (TypeError, KeyError): pass for cred_entry in credentials: try: (key, credential) = self._decode_credential_from_json(cred_entry) self._data[key] = credential except: # If something goes wrong loading a credential, just ignore it logger.info('Error decoding credential, skipping', exc_info=True) def _decode_credential_from_json(self, cred_entry): """Load a credential from our JSON serialization. Args: cred_entry: A dict entry from the data member of our format Returns: (key, cred) where the key is the key tuple and the cred is the OAuth2Credential object. """ raw_key = cred_entry['key'] client_id = raw_key['clientId'] user_agent = raw_key['userAgent'] scope = raw_key['scope'] key = (client_id, user_agent, scope) credential = None credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential'])) return (key, credential) def _write(self): """Write the cached data back out. The multistore must be locked. """ raw_data = {'file_version': 1} raw_creds = [] raw_data['data'] = raw_creds for (cred_key, cred) in self._data.items(): raw_key = { 'clientId': cred_key[0], 'userAgent': cred_key[1], 'scope': cred_key[2] } raw_cred = simplejson.loads(cred.to_json()) raw_creds.append({'key': raw_key, 'credential': raw_cred}) self._locked_json_write(raw_data) def _get_credential(self, client_id, user_agent, scope): """Get a credential from the multistore. The multistore must be locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: The credential specified or None if not present """ key = (client_id, user_agent, scope) return self._data.get(key, None) def _update_credential(self, cred, scope): """Update a credential and write the multistore. This must be called when the multistore is locked. Args: cred: The OAuth2Credential to update/set scope: The scope(s) that this credential covers """ key = (cred.client_id, cred.user_agent, scope) self._data[key] = cred self._write() def _get_storage(self, client_id, user_agent, scope): """Get a Storage object to get/set a credential. This Storage is a 'view' into the multistore. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: A Storage object that can be used to get/set this cred """ return self._Storage(self, client_id, user_agent, scope)
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. """Command-line tools for authenticating via OAuth 2.0 Do the OAuth 2.0 Web Server 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 socket import sys from client import FlowExchangeError 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 2.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 2.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 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. Returns: Credentials, the obtained credential. """ if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = ClientRedirectServer((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 ' print '--noauth_local_webserver.' print code = None if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print 'Failed to find "code" in the query parameters of the redirect.' sys.exit('Try running with --noauth_local_webserver.') else: code = raw_input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code) except FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print 'Authentication successful.' return credential
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. """An OAuth 2.0 client. Tools for interacting with OAuth 2.0 protected resources. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import clientsecrets import copy import datetime import httplib2 import logging import os import sys import time import urllib import urlparse HAS_OPENSSL = False try: from oauth2client.crypt import Signer from oauth2client.crypt import make_signed_jwt from oauth2client.crypt import verify_signed_jwt_with_certs HAS_OPENSSL = True except ImportError: pass 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 try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl # Determine if we can write to the file system, and if we can use a local file # cache behing httplib2. if hasattr(os, 'tempnam'): # Put cache file in the director '.cache'. CACHED_HTTP = httplib2.Http('.cache') else: CACHED_HTTP = httplib2.Http() logger = logging.getLogger(__name__) # Expiry is stored in RFC3339 UTC format EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # Which certs to use to validate id_tokens received. ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs' class Error(Exception): """Base error for this module.""" pass class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" pass class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token.""" pass class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow. """ pass class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" pass class VerifyJwtTokenError(Error): """Could on retrieve certificates for validation.""" pass def _abstract(): raise NotImplementedError('You need to override this function') class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instaniated Crentials object. """ NON_SERIALIZED_MEMBERS = ['store'] def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() def _to_json(self, strip): """Utility function for creating a JSON representation of an instance of Credentials. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) for member in strip: del d[member] if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) # Add in information we will need later to reconsistitue this instance. d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def new_from_json(cls, s): """Utility class method to instantiate a Credentials subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of Credentials that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" pass def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ pass def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ _abstract() def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ _abstract() def get(self): """Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials """ self.acquire_lock() try: return self.locked_get() finally: self.release_lock() def put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock() class OAuth2Credentials(Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, id_token=None): """Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. id_token: object, The identity of the resource owner. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed. """ self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token self.store = None self.token_expiry = token_expiry self.token_uri = token_uri self.user_agent = user_agent self.id_token = id_token # True if the credentials have been revoked or expired and can't be # refreshed. self.invalid = False def to_json(self): return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ data = simplejson.loads(s) if 'token_expiry' in data and not isinstance(data['token_expiry'], datetime.datetime): try: data['token_expiry'] = datetime.datetime.strptime( data['token_expiry'], EXPIRY_FORMAT) except: data['token_expiry'] = None retval = OAuth2Credentials( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], data.get('id_token', None)) retval.invalid = data['invalid'] return retval @property def access_token_expired(self): """True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire. """ if self.invalid: return True if not self.token_expiry: return False now = datetime.datetime.utcnow() if now >= self.token_expiry: logger.info('access_token is expired. Now: %s, token_expiry: %s', now, self.token_expiry) return True return False def set_store(self, store): """Set the Storage for the credential. Args: store: Storage, an implementation of Stroage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token. """ self.store = store def _updateFromCredential(self, other): """Update this Credential from another instance.""" self.__dict__.update(other.__getstate__()) def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def _generate_refresh_request_body(self): """Generate the body that will be used in the refresh request.""" body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, }) return body def _generate_refresh_request_headers(self): """Generate the headers that will be used in the refresh request.""" headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent return headers def _refresh(self, http_request): """Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. """ if not self.store: self._do_refresh_request(http_request) else: self.store.acquire_lock() try: new_cred = self.store.locked_get() if (new_cred and not new_cred.invalid and new_cred.access_token != self.access_token): logger.info('Updated access_token read from Storage') self._updateFromCredential(new_cred) else: self._do_refresh_request(http_request) finally: self.store.release_lock() def _do_refresh_request(self, http_request): """Refresh the access_token using the refresh_token. Args: http: An instance of httplib2.Http.request or something that acts like it. Raises: AccessTokenRefreshError: When the refresh fails. """ body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refresing access_token') resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if loads fails? d = simplejson.loads(content) self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: self.token_expiry = datetime.timedelta( seconds=int(d['expires_in'])) + datetime.datetime.utcnow() else: self.token_expiry = None if self.store: self.store.locked_put(self) else: # An {'error':...} response body means the token is expired or revoked, # so we flag the credentials as such. logger.error('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] self.invalid = True if self.store: self.store.locked_put(self) except: pass raise AccessTokenRefreshError(error_msg) def authorize(self, http): """Authorize an httplib2.Http instance with these credentials. Args: http: An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not self.access_token: logger.info('Attempting refresh to obtain initial access_token') self._refresh(request_orig) # Modify the request headers to add the appropriate # Authorization header. if headers is None: headers = {} headers['authorization'] = 'OAuth ' + self.access_token if self.user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent import logging logging.info(str(uri)) logging.info(str(headers)) resp, content = request_orig(uri, method, body, headers, redirections, connection_type) if resp.status == 401: logger.info('Refreshing due to a 401') self._refresh(request_orig) headers['authorization'] = 'OAuth ' + self.access_token return request_orig(uri, method, body, headers, redirections, connection_type) else: return (resp, content) http.request = new_request return http class AccessTokenCredentials(OAuth2Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from another place such as a JavaScript client or another web application, and wish to use it from Python. Because only the access_token is present it can not be refreshed and will in time expire. AccessTokenCredentials objects may be safely pickled and unpickled. Usage: credentials = AccessTokenCredentials('<an access token>', 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) Exceptions: AccessTokenCredentialsExpired: raised when the access_token expires or is revoked. """ def __init__(self, access_token, user_agent): """Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. Notes: store: callable, a callable that when passed a Credential will store the credential back to where it came from. """ super(AccessTokenCredentials, self).__init__( access_token, None, None, None, None, None, user_agent) @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = AccessTokenCredentials( data['access_token'], data['user_agent']) return retval def _refresh(self, http_request): raise AccessTokenCredentialsError( "The access_token is expired or invalid and can't be refreshed.") class AssertionCredentials(OAuth2Credentials): """Abstract Credentials object used for OAuth 2.0 assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. It must be subclassed to generate the appropriate assertion string. AssertionCredentials objects may be safely pickled and unpickled. """ def __init__(self, assertion_type, user_agent, token_uri='https://accounts.google.com/o/oauth2/token', **unused_kwargs): """Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. """ super(AssertionCredentials, self).__init__( None, None, None, None, None, token_uri, user_agent) self.assertion_type = assertion_type def _generate_refresh_request_body(self): assertion = self._generate_assertion() body = urllib.urlencode({ 'assertion_type': self.assertion_type, 'assertion': assertion, 'grant_type': 'assertion', }) return body def _generate_assertion(self): """Generate the assertion string that will be used in the access token request. """ _abstract() if HAS_OPENSSL: # PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then # don't create the SignedJwtAssertionCredentials or the verify_id_token() # method. class SignedJwtAssertionCredentials(AssertionCredentials): """Credentials object used for OAuth 2.0 Signed JWT assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds def __init__(self, service_account_name, private_key, scope, private_key_password='notasecret', user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for SignedJwtAssertionCredentials. Args: service_account_name: string, id for account, usually an email address. private_key: string, private key in P12 format. scope: string or list of strings, scope(s) of the credentials being requested. private_key_password: string, password for private_key. user_agent: string, HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. kwargs: kwargs, Additional parameters to add to the JWT token, for example prn=joe@xample.org.""" super(SignedJwtAssertionCredentials, self).__init__( 'http://oauth.net/grant_type/jwt/1.0/bearer', user_agent, token_uri=token_uri, ) if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.private_key = private_key self.private_key_password = private_key_password self.service_account_name = service_account_name self.kwargs = kwargs @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = SignedJwtAssertionCredentials( data['service_account_name'], data['private_key'], data['private_key_password'], data['scope'], data['user_agent'], data['token_uri'], data['kwargs'] ) retval.invalid = data['invalid'] return retval def _generate_assertion(self): """Generate the assertion that will be used in the request.""" now = long(time.time()) payload = { 'aud': self.token_uri, 'scope': self.scope, 'iat': now, 'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_name } payload.update(self.kwargs) logging.debug(str(payload)) return make_signed_jwt( Signer.from_string(self.private_key, self.private_key_password), payload) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS): """Verifies a signed JWT id_token. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP request. Callers should supply an instance that has caching enabled. cert_uri: string, URI of the certificates in JSON format to verify the JWT against. Returns: The deserialized JSON in the JWT. Raises: oauth2client.crypt.AppIdentityError if the JWT fails to verify. """ if http is None: http = CACHED_HTTP resp, content = http.request(cert_uri) if resp.status == 200: certs = simplejson.loads(content) return verify_signed_jwt_with_certs(id_token, certs, audience) else: raise VerifyJwtTokenError('Status code: %d' % resp.status) def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ segments = id_token.split('.') if (len(segments) != 3): raise VerifyJwtTokenError( 'Wrong number of segments in token: %s' % id_token) return simplejson.loads(_urlsafe_b64decode(segments[1])) class OAuth2WebServerFlow(Flow): """Does the Web Server Flow for OAuth 2.0. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, client_id, client_secret, scope, user_agent=None, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for OAuth2WebServerFlow. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls. """ self.client_id = client_id self.client_secret = client_secret if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.params = { 'access_type': 'offline', } self.params.update(kwargs) self.redirect_uri = None def step1_get_authorize_url(self, redirect_uri='oob'): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If redirect_uri is 'oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ self.redirect_uri = redirect_uri query = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope, } query.update(self.params) parts = list(urlparse.urlparse(self.auth_uri)) query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part parts[4] = urllib.urlencode(query) return urlparse.urlunparse(parts) def step2_exchange(self, code, http=None): """Exhanges a code for OAuth2Credentials. Args: code: string or dict, either the code as a string, or a dictionary of the query parameters to the redirect_uri, which contains the code. http: httplib2.Http, optional http instance to use to do the fetch """ if not (isinstance(code, str) or isinstance(code, unicode)): code = code['code'] body = urllib.urlencode({ 'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': self.redirect_uri, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = httplib2.Http() resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if simplejson.loads fails? d = simplejson.loads(content) access_token = d['access_token'] refresh_token = d.get('refresh_token', None) token_expiry = None if 'expires_in' in d: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(d['expires_in'])) if 'id_token' in d: d['id_token'] = _extract_id_token(d['id_token']) logger.info('Successfully retrieved access token: %s' % content) return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, id_token=d.get('id_token', None)) else: logger.error('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] except: pass raise FlowExchangeError(error_msg) def flow_from_clientsecrets(filename, scope, message=None): """Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) to request. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. Returns: A Flow object. Raises: UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: return OAuth2WebServerFlow( client_info['client_id'], client_info['client_secret'], scope, None, # user_agent client_info['auth_uri'], client_info['token_uri']) except clientsecrets.InvalidClientSecretsError: if message: sys.exit(message) else: raise else: raise UnknownClientSecretsFlowError( 'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
Python
# Copyright (C) 2011 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. """Utilities for reading OAuth 2.0 client secret files. A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service. """ __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 # Properties that make a client_secrets.json file valid. TYPE_WEB = 'web' TYPE_INSTALLED = 'installed' VALID_CLIENT = { TYPE_WEB: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] }, TYPE_INSTALLED: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] } } class Error(Exception): """Base error for this module.""" pass class InvalidClientSecretsError(Error): """Format of ClientSecrets file is invalid.""" pass def _validate_clientsecrets(obj): if obj is None or len(obj) != 1: raise InvalidClientSecretsError('Invalid file format.') client_type = obj.keys()[0] if client_type not in VALID_CLIENT.keys(): raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) client_info = obj[client_type] for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "%s" in a client type of "%s".' % (prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "%s" is not configured.' % prop_name) return client_type, client_info def load(fp): obj = simplejson.load(fp) return _validate_clientsecrets(obj) def loads(s): obj = simplejson.loads(s) return _validate_clientsecrets(obj) def loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except IOError: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj)
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. """Utilities for OAuth. Utilities for making it easier to work with OAuth 2.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import threading 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 from client import Storage as BaseStorage from client import Credentials class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" self._lock.acquire() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._lock.release() def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None try: f = open(self._filename, 'r') content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ f = open(self._filename, 'w') f.write(credentials.to_json()) f.close()
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. """OAuth 2.0 utilities for Django. Utilities for using OAuth 2.0 in conjunction with the Django datastore. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import oauth2client import base64 import pickle from django.db import models from oauth2client.client import Storage as BaseStorage class CredentialsField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None if isinstance(value, oauth2client.client.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): return base64.b64encode(pickle.dumps(value)) class FlowField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Flow): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): return base64.b64encode(pickle.dumps(value)) class Storage(BaseStorage): """Store and retrieve a single credential to and from the datastore. This Storage helper presumes the Credentials have been stored as a CredenialsField on a db model class. """ def __init__(self, model_class, key_name, key_value, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials key_value: string, key value for the entity that has the credentials property_name: string, name of the property that is an CredentialsProperty """ self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credential = None query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if len(entities) > 0: credential = getattr(entities[0], self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ args = {self.key_name: self.key_value} entity = self.model_class(**args) setattr(entity, self.property_name, credentials) entity.save()
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. """Classes to encapsulate a single HTTP request. The classes implement a command pattern, with every object supporting an execute() method that does the actuall HTTP request. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = [ 'HttpRequest', 'RequestMockBuilder', 'HttpMock' 'set_user_agent', 'tunnel_patch' ] import StringIO import copy import gzip import httplib2 import mimeparse import mimetypes import os import urllib import urlparse import uuid from anyjson import simplejson from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart from email.parser import FeedParser from errors import BatchError from errors import HttpError from errors import ResumableUploadError from errors import UnexpectedBodyError from errors import UnexpectedMethodError from model import JsonModel class MediaUploadProgress(object): """Status of a resumable upload.""" def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes sent so far. total_size: int, total bytes in complete upload. """ self.resumable_progress = resumable_progress self.total_size = total_size def progress(self): """Percent of upload completed, as a float.""" return float(self.resumable_progress) / float(self.total_size) class MediaUpload(object): """Describes a media object to upload. Base class that defines the interface of MediaUpload subclasses. """ def getbytes(self, begin, end): raise NotImplementedError() def size(self): raise NotImplementedError() def chunksize(self): raise NotImplementedError() def mimetype(self): return 'application/octet-stream' def resumable(self): return False def _to_json(self, strip=None): """Utility function for creating a JSON representation of a MediaUpload. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) if strip is not None: for member in strip: del d[member] d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Create a JSON representation of an instance of MediaUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json() @classmethod def new_from_json(cls, s): """Utility class method to instantiate a MediaUpload subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of MediaUpload that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) class MediaFileUpload(MediaUpload): """A MediaUpload for a file. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed uploading images: media = MediaFileUpload('smiley.png', mimetype='image/png', chunksize=1000, resumable=True) service.objects().insert( bucket=buckets['items'][0]['id'], name='smiley.png', media_body=media).execute() """ def __init__(self, filename, mimetype=None, chunksize=10000, resumable=False): """Constructor. Args: filename: string, Name of the file. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._filename = filename self._size = os.path.getsize(filename) self._fd = None if mimetype is None: (mimetype, encoding) = mimetypes.guess_type(filename) self._mimetype = mimetype self._chunksize = chunksize self._resumable = resumable def mimetype(self): return self._mimetype def size(self): return self._size def chunksize(self): return self._chunksize def resumable(self): return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorted than length if EOF was reached first. """ if self._fd is None: self._fd = open(self._filename, 'rb') self._fd.seek(begin) return self._fd.read(length) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(['_fd']) @staticmethod def from_json(s): d = simplejson.loads(s) return MediaFileUpload( d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable']) class HttpRequest(object): """Encapsulates a single HTTP request.""" def __init__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """Constructor for an HttpRequest. Args: http: httplib2.Http, the transport object to use to make a request postproc: callable, called on the HTTP response and content to transform it into a data object before returning, or raising an exception on an error. uri: string, the absolute URI to send the request to method: string, the HTTP method to use body: string, the request body of the HTTP request, headers: dict, the HTTP request headers methodId: string, a unique identifier for the API method being called. resumable: MediaUpload, None if this is not a resumbale request. """ self.uri = uri self.method = method self.body = body self.headers = headers or {} self.methodId = methodId self.http = http self.postproc = postproc self.resumable = resumable # Pull the multipart boundary out of the content-type header. major, minor, params = mimeparse.parse_mime_type( headers.get('content-type', 'application/json')) # Terminating multipart boundary get a trailing '--' appended. self.multipart_boundary = params.get('boundary', '').strip('"') + '--' # If this was a multipart resumable, the size of the non-media part. self.multipart_size = 0 # The resumable URI to send chunks to. self.resumable_uri = None # The bytes that have been uploaded. self.resumable_progress = 0 self.total_size = 0 if resumable is not None: if self.body is not None: self.multipart_size = len(self.body) else: self.multipart_size = 0 self.total_size = ( self.resumable.size() + self.multipart_size + len(self.multipart_boundary)) def execute(self, http=None): """Execute the request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. Returns: A deserialized object model of the response body as determined by the postproc. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if a transport error has occured. """ if http is None: http = self.http if self.resumable: body = None while body is None: _, body = self.next_chunk(http) return body else: resp, content = http.request(self.uri, self.method, body=self.body, headers=self.headers) if resp.status >= 300: raise HttpError(resp, content, self.uri) return self.postproc(resp, content) def next_chunk(self, http=None): """Execute the next step of a resumable upload. Can only be used if the method being executed supports media uploads and the MediaUpload object passed in was flagged as using resumable upload. Example: media = MediaFileUpload('smiley.png', mimetype='image/png', chunksize=1000, resumable=True) request = service.objects().insert( bucket=buckets['items'][0]['id'], name='smiley.png', media_body=media) response = None while response is None: status, response = request.next_chunk() if status: print "Upload %d%% complete." % int(status.progress() * 100) Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. """ if http is None: http = self.http if self.resumable_uri is None: start_headers = copy.copy(self.headers) start_headers['X-Upload-Content-Type'] = self.resumable.mimetype() start_headers['X-Upload-Content-Length'] = str(self.resumable.size()) start_headers['Content-Length'] = '0' resp, content = http.request(self.uri, self.method, body="", headers=start_headers) if resp.status == 200 and 'location' in resp: self.resumable_uri = resp['location'] else: raise ResumableUploadError("Failed to retrieve starting URI.") if self.body: begin = 0 data = self.body else: begin = self.resumable_progress - self.multipart_size data = self.resumable.getbytes(begin, self.resumable.chunksize()) # Tack on the multipart/related boundary if we are at the end of the file. if begin + self.resumable.chunksize() >= self.resumable.size(): data += self.multipart_boundary headers = { 'Content-Range': 'bytes %d-%d/%d' % ( self.resumable_progress, self.resumable_progress + len(data) - 1, self.total_size), } resp, content = http.request(self.resumable_uri, 'PUT', body=data, headers=headers) if resp.status in [200, 201]: return None, self.postproc(resp, content) elif resp.status == 308: # A "308 Resume Incomplete" indicates we are not done. self.resumable_progress = int(resp['range'].split('-')[1]) + 1 if self.resumable_progress >= self.multipart_size: self.body = None if 'location' in resp: self.resumable_uri = resp['location'] else: raise HttpError(resp, content, self.uri) return MediaUploadProgress(self.resumable_progress, self.total_size), None def to_json(self): """Returns a JSON representation of the HttpRequest.""" d = copy.copy(self.__dict__) if d['resumable'] is not None: d['resumable'] = self.resumable.to_json() del d['http'] del d['postproc'] return simplejson.dumps(d) @staticmethod def from_json(s, http, postproc): """Returns an HttpRequest populated with info from a JSON object.""" d = simplejson.loads(s) if d['resumable'] is not None: d['resumable'] = MediaUpload.new_from_json(d['resumable']) return HttpRequest( http, postproc, uri=d['uri'], method=d['method'], body=d['body'], headers=d['headers'], methodId=d['methodId'], resumable=d['resumable']) class BatchHttpRequest(object): """Batches multiple HttpRequest objects into a single HTTP request.""" def __init__(self, callback=None, batch_uri=None): """Constructor for a BatchHttpRequest. Args: callback: callable, A callback to be called for each response, of the form callback(id, response). The first parameter is the request id, and the second is the deserialized response object. batch_uri: string, URI to send batch requests to. """ if batch_uri is None: batch_uri = 'https://www.googleapis.com/batch' self._batch_uri = batch_uri # Global callback to be called for each individual response in the batch. self._callback = callback # A map from id to (request, callback) pairs. self._requests = {} # List of request ids, in the order in which they were added. self._order = [] # The last auto generated id. self._last_auto_id = 0 # Unique ID on which to base the Content-ID headers. self._base_id = None def _id_to_header(self, id_): """Convert an id to a Content-ID header value. Args: id_: string, identifier of individual request. Returns: A Content-ID header with the id_ encoded into it. A UUID is prepended to the value because Content-ID headers are supposed to be universally unique. """ if self._base_id is None: self._base_id = uuid.uuid4() return '<%s+%s>' % (self._base_id, urllib.quote(id_)) def _header_to_id(self, header): """Convert a Content-ID header value to an id. Presumes the Content-ID header conforms to the format that _id_to_header() returns. Args: header: string, Content-ID header value. Returns: The extracted id value. Raises: BatchError if the header is not in the expected format. """ if header[0] != '<' or header[-1] != '>': raise BatchError("Invalid value for Content-ID: %s" % header) if '+' not in header: raise BatchError("Invalid value for Content-ID: %s" % header) base, id_ = header[1:-1].rsplit('+', 1) return urllib.unquote(id_) def _serialize_request(self, request): """Convert an HttpRequest object into a string. Args: request: HttpRequest, the request to serialize. Returns: The request as a string in application/http format. """ # Construct status line parsed = urlparse.urlparse(request.uri) request_line = urlparse.urlunparse( (None, None, parsed.path, parsed.params, parsed.query, None) ) status_line = request.method + ' ' + request_line + ' HTTP/1.1\n' major, minor = request.headers.get('content-type', 'text/plain').split('/') msg = MIMENonMultipart(major, minor) headers = request.headers.copy() # MIMENonMultipart adds its own Content-Type header. if 'content-type' in headers: del headers['content-type'] for key, value in headers.iteritems(): msg[key] = value msg['Host'] = parsed.netloc msg.set_unixfrom(None) if request.body is not None: msg.set_payload(request.body) body = msg.as_string(False) # Strip off the \n\n that the MIME lib tacks onto the end of the payload. if request.body is None: body = body[:-2] return status_line + body def _deserialize_response(self, payload): """Convert string into httplib2 response and content. Args: payload: string, headers and body as a string. Returns: A pair (resp, content) like would be returned from httplib2.request. """ # Strip off the status line status_line, payload = payload.split('\n', 1) protocol, status, reason = status_line.split(' ') # Parse the rest of the response parser = FeedParser() parser.feed(payload) msg = parser.close() msg['status'] = status # Create httplib2.Response from the parsed headers. resp = httplib2.Response(msg) resp.reason = reason resp.version = int(protocol.split('/', 1)[1].replace('.', '')) content = payload.split('\r\n\r\n', 1)[1] return resp, content def _new_id(self): """Create a new id. Auto incrementing number that avoids conflicts with ids already used. Returns: string, a new unique id. """ self._last_auto_id += 1 while str(self._last_auto_id) in self._requests: self._last_auto_id += 1 return str(self._last_auto_id) def add(self, request, callback=None, request_id=None): """Add a new request. Every callback added will be paired with a unique id, the request_id. That unique id will be passed back to the callback when the response comes back from the server. The default behavior is to have the library generate it's own unique id. If the caller passes in a request_id then they must ensure uniqueness for each request_id, and if they are not an exception is raised. Callers should either supply all request_ids or nevery supply a request id, to avoid such an error. Args: request: HttpRequest, Request to add to the batch. callback: callable, A callback to be called for this response, of the form callback(id, response). The first parameter is the request id, and the second is the deserialized response object. request_id: string, A unique id for the request. The id will be passed to the callback with the response. Returns: None Raises: BatchError if a resumable request is added to a batch. KeyError is the request_id is not unique. """ if request_id is None: request_id = self._new_id() if request.resumable is not None: raise BatchError("Resumable requests cannot be used in a batch request.") if request_id in self._requests: raise KeyError("A request with this ID already exists: %s" % request_id) self._requests[request_id] = (request, callback) self._order.append(request_id) def execute(self, http=None): """Execute all the requests as a single batched HTTP request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. If one isn't supplied then use a http object from the requests in this batch. Returns: None Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if a transport error has occured. """ if http is None: for request_id in self._order: request, callback = self._requests[request_id] if request is not None: http = request.http break if http is None: raise ValueError("Missing a valid http object.") msgRoot = MIMEMultipart('mixed') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # Add all the individual requests. for request_id in self._order: request, callback = self._requests[request_id] msg = MIMENonMultipart('application', 'http') msg['Content-Transfer-Encoding'] = 'binary' msg['Content-ID'] = self._id_to_header(request_id) body = self._serialize_request(request) msg.set_payload(body) msgRoot.attach(msg) body = msgRoot.as_string() headers = {} headers['content-type'] = ('multipart/mixed; ' 'boundary="%s"') % msgRoot.get_boundary() resp, content = http.request(self._batch_uri, 'POST', body=body, headers=headers) if resp.status >= 300: raise HttpError(resp, content, self._batch_uri) # Now break up the response and process each one with the correct postproc # and trigger the right callbacks. boundary, _ = content.split(None, 1) # Prepend with a content-type header so FeedParser can handle it. header = 'Content-Type: %s\r\n\r\n' % resp['content-type'] content = header + content parser = FeedParser() parser.feed(content) respRoot = parser.close() if not respRoot.is_multipart(): raise BatchError("Response not in multipart/mixed format.") parts = respRoot.get_payload() for part in parts: request_id = self._header_to_id(part['Content-ID']) headers, content = self._deserialize_response(part.get_payload()) # TODO(jcgregorio) Remove this temporary hack once the server stops # gzipping individual response bodies. if content[0] != '{': gzipped_content = content content = gzip.GzipFile( fileobj=StringIO.StringIO(gzipped_content)).read() request, cb = self._requests[request_id] postproc = request.postproc response = postproc(resp, content) if cb is not None: cb(request_id, response) if self._callback is not None: self._callback(request_id, response) class HttpRequestMock(object): """Mock of HttpRequest. Do not construct directly, instead use RequestMockBuilder. """ def __init__(self, resp, content, postproc): """Constructor for HttpRequestMock Args: resp: httplib2.Response, the response to emulate coming from the request content: string, the response body postproc: callable, the post processing function usually supplied by the model class. See model.JsonModel.response() as an example. """ self.resp = resp self.content = content self.postproc = postproc if resp is None: self.resp = httplib2.Response({'status': 200, 'reason': 'OK'}) if 'reason' in self.resp: self.resp.reason = self.resp['reason'] def execute(self, http=None): """Execute the request. Same behavior as HttpRequest.execute(), but the response is mocked and not really from an HTTP request/response. """ return self.postproc(self.resp, self.content) class RequestMockBuilder(object): """A simple mock of HttpRequest Pass in a dictionary to the constructor that maps request methodIds to tuples of (httplib2.Response, content, opt_expected_body) that should be returned when that method is called. None may also be passed in for the httplib2.Response, in which case a 200 OK response will be generated. If an opt_expected_body (str or dict) is provided, it will be compared to the body and UnexpectedBodyError will be raised on inequality. Example: response = '{"data": {"id": "tag:google.c...' requestBuilder = RequestMockBuilder( { 'plus.activities.get': (None, response), } ) apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder) Methods that you do not supply a response for will return a 200 OK with an empty string as the response content or raise an excpetion if check_unexpected is set to True. The methodId is taken from the rpcName in the discovery document. For more details see the project wiki. """ def __init__(self, responses, check_unexpected=False): """Constructor for RequestMockBuilder The constructed object should be a callable object that can replace the class HttpResponse. responses - A dictionary that maps methodIds into tuples of (httplib2.Response, content). The methodId comes from the 'rpcName' field in the discovery document. check_unexpected - A boolean setting whether or not UnexpectedMethodError should be raised on unsupplied method. """ self.responses = responses self.check_unexpected = check_unexpected def __call__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """Implements the callable interface that discovery.build() expects of requestBuilder, which is to build an object compatible with HttpRequest.execute(). See that method for the description of the parameters and the expected response. """ if methodId in self.responses: response = self.responses[methodId] resp, content = response[:2] if len(response) > 2: # Test the body against the supplied expected_body. expected_body = response[2] if bool(expected_body) != bool(body): # Not expecting a body and provided one # or expecting a body and not provided one. raise UnexpectedBodyError(expected_body, body) if isinstance(expected_body, str): expected_body = simplejson.loads(expected_body) body = simplejson.loads(body) if body != expected_body: raise UnexpectedBodyError(expected_body, body) return HttpRequestMock(resp, content, postproc) elif self.check_unexpected: raise UnexpectedMethodError(methodId) else: model = JsonModel(False) return HttpRequestMock(None, '{}', model.response) class HttpMock(object): """Mock of httplib2.Http""" def __init__(self, filename, headers=None): """ Args: filename: string, absolute filename to read response from headers: dict, header to return with response """ if headers is None: headers = {'status': '200 OK'} f = file(filename, 'r') self.data = f.read() f.close() self.headers = headers def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): return httplib2.Response(self.headers), self.data class HttpMockSequence(object): """Mock of httplib2.Http Mocks a sequence of calls to request returning different responses for each call. Create an instance initialized with the desired response headers and content and then use as if an httplib2.Http instance. http = HttpMockSequence([ ({'status': '401'}, ''), ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), ({'status': '200'}, 'echo_request_headers'), ]) resp, content = http.request("http://examples.com") There are special values you can pass in for content to trigger behavours that are helpful in testing. 'echo_request_headers' means return the request headers in the response body 'echo_request_headers_as_json' means return the request headers in the response body 'echo_request_body' means return the request body in the response body 'echo_request_uri' means return the request uri in the response body """ def __init__(self, iterable): """ Args: iterable: iterable, a sequence of pairs of (headers, body) """ self._iterable = iterable def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): resp, content = self._iterable.pop(0) if content == 'echo_request_headers': content = headers elif content == 'echo_request_headers_as_json': content = simplejson.dumps(headers) elif content == 'echo_request_body': content = body elif content == 'echo_request_uri': content = uri return httplib2.Response(resp), content def set_user_agent(http, user_agent): """Set the user-agent on every request. Args: http - An instance of httplib2.Http or something that acts like it. user_agent: string, the value for the user-agent header. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = set_user_agent(h, "my-app-name/6.0") Most of the time the user-agent will be set doing auth, this is for the rare cases where you are accessing an unauthenticated endpoint. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if 'user-agent' in headers: headers['user-agent'] = user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http def tunnel_patch(http): """Tunnel PATCH requests over POST. Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = tunnel_patch(h, "my-app-name/6.0") Useful if you are running on a platform that doesn't support PATCH. Apply this last if you are using OAuth 1.0, as changing the method will result in a different signature. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if method == 'PATCH': if 'oauth_token' in headers.get('authorization', ''): logging.warning( 'OAuth 1.0 request made with Credentials after tunnel_patch.') headers['x-http-method-override'] = "PATCH" method = 'POST' resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http
Python
# Copyright (C) 2007 Joe Gregorio # # Licensed under the MIT License """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ __version__ = '0.1.3' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' __license__ = 'MIT License' __credits__ = '' def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if not params.has_key('q') or not params['q'] or \ not float(params['q']) or float(params['q']) > 1\ or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: type_match = (type == target_type or\ type == '*' or\ target_type == '*') subtype_match = (subtype == target_subtype or\ subtype == '*' or\ target_subtype == '*') if type_match and subtype_match: param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \ target_params.iteritems() if key != 'q' and \ params.has_key(key) and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return best_fitness, float(best_fit_q) def quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] def quality(mime_type, ranges): """Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie. >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][1] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s
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
# 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. """Utilities for OAuth. Utilities for making it easier to work with OAuth. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy import httplib2 import logging import oauth2 as oauth import urllib import urlparse from anyjson import simplejson try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl class Error(Exception): """Base error for this module.""" pass class RequestError(Error): """Error occurred during request.""" pass class MissingParameter(Error): pass class CredentialsInvalidError(Error): pass def _abstract(): raise NotImplementedError('You need to override this function') def _oauth_uri(name, discovery, params): """Look up the OAuth URI from the discovery document and add query parameters based on params. name - The name of the OAuth URI to lookup, one of 'request', 'access', or 'authorize'. discovery - Portion of discovery document the describes the OAuth endpoints. params - Dictionary that is used to form the query parameters for the specified URI. """ if name not in ['request', 'access', 'authorize']: raise KeyError(name) keys = discovery[name]['parameters'].keys() query = {} for key in keys: if key in params: query[key] = params[key] return discovery[name]['url'] + '?' + urllib.urlencode(query) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. """ def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. """ def get(self): """Retrieve credential. Returns: apiclient.oauth.Credentials """ _abstract() def put(self, credentials): """Write a credential. Args: credentials: Credentials, the credentials to store. """ _abstract() class OAuthCredentials(Credentials): """Credentials object for OAuth 1.0a """ def __init__(self, consumer, token, user_agent): """ consumer - An instance of oauth.Consumer. token - An instance of oauth.Token constructed with the access token and secret. user_agent - The HTTP User-Agent to provide for this application. """ self.consumer = consumer self.token = token self.user_agent = user_agent self.store = None # True if the credentials have been revoked self._invalid = False @property def invalid(self): """True if the credentials are invalid, such as being revoked.""" return getattr(self, "_invalid", False) def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: req = oauth.Request.from_consumer_and_token( self.consumer, self.token, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, self.token) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] # Update the stored credential if it becomes invalid. if response_code == 401: logging.info('Access token no longer valid: %s' % content) self._invalid = True if self.store is not None: self.store(self) raise CredentialsInvalidError("Credentials are no longer valid.") return resp, content http.request = new_request return http class TwoLeggedOAuthCredentials(Credentials): """Two Legged Credentials object for OAuth 1.0a. The Two Legged object is created directly, not from a flow. Once you authorize and httplib2.Http instance you can change the requestor and that change will propogate to the authorized httplib2.Http instance. For example: http = httplib2.Http() http = credentials.authorize(http) credentials.requestor = 'foo@example.info' http.request(...) credentials.requestor = 'bar@example.info' http.request(...) """ def __init__(self, consumer_key, consumer_secret, user_agent): """ Args: consumer_key: string, An OAuth 1.0 consumer key consumer_secret: string, An OAuth 1.0 consumer secret user_agent: string, The HTTP User-Agent to provide for this application. """ self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.user_agent = user_agent self.store = None # email address of the user to act on the behalf of. self._requestor = None @property def invalid(self): """True if the credentials are invalid, such as being revoked. Always returns False for Two Legged Credentials. """ return False def getrequestor(self): return self._requestor def setrequestor(self, email): self._requestor = email requestor = property(getrequestor, setrequestor, None, 'The email address of the user to act on behalf of') def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: # add in xoauth_requestor_id=self._requestor to the uri if self._requestor is None: raise MissingParameter( 'Requestor must be set before using TwoLeggedOAuthCredentials') parsed = list(urlparse.urlparse(uri)) q = parse_qsl(parsed[4]) q.append(('xoauth_requestor_id', self._requestor)) parsed[4] = urllib.urlencode(q) uri = urlparse.urlunparse(parsed) req = oauth.Request.from_consumer_and_token( self.consumer, None, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, None) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] if response_code == 401: logging.info('Access token no longer valid: %s' % content) # Do not store the invalid state of the Credentials because # being 2LO they could be reinstated in the future. raise CredentialsInvalidError("Credentials are invalid.") return resp, content http.request = new_request return http class FlowThreeLegged(Flow): """Does the Three Legged Dance for OAuth 1.0a. """ def __init__(self, discovery, consumer_key, consumer_secret, user_agent, **kwargs): """ discovery - Section of the API discovery document that describes the OAuth endpoints. consumer_key - OAuth consumer key consumer_secret - OAuth consumer secret user_agent - The HTTP User-Agent that identifies the application. **kwargs - The keyword arguments are all optional and required parameters for the OAuth calls. """ self.discovery = discovery self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.user_agent = user_agent self.params = kwargs self.request_token = {} required = {} for uriinfo in discovery.itervalues(): for name, value in uriinfo['parameters'].iteritems(): if value['required'] and not name.startswith('oauth_'): required[name] = 1 for key in required.iterkeys(): if key not in self.params: raise MissingParameter('Required parameter %s not supplied' % key) def step1_get_authorize_url(self, oauth_callback='oob'): """Returns a URI to redirect to the provider. oauth_callback - Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If oauth_callback is 'oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } body = urllib.urlencode({'oauth_callback': oauth_callback}) uri = _oauth_uri('request', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers, body=body) if resp['status'] != '200': logging.error('Failed to retrieve temporary authorization: %s', content) raise RequestError('Invalid response %s.' % resp['status']) self.request_token = dict(parse_qsl(content)) auth_params = copy.copy(self.params) auth_params['oauth_token'] = self.request_token['oauth_token'] return _oauth_uri('authorize', self.discovery, auth_params) def step2_exchange(self, verifier): """Exhanges an authorized request token for OAuthCredentials. Args: verifier: string, dict - either the verifier token, or a dictionary of the query parameters to the callback, which contains the oauth_verifier. Returns: The Credentials object. """ if not (isinstance(verifier, str) or isinstance(verifier, unicode)): verifier = verifier['oauth_verifier'] token = oauth.Token( self.request_token['oauth_token'], self.request_token['oauth_token_secret']) token.set_verifier(verifier) consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer, token) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } uri = _oauth_uri('access', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers) if resp['status'] != '200': logging.error('Failed to retrieve access token: %s', content) raise RequestError('Invalid response %s.' % resp['status']) oauth_params = dict(parse_qsl(content)) token = oauth.Token( oauth_params['oauth_token'], oauth_params['oauth_token_secret']) return OAuthCredentials(consumer, token, self.user_agent)
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. """Client for discovery based APIs A client library for Google's discovery based APIs. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = [ 'build', 'build_from_document' ] import copy import httplib2 import logging import os import random import re import uritemplate import urllib import urlparse import mimeparse import mimetypes try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl from apiclient.anyjson import simplejson from apiclient.errors import HttpError from apiclient.errors import InvalidJsonError from apiclient.errors import MediaUploadSizeError from apiclient.errors import UnacceptableMimeTypeError from apiclient.errors import UnknownApiNameOrVersion from apiclient.errors import UnknownLinkType from apiclient.http import HttpRequest from apiclient.http import MediaFileUpload from apiclient.http import MediaUpload from apiclient.model import JsonModel from apiclient.model import RawModel from apiclient.schema import Schemas from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart URITEMPLATE = re.compile('{[^}]*}') VARNAME = re.compile('[a-zA-Z0-9_-]+') DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/' '{api}/{apiVersion}/rest') DEFAULT_METHOD_DOC = 'A description of how to use this function' # Query parameters that work, but don't appear in discovery STACK_QUERY_PARAMETERS = ['trace', 'fields', 'pp', 'prettyPrint', 'userIp', 'userip', 'strict'] RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while' ] def _fix_method_name(name): if name in RESERVED_WORDS: return name + '_' else: return name def _write_headers(self): # Utility no-op method for multipart media handling pass def _add_query_parameter(url, name, value): """Adds a query parameter to a url Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None. """ if value is None: return url else: parsed = list(urlparse.urlparse(url)) q = parse_qsl(parsed[4]) q.append((name, value)) parsed[4] = urllib.urlencode(q) return urlparse.urlunparse(parsed) def key2param(key): """Converts key names into parameter names. For example, converting "max-results" -> "max_results" """ result = [] key = list(key) if not key[0].isalpha(): result.append('x') for c in key: if c.isalnum(): result.append(c) else: result.append('_') return ''.join(result) def build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest): """Construct a Resource for interacting with an API. Construct a Resource object for interacting with an API. The serviceName and version are the names from the Discovery service. Args: serviceName: string, name of the service version: string, the version of the service discoveryServiceUrl: string, a URI Template that points to the location of the discovery service. It should have two parameters {api} and {apiVersion} that when filled in produce an absolute URI to the discovery document for that service. developerKey: string, key obtained from https://code.google.com/apis/console model: apiclient.Model, converts to and from the wire format requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP request Returns: A Resource object with methods for interacting with the service. """ params = { 'api': serviceName, 'apiVersion': version } if http is None: http = httplib2.Http() requested_url = uritemplate.expand(discoveryServiceUrl, params) # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment # variable that contains the network address of the client sending the # request. If it exists then add that to the request for the discovery # document to avoid exceeding the quota on discovery requests. if 'REMOTE_ADDR' in os.environ: requested_url = _add_query_parameter(requested_url, 'userIp', os.environ['REMOTE_ADDR']) logging.info('URL being requested: %s' % requested_url) resp, content = http.request(requested_url) if resp.status == 404: raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName, version)) if resp.status >= 400: raise HttpError(resp, content, requested_url) try: service = simplejson.loads(content) except ValueError, e: logging.error('Failed to parse as JSON: ' + content) raise InvalidJsonError() filename = os.path.join(os.path.dirname(__file__), 'contrib', serviceName, 'future.json') try: f = file(filename, 'r') future = f.read() f.close() except IOError: future = None return build_from_document(content, discoveryServiceUrl, future, http, developerKey, model, requestBuilder) def build_from_document( service, base, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest): """Create a Resource for interacting with an API. Same as `build()`, but constructs the Resource object from a discovery document that is it given, as opposed to retrieving one over HTTP. Args: service: string, discovery document base: string, base URI for all HTTP requests, usually the discovery URI future: string, discovery document with future capabilities auth_discovery: dict, information about the authentication the API supports http: httplib2.Http, An instance of httplib2.Http or something that acts like it that HTTP requests will be made through. developerKey: string, Key for controlling API usage, generated from the API Console. model: Model class instance that serializes and de-serializes requests and responses. requestBuilder: Takes an http request and packages it up to be executed. Returns: A Resource object with methods for interacting with the service. """ service = simplejson.loads(service) base = urlparse.urljoin(base, service['basePath']) if future: future = simplejson.loads(future) auth_discovery = future.get('auth', {}) else: future = {} auth_discovery = {} schema = Schemas(service) if model is None: features = service.get('features', []) model = JsonModel('dataWrapper' in features) resource = createResource(http, base, model, requestBuilder, developerKey, service, future, schema) def auth_method(): """Discovery information about the authentication the API uses.""" return auth_discovery setattr(resource, 'auth_discovery', auth_method) return resource def _cast(value, schema_type): """Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A string representation of 'value' based on the schema_type. """ if schema_type == 'string': if type(value) == type('') or type(value) == type(u''): return value else: return str(value) elif schema_type == 'integer': return str(int(value)) elif schema_type == 'number': return str(float(value)) elif schema_type == 'boolean': return str(bool(value)).lower() else: if type(value) == type('') or type(value) == type(u''): return value else: return str(value) MULTIPLIERS = { "KB": 2 ** 10, "MB": 2 ** 20, "GB": 2 ** 30, "TB": 2 ** 40, } def _media_size_to_long(maxSize): """Convert a string media size, such as 10GB or 3TB into an integer.""" if len(maxSize) < 2: return 0 units = maxSize[-2:].upper() multiplier = MULTIPLIERS.get(units, 0) if multiplier: return int(maxSize[:-2]) * multiplier else: return int(maxSize) def createResource(http, baseUrl, model, requestBuilder, developerKey, resourceDesc, futureDesc, schema): class Resource(object): """A class for interacting with a resource.""" def __init__(self): self._http = http self._baseUrl = baseUrl self._model = model self._developerKey = developerKey self._requestBuilder = requestBuilder def createMethod(theclass, methodName, methodDesc, futureDesc): methodName = _fix_method_name(methodName) pathUrl = methodDesc['path'] httpMethod = methodDesc['httpMethod'] methodId = methodDesc['id'] mediaPathUrl = None accept = [] maxSize = 0 if 'mediaUpload' in methodDesc: mediaUpload = methodDesc['mediaUpload'] mediaPathUrl = mediaUpload['protocols']['simple']['path'] mediaResumablePathUrl = mediaUpload['protocols']['resumable']['path'] accept = mediaUpload['accept'] maxSize = _media_size_to_long(mediaUpload.get('maxSize', '')) if 'parameters' not in methodDesc: methodDesc['parameters'] = {} for name in STACK_QUERY_PARAMETERS: methodDesc['parameters'][name] = { 'type': 'string', 'location': 'query' } if httpMethod in ['PUT', 'POST', 'PATCH']: methodDesc['parameters']['body'] = { 'description': 'The request body.', 'type': 'object', 'required': True, } if 'request' in methodDesc: methodDesc['parameters']['body'].update(methodDesc['request']) else: methodDesc['parameters']['body']['type'] = 'object' if 'mediaUpload' in methodDesc: methodDesc['parameters']['media_body'] = { 'description': 'The filename of the media request body.', 'type': 'string', 'required': False, } methodDesc['parameters']['body']['required'] = False argmap = {} # Map from method parameter name to query parameter name required_params = [] # Required parameters repeated_params = [] # Repeated parameters pattern_params = {} # Parameters that must match a regex query_params = [] # Parameters that will be used in the query string path_params = {} # Parameters that will be used in the base URL param_type = {} # The type of the parameter enum_params = {} # Allowable enumeration values for each parameter if 'parameters' in methodDesc: for arg, desc in methodDesc['parameters'].iteritems(): param = key2param(arg) argmap[param] = arg if desc.get('pattern', ''): pattern_params[param] = desc['pattern'] if desc.get('enum', ''): enum_params[param] = desc['enum'] if desc.get('required', False): required_params.append(param) if desc.get('repeated', False): repeated_params.append(param) if desc.get('location') == 'query': query_params.append(param) if desc.get('location') == 'path': path_params[param] = param param_type[param] = desc.get('type', 'string') for match in URITEMPLATE.finditer(pathUrl): for namematch in VARNAME.finditer(match.group(0)): name = key2param(namematch.group(0)) path_params[name] = name if name in query_params: query_params.remove(name) def method(self, **kwargs): for name in kwargs.iterkeys(): if name not in argmap: raise TypeError('Got an unexpected keyword argument "%s"' % name) for name in required_params: if name not in kwargs: raise TypeError('Missing required parameter "%s"' % name) for name, regex in pattern_params.iteritems(): if name in kwargs: if isinstance(kwargs[name], basestring): pvalues = [kwargs[name]] else: pvalues = kwargs[name] for pvalue in pvalues: if re.match(regex, pvalue) is None: raise TypeError( 'Parameter "%s" value "%s" does not match the pattern "%s"' % (name, pvalue, regex)) for name, enums in enum_params.iteritems(): if name in kwargs: if kwargs[name] not in enums: raise TypeError( 'Parameter "%s" value "%s" is not an allowed value in "%s"' % (name, kwargs[name], str(enums))) actual_query_params = {} actual_path_params = {} for key, value in kwargs.iteritems(): to_type = param_type.get(key, 'string') # For repeated parameters we cast each member of the list. if key in repeated_params and type(value) == type([]): cast_value = [_cast(x, to_type) for x in value] else: cast_value = _cast(value, to_type) if key in query_params: actual_query_params[argmap[key]] = cast_value if key in path_params: actual_path_params[argmap[key]] = cast_value body_value = kwargs.get('body', None) media_filename = kwargs.get('media_body', None) if self._developerKey: actual_query_params['key'] = self._developerKey model = self._model # If there is no schema for the response then presume a binary blob. if 'response' not in methodDesc: model = RawModel() headers = {} headers, params, query, body = model.request(headers, actual_path_params, actual_query_params, body_value) expanded_url = uritemplate.expand(pathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) resumable = None multipart_boundary = '' if media_filename: # Convert a simple filename into a MediaUpload object. if isinstance(media_filename, basestring): (media_mime_type, encoding) = mimetypes.guess_type(media_filename) if media_mime_type is None: raise UnknownFileType(media_filename) if not mimeparse.best_match([media_mime_type], ','.join(accept)): raise UnacceptableMimeTypeError(media_mime_type) media_upload = MediaFileUpload(media_filename, media_mime_type) elif isinstance(media_filename, MediaUpload): media_upload = media_filename else: raise TypeError('media_filename must be str or MediaUpload.') if media_upload.resumable(): resumable = media_upload # Check the maxSize if maxSize > 0 and media_upload.size() > maxSize: raise MediaUploadSizeError("Media larger than: %s" % maxSize) # Use the media path uri for media uploads if media_upload.resumable(): expanded_url = uritemplate.expand(mediaResumablePathUrl, params) else: expanded_url = uritemplate.expand(mediaPathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) if body is None: # This is a simple media upload headers['content-type'] = media_upload.mimetype() expanded_url = uritemplate.expand(mediaResumablePathUrl, params) if not media_upload.resumable(): body = media_upload.getbytes(0, media_upload.size()) else: # This is a multipart/related upload. msgRoot = MIMEMultipart('related') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # attach the body as one part msg = MIMENonMultipart(*headers['content-type'].split('/')) msg.set_payload(body) msgRoot.attach(msg) # attach the media as the second part msg = MIMENonMultipart(*media_upload.mimetype().split('/')) msg['Content-Transfer-Encoding'] = 'binary' if media_upload.resumable(): # This is a multipart resumable upload, where a multipart payload # looks like this: # # --===============1678050750164843052== # Content-Type: application/json # MIME-Version: 1.0 # # {'foo': 'bar'} # --===============1678050750164843052== # Content-Type: image/png # MIME-Version: 1.0 # Content-Transfer-Encoding: binary # # <BINARY STUFF> # --===============1678050750164843052==-- # # In the case of resumable multipart media uploads, the <BINARY # STUFF> is large and will be spread across multiple PUTs. What we # do here is compose the multipart message with a random payload in # place of <BINARY STUFF> and then split the resulting content into # two pieces, text before <BINARY STUFF> and text after <BINARY # STUFF>. The text after <BINARY STUFF> is the multipart boundary. # In apiclient.http the HttpRequest will send the text before # <BINARY STUFF>, then send the actual binary media in chunks, and # then will send the multipart delimeter. payload = hex(random.getrandbits(300)) msg.set_payload(payload) msgRoot.attach(msg) body = msgRoot.as_string() body, _ = body.split(payload) resumable = media_upload else: payload = media_upload.getbytes(0, media_upload.size()) msg.set_payload(payload) msgRoot.attach(msg) body = msgRoot.as_string() multipart_boundary = msgRoot.get_boundary() headers['content-type'] = ('multipart/related; ' 'boundary="%s"') % multipart_boundary logging.info('URL being requested: %s' % url) return self._requestBuilder(self._http, model.response, url, method=httpMethod, body=body, headers=headers, methodId=methodId, resumable=resumable) docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n'] if len(argmap) > 0: docs.append('Args:\n') for arg in argmap.iterkeys(): if arg in STACK_QUERY_PARAMETERS: continue repeated = '' if arg in repeated_params: repeated = ' (repeated)' required = '' if arg in required_params: required = ' (required)' paramdesc = methodDesc['parameters'][argmap[arg]] paramdoc = paramdesc.get('description', 'A parameter') if '$ref' in paramdesc: docs.append( (' %s: object, %s%s%s\n The object takes the' ' form of:\n\n%s\n\n') % (arg, paramdoc, required, repeated, schema.prettyPrintByName(paramdesc['$ref']))) else: paramtype = paramdesc.get('type', 'string') docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required, repeated)) enum = paramdesc.get('enum', []) enumDesc = paramdesc.get('enumDescriptions', []) if enum and enumDesc: docs.append(' Allowed values\n') for (name, desc) in zip(enum, enumDesc): docs.append(' %s - %s\n' % (name, desc)) if 'response' in methodDesc: docs.append('\nReturns:\n An object of the form\n\n ') docs.append(schema.prettyPrintSchema(methodDesc['response'])) setattr(method, '__doc__', ''.join(docs)) setattr(theclass, methodName, method) def createNextMethodFromFuture(theclass, methodName, methodDesc, futureDesc): """ This is a legacy method, as only Buzz and Moderator use the future.json functionality for generating _next methods. It will be kept around as long as those API versions are around, but no new APIs should depend upon it. """ methodName = _fix_method_name(methodName) methodId = methodDesc['id'] + '.next' def methodNext(self, previous): """Retrieve the next page of results. Takes a single argument, 'body', which is the results from the last call, and returns the next set of items in the collection. Returns: None if there are no more items in the collection. """ if futureDesc['type'] != 'uri': raise UnknownLinkType(futureDesc['type']) try: p = previous for key in futureDesc['location']: p = p[key] url = p except (KeyError, TypeError): return None url = _add_query_parameter(url, 'key', self._developerKey) headers = {} headers, params, query, body = self._model.request(headers, {}, {}, None) logging.info('URL being requested: %s' % url) resp, content = self._http.request(url, method='GET', headers=headers) return self._requestBuilder(self._http, self._model.response, url, method='GET', headers=headers, methodId=methodId) setattr(theclass, methodName, methodNext) def createNextMethod(theclass, methodName, methodDesc, futureDesc): methodName = _fix_method_name(methodName) methodId = methodDesc['id'] + '.next' def methodNext(self, previous_request, previous_response): """Retrieves the next page of results. Args: previous_request: The request for the previous page. previous_response: The response from the request for the previous page. Returns: A request object that you can call 'execute()' on to request the next page. Returns None if there are no more items in the collection. """ # Retrieve nextPageToken from previous_response # Use as pageToken in previous_request to create new request. if 'nextPageToken' not in previous_response: return None request = copy.copy(previous_request) pageToken = previous_response['nextPageToken'] parsed = list(urlparse.urlparse(request.uri)) q = parse_qsl(parsed[4]) # Find and remove old 'pageToken' value from URI newq = [(key, value) for (key, value) in q if key != 'pageToken'] newq.append(('pageToken', pageToken)) parsed[4] = urllib.urlencode(newq) uri = urlparse.urlunparse(parsed) request.uri = uri logging.info('URL being requested: %s' % uri) return request setattr(theclass, methodName, methodNext) # Add basic methods to Resource if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): if futureDesc: future = futureDesc['methods'].get(methodName, {}) else: future = None createMethod(Resource, methodName, methodDesc, future) # Add in nested resources if 'resources' in resourceDesc: def createResourceMethod(theclass, methodName, methodDesc, futureDesc): methodName = _fix_method_name(methodName) def methodResource(self): return createResource(self._http, self._baseUrl, self._model, self._requestBuilder, self._developerKey, methodDesc, futureDesc, schema) setattr(methodResource, '__doc__', 'A collection resource.') setattr(methodResource, '__is_resource__', True) setattr(theclass, methodName, methodResource) for methodName, methodDesc in resourceDesc['resources'].iteritems(): if futureDesc and 'resources' in futureDesc: future = futureDesc['resources'].get(methodName, {}) else: future = {} createResourceMethod(Resource, methodName, methodDesc, future) # Add <m>_next() methods to Resource if futureDesc and 'methods' in futureDesc: for methodName, methodDesc in futureDesc['methods'].iteritems(): if 'next' in methodDesc and methodName in resourceDesc['methods']: createNextMethodFromFuture(Resource, methodName + '_next', resourceDesc['methods'][methodName], methodDesc['next']) # Add _next() methods # Look for response bodies in schema that contain nextPageToken, and methods # that take a pageToken parameter. if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): if 'response' in methodDesc: responseSchema = methodDesc['response'] if '$ref' in responseSchema: responseSchema = schema.get(responseSchema['$ref']) hasNextPageToken = 'nextPageToken' in responseSchema.get('properties', {}) hasPageToken = 'pageToken' in methodDesc.get('parameters', {}) if hasNextPageToken and hasPageToken: createNextMethod(Resource, methodName + '_next', resourceDesc['methods'][methodName], methodName) return Resource()
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. """Utilities for Google App Engine Utilities for making it easier to use the Google API Client for Python on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle from google.appengine.ext import db from apiclient.oauth import OAuthCredentials from apiclient.oauth import FlowThreeLegged class FlowThreeLeggedProperty(db.Property): """Utility property that allows easy storage and retreival of an apiclient.oauth.FlowThreeLegged""" # Tell what the user type is. data_type = FlowThreeLegged # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowThreeLeggedProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, FlowThreeLegged): raise BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowThreeLeggedProperty, self).validate(value) def empty(self, value): return not value class OAuthCredentialsProperty(db.Property): """Utility property that allows easy storage and retrieval of apiclient.oath.OAuthCredentials """ # Tell what the user type is. data_type = OAuthCredentials # For writing to datastore. def get_value_for_datastore(self, model_instance): cred = super(OAuthCredentialsProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(cred)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, OAuthCredentials): raise BadValueError('Property %s must be convertible ' 'to an OAuthCredentials instance (%s)' % (self.name, value)) return super(OAuthCredentialsProperty, self).validate(value) def empty(self, value): return not value class StorageByKeyName(object): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty """ self.model = model self.key_name = key_name self.property_name = property_name def get(self): """Retrieve Credential from datastore. Returns: Credentials """ entity = self.model.get_or_insert(self.key_name) credential = getattr(entity, self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self.put) return credential def put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self.model.get_or_insert(self.key_name) setattr(entity, self.property_name, credentials) entity.put()
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. """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
# 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. """Utilities for OAuth. Utilities for making it easier to work with OAuth 1.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle import threading from apiclient.oauth import Storage as BaseStorage class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def get(self): """Retrieve Credential from file. Returns: apiclient.oauth.Credentials """ self._lock.acquire() try: f = open(self._filename, 'r') credentials = pickle.loads(f.read()) f.close() credentials.set_store(self.put) except: credentials = None self._lock.release() return credentials def put(self, credentials): """Write a pickled Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._lock.acquire() f = open(self._filename, 'w') f.write(pickle.dumps(credentials)) f.close() self._lock.release()
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. import apiclient import base64 import pickle from django.db import models class OAuthCredentialsField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): if value is None: return None if isinstance(value, apiclient.oauth.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value)) class FlowThreeLeggedField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): print "In to_python", value if value is None: return None if isinstance(value, apiclient.oauth.FlowThreeLegged): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value))
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. """Model objects for requests and responses. Each API may support one or more serializations, such as JSON, Atom, etc. The model classes are responsible for converting between the wire format and the Python object representation. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import gflags import logging import urllib from anyjson import simplejson from errors import HttpError FLAGS = gflags.FLAGS gflags.DEFINE_boolean('dump_request_response', False, 'Dump all http server requests and responses. ' ) def _abstract(): raise NotImplementedError('You need to override this function') class Model(object): """Model base class. All Model classes should implement this interface. The Model serializes and de-serializes between a wire format such as JSON and a Python object representation. """ def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized in the desired wire format. """ _abstract() def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ _abstract() class BaseModel(Model): """Base model class. Subclasses should provide implementations for the "serialize" and "deserialize" methods, as well as values for the following class attributes. Attributes: accept: The value to use for the HTTP Accept header. content_type: The value to use for the HTTP Content-type header. no_content_response: The value to return when deserializing a 204 "No Content" response. alt_param: The value to supply as the "alt" query parameter for requests. """ accept = None content_type = None no_content_response = None alt_param = None def _log_request(self, headers, path_params, query, body): """Logs debugging information about the request if requested.""" if FLAGS.dump_request_response: logging.info('--request-start--') logging.info('-headers-start-') for h, v in headers.iteritems(): logging.info('%s: %s', h, v) logging.info('-headers-end-') logging.info('-path-parameters-start-') for h, v in path_params.iteritems(): logging.info('%s: %s', h, v) logging.info('-path-parameters-end-') logging.info('body: %s', body) logging.info('query: %s', query) logging.info('--request-end--') def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable by simplejson. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized as JSON """ query = self._build_query(query_params) headers['accept'] = self.accept headers['accept-encoding'] = 'gzip, deflate' if 'user-agent' in headers: headers['user-agent'] += ' ' else: headers['user-agent'] = '' headers['user-agent'] += 'google-api-python-client/1.0' if body_value is not None: headers['content-type'] = self.content_type body_value = self.serialize(body_value) self._log_request(headers, path_params, query, body_value) return (headers, path_params, query, body_value) def _build_query(self, params): """Builds a query string. Args: params: dict, the query parameters Returns: The query parameters properly encoded into an HTTP URI query string. """ if self.alt_param is not None: params.update({'alt': self.alt_param}) astuples = [] for key, value in params.iteritems(): if type(value) == type([]): for x in value: x = x.encode('utf-8') astuples.append((key, x)) else: if getattr(value, 'encode', False) and callable(value.encode): value = value.encode('utf-8') astuples.append((key, value)) return '?' + urllib.urlencode(astuples) def _log_response(self, resp, content): """Logs debugging information about the response if requested.""" if FLAGS.dump_request_response: logging.info('--response-start--') for h, v in resp.iteritems(): logging.info('%s: %s', h, v) if content: logging.info(content) logging.info('--response-end--') def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ self._log_response(resp, content) # Error handling is TBD, for example, do we retry # for some operation/error combinations? if resp.status < 300: if resp.status == 204: # A 204: No Content response should be treated differently # to all the other success states return self.no_content_response return self.deserialize(content) else: logging.debug('Content from bad request was: %s' % content) raise HttpError(resp, content) def serialize(self, body_value): """Perform the actual Python object serialization. Args: body_value: object, the request body as a Python object. Returns: string, the body in serialized form. """ _abstract() def deserialize(self, content): """Perform the actual deserialization from response string to Python object. Args: content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. """ _abstract() class JsonModel(BaseModel): """Model class for JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request and response bodies. """ accept = 'application/json' content_type = 'application/json' alt_param = 'json' def __init__(self, data_wrapper=False): """Construct a JsonModel. Args: data_wrapper: boolean, wrap requests and responses in a data wrapper """ self._data_wrapper = data_wrapper def serialize(self, body_value): if (isinstance(body_value, dict) and 'data' not in body_value and self._data_wrapper): body_value = {'data': body_value} return simplejson.dumps(body_value) def deserialize(self, content): body = simplejson.loads(content) if isinstance(body, dict) and 'data' in body: body = body['data'] return body @property def no_content_response(self): return {} class RawModel(JsonModel): """Model class for requests that don't return JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = None def deserialize(self, content): return content @property def no_content_response(self): return '' class ProtocolBufferModel(BaseModel): """Model class for protocol buffers. Serializes and de-serializes the binary protocol buffer sent in the HTTP request and response bodies. """ accept = 'application/x-protobuf' content_type = 'application/x-protobuf' alt_param = 'proto' def __init__(self, protocol_buffer): """Constructs a ProtocolBufferModel. The serialzed protocol buffer returned in an HTTP response will be de-serialized using the given protocol buffer class. Args: protocol_buffer: The protocol buffer class used to de-serialize a response from the API. """ self._protocol_buffer = protocol_buffer def serialize(self, body_value): return body_value.SerializeToString() def deserialize(self, content): return self._protocol_buffer.FromString(content) @property def no_content_response(self): return self._protocol_buffer() def makepatch(original, modified): """Create a patch object. Some methods support PATCH, an efficient way to send updates to a resource. This method allows the easy construction of patch bodies by looking at the differences between a resource before and after it was modified. Args: original: object, the original deserialized resource modified: object, the modified deserialized resource Returns: An object that contains only the changes from original to modified, in a form suitable to pass to a PATCH method. Example usage: item = service.activities().get(postid=postid, userid=userid).execute() original = copy.deepcopy(item) item['object']['content'] = 'This is updated.' service.activities.patch(postid=postid, userid=userid, body=makepatch(original, item)).execute() """ patch = {} for key, original_value in original.iteritems(): modified_value = modified.get(key, None) if modified_value is None: # Use None to signal that the element is deleted patch[key] = None elif original_value != modified_value: if type(original_value) == type({}): # Recursively descend objects patch[key] = makepatch(original_value, modified_value) else: # In the case of simple types or arrays we just replace patch[key] = modified_value else: # Don't add anything to patch if there's no change pass for key in modified: if key not in original: patch[key] = modified[key] return patch
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
""" 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
"""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
import Cookie import datetime import time import email.utils import calendar import base64 import hashlib import hmac import re import logging # Ripped from the Tornado Framework's web.py # http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09 # # Tornado is licensed under the Apache Licence, Version 2.0 # (http://www.apache.org/licenses/LICENSE-2.0.html). # # Example: # from vendor.prayls.lilcookies import LilCookies # cookieutil = LilCookies(self, application_settings['cookie_secret']) # cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100) # cookieutil.get_secure_cookie(name = 'mykey') class LilCookies: @staticmethod def _utf8(s): if isinstance(s, unicode): return s.encode("utf-8") assert isinstance(s, str) return s @staticmethod def _time_independent_equals(a, b): if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 @staticmethod def _signature_from_secret(cookie_secret, *parts): """ Takes a secret salt value to create a signature for values in the `parts` param.""" hash = hmac.new(cookie_secret, digestmod=hashlib.sha1) for part in parts: hash.update(part) return hash.hexdigest() @staticmethod def _signed_cookie_value(cookie_secret, name, value): """ Returns a signed value for use in a cookie. This is helpful to have in its own method if you need to re-use this function for other needs. """ timestamp = str(int(time.time())) value = base64.b64encode(value) signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp) return "|".join([value, timestamp, signature]) @staticmethod def _verified_cookie_value(cookie_secret, name, signed_value): """Returns the un-encrypted value given the signed value if it validates, or None.""" value = signed_value if not value: return None parts = value.split("|") if len(parts) != 3: return None signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1]) if not LilCookies._time_independent_equals(parts[2], signature): logging.warning("Invalid cookie signature %r", value) return None timestamp = int(parts[1]) if timestamp < time.time() - 31 * 86400: logging.warning("Expired cookie %r", value) return None try: return base64.b64decode(parts[0]) except: return None def __init__(self, handler, cookie_secret): """You must specify the cookie_secret to use any of the secure methods. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. """ if len(cookie_secret) < 45: raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret) self.handler = handler self.request = handler.request self.response = handler.response self.cookie_secret = cookie_secret def cookies(self): """A dictionary of Cookie.Morsel objects.""" if not hasattr(self, "_cookies"): self._cookies = Cookie.BaseCookie() if "Cookie" in self.request.headers: try: self._cookies.load(self.request.headers["Cookie"]) except: self.clear_all_cookies() return self._cookies def get_cookie(self, name, default=None): """Gets the value of the cookie with the given name, else default.""" if name in self.cookies(): return self._cookies[name].value return default def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ name = LilCookies._utf8(name) value = LilCookies._utf8(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookies"): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: timestamp = calendar.timegm(expires.utctimetuple()) new_cookie[name]["expires"] = email.utils.formatdate( timestamp, localtime=False, usegmt=True) if path: new_cookie[name]["path"] = path for k, v in kwargs.iteritems(): new_cookie[name][k] = v # The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush. for vals in new_cookie.values(): self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None))) def clear_cookie(self, name, path="/", domain=None): """Deletes the cookie with the given name.""" expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain) def clear_all_cookies(self): """Deletes all the cookies the user sent with this request.""" for name in self.cookies().iterkeys(): self.clear_cookie(name) def set_secure_cookie(self, name, value, expires_days=30, **kwargs): """Signs and timestamps a cookie so it cannot be forged. To read a cookie set with this method, use get_secure_cookie(). """ value = LilCookies._signed_cookie_value(self.cookie_secret, name, value) self.set_cookie(name, value, expires_days=expires_days, **kwargs) def get_secure_cookie(self, name, value=None): """Returns the given signed cookie if it validates, or None.""" if value is None: value = self.get_cookie(name) return LilCookies._verified_cookie_value(self.cookie_secret, name, value) def _cookie_signature(self, *parts): return LilCookies._signature_from_secret(self.cookie_secret)
Python
# This is the version of this source code. manual_verstr = "1.5" auto_build_num = "211" verstr = manual_verstr + "." + auto_build_num try: from pyutil.version_class import Version as pyutil_Version __version__ = pyutil_Version(verstr) except (ImportError, ValueError): # Maybe there is no pyutil installed. from distutils.version import LooseVersion as distutils_Version __version__ = distutils_Version(verstr)
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import imaplib class IMAP4_SSL(imaplib.IMAP4_SSL): """IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH', lambda x: oauth2.build_xoauth_string(url, consumer, token))
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import base64 import urllib import time import random import urlparse import hmac import binascii import httplib2 try: from urlparse import parse_qs parse_qs # placate pyflakes except ImportError: # fall back for Python 2.5 from cgi import parse_qs try: from hashlib import sha1 sha = sha1 except ImportError: # hashlib was added in Python 2.5 import sha import _version __version__ = _version.__version__ OAUTH_VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class Error(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occurred.'): self._message = message @property def message(self): """A hack to get around the deprecation errors in 2.6.""" return self._message def __str__(self): return self._message class MissingSignature(Error): pass def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def build_xoauth_string(url, consumer, token=None): """Build an XOAUTH string for use in SMTP/IMPA authentication.""" request = Request.from_consumer_and_token(consumer, token, "GET", url) signing_method = SignatureMethod_HMAC_SHA1() request.sign_request(signing_method, consumer, token) params = [] for k, v in sorted(request.iteritems()): if v is not None: params.append('%s="%s"' % (k, escape(v))) return "%s %s %s" % ("GET", url, ','.join(params)) def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, unicode): if not isinstance(s, str): raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s)) try: s = s.decode('utf-8') except UnicodeDecodeError, le: raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,)) return s def to_utf8(s): return to_unicode(s).encode('utf-8') def to_unicode_if_string(s): if isinstance(s, basestring): return to_unicode(s) else: return s def to_utf8_if_string(s): if isinstance(s, basestring): return to_utf8(s) else: return s def to_unicode_optional_iterator(x): """ Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str. """ if isinstance(x, basestring): return to_unicode(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_unicode(e) for e in l ] def to_utf8_optional_iterator(x): """ Raise TypeError if x is a str or if x is an iterable which contains a str. """ if isinstance(x, basestring): return to_utf8(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_utf8_if_string(e) for e in l ] def escape(s): """Escape a URL including any /.""" return urllib.quote(s.encode('utf-8'), safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class Consumer(object): """A consumer of OAuth-protected services. The OAuth consumer is a "third-party" service that wants to access protected resources from an OAuth service provider on behalf of an end user. It's kind of the OAuth client. Usually a consumer must be registered with the service provider by the developer of the consumer software. As part of that process, the service provider gives the consumer a *key* and a *secret* with which the consumer software can identify itself to the service. The consumer will include its key in each request to identify itself, but will use its secret only when signing requests, to prove that the request is from that particular registered consumer. Once registered, the consumer can then use its consumer credentials to ask the service provider for a request token, kicking off the OAuth authorization process. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def __str__(self): data = {'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret} return urllib.urlencode(data) class Token(object): """An OAuth credential used to request authorization or a protected resource. Tokens in OAuth comprise a *key* and a *secret*. The key is included in requests to identify the token being used, but the secret is used only in the signature, to prove that the requester is who the server gave the token to. When first negotiating the authorization, the consumer asks for a *request token* that the live user authorizes with the service provider. The consumer then exchanges the request token for an *access token* that can be used to access protected resources. """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) @staticmethod def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token def __str__(self): return self.to_string() def setter(attr): name = attr.__name__ def getter(self): try: return self.__dict__[name] except KeyError: raise AttributeError(name) def deleter(self): del self.__dict__[name] return property(getter, attr, deleter) class Request(dict): """The parameters and information for an HTTP request, suitable for authorizing with OAuth credentials. When a consumer wants to access a service's protected resources, it does so using a signed HTTP request identifying itself (the consumer) with its key, and providing an access token authorized by the end user to access those resources. """ version = OAUTH_VERSION def __init__(self, method=HTTP_METHOD, url=None, parameters=None, body='', is_form_encoded=False): if url is not None: self.url = to_unicode(url) self.method = method if parameters is not None: for k, v in parameters.iteritems(): k = to_unicode(k) v = to_unicode_optional_iterator(v) self[k] = v self.body = body self.is_form_encoded = is_form_encoded @setter def url(self, value): self.__dict__['url'] = value if value is not None: scheme, netloc, path, params, query, fragment = urlparse.urlparse(value) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] if scheme not in ('http', 'https'): raise ValueError("Unsupported URL %s (%s)." % (value, scheme)) # Normalized URL excludes params, query, and fragment. self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None)) else: self.normalized_url = None self.__dict__['url'] = None @setter def method(self, value): self.__dict__['method'] = value.upper() def _get_timestamp_nonce(self): return self['oauth_timestamp'], self['oauth_nonce'] def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.iteritems() if not k.startswith('oauth_')]) def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" d = {} for k, v in self.iteritems(): d[k.encode('utf-8')] = to_utf8_optional_iterator(v) # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(d, True).replace('+', '%20') def to_url(self): """Serialize as a URL for a GET request.""" base_url = urlparse.urlparse(self.url) try: query = base_url.query except AttributeError: # must be python <2.5 query = base_url[4] query = parse_qs(query) for k, v in self.items(): query.setdefault(k, []).append(v) try: scheme = base_url.scheme netloc = base_url.netloc path = base_url.path params = base_url.params fragment = base_url.fragment except AttributeError: # must be python <2.5 scheme = base_url[0] netloc = base_url[1] path = base_url[2] params = base_url[3] fragment = base_url[5] url = (scheme, netloc, path, params, urllib.urlencode(query, True), fragment) return urlparse.urlunparse(url) def get_parameter(self, parameter): ret = self.get(parameter) if ret is None: raise Error('Parameter not found: %s' % parameter) return ret def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] for key, value in self.iteritems(): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, # so we unpack sequence values into multiple items for sorting. if isinstance(value, basestring): items.append((to_utf8_if_string(key), to_utf8(value))) else: try: value = list(value) except TypeError, e: assert 'is not iterable' in str(e) items.append((to_utf8_if_string(key), to_utf8_if_string(value))) else: items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value) # Include any query string parameters from the provided URL query = urlparse.urlparse(self.url)[4] url_items = self._split_url_string(query).items() url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ] items.extend(url_items) items.sort() encoded_str = urllib.urlencode(items) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20').replace('%7E', '~') def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None, body='', is_form_encoded=False): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': consumer.key, 'oauth_timestamp': cls.make_timestamp(), 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key if token.verifier: parameters['oauth_verifier'] = token.verifier return Request(http_method, http_url, parameters, body=body, is_form_encoded=is_form_encoded) @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return cls(http_method, http_url, parameters) @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters class Client(httplib2.Http): """OAuthClient is a worker to attempt to execute a request.""" def __init__(self, consumer, token=None, cache=None, timeout=None, proxy_info=None): if consumer is not None and not isinstance(consumer, Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, Token): raise ValueError("Invalid token.") self.consumer = consumer self.token = token self.method = SignatureMethod_HMAC_SHA1() httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info) def set_signature_method(self, method): if not isinstance(method, SignatureMethod): raise ValueError("Invalid signature method.") self.method = method def request(self, uri, method="GET", body='', headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded' if not isinstance(headers, dict): headers = {} if method == "POST": headers['Content-Type'] = headers.get('Content-Type', DEFAULT_POST_CONTENT_TYPE) is_form_encoded = \ headers.get('Content-Type') == 'application/x-www-form-urlencoded' if is_form_encoded and body: parameters = parse_qs(body) else: parameters = None req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters, body=body, is_form_encoded=is_form_encoded) req.sign_request(self.method, self.consumer, self.token) schema, rest = urllib.splittype(uri) if rest.startswith('//'): hierpart = '//' else: hierpart = '' host, rest = urllib.splithost(rest) realm = schema + ':' + hierpart + host if is_form_encoded: body = req.to_postdata() elif method == "GET": uri = req.to_url() else: headers.update(req.to_header(realm=realm)) return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) class Server(object): """A skeletal implementation of a service provider, providing protected resources to requests from authorized consumers. This class implements the logic to check requests for authorization. You can use it with your web server or web framework to protect certain resources with OAuth. """ timestamp_threshold = 300 # In seconds, five minutes. version = OAUTH_VERSION signature_methods = None def __init__(self, signature_methods=None): self.signature_methods = signature_methods or {} def add_signature_method(self, signature_method): self.signature_methods[signature_method.name] = signature_method return self.signature_methods def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" self._check_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _check_version(self, request): """Verify the correct version of the request for this server.""" version = self._get_version(request) if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version)) def _get_version(self, request): """Return the version of the request for this server.""" try: version = request.get_parameter('oauth_version') except: version = OAUTH_VERSION return version def _get_signature_method(self, request): """Figure out the signature with some defaults.""" try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_verifier(self, request): return request.get_parameter('oauth_verifier') def _check_signature(self, request, consumer, token): timestamp, nonce = request._get_timestamp_nonce() self._check_timestamp(timestamp) signature_method = self._get_signature_method(request) try: signature = request.get_parameter('oauth_signature') except: raise MissingSignature('Missing oauth_signature.') # Validate the signature. valid = signature_method.check(request, consumer, token, signature) if not valid: key, base = signature_method.signing_base(request, consumer, token) raise Error('Invalid signature. Expected signature base ' 'string: %s' % base) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) class SignatureMethod(object): """A way of signing requests. The OAuth protocol lets consumers and service providers pick a way to sign requests. This interface shows the methods expected by the other `oauth` modules for signing requests. Subclass it and implement its methods to provide a new way to sign requests. """ def signing_base(self, request, consumer, token): """Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software. """ raise NotImplementedError def sign(self, request, consumer, token): """Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): if not hasattr(request, 'normalized_url') or request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( escape(request.method), escape(request.normalized_url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class SignatureMethod_PLAINTEXT(SignatureMethod): name = 'PLAINTEXT' def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def sign(self, request, consumer, token): key, raw = self.signing_base(request, consumer, token) return raw
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
''' Module which prompts the user for translations and saves them. TODO: implement @author: Rodrigo Damazio ''' class Translator(object): ''' classdocs ''' def __init__(self, language): ''' Constructor ''' self._language = language def Translate(self, string_names): print string_names
Python
''' Module which brings history information about files from Mercurial. @author: Rodrigo Damazio ''' import re import subprocess REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*') def _GetOutputLines(args): ''' Runs an external process and returns its output as a list of lines. @param args: the arguments to run ''' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines = True, shell = False) output = process.communicate()[0] return output.splitlines() def FillMercurialRevisions(filename, parsed_file): ''' Fills the revs attribute of all strings in the given parsed file with a list of revisions that touched the lines corresponding to that string. @param filename: the name of the file to get history for @param parsed_file: the parsed file to modify ''' # Take output of hg annotate to get revision of each line output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename]) # Create a map of line -> revision (key is list index, line 0 doesn't exist) line_revs = ['dummy'] for line in output_lines: rev_match = REVISION_REGEX.match(line) if not rev_match: raise 'Unexpected line of output from hg: %s' % line rev_hash = rev_match.group('hash') line_revs.append(rev_hash) for str in parsed_file.itervalues(): # Get the lines that correspond to each string start_line = str['startLine'] end_line = str['endLine'] # Get the revisions that touched those lines revs = [] for line_number in range(start_line, end_line + 1): revs.append(line_revs[line_number]) # Merge with any revisions that were already there # (for explict revision specification) if 'revs' in str: revs += str['revs'] # Assign the revisions to the string str['revs'] = frozenset(revs) def DoesRevisionSuperceed(filename, rev1, rev2): ''' Tells whether a revision superceeds another. This essentially means that the older revision is an ancestor of the newer one. This also returns True if the two revisions are the same. @param rev1: the revision that may be superceeding the other @param rev2: the revision that may be superceeded @return: True if rev1 superceeds rev2 or they're the same ''' if rev1 == rev2: return True # TODO: Add filename args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename] output_lines = _GetOutputLines(args) return rev2 in output_lines def NewestRevision(filename, rev1, rev2): ''' Returns which of two revisions is closest to the head of the repository. If none of them is the ancestor of the other, then we return either one. @param rev1: the first revision @param rev2: the second revision ''' if DoesRevisionSuperceed(filename, rev1, rev2): return rev1 return rev2
Python
''' Module which parses a string XML file. @author: Rodrigo Damazio ''' from xml.parsers.expat import ParserCreate import re #import xml.etree.ElementTree as ET class StringsParser(object): ''' Parser for string XML files. This object is not thread-safe and should be used for parsing a single file at a time, only. ''' def Parse(self, file): ''' Parses the given file and returns a dictionary mapping keys to an object with attributes for that key, such as the value, start/end line and explicit revisions. In addition to the standard XML format of the strings file, this parser supports an annotation inside comments, in one of these formats: <!-- KEEP_PARENT name="bla" --> <!-- KEEP_PARENT name="bla" rev="123456789012" --> Such an annotation indicates that we're explicitly inheriting form the master file (and the optional revision says that this decision is compatible with the master file up to that revision). @param file: the name of the file to parse ''' self._Reset() # Unfortunately expat is the only parser that will give us line numbers self._xml_parser = ParserCreate() self._xml_parser.StartElementHandler = self._StartElementHandler self._xml_parser.EndElementHandler = self._EndElementHandler self._xml_parser.CharacterDataHandler = self._CharacterDataHandler self._xml_parser.CommentHandler = self._CommentHandler file_obj = open(file) self._xml_parser.ParseFile(file_obj) file_obj.close() return self._all_strings def _Reset(self): self._currentString = None self._currentStringName = None self._currentStringValue = None self._all_strings = {} def _StartElementHandler(self, name, attrs): if name != 'string': return if 'name' not in attrs: return assert not self._currentString assert not self._currentStringName self._currentString = { 'startLine' : self._xml_parser.CurrentLineNumber, } if 'rev' in attrs: self._currentString['revs'] = [attrs['rev']] self._currentStringName = attrs['name'] self._currentStringValue = '' def _EndElementHandler(self, name): if name != 'string': return assert self._currentString assert self._currentStringName self._currentString['value'] = self._currentStringValue self._currentString['endLine'] = self._xml_parser.CurrentLineNumber self._all_strings[self._currentStringName] = self._currentString self._currentString = None self._currentStringName = None self._currentStringValue = None def _CharacterDataHandler(self, data): if not self._currentString: return self._currentStringValue += data _KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+' r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?' r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*', re.MULTILINE | re.DOTALL) def _CommentHandler(self, data): keep_parent_match = self._KEEP_PARENT_REGEX.match(data) if not keep_parent_match: return name = keep_parent_match.group('name') self._all_strings[name] = { 'keepParent' : True, 'startLine' : self._xml_parser.CurrentLineNumber, 'endLine' : self._xml_parser.CurrentLineNumber } rev = keep_parent_match.group('rev') if rev: self._all_strings[name]['revs'] = [rev]
Python
#!/usr/bin/python ''' Entry point for My Tracks i18n tool. @author: Rodrigo Damazio ''' import mytracks.files import mytracks.translate import mytracks.validate import sys def Usage(): print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0] print 'Commands are:' print ' cleanup' print ' translate' print ' validate' sys.exit(1) def Translate(languages): ''' Asks the user to interactively translate any missing or oudated strings from the files for the given languages. @param languages: the languages to translate ''' validator = mytracks.validate.Validator(languages) validator.Validate() missing = validator.missing_in_lang() outdated = validator.outdated_in_lang() for lang in languages: untranslated = missing[lang] + outdated[lang] if len(untranslated) == 0: continue translator = mytracks.translate.Translator(lang) translator.Translate(untranslated) def Validate(languages): ''' Computes and displays errors in the string files for the given languages. @param languages: the languages to compute for ''' validator = mytracks.validate.Validator(languages) validator.Validate() error_count = 0 if (validator.valid()): print 'All files OK' else: for lang, missing in validator.missing_in_master().iteritems(): print 'Missing in master, present in %s: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, missing in validator.missing_in_lang().iteritems(): print 'Missing in %s, present in master: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, outdated in validator.outdated_in_lang().iteritems(): print 'Outdated in %s: %s:' % (lang, str(outdated)) error_count = error_count + len(outdated) return error_count if __name__ == '__main__': argv = sys.argv argc = len(argv) if argc < 2: Usage() languages = mytracks.files.GetAllLanguageFiles() if argc == 3: langs = set(argv[2:]) if not langs.issubset(languages): raise 'Language(s) not found' # Filter just to the languages specified languages = dict((lang, lang_file) for lang, lang_file in languages.iteritems() if lang in langs or lang == 'en' ) cmd = argv[1] if cmd == 'translate': Translate(languages) elif cmd == 'validate': error_count = Validate(languages) else: Usage() error_count = 0 print '%d errors found.' % error_count
Python
''' Module which compares languague files to the master file and detects issues. @author: Rodrigo Damazio ''' import os from mytracks.parser import StringsParser import mytracks.history class Validator(object): def __init__(self, languages): ''' Builds a strings file validator. Params: @param languages: a dictionary mapping each language to its corresponding directory ''' self._langs = {} self._master = None self._language_paths = languages parser = StringsParser() for lang, lang_dir in languages.iteritems(): filename = os.path.join(lang_dir, 'strings.xml') parsed_file = parser.Parse(filename) mytracks.history.FillMercurialRevisions(filename, parsed_file) if lang == 'en': self._master = parsed_file else: self._langs[lang] = parsed_file self._Reset() def Validate(self): ''' Computes whether all the data in the files for the given languages is valid. ''' self._Reset() self._ValidateMissingKeys() self._ValidateOutdatedKeys() def valid(self): return (len(self._missing_in_master) == 0 and len(self._missing_in_lang) == 0 and len(self._outdated_in_lang) == 0) def missing_in_master(self): return self._missing_in_master def missing_in_lang(self): return self._missing_in_lang def outdated_in_lang(self): return self._outdated_in_lang def _Reset(self): # These are maps from language to string name list self._missing_in_master = {} self._missing_in_lang = {} self._outdated_in_lang = {} def _ValidateMissingKeys(self): ''' Computes whether there are missing keys on either side. ''' master_keys = frozenset(self._master.iterkeys()) for lang, file in self._langs.iteritems(): keys = frozenset(file.iterkeys()) missing_in_master = keys - master_keys missing_in_lang = master_keys - keys if len(missing_in_master) > 0: self._missing_in_master[lang] = missing_in_master if len(missing_in_lang) > 0: self._missing_in_lang[lang] = missing_in_lang def _ValidateOutdatedKeys(self): ''' Computers whether any of the language keys are outdated with relation to the master keys. ''' for lang, file in self._langs.iteritems(): outdated = [] for key, str in file.iteritems(): # Get all revisions that touched master and language files for this # string. master_str = self._master[key] master_revs = master_str['revs'] lang_revs = str['revs'] if not master_revs or not lang_revs: print 'WARNING: No revision for %s in %s' % (key, lang) continue master_file = os.path.join(self._language_paths['en'], 'strings.xml') lang_file = os.path.join(self._language_paths[lang], 'strings.xml') # Assume that the repository has a single head (TODO: check that), # and as such there is always one revision which superceeds all others. master_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2), master_revs) lang_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2), lang_revs) # If the master version is newer than the lang version if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev): outdated.append(key) if len(outdated) > 0: self._outdated_in_lang[lang] = outdated
Python
''' Module for dealing with resource files (but not their contents). @author: Rodrigo Damazio ''' import os.path from glob import glob import re MYTRACKS_RES_DIR = 'MyTracks/res' ANDROID_MASTER_VALUES = 'values' ANDROID_VALUES_MASK = 'values-*' def GetMyTracksDir(): ''' Returns the directory in which the MyTracks directory is located. ''' path = os.getcwd() while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)): if path == '/': raise 'Not in My Tracks project' # Go up one level path = os.path.split(path)[0] return path def GetAllLanguageFiles(): ''' Returns a mapping from all found languages to their respective directories. ''' mytracks_path = GetMyTracksDir() res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK) language_dirs = glob(res_dir) master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES) if len(language_dirs) == 0: raise 'No languages found!' if not os.path.isdir(master_dir): raise 'Couldn\'t find master file' language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs] language_tuples.append(('en', master_dir)) return dict(language_tuples)
Python
#/usr/bin/env python from optparse import OptionParser import httplib, urllib import os, fnmatch, shutil, re usage = """usage: %prog [options] command Commands: build build the script debug print the header to include js files clean remove any built files """ parser = OptionParser(usage=usage) parser.add_option('-l', '--level', dest='level', default='SIMPLE_OPTIMIZATIONS', help='Closure compilation level [WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, \ ADVANCED_OPTIMIZATIONS]') UTILS = os.path.dirname(os.path.relpath(__file__)) PREFIX = os.path.join(UTILS,'..') SRC_ROOT= os.path.join(PREFIX,'src') BUILD_ROOT = os.path.join(PREFIX,'build') INDEX = os.path.join(PREFIX,'index.html') BUILD_NAME = 'DAT.GUI' ALL_JS = ['DAT.GUI.js','DAT.GUI'] LICENSE = """/** * dat.gui Javascript Controller Library * http://dataarts.github.com/dat.gui * * Copyright 2011 Data Arts Team, Google Creative Lab * * 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 */ """ def flatten(l, ltypes=(list, tuple)): ltype = type(l) l = list(l) i = 0 while i < len(l): while isinstance(l[i], ltypes): if not l[i]: l.pop(i) i -= 1 break else: l[i:i + 1] = l[i] i += 1 return ltype(l) def expand(path, globby): matches = [] path = path.split('.') path.insert(0,SRC_ROOT) filename = "%s.%s"%(path[-2],path[-1]) if fnmatch.fnmatch(filename, globby): tmppath = os.path.join(*(path[:-1]+[filename])) if os.path.exists(tmppath): path[-1] = filename else: path = path[:-2]+[filename] path = os.path.join(*path) if os.path.isdir(path): for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, globby): matches.append(os.path.join(root, filename)) else: matches.append(path) return matches def unique(seq, idfun=None): """Ordered uniquify function if in 2.7 use: OrderedDict.fromkeys(seq).keys() """ if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result def source_list(src, globby='*.js'): def expander(f): return expand(f,globby) return unique(flatten(map(expander, src))) def compile(code): params = urllib.urlencode([ ('js_code', code), ('compilation_level', options.level), ('output_format', 'text'), ('output_info', 'compiled_code'), ]) headers = { 'Content-type': 'application/x-www-form-urlencoded' } conn = httplib.HTTPConnection('closure-compiler.appspot.com') conn.request('POST', '/compile', params, headers) response = conn.getresponse() data = response.read() conn.close() return data def bytes_to_kb(b,digits=1): return round(0.0009765625 * b, digits) def clean(): if os.path.exists(BUILD_ROOT): shutil.rmtree(BUILD_ROOT) print('DONE. Removed %s'%(BUILD_ROOT,)) else: print('DONE. Nothing to clean') def build(jssrc, csssrc=list([''])): if not os.path.exists(BUILD_ROOT): os.makedirs(BUILD_ROOT) if csssrc: cssfiles = source_list(csssrc, '*.css') print('CSS files being compiled: ', cssfiles) css = '\n'.join([open(f).read() for f in cssfiles]) css = re.sub(r'[ \t\n\r]+',' ',css) jsfiles = source_list(jssrc, '*.js') print('JS files being compiled: ', jsfiles) code = '\n'.join([open(f).read() for f in jsfiles]) if csssrc: code += """DAT.GUI.inlineCSS = '%s';\n"""%(css,) outpath = os.path.join(BUILD_ROOT, BUILD_NAME+'.js') with open(outpath,'w') as f: f.write(LICENSE) f.write(code) compiled = compile(code) outpathmin = os.path.join(BUILD_ROOT, BUILD_NAME+'.min.js') with open(outpathmin,'w') as f: f.write(LICENSE) f.write(compiled) size = bytes_to_kb(os.path.getsize(outpath)) sizemin = bytes_to_kb(os.path.getsize(outpathmin)) with open(INDEX,'r') as f: index = f.read() with open(INDEX,'w') as f: index = re.sub(r'<small id=\'buildsize\'>\[[0-9.]+kb\]','<small id=\'buildsize\'>[%skb]'%(size,),index) index = re.sub(r'<small id=\'buildsizemin\'>\[[0-9.]+kb\]','<small id=\'buildsizemin\'>[%skb]'%(sizemin,),index) f.write(index) print('DONE. Built files in %s.'%(BUILD_ROOT,)) def debug(jssrc, csssrc=list([''])): head = "" files = source_list(csssrc, '*.css') for f in files: f = f.replace(PREFIX+'/','') head += '<link href="%s" media="screen" rel="stylesheet" type="text/css"/>\n'%(f,) files = source_list(jssrc, '*.js') for f in files: f = f.replace(PREFIX+'/','') head += '<script type="text/javascript" src="%s"></script>\n'%(f,) print(head) if __name__ == '__main__': global options (options, args) = parser.parse_args() if len(args) != 1: print(parser.usage) exit(0) command = args[0] if command == 'build': build(ALL_JS) elif command == 'clean': clean() elif command == 'debug': debug(ALL_JS)
Python
#!/usr/bin/env python USAGE = '''Usage: testasciidoc.py [OPTIONS] COMMAND Run AsciiDoc conformance tests specified in configuration FILE. Commands: list List tests run [NUMBER] [BACKEND] Execute tests update [NUMBER] [BACKEND] Regenerate and update test data Options: -f, --conf-file=CONF_FILE Use configuration file CONF_FILE (default configuration file is testasciidoc.conf in testasciidoc.py directory) --force Update all test data overwriting existing data''' __version__ = '0.1.1' __copyright__ = 'Copyright (C) 2009 Stuart Rackham' import os, sys, re, StringIO, difflib import asciidocapi BACKENDS = ('html4','xhtml11','docbook','wordpress','html5') # Default backends. BACKEND_EXT = {'html4':'.html', 'xhtml11':'.html', 'docbook':'.xml', 'wordpress':'.html','slidy':'.html','html5':'.html'} def iif(condition, iftrue, iffalse=None): """ Immediate if c.f. ternary ?: operator. False value defaults to '' if the true value is a string. False value defaults to 0 if the true value is a number. """ if iffalse is None: if isinstance(iftrue, basestring): iffalse = '' if type(iftrue) in (int, float): iffalse = 0 if condition: return iftrue else: return iffalse def message(msg=''): print >>sys.stderr, msg def strip_end(lines): """ Strip blank strings from the end of list of strings. """ for i in range(len(lines)-1,-1,-1): if not lines[i]: del lines[i] else: break def normalize_data(lines): """ Strip comments and trailing blank strings from lines. """ result = [ s for s in lines if not s.startswith('#') ] strip_end(result) return result class AsciiDocTest(object): def __init__(self): self.number = None # Test number (1..). self.name = '' # Optional test name. self.title = '' # Optional test name. self.description = [] # List of lines followoing title. self.source = None # AsciiDoc test source file name. self.options = [] self.attributes = {} self.backends = BACKENDS self.datadir = None # Where output files are stored. self.disabled = False def backend_filename(self, backend): """ Return the path name of the backend output file that is generated from the test name and output file type. """ return '%s-%s%s' % ( os.path.normpath(os.path.join(self.datadir, self.name)), backend, BACKEND_EXT[backend]) def parse(self, lines, confdir, datadir): """ Parse conf file test section from list of text lines. """ self.__init__() self.confdir = confdir self.datadir = datadir lines = Lines(lines) while not lines.eol(): l = lines.read_until(r'^%') if l: if not l[0].startswith('%'): if l[0][0] == '!': self.disabled = True self.title = l[0][1:] else: self.title = l[0] self.description = l[1:] continue reo = re.match(r'^%\s*(?P<directive>[\w_-]+)', l[0]) if not reo: raise (ValueError, 'illegal directive: %s' % l[0]) directive = reo.groupdict()['directive'] data = normalize_data(l[1:]) if directive == 'source': if data: self.source = os.path.normpath(os.path.join( self.confdir, os.path.normpath(data[0]))) elif directive == 'options': self.options = eval(' '.join(data)) for i,v in enumerate(self.options): if isinstance(v, basestring): self.options[i] = (v,None) elif directive == 'attributes': self.attributes = eval(' '.join(data)) elif directive == 'backends': self.backends = eval(' '.join(data)) elif directive == 'name': self.name = data[0].strip() else: raise (ValueError, 'illegal directive: %s' % l[0]) if not self.title: self.title = self.source if not self.name: self.name = os.path.basename(os.path.splitext(self.source)[0]) def is_missing(self, backend): """ Returns True if there is no output test data file for backend. """ return not os.path.isfile(self.backend_filename(backend)) def is_missing_or_outdated(self, backend): """ Returns True if the output test data file is missing or out of date. """ return self.is_missing(backend) or ( os.path.getmtime(self.source) > os.path.getmtime(self.backend_filename(backend))) def get_expected(self, backend): """ Return expected test data output for backend. """ f = open(self.backend_filename(backend)) try: result = f.readlines() # Strip line terminators. result = [ s.rstrip() for s in result ] finally: f.close() return result def generate_expected(self, backend): """ Generate and return test data output for backend. """ asciidoc = asciidocapi.AsciiDocAPI() asciidoc.options.values = self.options asciidoc.attributes = self.attributes infile = self.source outfile = StringIO.StringIO() asciidoc.execute(infile, outfile, backend) return outfile.getvalue().splitlines() def update_expected(self, backend): """ Generate and write backend data. """ lines = self.generate_expected(backend) if not os.path.isdir(self.datadir): print('CREATING: %s' % self.datadir) os.mkdir(self.datadir) f = open(self.backend_filename(backend),'w+') try: print('WRITING: %s' % f.name) f.writelines([ s + os.linesep for s in lines]) finally: f.close() def update(self, backend=None, force=False): """ Regenerate and update expected test data outputs. """ if backend is None: backends = self.backends else: backends = [backend] for backend in backends: if force or self.is_missing_or_outdated(backend): self.update_expected(backend) def run(self, backend=None): """ Execute test. Return True if test passes. """ if backend is None: backends = self.backends else: backends = [backend] result = True # Assume success. self.passed = self.failed = self.skipped = 0 print('%d: %s' % (self.number, self.title)) if self.source and os.path.isfile(self.source): print('SOURCE: asciidoc: %s' % self.source) for backend in backends: fromfile = self.backend_filename(backend) if not self.is_missing(backend): expected = self.get_expected(backend) strip_end(expected) got = self.generate_expected(backend) strip_end(got) lines = [] for line in difflib.unified_diff(got, expected, n=0): lines.append(line) if lines: result = False self.failed +=1 lines = lines[3:] print('FAILED: %s: %s' % (backend, fromfile)) message('+++ %s' % fromfile) message('--- got') for line in lines: message(line) message() else: self.passed += 1 print('PASSED: %s: %s' % (backend, fromfile)) else: self.skipped += 1 print('SKIPPED: %s: %s' % (backend, fromfile)) else: self.skipped += len(backends) if self.source: msg = 'MISSING: %s' % self.source else: msg = 'NO ASCIIDOC SOURCE FILE SPECIFIED' print(msg) print('') return result class AsciiDocTests(object): def __init__(self, conffile): """ Parse configuration file. """ self.conffile = os.path.normpath(conffile) # All file names are relative to configuration file directory. self.confdir = os.path.dirname(self.conffile) self.datadir = self.confdir # Default expected files directory. self.tests = [] # List of parsed AsciiDocTest objects. self.globals = {} f = open(self.conffile) try: lines = Lines(f.readlines()) finally: f.close() first = True while not lines.eol(): s = lines.read_until(r'^%+$') if s: # Optional globals precede all tests. if first and re.match(r'^%\s*globals$',s[0]): self.globals = eval(' '.join(normalize_data(s[1:]))) if 'datadir' in self.globals: self.datadir = os.path.join( self.confdir, os.path.normpath(self.globals['datadir'])) else: test = AsciiDocTest() test.parse(s[1:], self.confdir, self.datadir) self.tests.append(test) test.number = len(self.tests) first = False def run(self, number=None, backend=None): """ Run all tests. If number is specified run test number (1..). """ self.passed = self.failed = self.skipped = 0 for test in self.tests: if (not test.disabled or number) and (not number or number == test.number) and (not backend or backend in test.backends): test.run(backend) self.passed += test.passed self.failed += test.failed self.skipped += test.skipped if self.passed > 0: print('TOTAL PASSED: %s' % self.passed) if self.failed > 0: print('TOTAL FAILED: %s' % self.failed) if self.skipped > 0: print('TOTAL SKIPPED: %s' % self.skipped) def update(self, number=None, backend=None, force=False): """ Regenerate expected test data and update configuratio file. """ for test in self.tests: if (not test.disabled or number) and (not number or number == test.number): test.update(backend, force=force) def list(self): """ Lists tests to stdout. """ for test in self.tests: print '%d: %s%s' % (test.number, iif(test.disabled,'!'), test.title) class Lines(list): """ A list of strings. Adds eol() and read_until() to list type. """ def __init__(self, lines): super(Lines, self).__init__() self.extend([s.rstrip() for s in lines]) self.pos = 0 def eol(self): return self.pos >= len(self) def read_until(self, regexp): """ Return a list of lines from current position up until the next line matching regexp. Advance position to matching line. """ result = [] if not self.eol(): result.append(self[self.pos]) self.pos += 1 while not self.eol(): if re.match(regexp, self[self.pos]): break result.append(self[self.pos]) self.pos += 1 return result def usage(msg=None): if msg: message(msg + '\n') message(USAGE) if __name__ == '__main__': # Process command line options. import getopt try: opts,args = getopt.getopt(sys.argv[1:], 'f:', ['force']) except getopt.GetoptError: usage('illegal command options') sys.exit(1) if len(args) == 0: usage() sys.exit(1) conffile = os.path.join(os.path.dirname(sys.argv[0]), 'testasciidoc.conf') force = False for o,v in opts: if o == '--force': force = True if o in ('-f','--conf-file'): conffile = v if not os.path.isfile(conffile): message('missing CONF_FILE: %s' % conffile) sys.exit(1) tests = AsciiDocTests(conffile) cmd = args[0] number = None backend = None for arg in args[1:3]: try: number = int(arg) except ValueError: backend = arg if backend and backend not in BACKENDS: message('illegal BACKEND: %s' % backend) sys.exit(1) if number is not None and number not in range(1, len(tests.tests)+1): message('illegal test NUMBER: %d' % number) sys.exit(1) if cmd == 'run': tests.run(number, backend) if tests.failed: exit(1) elif cmd == 'update': tests.update(number, backend, force=force) elif cmd == 'list': tests.list() else: usage('illegal COMMAND: %s' % cmd)
Python
#!/usr/bin/env python """ asciidocapi - AsciiDoc API wrapper class. The AsciiDocAPI class provides an API for executing asciidoc. Minimal example compiles `mydoc.txt` to `mydoc.html`: import asciidocapi asciidoc = asciidocapi.AsciiDocAPI() asciidoc.execute('mydoc.txt') - Full documentation in asciidocapi.txt. - See the doctests below for more examples. Doctests: 1. Check execution: >>> import StringIO >>> infile = StringIO.StringIO('Hello *{author}*') >>> outfile = StringIO.StringIO() >>> asciidoc = AsciiDocAPI() >>> asciidoc.options('--no-header-footer') >>> asciidoc.attributes['author'] = 'Joe Bloggs' >>> asciidoc.execute(infile, outfile, backend='html4') >>> print outfile.getvalue() <p>Hello <strong>Joe Bloggs</strong></p> >>> asciidoc.attributes['author'] = 'Bill Smith' >>> infile = StringIO.StringIO('Hello _{author}_') >>> outfile = StringIO.StringIO() >>> asciidoc.execute(infile, outfile, backend='docbook') >>> print outfile.getvalue() <simpara>Hello <emphasis>Bill Smith</emphasis></simpara> 2. Check error handling: >>> import StringIO >>> asciidoc = AsciiDocAPI() >>> infile = StringIO.StringIO('---------') >>> outfile = StringIO.StringIO() >>> asciidoc.execute(infile, outfile) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "asciidocapi.py", line 189, in execute raise AsciiDocError(self.messages[-1]) AsciiDocError: ERROR: <stdin>: line 1: [blockdef-listing] missing closing delimiter Copyright (C) 2009 Stuart Rackham. Free use of this software is granted under the terms of the GNU General Public License (GPL). """ import sys,os,re,imp API_VERSION = '0.1.2' MIN_ASCIIDOC_VERSION = '8.4.1' # Minimum acceptable AsciiDoc version. def find_in_path(fname, path=None): """ Find file fname in paths. Return None if not found. """ if path is None: path = os.environ.get('PATH', '') for dir in path.split(os.pathsep): fpath = os.path.join(dir, fname) if os.path.isfile(fpath): return fpath else: return None class AsciiDocError(Exception): pass class Options(object): """ Stores asciidoc(1) command options. """ def __init__(self, values=[]): self.values = values[:] def __call__(self, name, value=None): """Shortcut for append method.""" self.append(name, value) def append(self, name, value=None): if type(value) in (int,float): value = str(value) self.values.append((name,value)) class Version(object): """ Parse and compare AsciiDoc version numbers. Instance attributes: string: String version number '<major>.<minor>[.<micro>][suffix]'. major: Integer major version number. minor: Integer minor version number. micro: Integer micro version number. suffix: Suffix (begins with non-numeric character) is ignored when comparing. Doctest examples: >>> Version('8.2.5') < Version('8.3 beta 1') True >>> Version('8.3.0') == Version('8.3. beta 1') True >>> Version('8.2.0') < Version('8.20') True >>> Version('8.20').major 8 >>> Version('8.20').minor 20 >>> Version('8.20').micro 0 >>> Version('8.20').suffix '' >>> Version('8.20 beta 1').suffix 'beta 1' """ def __init__(self, version): self.string = version reo = re.match(r'^(\d+)\.(\d+)(\.(\d+))?\s*(.*?)\s*$', self.string) if not reo: raise ValueError('invalid version number: %s' % self.string) groups = reo.groups() self.major = int(groups[0]) self.minor = int(groups[1]) self.micro = int(groups[3] or '0') self.suffix = groups[4] or '' def __cmp__(self, other): result = cmp(self.major, other.major) if result == 0: result = cmp(self.minor, other.minor) if result == 0: result = cmp(self.micro, other.micro) return result class AsciiDocAPI(object): """ AsciiDoc API class. """ def __init__(self, asciidoc_py=None): """ Locate and import asciidoc.py. Initialize instance attributes. """ self.options = Options() self.attributes = {} self.messages = [] # Search for the asciidoc command file. # Try ASCIIDOC_PY environment variable first. cmd = os.environ.get('ASCIIDOC_PY') if cmd: if not os.path.isfile(cmd): raise AsciiDocError('missing ASCIIDOC_PY file: %s' % cmd) elif asciidoc_py: # Next try path specified by caller. cmd = asciidoc_py if not os.path.isfile(cmd): raise AsciiDocError('missing file: %s' % cmd) else: # Try shell search paths. for fname in ['asciidoc.py','asciidoc.pyc','asciidoc']: cmd = find_in_path(fname) if cmd: break else: # Finally try current working directory. for cmd in ['asciidoc.py','asciidoc.pyc','asciidoc']: if os.path.isfile(cmd): break else: raise AsciiDocError('failed to locate asciidoc') self.cmd = os.path.realpath(cmd) self.__import_asciidoc() def __import_asciidoc(self, reload=False): ''' Import asciidoc module (script or compiled .pyc). See http://groups.google.com/group/asciidoc/browse_frm/thread/66e7b59d12cd2f91 for an explanation of why a seemingly straight-forward job turned out quite complicated. ''' if os.path.splitext(self.cmd)[1] in ['.py','.pyc']: sys.path.insert(0, os.path.dirname(self.cmd)) try: try: if reload: import __builtin__ # Because reload() is shadowed. __builtin__.reload(self.asciidoc) else: import asciidoc self.asciidoc = asciidoc except ImportError: raise AsciiDocError('failed to import ' + self.cmd) finally: del sys.path[0] else: # The import statement can only handle .py or .pyc files, have to # use imp.load_source() for scripts with other names. try: imp.load_source('asciidoc', self.cmd) import asciidoc self.asciidoc = asciidoc except ImportError: raise AsciiDocError('failed to import ' + self.cmd) if Version(self.asciidoc.VERSION) < Version(MIN_ASCIIDOC_VERSION): raise AsciiDocError( 'asciidocapi %s requires asciidoc %s or better' % (API_VERSION, MIN_ASCIIDOC_VERSION)) def execute(self, infile, outfile=None, backend=None): """ Compile infile to outfile using backend format. infile can outfile can be file path strings or file like objects. """ self.messages = [] opts = Options(self.options.values) if outfile is not None: opts('--out-file', outfile) if backend is not None: opts('--backend', backend) for k,v in self.attributes.items(): if v == '' or k[-1] in '!@': s = k elif v is None: # A None value undefines the attribute. s = k + '!' else: s = '%s=%s' % (k,v) opts('--attribute', s) args = [infile] # The AsciiDoc command was designed to process source text then # exit, there are globals and statics in asciidoc.py that have # to be reinitialized before each run -- hence the reload. self.__import_asciidoc(reload=True) try: try: self.asciidoc.execute(self.cmd, opts.values, args) finally: self.messages = self.asciidoc.messages[:] except SystemExit, e: if e.code: raise AsciiDocError(self.messages[-1]) if __name__ == "__main__": """ Run module doctests. """ import doctest options = doctest.NORMALIZE_WHITESPACE + doctest.ELLIPSIS doctest.testmod(optionflags=options)
Python
#!/usr/bin/env python ''' a2x - A toolchain manager for AsciiDoc (converts Asciidoc text files to other file formats) Copyright: Stuart Rackham (c) 2009 License: MIT Email: srackham@gmail.com ''' import os import fnmatch import HTMLParser import re import shutil import subprocess import sys import traceback import urlparse import zipfile import xml.dom.minidom import mimetypes PROG = os.path.basename(os.path.splitext(__file__)[0]) VERSION = '8.6.5' # AsciiDoc global configuration file directory. # NOTE: CONF_DIR is "fixed up" by Makefile -- don't rename or change syntax. CONF_DIR = '/etc/asciidoc' ###################################################################### # Default configuration file parameters. ###################################################################### # Optional environment variable dictionary passed to # executing programs. If set to None the existing # environment is used. ENV = None # External executables. ASCIIDOC = 'asciidoc' XSLTPROC = 'xsltproc' DBLATEX = 'dblatex' # pdf generation. FOP = 'fop' # pdf generation (--fop option). W3M = 'w3m' # text generation. LYNX = 'lynx' # text generation (if no w3m). XMLLINT = 'xmllint' # Set to '' to disable. EPUBCHECK = 'epubcheck' # Set to '' to disable. # External executable default options. ASCIIDOC_OPTS = '' DBLATEX_OPTS = '' FOP_OPTS = '' XSLTPROC_OPTS = '' ###################################################################### # End of configuration file parameters. ###################################################################### ##################################################################### # Utility functions ##################################################################### OPTIONS = None # These functions read verbose and dry_run command options. def errmsg(msg): sys.stderr.write('%s: %s\n' % (PROG,msg)) def warning(msg): errmsg('WARNING: %s' % msg) def infomsg(msg): print '%s: %s' % (PROG,msg) def die(msg, exit_code=1): errmsg('ERROR: %s' % msg) sys.exit(exit_code) def trace(): """Print traceback to stderr.""" errmsg('-'*60) traceback.print_exc(file=sys.stderr) errmsg('-'*60) def verbose(msg): if OPTIONS.verbose or OPTIONS.dry_run: infomsg(msg) class AttrDict(dict): """ Like a dictionary except values can be accessed as attributes i.e. obj.foo can be used in addition to obj['foo']. If self._default has been set then it will be returned if a non-existant attribute is accessed (instead of raising an AttributeError). """ def __getattr__(self, key): try: return self[key] except KeyError, k: if self.has_key('_default'): return self['_default'] else: raise AttributeError, k def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError, k: raise AttributeError, k def __repr__(self): return '<AttrDict ' + dict.__repr__(self) + '>' def __getstate__(self): return dict(self) def __setstate__(self,value): for k,v in value.items(): self[k]=v def isexecutable(file_name): return os.path.isfile(file_name) and os.access(file_name, os.X_OK) def find_executable(file_name): ''' Search for executable file_name in the system PATH. Return full path name or None if not found. ''' def _find_executable(file_name): if os.path.split(file_name)[0] != '': # file_name includes directory so don't search path. if not isexecutable(file_name): return None else: return file_name for p in os.environ.get('PATH', os.defpath).split(os.pathsep): f = os.path.join(p, file_name) if isexecutable(f): return os.path.realpath(f) return None if os.name == 'nt' and os.path.splitext(file_name)[1] == '': for ext in ('.cmd','.bat','.exe'): result = _find_executable(file_name + ext) if result: break else: result = _find_executable(file_name) return result def shell_cd(path): verbose('chdir %s' % path) if not OPTIONS.dry_run: os.chdir(path) def shell_makedirs(path): if os.path.isdir(path): return verbose('creating %s' % path) if not OPTIONS.dry_run: os.makedirs(path) def shell_copy(src, dst): verbose('copying "%s" to "%s"' % (src,dst)) if not OPTIONS.dry_run: shutil.copy(src, dst) def shell_rm(path): if not os.path.exists(path): return verbose('deleting %s' % path) if not OPTIONS.dry_run: os.unlink(path) def shell_rmtree(path): if not os.path.isdir(path): return verbose('deleting %s' % path) if not OPTIONS.dry_run: shutil.rmtree(path) def shell(cmd, raise_error=True): ''' Execute command cmd in shell and return resulting subprocess.Popen object. If raise_error is True then a non-zero return terminates the application. ''' if os.name == 'nt': # TODO: this is probably unnecessary, see: # http://groups.google.com/group/asciidoc/browse_frm/thread/9442ee0c419f1242 # Windows doesn't like running scripts directly so explicitly # specify python interpreter. # Extract first (quoted or unquoted) argument. mo = re.match(r'^\s*"\s*(?P<arg0>[^"]+)\s*"', cmd) if not mo: mo = re.match(r'^\s*(?P<arg0>[^ ]+)', cmd) if mo.group('arg0').endswith('.py'): cmd = 'python ' + cmd # Remove redundant quoting -- this is not just costmetic, quoting seems to # dramatically decrease the allowed command length in Windows XP. cmd = re.sub(r'"([^ ]+?)"', r'\1', cmd) verbose('executing: %s' % cmd) if OPTIONS.dry_run: return if OPTIONS.verbose: stdout = stderr = None else: stdout = stderr = subprocess.PIPE try: popen = subprocess.Popen(cmd, stdout=stdout, stderr=stderr, shell=True, env=ENV) except OSError, e: die('failed: %s: %s' % (cmd, e)) popen.wait() if popen.returncode != 0 and raise_error: die('%s returned non-zero exit status %d' % (cmd, popen.returncode)) return popen def find_resources(files, tagname, attrname, filter=None): ''' Search all files and return a list of local URIs from attrname attribute values in tagname tags. Handles HTML open and XHTML closed tags. Non-local URIs are skipped. files can be a file name or a list of file names. The filter function takes a dictionary of tag attributes and returns True if the URI is to be included. ''' class FindResources(HTMLParser.HTMLParser): # Nested parser class shares locals with enclosing function. def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) def handle_starttag(self, tag, attrs): attrs = dict(attrs) if tag == tagname and (filter is None or filter(attrs)): # Accept only local URIs. uri = urlparse.urlparse(attrs[attrname]) if uri[0] in ('','file') and not uri[1] and uri[2]: result.append(uri[2]) if isinstance(files, str): files = [files] result = [] for f in files: verbose('finding resources in: %s' % f) if OPTIONS.dry_run: continue parser = FindResources() # HTMLParser has problems with non-ASCII strings. # See http://bugs.python.org/issue3932 mo = re.search(r'^<\?xml.* encoding="(.*?)"', open(f).readline()) if mo: encoding = mo.group(1) parser.feed(open(f).read().decode(encoding)) else: parser.feed(open(f).read()) parser.close() result = list(set(result)) # Drop duplicate values. result.sort() return result # NOT USED. def copy_files(files, src_dir, dst_dir): ''' Copy list of relative file names from src_dir to dst_dir. ''' for f in files: f = os.path.normpath(f) if os.path.isabs(f): continue src = os.path.join(src_dir, f) dst = os.path.join(dst_dir, f) if not os.path.exists(dst): if not os.path.isfile(src): warning('missing file: %s' % src) continue dstdir = os.path.dirname(dst) shell_makedirs(dstdir) shell_copy(src, dst) def find_files(path, pattern): ''' Return list of file names matching pattern in directory path. ''' result = [] for (p,dirs,files) in os.walk(path): for f in files: if fnmatch.fnmatch(f, pattern): result.append(os.path.normpath(os.path.join(p,f))) return result def exec_xsltproc(xsl_file, xml_file, dst_dir, opts = ''): cwd = os.getcwd() shell_cd(dst_dir) try: shell('"%s" %s "%s" "%s"' % (XSLTPROC, opts, xsl_file, xml_file)) finally: shell_cd(cwd) def get_source_options(asciidoc_file): ''' Look for a2x command options in AsciiDoc source file. Limitation: options cannot contain double-quote characters. ''' def parse_options(): # Parse options to result sequence. inquotes = False opt = '' for c in options: if c == '"': if inquotes: result.append(opt) opt = '' inquotes = False else: inquotes = True elif c == ' ': if inquotes: opt += c elif opt: result.append(opt) opt = '' else: opt += c if opt: result.append(opt) result = [] if os.path.isfile(asciidoc_file): options = '' for line in open(asciidoc_file): mo = re.search(r'^//\s*a2x:', line) if mo: options += ' ' + line[mo.end():].strip() parse_options() return result ##################################################################### # Application class ##################################################################### class A2X(AttrDict): ''' a2x options and conversion functions. ''' def execute(self): ''' Process a2x command. ''' self.process_options() # Append configuration file options. self.asciidoc_opts += ' ' + ASCIIDOC_OPTS self.dblatex_opts += ' ' + DBLATEX_OPTS self.fop_opts += ' ' + FOP_OPTS self.xsltproc_opts += ' ' + XSLTPROC_OPTS # Execute to_* functions. self.__getattribute__('to_'+self.format)() if not (self.keep_artifacts or self.format == 'docbook' or self.skip_asciidoc): shell_rm(self.dst_path('.xml')) def load_conf(self): ''' Load a2x configuration file from default locations and --conf-file option. ''' global ASCIIDOC CONF_FILE = 'a2x.conf' a2xdir = os.path.dirname(os.path.realpath(__file__)) conf_files = [] # From a2x.py directory. conf_files.append(os.path.join(a2xdir, CONF_FILE)) # If the asciidoc executable and conf files are in the a2x directory # then use the local copy of asciidoc and skip the global a2x conf. asciidoc = os.path.join(a2xdir, 'asciidoc.py') asciidoc_conf = os.path.join(a2xdir, 'asciidoc.conf') if os.path.isfile(asciidoc) and os.path.isfile(asciidoc_conf): self.asciidoc = asciidoc else: self.asciidoc = None # From global conf directory. conf_files.append(os.path.join(CONF_DIR, CONF_FILE)) # From $HOME directory. home_dir = os.environ.get('HOME') if home_dir is not None: conf_files.append(os.path.join(home_dir, '.asciidoc', CONF_FILE)) # From --conf-file option. if self.conf_file is not None: if not os.path.isfile(self.conf_file): die('missing configuration file: %s' % self.conf_file) conf_files.append(self.conf_file) # From --xsl-file option. if self.xsl_file is not None: if not os.path.isfile(self.xsl_file): die('missing XSL file: %s' % self.xsl_file) self.xsl_file = os.path.abspath(self.xsl_file) # Load ordered files. for f in conf_files: if os.path.isfile(f): verbose('loading conf file: %s' % f) execfile(f, globals()) # If asciidoc is not local to a2x then search the PATH. if not self.asciidoc: self.asciidoc = find_executable(ASCIIDOC) if not self.asciidoc: die('unable to find asciidoc: %s' % ASCIIDOC) def process_options(self): ''' Validate and command options and set defaults. ''' if not os.path.isfile(self.asciidoc_file): die('missing SOURCE_FILE: %s' % self.asciidoc_file) self.asciidoc_file = os.path.abspath(self.asciidoc_file) if not self.destination_dir: self.destination_dir = os.path.dirname(self.asciidoc_file) else: if not os.path.isdir(self.destination_dir): die('missing --destination-dir: %s' % self.destination_dir) self.destination_dir = os.path.abspath(self.destination_dir) self.resource_dirs = [] self.resource_files = [] if self.resource_manifest: if not os.path.isfile(self.resource_manifest): die('missing --resource-manifest: %s' % self.resource_manifest) for r in open(self.resource_manifest): self.resources.append(r.strip()) for r in self.resources: r = os.path.expanduser(r) r = os.path.expandvars(r) if r.endswith(('/','\\')): if os.path.isdir(r): self.resource_dirs.append(r) else: die('missing resource directory: %s' % r) elif os.path.isdir(r): self.resource_dirs.append(r) elif r.startswith('.') and '=' in r: ext, mimetype = r.split('=') mimetypes.add_type(mimetype, ext) else: self.resource_files.append(r) for p in (os.path.dirname(self.asciidoc), CONF_DIR): for d in ('images','stylesheets'): d = os.path.join(p,d) if os.path.isdir(d): self.resource_dirs.append(d) verbose('resource files: %s' % self.resource_files) verbose('resource directories: %s' % self.resource_dirs) if not self.doctype and self.format == 'manpage': self.doctype = 'manpage' if self.doctype: self.asciidoc_opts += ' --doctype %s' % self.doctype for attr in self.attributes: self.asciidoc_opts += ' --attribute "%s"' % attr # self.xsltproc_opts += ' --nonet' if self.verbose: self.asciidoc_opts += ' --verbose' self.dblatex_opts += ' -V' if self.icons or self.icons_dir: params = [ 'callout.graphics 1', 'navig.graphics 1', 'admon.textlabel 0', 'admon.graphics 1', ] if self.icons_dir: params += [ 'admon.graphics.path "%s/"' % self.icons_dir, 'callout.graphics.path "%s/callouts/"' % self.icons_dir, 'navig.graphics.path "%s/"' % self.icons_dir, ] else: params = [ 'callout.graphics 0', 'navig.graphics 0', 'admon.textlabel 1', 'admon.graphics 0', ] if self.stylesheet: params += ['html.stylesheet "%s"' % self.stylesheet] if self.format == 'htmlhelp': params += ['htmlhelp.chm "%s"' % self.basename('.chm'), 'htmlhelp.hhp "%s"' % self.basename('.hhp'), 'htmlhelp.hhk "%s"' % self.basename('.hhk'), 'htmlhelp.hhc "%s"' % self.basename('.hhc')] if self.doctype == 'book': params += ['toc.section.depth 1'] # Books are chunked at chapter level. params += ['chunk.section.depth 0'] for o in params: if o.split()[0]+' ' not in self.xsltproc_opts: self.xsltproc_opts += ' --stringparam ' + o if self.fop_opts: self.fop = True if os.path.splitext(self.asciidoc_file)[1].lower() == '.xml': self.skip_asciidoc = True else: self.skip_asciidoc = False def dst_path(self, ext): ''' Return name of file or directory in the destination directory with the same name as the asciidoc source file but with extension ext. ''' return os.path.join(self.destination_dir, self.basename(ext)) def basename(self, ext): ''' Return the base name of the asciidoc source file but with extension ext. ''' return os.path.basename(os.path.splitext(self.asciidoc_file)[0]) + ext def asciidoc_conf_file(self, path): ''' Return full path name of file in asciidoc configuration files directory. Search first the directory containing the asciidoc executable then the global configuration file directory. ''' f = os.path.join(os.path.dirname(self.asciidoc), path) if not os.path.isfile(f): f = os.path.join(CONF_DIR, path) if not os.path.isfile(f): die('missing configuration file: %s' % f) return os.path.normpath(f) def xsl_stylesheet(self, file_name=None): ''' Return full path name of file in asciidoc docbook-xsl configuration directory. If an XSL file was specified with the --xsl-file option then it is returned. ''' if self.xsl_file is not None: return self.xsl_file if not file_name: file_name = self.format + '.xsl' return self.asciidoc_conf_file(os.path.join('docbook-xsl', file_name)) def copy_resources(self, html_files, src_dir, dst_dir, resources=[]): ''' Search html_files for images and CSS resource URIs (html_files can be a list of file names or a single file name). Copy them from the src_dir to the dst_dir. If not found in src_dir then recursively search all specified resource directories. Optional additional resources files can be passed in the resources list. ''' resources = resources[:] resources += find_resources(html_files, 'link', 'href', lambda attrs: attrs.get('type') == 'text/css') resources += find_resources(html_files, 'img', 'src') resources += self.resource_files resources = list(set(resources)) # Drop duplicates. resources.sort() for f in resources: if '=' in f: src, dst = f.split('=') if not dst: dst = src else: src = dst = f src = os.path.normpath(src) dst = os.path.normpath(dst) if os.path.isabs(dst): die('absolute resource file name: %s' % dst) if dst.startswith(os.pardir): die('resource file outside destination directory: %s' % dst) src = os.path.join(src_dir, src) dst = os.path.join(dst_dir, dst) if not os.path.isfile(src): for d in self.resource_dirs: d = os.path.join(src_dir, d) found = find_files(d, os.path.basename(src)) if found: src = found[0] break else: if not os.path.isfile(dst): die('missing resource: %s' % src) continue # Arrive here if resource file has been found. if os.path.normpath(src) != os.path.normpath(dst): dstdir = os.path.dirname(dst) shell_makedirs(dstdir) shell_copy(src, dst) def to_docbook(self): ''' Use asciidoc to convert asciidoc_file to DocBook. args is a string containing additional asciidoc arguments. ''' docbook_file = self.dst_path('.xml') if self.skip_asciidoc: if not os.path.isfile(docbook_file): die('missing docbook file: %s' % docbook_file) return shell('"%s" --backend docbook -a "a2x-format=%s" %s --out-file "%s" "%s"' % (self.asciidoc, self.format, self.asciidoc_opts, docbook_file, self.asciidoc_file)) if not self.no_xmllint and XMLLINT: shell('"%s" --nonet --noout --valid "%s"' % (XMLLINT, docbook_file)) def to_xhtml(self): self.to_docbook() docbook_file = self.dst_path('.xml') xhtml_file = self.dst_path('.html') opts = '%s --output "%s"' % (self.xsltproc_opts, xhtml_file) exec_xsltproc(self.xsl_stylesheet(), docbook_file, self.destination_dir, opts) src_dir = os.path.dirname(self.asciidoc_file) self.copy_resources(xhtml_file, src_dir, self.destination_dir) def to_manpage(self): self.to_docbook() docbook_file = self.dst_path('.xml') opts = self.xsltproc_opts exec_xsltproc(self.xsl_stylesheet(), docbook_file, self.destination_dir, opts) def to_pdf(self): if self.fop: self.exec_fop() else: self.exec_dblatex() def exec_fop(self): self.to_docbook() docbook_file = self.dst_path('.xml') xsl = self.xsl_stylesheet('fo.xsl') fo = self.dst_path('.fo') pdf = self.dst_path('.pdf') opts = '%s --output "%s"' % (self.xsltproc_opts, fo) exec_xsltproc(xsl, docbook_file, self.destination_dir, opts) shell('"%s" %s -fo "%s" -pdf "%s"' % (FOP, self.fop_opts, fo, pdf)) if not self.keep_artifacts: shell_rm(fo) def exec_dblatex(self): self.to_docbook() docbook_file = self.dst_path('.xml') xsl = self.asciidoc_conf_file(os.path.join('dblatex','asciidoc-dblatex.xsl')) sty = self.asciidoc_conf_file(os.path.join('dblatex','asciidoc-dblatex.sty')) shell('"%s" -t %s -p "%s" -s "%s" %s "%s"' % (DBLATEX, self.format, xsl, sty, self.dblatex_opts, docbook_file)) def to_dvi(self): self.exec_dblatex() def to_ps(self): self.exec_dblatex() def to_tex(self): self.exec_dblatex() def to_htmlhelp(self): self.to_chunked() def to_chunked(self): self.to_docbook() docbook_file = self.dst_path('.xml') opts = self.xsltproc_opts xsl_file = self.xsl_stylesheet() if self.format == 'chunked': dst_dir = self.dst_path('.chunked') elif self.format == 'htmlhelp': dst_dir = self.dst_path('.htmlhelp') if not 'base.dir ' in opts: opts += ' --stringparam base.dir "%s/"' % os.path.basename(dst_dir) # Create content. shell_rmtree(dst_dir) shell_makedirs(dst_dir) exec_xsltproc(xsl_file, docbook_file, self.destination_dir, opts) html_files = find_files(dst_dir, '*.html') src_dir = os.path.dirname(self.asciidoc_file) self.copy_resources(html_files, src_dir, dst_dir) def update_epub_manifest(self, opf_file): ''' Scan the OEBPS directory for any files that have not been registered in the OPF manifest then add them to the manifest. ''' opf_dir = os.path.dirname(opf_file) resource_files = [] for (p,dirs,files) in os.walk(os.path.dirname(opf_file)): for f in files: f = os.path.join(p,f) if os.path.isfile(f): assert f.startswith(opf_dir) f = '.' + f[len(opf_dir):] f = os.path.normpath(f) if f not in ['content.opf']: resource_files.append(f) opf = xml.dom.minidom.parseString(open(opf_file).read()) manifest_files = [] manifest = opf.getElementsByTagName('manifest')[0] for el in manifest.getElementsByTagName('item'): f = el.getAttribute('href') f = os.path.normpath(f) manifest_files.append(f) count = 0 for f in resource_files: if f not in manifest_files: count += 1 verbose('adding to manifest: %s' % f) item = opf.createElement('item') item.setAttribute('href', f.replace(os.path.sep, '/')) item.setAttribute('id', 'a2x-%d' % count) mimetype = mimetypes.guess_type(f)[0] if mimetype is None: die('unknown mimetype: %s' % f) item.setAttribute('media-type', mimetype) manifest.appendChild(item) if count > 0: open(opf_file, 'w').write(opf.toxml()) def to_epub(self): self.to_docbook() xsl_file = self.xsl_stylesheet() docbook_file = self.dst_path('.xml') epub_file = self.dst_path('.epub') build_dir = epub_file + '.d' shell_rmtree(build_dir) shell_makedirs(build_dir) # Create content. exec_xsltproc(xsl_file, docbook_file, build_dir, self.xsltproc_opts) # Copy resources referenced in the OPF and resources referenced by the # generated HTML (in theory DocBook XSL should ensure they are # identical but this is not always the case). src_dir = os.path.dirname(self.asciidoc_file) dst_dir = os.path.join(build_dir, 'OEBPS') opf_file = os.path.join(dst_dir, 'content.opf') opf_resources = find_resources(opf_file, 'item', 'href') html_files = find_files(dst_dir, '*.html') self.copy_resources(html_files, src_dir, dst_dir, opf_resources) # Register any unregistered resources. self.update_epub_manifest(opf_file) # Build epub archive. cwd = os.getcwd() shell_cd(build_dir) try: if not self.dry_run: zip = zipfile.ZipFile(epub_file, 'w') try: # Create and add uncompressed mimetype file. verbose('archiving: mimetype') open('mimetype','w').write('application/epub+zip') zip.write('mimetype', compress_type=zipfile.ZIP_STORED) # Compress all remaining files. for (p,dirs,files) in os.walk('.'): for f in files: f = os.path.normpath(os.path.join(p,f)) if f != 'mimetype': verbose('archiving: %s' % f) zip.write(f, compress_type=zipfile.ZIP_DEFLATED) finally: zip.close() verbose('created archive: %s' % epub_file) finally: shell_cd(cwd) if not self.keep_artifacts: shell_rmtree(build_dir) if self.epubcheck and EPUBCHECK: if not find_executable(EPUBCHECK): warning('epubcheck skipped: unable to find executable: %s' % EPUBCHECK) else: shell('"%s" "%s"' % (EPUBCHECK, epub_file)) def to_text(self): text_file = self.dst_path('.text') html_file = self.dst_path('.text.html') if self.lynx: shell('"%s" %s --conf-file "%s" -b html4 -a "a2x-format=%s" -o "%s" "%s"' % (self.asciidoc, self.asciidoc_opts, self.asciidoc_conf_file('text.conf'), self.format, html_file, self.asciidoc_file)) shell('"%s" -dump "%s" > "%s"' % (LYNX, html_file, text_file)) else: # Use w3m(1). self.to_docbook() docbook_file = self.dst_path('.xml') opts = '%s --output "%s"' % (self.xsltproc_opts, html_file) exec_xsltproc(self.xsl_stylesheet(), docbook_file, self.destination_dir, opts) shell('"%s" -cols 70 -dump -T text/html -no-graph "%s" > "%s"' % (W3M, html_file, text_file)) if not self.keep_artifacts: shell_rm(html_file) ##################################################################### # Script main line. ##################################################################### if __name__ == '__main__': description = '''A toolchain manager for AsciiDoc (converts Asciidoc text files to other file formats)''' from optparse import OptionParser parser = OptionParser(usage='usage: %prog [OPTIONS] SOURCE_FILE', version='%s %s' % (PROG,VERSION), description=description) parser.add_option('-a', '--attribute', action='append', dest='attributes', default=[], metavar='ATTRIBUTE', help='set asciidoc attribute value') parser.add_option('--asciidoc-opts', action='append', dest='asciidoc_opts', default=[], metavar='ASCIIDOC_OPTS', help='asciidoc options') #DEPRECATED parser.add_option('--copy', action='store_true', dest='copy', default=False, help='DEPRECATED: does nothing') parser.add_option('--conf-file', dest='conf_file', default=None, metavar='CONF_FILE', help='configuration file') parser.add_option('-D', '--destination-dir', action='store', dest='destination_dir', default=None, metavar='PATH', help='output directory (defaults to SOURCE_FILE directory)') parser.add_option('-d','--doctype', action='store', dest='doctype', metavar='DOCTYPE', choices=('article','manpage','book'), help='article, manpage, book') parser.add_option('--epubcheck', action='store_true', dest='epubcheck', default=False, help='check EPUB output with epubcheck') parser.add_option('-f','--format', action='store', dest='format', metavar='FORMAT', default = 'pdf', choices=('chunked','epub','htmlhelp','manpage','pdf', 'text', 'xhtml','dvi','ps','tex','docbook'), help='chunked, epub, htmlhelp, manpage, pdf, text, xhtml, dvi, ps, tex, docbook') parser.add_option('--icons', action='store_true', dest='icons', default=False, help='use admonition, callout and navigation icons') parser.add_option('--icons-dir', action='store', dest='icons_dir', default=None, metavar='PATH', help='admonition and navigation icon directory') parser.add_option('-k', '--keep-artifacts', action='store_true', dest='keep_artifacts', default=False, help='do not delete temporary build files') parser.add_option('--lynx', action='store_true', dest='lynx', default=False, help='use lynx to generate text files') parser.add_option('-L', '--no-xmllint', action='store_true', dest='no_xmllint', default=False, help='do not check asciidoc output with xmllint') parser.add_option('-n','--dry-run', action='store_true', dest='dry_run', default=False, help='just print the commands that would have been executed') parser.add_option('-r','--resource', action='append', dest='resources', default=[], metavar='PATH', help='resource file or directory containing resource files') parser.add_option('-m', '--resource-manifest', action='store', dest='resource_manifest', default=None, metavar='FILE', help='read resources from FILE') #DEPRECATED parser.add_option('--resource-dir', action='append', dest='resources', default=[], metavar='PATH', help='DEPRECATED: use --resource') #DEPRECATED parser.add_option('-s','--skip-asciidoc', action='store_true', dest='skip_asciidoc', default=False, help='DEPRECATED: redundant') parser.add_option('--stylesheet', action='store', dest='stylesheet', default=None, metavar='STYLESHEET', help='HTML CSS stylesheet file name') #DEPRECATED parser.add_option('--safe', action='store_true', dest='safe', default=False, help='DEPRECATED: does nothing') parser.add_option('--dblatex-opts', action='append', dest='dblatex_opts', default=[], metavar='DBLATEX_OPTS', help='dblatex options') parser.add_option('--fop', action='store_true', dest='fop', default=False, help='use FOP to generate PDF files') parser.add_option('--fop-opts', action='append', dest='fop_opts', default=[], metavar='FOP_OPTS', help='options for FOP pdf generation') parser.add_option('--xsltproc-opts', action='append', dest='xsltproc_opts', default=[], metavar='XSLTPROC_OPTS', help='xsltproc options for XSL stylesheets') parser.add_option('--xsl-file', action='store', dest='xsl_file', metavar='XSL_FILE', help='custom XSL stylesheet') parser.add_option('-v', '--verbose', action='count', dest='verbose', default=0, help='increase verbosity') if len(sys.argv) == 1: parser.parse_args(['--help']) source_options = get_source_options(sys.argv[-1]) argv = source_options + sys.argv[1:] opts, args = parser.parse_args(argv) if len(args) != 1: parser.error('incorrect number of arguments') opts.asciidoc_opts = ' '.join(opts.asciidoc_opts) opts.dblatex_opts = ' '.join(opts.dblatex_opts) opts.fop_opts = ' '.join(opts.fop_opts) opts.xsltproc_opts = ' '.join(opts.xsltproc_opts) opts = eval(str(opts)) # Convert optparse.Values to dict. a2x = A2X(opts) OPTIONS = a2x # verbose and dry_run used by utility functions. verbose('args: %r' % argv) a2x.asciidoc_file = args[0] try: a2x.load_conf() a2x.execute() except KeyboardInterrupt: exit(1)
Python
#!/usr/bin/env python ''' NAME music2png - Converts textual music notation to classically notated PNG file SYNOPSIS music2png [options] INFILE DESCRIPTION This filter reads LilyPond or ABC music notation text from the input file INFILE (or stdin if INFILE is -), converts it to classical music notation and writes it to a trimmed PNG image file. This script is a wrapper for LilyPond and ImageMagick commands. OPTIONS -f FORMAT The INFILE music format. 'abc' for ABC notation, 'ly' for LilyPond notation. Defaults to 'abc' unless source starts with backslash. -o OUTFILE The file name of the output file. If not specified the output file is named like INFILE but with a .png file name extension. -m Skip if the PNG output file is newer that than the INFILE. Compares timestamps on INFILE and OUTFILE. If INFILE is - (stdin) then compares MD5 checksum stored in file named like OUTFILE but with a .md5 file name extension. The .md5 file is created if the -m option is used and the INFILE is - (stdin). -v Verbosely print processing information to stderr. --help, -h Print this documentation. --version Print program version number. SEE ALSO lilypond(1), abc2ly(1), convert(1) AUTHOR Written by Stuart Rackham, <srackham@gmail.com> COPYING Copyright (C) 2006 Stuart Rackham. Free use of this software is granted under the terms of the GNU General Public License (GPL). ''' # Suppress warning: "the md5 module is deprecated; use hashlib instead" import warnings warnings.simplefilter('ignore',DeprecationWarning) import os, sys, tempfile, md5 VERSION = '0.1.1' # Globals. verbose = False class EApp(Exception): pass # Application specific exception. def print_stderr(line): sys.stderr.write(line + os.linesep) def print_verbose(line): if verbose: print_stderr(line) def run(cmd): global verbose if not verbose: cmd += ' 2>%s' % os.devnull print_verbose('executing: %s' % cmd) if os.system(cmd): raise EApp, 'failed command: %s' % cmd def music2png(format, infile, outfile, modified): '''Convert ABC notation in file infile to cropped PNG file named outfile.''' outfile = os.path.abspath(outfile) outdir = os.path.dirname(outfile) if not os.path.isdir(outdir): raise EApp, 'directory does not exist: %s' % outdir basefile = tempfile.mktemp(dir=os.path.dirname(outfile)) temps = [basefile + ext for ext in ('.abc', '.ly', '.ps', '.midi')] skip = False if infile == '-': source = sys.stdin.read() checksum = md5.new(source).digest() f = os.path.splitext(outfile)[0] + '.md5' if modified: if os.path.isfile(f) and os.path.isfile(outfile) and \ checksum == open(f,'rb').read(): skip = True open(f,'wb').write(checksum) else: if not os.path.isfile(infile): raise EApp, 'input file does not exist: %s' % infile if modified and os.path.isfile(outfile) and \ os.path.getmtime(infile) <= os.path.getmtime(outfile): skip = True source = open(infile).read() if skip: print_verbose('skipped: no change: %s' % outfile) return if format is None: if source and source.startswith('\\'): # Guess input format. format = 'ly' else: format = 'abc' open('%s.%s' % (basefile,format), 'w').write(source) # Temp source file. abc = basefile + '.abc' ly = basefile + '.ly' png = basefile + '.png' saved_pwd = os.getcwd() os.chdir(outdir) try: if format == 'abc': run('abc2ly --beams=None -o "%s" "%s"' % (ly,abc)) run('lilypond --png -o "%s" "%s"' % (basefile,ly)) os.rename(png, outfile) finally: os.chdir(saved_pwd) # Chop the bottom 75 pixels off to get rid of the page footer. run('convert "%s" -gravity South -crop 1000x10000+0+75 "%s"' % (outfile, outfile)) # Trim all blank areas from sides, top and bottom. run('convert "%s" -trim "%s"' % (outfile, outfile)) for f in temps: if os.path.isfile(f): print_verbose('deleting: %s' % f) os.remove(f) def usage(msg=''): if msg: print_stderr(msg) print_stderr('\n' 'usage:\n' ' music2png [options] INFILE\n' '\n' 'options:\n' ' -f FORMAT\n' ' -o OUTFILE\n' ' -m\n' ' -v\n' ' --help\n' ' --version') def main(): # Process command line options. global verbose format = None outfile = None modified = False import getopt opts,args = getopt.getopt(sys.argv[1:], 'f:o:mhv', ['help','version']) for o,v in opts: if o in ('--help','-h'): print __doc__ sys.exit(0) if o =='--version': print('music2png version %s' % (VERSION,)) sys.exit(0) if o == '-f': format = v if o == '-o': outfile = v if o == '-m': modified = True if o == '-v': verbose = True if len(args) != 1: usage() sys.exit(1) infile = args[0] if format not in (None, 'abc', 'ly'): usage('invalid FORMAT') sys.exit(1) if outfile is None: if infile == '-': usage('OUTFILE must be specified') sys.exit(1) outfile = os.path.splitext(infile)[0] + '.png' # Do the work. music2png(format, infile, outfile, modified) # Print something to suppress asciidoc 'no output from filter' warnings. if infile == '-': sys.stdout.write(' ') if __name__ == "__main__": try: main() except SystemExit: raise except KeyboardInterrupt: sys.exit(1) except Exception, e: print_stderr("%s: %s" % (os.path.basename(sys.argv[0]), str(e))) sys.exit(1)
Python
#!/usr/bin/env python ''' NAME code-filter - AsciiDoc filter to highlight language keywords SYNOPSIS code-filter -b backend -l language [ -t tabsize ] [ --help | -h ] [ --version | -v ] DESCRIPTION This filter reads source code from the standard input, highlights language keywords and comments and writes to the standard output. The purpose of this program is to demonstrate how to write an AsciiDoc filter -- it's much to simplistic to be passed off as a code syntax highlighter. Use the 'source-highlight-filter' instead. OPTIONS --help, -h Print this documentation. -b Backend output file format: 'docbook', 'linuxdoc', 'html', 'css'. -l The name of the source code language: 'python', 'ruby', 'c++', 'c'. -t tabsize Expand source tabs to tabsize spaces. --version, -v Print program version number. BUGS - Code on the same line as a block comment is treated as comment. Keywords inside literal strings are highlighted. - There doesn't appear to be an easy way to accomodate linuxdoc so just pass it through without markup. AUTHOR Written by Stuart Rackham, <srackham@gmail.com> URLS http://sourceforge.net/projects/asciidoc/ http://www.methods.co.nz/asciidoc/ COPYING Copyright (C) 2002-2006 Stuart Rackham. Free use of this software is granted under the terms of the GNU General Public License (GPL). ''' import os, sys, re, string VERSION = '1.1.2' # Globals. language = None backend = None tabsize = 8 keywordtags = { 'html': ('<strong>','</strong>'), 'css': ('<strong>','</strong>'), 'docbook': ('<emphasis role="strong">','</emphasis>'), 'linuxdoc': ('','') } commenttags = { 'html': ('<i>','</i>'), 'css': ('<i>','</i>'), 'docbook': ('<emphasis>','</emphasis>'), 'linuxdoc': ('','') } keywords = { 'python': ('and', 'del', 'for', 'is', 'raise', 'assert', 'elif', 'from', 'lambda', 'return', 'break', 'else', 'global', 'not', 'try', 'class', 'except', 'if', 'or', 'while', 'continue', 'exec', 'import', 'pass', 'yield', 'def', 'finally', 'in', 'print'), 'ruby': ('__FILE__', 'and', 'def', 'end', 'in', 'or', 'self', 'unless', '__LINE__', 'begin', 'defined?' 'ensure', 'module', 'redo', 'super', 'until', 'BEGIN', 'break', 'do', 'false', 'next', 'rescue', 'then', 'when', 'END', 'case', 'else', 'for', 'nil', 'retry', 'true', 'while', 'alias', 'class', 'elsif', 'if', 'not', 'return', 'undef', 'yield'), 'c++': ('asm', 'auto', 'bool', 'break', 'case', 'catch', 'char', 'class', 'const', 'const_cast', 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable', 'namespace', 'new', 'operator', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast', 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile', 'wchar_t', 'while') } block_comments = { 'python': ("'''","'''"), 'ruby': None, 'c++': ('/*','*/') } inline_comments = { 'python': '#', 'ruby': '#', 'c++': '//' } def print_stderr(line): sys.stderr.write(line+os.linesep) def sub_keyword(mo): '''re.subs() argument to tag keywords.''' word = mo.group('word') if word in keywords[language]: stag,etag = keywordtags[backend] return stag+word+etag else: return word def code_filter(): '''This function does all the work.''' global language, backend inline_comment = inline_comments[language] blk_comment = block_comments[language] if blk_comment: blk_comment = (re.escape(block_comments[language][0]), re.escape(block_comments[language][1])) stag,etag = commenttags[backend] in_comment = 0 # True if we're inside a multi-line block comment. tag_comment = 0 # True if we should tag the current line as a comment. line = sys.stdin.readline() while line: line = string.rstrip(line) line = string.expandtabs(line,tabsize) # Escape special characters. line = string.replace(line,'&','&amp;') line = string.replace(line,'<','&lt;') line = string.replace(line,'>','&gt;') # Process block comment. if blk_comment: if in_comment: if re.match(r'.*'+blk_comment[1]+r'$',line): in_comment = 0 else: if re.match(r'^\s*'+blk_comment[0]+r'.*'+blk_comment[1],line): # Single line block comment. tag_comment = 1 elif re.match(r'^\s*'+blk_comment[0],line): # Start of multi-line block comment. tag_comment = 1 in_comment = 1 else: tag_comment = 0 if tag_comment: if line: line = stag+line+etag else: if inline_comment: pos = string.find(line,inline_comment) else: pos = -1 if pos >= 0: # Process inline comment. line = re.sub(r'\b(?P<word>\w+)\b',sub_keyword,line[:pos]) \ + stag + line[pos:] + etag else: line = re.sub(r'\b(?P<word>\w+)\b',sub_keyword,line) sys.stdout.write(line + os.linesep) line = sys.stdin.readline() def usage(msg=''): if msg: print_stderr(msg) print_stderr('Usage: code-filter -b backend -l language [ -t tabsize ]') print_stderr(' [ --help | -h ] [ --version | -v ]') def main(): global language, backend, tabsize # Process command line options. import getopt opts,args = getopt.getopt(sys.argv[1:], 'b:l:ht:v', ['help','version']) if len(args) > 0: usage() sys.exit(1) for o,v in opts: if o in ('--help','-h'): print __doc__ sys.exit(0) if o in ('--version','-v'): print('code-filter version %s' % (VERSION,)) sys.exit(0) if o == '-b': backend = v if o == '-l': v = string.lower(v) if v == 'c': v = 'c++' language = v if o == '-t': try: tabsize = int(v) except: usage('illegal tabsize') sys.exit(1) if tabsize <= 0: usage('illegal tabsize') sys.exit(1) if backend is None: usage('backend option is mandatory') sys.exit(1) if not keywordtags.has_key(backend): usage('illegal backend option') sys.exit(1) if language is None: usage('language option is mandatory') sys.exit(1) if not keywords.has_key(language): usage('illegal language option') sys.exit(1) # Do the work. code_filter() if __name__ == "__main__": try: main() except (KeyboardInterrupt, SystemExit): pass except: print_stderr("%s: unexpected exit status: %s" % (os.path.basename(sys.argv[0]), sys.exc_info()[1])) # Exit with previous sys.exit() status or zero if no sys.exit(). sys.exit(sys.exc_info()[1])
Python
#!/usr/bin/env python ''' NAME latex2png - Converts LaTeX source to PNG file SYNOPSIS latex2png [options] INFILE DESCRIPTION This filter reads LaTeX source text from the input file INFILE (or stdin if INFILE is -) and renders it to PNG image file. Typically used to render math equations. Requires latex(1), dvipng(1) commands and LaTeX math packages. OPTIONS -D DPI Set the output resolution to DPI dots per inch. Use this option to scale the output image size. -o OUTFILE The file name of the output file. If not specified the output file is named like INFILE but with a .png file name extension. -m Skip if the PNG output file is newer that than the INFILE. Compares timestamps on INFILE and OUTFILE. If INFILE is - (stdin) then compares MD5 checksum stored in file named like OUTFILE but with a .md5 file name extension. The .md5 file is created if the -m option is used and the INFILE is - (stdin). -v Verbosely print processing information to stderr. --help, -h Print this documentation. --version Print program version number. SEE ALSO latex(1), dvipng(1) AUTHOR Written by Stuart Rackham, <srackham@gmail.com> The code was inspired by Kjell Magne Fauske's code: http://fauskes.net/nb/htmleqII/ See also: http://www.amk.ca/python/code/mt-math http://code.google.com/p/latexmath2png/ COPYING Copyright (C) 2010 Stuart Rackham. Free use of this software is granted under the terms of the MIT License. ''' # Suppress warning: "the md5 module is deprecated; use hashlib instead" import warnings warnings.simplefilter('ignore',DeprecationWarning) import os, sys, tempfile, md5 VERSION = '0.1.0' # Include LaTeX packages and commands here. TEX_HEADER = r'''\documentclass{article} \usepackage{amsmath} \usepackage{amsthm} \usepackage{amssymb} \usepackage{bm} \newcommand{\mx}[1]{\mathbf{\bm{#1}}} % Matrix command \newcommand{\vc}[1]{\mathbf{\bm{#1}}} % Vector command \newcommand{\T}{\text{T}} % Transpose \pagestyle{empty} \begin{document}''' TEX_FOOTER = r'''\end{document}''' # Globals. verbose = False class EApp(Exception): pass # Application specific exception. def print_stderr(line): sys.stderr.write(line + os.linesep) def print_verbose(line): if verbose: print_stderr(line) def run(cmd): global verbose if verbose: cmd += ' 1>&2' else: cmd += ' 2>%s 1>&2' % os.devnull print_verbose('executing: %s' % cmd) if os.system(cmd): raise EApp, 'failed command: %s' % cmd def latex2png(infile, outfile, dpi, modified): '''Convert LaTeX input file infile to PNG file named outfile.''' outfile = os.path.abspath(outfile) outdir = os.path.dirname(outfile) if not os.path.isdir(outdir): raise EApp, 'directory does not exist: %s' % outdir texfile = tempfile.mktemp(suffix='.tex', dir=os.path.dirname(outfile)) basefile = os.path.splitext(texfile)[0] dvifile = basefile + '.dvi' temps = [basefile + ext for ext in ('.tex','.dvi', '.aux', '.log')] skip = False if infile == '-': tex = sys.stdin.read() if modified: checksum = md5.new(tex).digest() md5_file = os.path.splitext(outfile)[0] + '.md5' if os.path.isfile(md5_file) and os.path.isfile(outfile) and \ checksum == open(md5_file,'rb').read(): skip = True else: if not os.path.isfile(infile): raise EApp, 'input file does not exist: %s' % infile tex = open(infile).read() if modified and os.path.isfile(outfile) and \ os.path.getmtime(infile) <= os.path.getmtime(outfile): skip = True if skip: print_verbose('skipped: no change: %s' % outfile) return tex = '%s\n%s\n%s\n' % (TEX_HEADER, tex.strip(), TEX_FOOTER) print_verbose('tex:\n%s' % tex) open(texfile, 'w').write(tex) saved_pwd = os.getcwd() os.chdir(outdir) try: # Compile LaTeX document to DVI file. run('latex %s' % texfile) # Convert DVI file to PNG. cmd = 'dvipng' if dpi: cmd += ' -D %s' % dpi cmd += ' -T tight -x 1000 -z 9 -bg Transparent --truecolor -o "%s" "%s" ' \ % (outfile,dvifile) run(cmd) finally: os.chdir(saved_pwd) for f in temps: if os.path.isfile(f): print_verbose('deleting: %s' % f) os.remove(f) if 'md5_file' in locals(): print_verbose('writing: %s' % md5_file) open(md5_file,'wb').write(checksum) def usage(msg=''): if msg: print_stderr(msg) print_stderr('\n' 'usage:\n' ' latex2png [options] INFILE\n' '\n' 'options:\n' ' -D DPI\n' ' -o OUTFILE\n' ' -m\n' ' -v\n' ' --help\n' ' --version') def main(): # Process command line options. global verbose dpi = None outfile = None modified = False import getopt opts,args = getopt.getopt(sys.argv[1:], 'D:o:mhv', ['help','version']) for o,v in opts: if o in ('--help','-h'): print __doc__ sys.exit(0) if o =='--version': print('latex2png version %s' % (VERSION,)) sys.exit(0) if o == '-D': dpi = v if o == '-o': outfile = v if o == '-m': modified = True if o == '-v': verbose = True if len(args) != 1: usage() sys.exit(1) infile = args[0] if dpi and not dpi.isdigit(): usage('invalid DPI') sys.exit(1) if outfile is None: if infile == '-': usage('OUTFILE must be specified') sys.exit(1) outfile = os.path.splitext(infile)[0] + '.png' # Do the work. latex2png(infile, outfile, dpi, modified) # Print something to suppress asciidoc 'no output from filter' warnings. if infile == '-': sys.stdout.write(' ') if __name__ == "__main__": try: main() except SystemExit: raise except KeyboardInterrupt: sys.exit(1) except Exception, e: print_stderr("%s: %s" % (os.path.basename(sys.argv[0]), str(e))) sys.exit(1)
Python
#!/usr/bin/env python import os, sys, subprocess from optparse import * __AUTHOR__ = "Gouichi Iisaka <iisaka51@gmail.com>" __VERSION__ = '1.1.4' class EApp(Exception): '''Application specific exception.''' pass class Application(): ''' NAME graphviz2png - Converts textual graphviz notation to PNG file SYNOPSIS graphviz2png [options] INFILE DESCRIPTION This filter reads Graphviz notation text from the input file INFILE (or stdin if INFILE is -), converts it to a PNG image file. OPTIONS -o OUTFILE, --outfile=OUTFILE The file name of the output file. If not specified the output file is named like INFILE but with a .png file name extension. -L LAYOUT, --layout=LAYOUT Graphviz layout: dot, neato, twopi, circo, fdp Default is 'dot'. -F FORMAT, --format=FORMAT Graphviz output format: png, svg, or any other format Graphviz supports. Run dot -T? to get the full list. Default is 'png'. -v, --verbose Verbosely print processing information to stderr. -h, --help Print this documentation. -V, --version Print program version number. SEE ALSO graphviz(1) AUTHOR Written by Gouichi Iisaka, <iisaka51@gmail.com> Format support added by Elmo Todurov, <todurov@gmail.com> THANKS Stuart Rackham, <srackham@gmail.com> This script was inspired by his music2png.py and AsciiDoc LICENSE Copyright (C) 2008-2009 Gouichi Iisaka. Free use of this software is granted under the terms of the GNU General Public License (GPL). ''' def __init__(self, argv=None): # Run dot, get the list of supported formats. It's prefixed by some junk. format_output = subprocess.Popen(["dot", "-T?"], stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[1] # The junk contains : and ends with :. So we split it, then strip the final endline, then split the list for future usage. supported_formats = format_output.split(": ")[2][:-1].split(" ") if not argv: argv = sys.argv self.usage = '%prog [options] inputfile' self.version = 'Version: %s\n' % __VERSION__ self.version += 'Copyright(c) 2008-2009: %s\n' % __AUTHOR__ self.option_list = [ Option("-o", "--outfile", action="store", dest="outfile", help="Output file"), Option("-L", "--layout", action="store", dest="layout", default="dot", type="choice", choices=['dot','neato','twopi','circo','fdp'], help="Layout type. LAYOUT=<dot|neato|twopi|circo|fdp>"), Option("-F", "--format", action="store", dest="format", default="png", type="choice", choices=supported_formats, help="Format type. FORMAT=<" + "|".join(supported_formats) + ">"), Option("--debug", action="store_true", dest="do_debug", help=SUPPRESS_HELP), Option("-v", "--verbose", action="store_true", dest="do_verbose", default=False, help="verbose output"), ] self.parser = OptionParser( usage=self.usage, version=self.version, option_list=self.option_list) (self.options, self.args) = self.parser.parse_args() if len(self.args) != 1: self.parser.print_help() sys.exit(1) self.options.infile = self.args[0] def systemcmd(self, cmd): if self.options.do_verbose: msg = 'Execute: %s' % cmd sys.stderr.write(msg + os.linesep) else: cmd += ' 2>%s' % os.devnull if os.system(cmd): raise EApp, 'failed command: %s' % cmd def graphviz2png(self, infile, outfile): '''Convert Graphviz notation in file infile to PNG file named outfile.''' outfile = os.path.abspath(outfile) outdir = os.path.dirname(outfile) if not os.path.isdir(outdir): raise EApp, 'directory does not exist: %s' % outdir basefile = os.path.splitext(outfile)[0] saved_cwd = os.getcwd() os.chdir(outdir) try: cmd = '%s -T%s "%s" > "%s"' % ( self.options.layout, self.options.format, infile, outfile) self.systemcmd(cmd) finally: os.chdir(saved_cwd) if not self.options.do_debug: os.unlink(infile) def run(self): if self.options.format == '': self.options.format = 'png' if self.options.infile == '-': if self.options.outfile is None: sys.stderr.write('OUTFILE must be specified') sys.exit(1) infile = os.path.splitext(self.options.outfile)[0] + '.txt' lines = sys.stdin.readlines() open(infile, 'w').writelines(lines) if not os.path.isfile(infile): raise EApp, 'input file does not exist: %s' % infile if self.options.outfile is None: outfile = os.path.splitext(infile)[0] + '.png' else: outfile = self.options.outfile self.graphviz2png(infile, outfile) # To suppress asciidoc 'no output from filter' warnings. if self.options.infile == '-': sys.stdout.write(' ') if __name__ == "__main__": app = Application() app.run()
Python
#!/usr/bin/env python """ asciidoc - converts an AsciiDoc text file to HTML or DocBook Copyright (C) 2002-2010 Stuart Rackham. Free use of this software is granted under the terms of the GNU General Public License (GPL). """ import sys, os, re, time, traceback, tempfile, subprocess, codecs, locale, unicodedata, copy ### Used by asciidocapi.py ### VERSION = '8.6.5' # See CHANGLOG file for version history. MIN_PYTHON_VERSION = 2.4 # Require this version of Python or better. #--------------------------------------------------------------------------- # Program constants. #--------------------------------------------------------------------------- DEFAULT_BACKEND = 'html' DEFAULT_DOCTYPE = 'article' # Allowed substitution options for List, Paragraph and DelimitedBlock # definition subs entry. SUBS_OPTIONS = ('specialcharacters','quotes','specialwords', 'replacements', 'attributes','macros','callouts','normal','verbatim', 'none','replacements2') # Default value for unspecified subs and presubs configuration file entries. SUBS_NORMAL = ('specialcharacters','quotes','attributes', 'specialwords','replacements','macros','replacements2') SUBS_VERBATIM = ('specialcharacters','callouts') NAME_RE = r'(?u)[^\W\d][-\w]*' # Valid section or attribute name. OR, AND = ',', '+' # Attribute list separators. #--------------------------------------------------------------------------- # Utility functions and classes. #--------------------------------------------------------------------------- class EAsciiDoc(Exception): pass class OrderedDict(dict): """ Dictionary ordered by insertion order. Python Cookbook: Ordered Dictionary, Submitter: David Benjamin. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 """ def __init__(self, d=None, **kwargs): self._keys = [] if d is None: d = kwargs dict.__init__(self, d) def __delitem__(self, key): dict.__delitem__(self, key) self._keys.remove(key) def __setitem__(self, key, item): dict.__setitem__(self, key, item) if key not in self._keys: self._keys.append(key) def clear(self): dict.clear(self) self._keys = [] def copy(self): d = dict.copy(self) d._keys = self._keys[:] return d def items(self): return zip(self._keys, self.values()) def keys(self): return self._keys def popitem(self): try: key = self._keys[-1] except IndexError: raise KeyError('dictionary is empty') val = self[key] del self[key] return (key, val) def setdefault(self, key, failobj = None): dict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) def update(self, d=None, **kwargs): if d is None: d = kwargs dict.update(self, d) for key in d.keys(): if key not in self._keys: self._keys.append(key) def values(self): return map(self.get, self._keys) class AttrDict(dict): """ Like a dictionary except values can be accessed as attributes i.e. obj.foo can be used in addition to obj['foo']. If an item is not present None is returned. """ def __getattr__(self, key): try: return self[key] except KeyError: return None def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError, k: raise AttributeError, k def __repr__(self): return '<AttrDict ' + dict.__repr__(self) + '>' def __getstate__(self): return dict(self) def __setstate__(self,value): for k,v in value.items(): self[k]=v class InsensitiveDict(dict): """ Like a dictionary except key access is case insensitive. Keys are stored in lower case. """ def __getitem__(self, key): return dict.__getitem__(self, key.lower()) def __setitem__(self, key, value): dict.__setitem__(self, key.lower(), value) def has_key(self, key): return dict.has_key(self,key.lower()) def get(self, key, default=None): return dict.get(self, key.lower(), default) def update(self, dict): for k,v in dict.items(): self[k] = v def setdefault(self, key, default = None): return dict.setdefault(self, key.lower(), default) class Trace(object): """ Used in conjunction with the 'trace' attribute to generate diagnostic output. There is a single global instance of this class named trace. """ SUBS_NAMES = ('specialcharacters','quotes','specialwords', 'replacements', 'attributes','macros','callouts', 'replacements2') def __init__(self): self.name_re = '' # Regexp pattern to match trace names. self.linenos = True self.offset = 0 def __call__(self, name, before, after=None): """ Print trace message if tracing is on and the trace 'name' matches the document 'trace' attribute (treated as a regexp). 'before' is the source text before substitution; 'after' text is the source text after substitutuion. The 'before' and 'after' messages are only printed if they differ. """ name_re = document.attributes.get('trace') if name_re == 'subs': # Alias for all the inline substitutions. name_re = '|'.join(self.SUBS_NAMES) self.name_re = name_re if self.name_re is not None: msg = message.format(name, 'TRACE: ', self.linenos, offset=self.offset) if before != after and re.match(self.name_re,name): if is_array(before): before = '\n'.join(before) if after is None: msg += '\n%s\n' % before else: if is_array(after): after = '\n'.join(after) msg += '\n<<<\n%s\n>>>\n%s\n' % (before,after) message.stderr(msg) class Message: """ Message functions. """ PROG = os.path.basename(os.path.splitext(__file__)[0]) def __init__(self): # Set to True or False to globally override line numbers method # argument. Has no effect when set to None. self.linenos = None self.messages = [] def stdout(self,msg): print msg def stderr(self,msg=''): self.messages.append(msg) if __name__ == '__main__': sys.stderr.write('%s: %s%s' % (self.PROG, msg, os.linesep)) def verbose(self, msg,linenos=True): if config.verbose: msg = self.format(msg,linenos=linenos) self.stderr(msg) def warning(self, msg,linenos=True,offset=0): msg = self.format(msg,'WARNING: ',linenos,offset=offset) document.has_warnings = True self.stderr(msg) def deprecated(self, msg, linenos=True): msg = self.format(msg, 'DEPRECATED: ', linenos) self.stderr(msg) def format(self, msg, prefix='', linenos=True, cursor=None, offset=0): """Return formatted message string.""" if self.linenos is not False and ((linenos or self.linenos) and reader.cursor): if cursor is None: cursor = reader.cursor prefix += '%s: line %d: ' % (os.path.basename(cursor[0]),cursor[1]+offset) return prefix + msg def error(self, msg, cursor=None, halt=False): """ Report fatal error. If halt=True raise EAsciiDoc exception. If halt=False don't exit application, continue in the hope of reporting all fatal errors finishing with a non-zero exit code. """ if halt: raise EAsciiDoc, self.format(msg,linenos=False,cursor=cursor) else: msg = self.format(msg,'ERROR: ',cursor=cursor) self.stderr(msg) document.has_errors = True def unsafe(self, msg): self.error('unsafe: '+msg) def userdir(): """ Return user's home directory or None if it is not defined. """ result = os.path.expanduser('~') if result == '~': result = None return result def localapp(): """ Return True if we are not executing the system wide version i.e. the configuration is in the executable's directory. """ return os.path.isfile(os.path.join(APP_DIR, 'asciidoc.conf')) def file_in(fname, directory): """Return True if file fname resides inside directory.""" assert os.path.isfile(fname) # Empty directory (not to be confused with None) is the current directory. if directory == '': directory = os.getcwd() else: assert os.path.isdir(directory) directory = os.path.realpath(directory) fname = os.path.realpath(fname) return os.path.commonprefix((directory, fname)) == directory def safe(): return document.safe def is_safe_file(fname, directory=None): # A safe file must reside in directory directory (defaults to the source # file directory). if directory is None: if document.infile == '<stdin>': return not safe() directory = os.path.dirname(document.infile) elif directory == '': directory = '.' return ( not safe() or file_in(fname, directory) or file_in(fname, APP_DIR) or file_in(fname, CONF_DIR) ) def safe_filename(fname, parentdir): """ Return file name which must reside in the parent file directory. Return None if file is not safe. """ if not os.path.isabs(fname): # Include files are relative to parent document # directory. fname = os.path.normpath(os.path.join(parentdir,fname)) if not is_safe_file(fname, parentdir): message.unsafe('include file: %s' % fname) return None return fname def assign(dst,src): """Assign all attributes from 'src' object to 'dst' object.""" for a,v in src.__dict__.items(): setattr(dst,a,v) def strip_quotes(s): """Trim white space and, if necessary, quote characters from s.""" s = s.strip() # Strip quotation mark characters from quoted strings. if len(s) >= 3 and s[0] == '"' and s[-1] == '"': s = s[1:-1] return s def is_re(s): """Return True if s is a valid regular expression else return False.""" try: re.compile(s) except: return False else: return True def re_join(relist): """Join list of regular expressions re1,re2,... to single regular expression (re1)|(re2)|...""" if len(relist) == 0: return None result = [] # Delete named groups to avoid ambiguity. for s in relist: result.append(re.sub(r'\?P<\S+?>','',s)) result = ')|('.join(result) result = '('+result+')' return result def lstrip_list(s): """ Return list with empty items from start of list removed. """ for i in range(len(s)): if s[i]: break else: return [] return s[i:] def rstrip_list(s): """ Return list with empty items from end of list removed. """ for i in range(len(s)-1,-1,-1): if s[i]: break else: return [] return s[:i+1] def strip_list(s): """ Return list with empty items from start and end of list removed. """ s = lstrip_list(s) s = rstrip_list(s) return s def is_array(obj): """ Return True if object is list or tuple type. """ return isinstance(obj,list) or isinstance(obj,tuple) def dovetail(lines1, lines2): """ Append list or tuple of strings 'lines2' to list 'lines1'. Join the last non-blank item in 'lines1' with the first non-blank item in 'lines2' into a single string. """ assert is_array(lines1) assert is_array(lines2) lines1 = strip_list(lines1) lines2 = strip_list(lines2) if not lines1 or not lines2: return list(lines1) + list(lines2) result = list(lines1[:-1]) result.append(lines1[-1] + lines2[0]) result += list(lines2[1:]) return result def dovetail_tags(stag,content,etag): """Merge the end tag with the first content line and the last content line with the end tag. This ensures verbatim elements don't include extraneous opening and closing line breaks.""" return dovetail(dovetail(stag,content), etag) if float(sys.version[:3]) < 2.4: pass # No compiler elif float(sys.version[:3]) < 2.6: import compiler from compiler.ast import Const, Dict, Expression, Name, Tuple, UnarySub, Keyword # Code from: # http://mail.python.org/pipermail/python-list/2009-September/1219992.html # Modified to use compiler.ast.List as this module has a List def literal_eval(node_or_string): """ Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. """ _safe_names = {'None': None, 'True': True, 'False': False} if isinstance(node_or_string, basestring): node_or_string = compiler.parse(node_or_string, mode='eval') if isinstance(node_or_string, Expression): node_or_string = node_or_string.node def _convert(node): if isinstance(node, Const) and isinstance(node.value, (basestring, int, float, long, complex)): return node.value elif isinstance(node, Tuple): return tuple(map(_convert, node.nodes)) elif isinstance(node, compiler.ast.List): return list(map(_convert, node.nodes)) elif isinstance(node, Dict): return dict((_convert(k), _convert(v)) for k, v in node.items) elif isinstance(node, Name): if node.name in _safe_names: return _safe_names[node.name] elif isinstance(node, UnarySub): return -_convert(node.expr) raise ValueError('malformed string') return _convert(node_or_string) def get_args(val): d = {} args = compiler.parse("d(" + val + ")", mode='eval').node.args i = 1 for arg in args: if isinstance(arg, Keyword): break d[str(i)] = literal_eval(arg) i = i + 1 return d def get_kwargs(val): d = {} args = compiler.parse("d(" + val + ")", mode='eval').node.args i = 0 for arg in args: if isinstance(arg, Keyword): break i += 1 args = args[i:] for arg in args: d[str(arg.name)] = literal_eval(arg.expr) return d def parse_to_list(val): values = compiler.parse("[" + val + "]", mode='eval').node.asList() return [literal_eval(v) for v in values] else: import ast from ast import literal_eval def get_args(val): d = {} args = ast.parse("d(" + val + ")", mode='eval').body.args i = 1 for arg in args: if isinstance(arg, ast.Name): d[str(i)] = literal_eval(arg.id) else: d[str(i)] = literal_eval(arg) i += 1 return d def get_kwargs(val): d = {} args = ast.parse("d(" + val + ")", mode='eval').body.keywords for arg in args: d[arg.arg] = literal_eval(arg.value) return d def parse_to_list(val): values = ast.parse("[" + val + "]", mode='eval').body.elts return [literal_eval(v) for v in values] def parse_attributes(attrs,dict): """Update a dictionary with name/value attributes from the attrs string. The attrs string is a comma separated list of values and keyword name=value pairs. Values must preceed keywords and are named '1','2'... The entire attributes list is named '0'. If keywords are specified string values must be quoted. Examples: attrs: '' dict: {} attrs: 'hello,world' dict: {'2': 'world', '0': 'hello,world', '1': 'hello'} attrs: '"hello", planet="earth"' dict: {'planet': 'earth', '0': '"hello",planet="earth"', '1': 'hello'} """ def f(*args,**keywords): # Name and add aguments '1','2'... to keywords. for i in range(len(args)): if not str(i+1) in keywords: keywords[str(i+1)] = args[i] return keywords if not attrs: return dict['0'] = attrs # Replace line separators with spaces so line spanning works. s = re.sub(r'\s', ' ', attrs) d = {} try: d.update(get_args(s)) d.update(get_kwargs(s)) for v in d.values(): if not (isinstance(v,str) or isinstance(v,int) or isinstance(v,float) or v is None): raise Exception except Exception: s = s.replace('"','\\"') s = s.split(',') s = map(lambda x: '"' + x.strip() + '"', s) s = ','.join(s) try: d = {} d.update(get_args(s)) d.update(get_kwargs(s)) except Exception: return # If there's a syntax error leave with {0}=attrs. for k in d.keys(): # Drop any empty positional arguments. if d[k] == '': del d[k] dict.update(d) assert len(d) > 0 def parse_named_attributes(s,attrs): """Update a attrs dictionary with name="value" attributes from the s string. Returns False if invalid syntax. Example: attrs: 'star="sun",planet="earth"' dict: {'planet':'earth', 'star':'sun'} """ def f(**keywords): return keywords try: d = {} d = get_kwargs(s) attrs.update(d) return True except Exception: return False def parse_list(s): """Parse comma separated string of Python literals. Return a tuple of of parsed values.""" try: result = tuple(parse_to_list(s)) except Exception: raise EAsciiDoc,'malformed list: '+s return result def parse_options(options,allowed,errmsg): """Parse comma separated string of unquoted option names and return as a tuple of valid options. 'allowed' is a list of allowed option values. If allowed=() then all legitimate names are allowed. 'errmsg' is an error message prefix if an illegal option error is thrown.""" result = [] if options: for s in re.split(r'\s*,\s*',options): if (allowed and s not in allowed) or not is_name(s): raise EAsciiDoc,'%s: %s' % (errmsg,s) result.append(s) return tuple(result) def symbolize(s): """Drop non-symbol characters and convert to lowercase.""" return re.sub(r'(?u)[^\w\-_]', '', s).lower() def is_name(s): """Return True if s is valid attribute, macro or tag name (starts with alpha containing alphanumeric and dashes only).""" return re.match(r'^'+NAME_RE+r'$',s) is not None def subs_quotes(text): """Quoted text is marked up and the resulting text is returned.""" keys = config.quotes.keys() for q in keys: i = q.find('|') if i != -1 and q != '|' and q != '||': lq = q[:i] # Left quote. rq = q[i+1:] # Right quote. else: lq = rq = q tag = config.quotes[q] if not tag: continue # Unconstrained quotes prefix the tag name with a hash. if tag[0] == '#': tag = tag[1:] # Unconstrained quotes can appear anywhere. reo = re.compile(r'(?msu)(^|.)(\[(?P<attrlist>[^[\]]+?)\])?' \ + r'(?:' + re.escape(lq) + r')' \ + r'(?P<content>.+?)(?:'+re.escape(rq)+r')') else: # The text within constrained quotes must be bounded by white space. # Non-word (\W) characters are allowed at boundaries to accomodate # enveloping quotes and punctuation e.g. a='x', ('x'), 'x', ['x']. reo = re.compile(r'(?msu)(^|[^\w;:}])(\[(?P<attrlist>[^[\]]+?)\])?' \ + r'(?:' + re.escape(lq) + r')' \ + r'(?P<content>\S|\S.*?\S)(?:'+re.escape(rq)+r')(?=\W|$)') pos = 0 while True: mo = reo.search(text,pos) if not mo: break if text[mo.start()] == '\\': # Delete leading backslash. text = text[:mo.start()] + text[mo.start()+1:] # Skip past start of match. pos = mo.start() + 1 else: attrlist = {} parse_attributes(mo.group('attrlist'), attrlist) stag,etag = config.tag(tag, attrlist) s = mo.group(1) + stag + mo.group('content') + etag text = text[:mo.start()] + s + text[mo.end():] pos = mo.start() + len(s) return text def subs_tag(tag,dict={}): """Perform attribute substitution and split tag string returning start, end tag tuple (c.f. Config.tag()).""" if not tag: return [None,None] s = subs_attrs(tag,dict) if not s: message.warning('tag \'%s\' dropped: contains undefined attribute' % tag) return [None,None] result = s.split('|') if len(result) == 1: return result+[None] elif len(result) == 2: return result else: raise EAsciiDoc,'malformed tag: %s' % tag def parse_entry(entry, dict=None, unquote=False, unique_values=False, allow_name_only=False, escape_delimiter=True): """Parse name=value entry to dictionary 'dict'. Return tuple (name,value) or None if illegal entry. If name= then value is set to ''. If name and allow_name_only=True then value is set to ''. If name! and allow_name_only=True then value is set to None. Leading and trailing white space is striped from 'name' and 'value'. 'name' can contain any printable characters. If the '=' delimiter character is allowed in the 'name' then it must be escaped with a backslash and escape_delimiter must be True. If 'unquote' is True leading and trailing double-quotes are stripped from 'name' and 'value'. If unique_values' is True then dictionary entries with the same value are removed before the parsed entry is added.""" if escape_delimiter: mo = re.search(r'(?:[^\\](=))',entry) else: mo = re.search(r'(=)',entry) if mo: # name=value entry. if mo.group(1): name = entry[:mo.start(1)] if escape_delimiter: name = name.replace(r'\=','=') # Unescape \= in name. value = entry[mo.end(1):] elif allow_name_only and entry: # name or name! entry. name = entry if name[-1] == '!': name = name[:-1] value = None else: value = '' else: return None if unquote: name = strip_quotes(name) if value is not None: value = strip_quotes(value) else: name = name.strip() if value is not None: value = value.strip() if not name: return None if dict is not None: if unique_values: for k,v in dict.items(): if v == value: del dict[k] dict[name] = value return name,value def parse_entries(entries, dict, unquote=False, unique_values=False, allow_name_only=False,escape_delimiter=True): """Parse name=value entries from from lines of text in 'entries' into dictionary 'dict'. Blank lines are skipped.""" entries = config.expand_templates(entries) for entry in entries: if entry and not parse_entry(entry, dict, unquote, unique_values, allow_name_only, escape_delimiter): raise EAsciiDoc,'malformed section entry: %s' % entry def dump_section(name,dict,f=sys.stdout): """Write parameters in 'dict' as in configuration file section format with section 'name'.""" f.write('[%s]%s' % (name,writer.newline)) for k,v in dict.items(): k = str(k) k = k.replace('=',r'\=') # Escape = in name. # Quote if necessary. if len(k) != len(k.strip()): k = '"'+k+'"' if v and len(v) != len(v.strip()): v = '"'+v+'"' if v is None: # Don't dump undefined attributes. continue else: s = k+'='+v if s[0] == '#': s = '\\' + s # Escape so not treated as comment lines. f.write('%s%s' % (s,writer.newline)) f.write(writer.newline) def update_attrs(attrs,dict): """Update 'attrs' dictionary with parsed attributes in dictionary 'dict'.""" for k,v in dict.items(): if not is_name(k): raise EAsciiDoc,'illegal attribute name: %s' % k attrs[k] = v def is_attr_defined(attrs,dic): """ Check if the sequence of attributes is defined in dictionary 'dic'. Valid 'attrs' sequence syntax: <attr> Return True if single attrbiute is defined. <attr1>,<attr2>,... Return True if one or more attributes are defined. <attr1>+<attr2>+... Return True if all the attributes are defined. """ if OR in attrs: for a in attrs.split(OR): if dic.get(a.strip()) is not None: return True else: return False elif AND in attrs: for a in attrs.split(AND): if dic.get(a.strip()) is None: return False else: return True else: return dic.get(attrs.strip()) is not None def filter_lines(filter_cmd, lines, attrs={}): """ Run 'lines' through the 'filter_cmd' shell command and return the result. The 'attrs' dictionary contains additional filter attributes. """ def findfilter(name,dir,filter): """Find filter file 'fname' with style name 'name' in directory 'dir'. Return found file path or None if not found.""" if name: result = os.path.join(dir,'filters',name,filter) if os.path.isfile(result): return result result = os.path.join(dir,'filters',filter) if os.path.isfile(result): return result return None # Return input lines if there's not filter. if not filter_cmd or not filter_cmd.strip(): return lines # Perform attributes substitution on the filter command. s = subs_attrs(filter_cmd, attrs) if not s: message.error('undefined filter attribute in command: %s' % filter_cmd) return [] filter_cmd = s.strip() # Parse for quoted and unquoted command and command tail. # Double quoted. mo = re.match(r'^"(?P<cmd>[^"]+)"(?P<tail>.*)$', filter_cmd) if not mo: # Single quoted. mo = re.match(r"^'(?P<cmd>[^']+)'(?P<tail>.*)$", filter_cmd) if not mo: # Unquoted catch all. mo = re.match(r'^(?P<cmd>\S+)(?P<tail>.*)$', filter_cmd) cmd = mo.group('cmd').strip() found = None if not os.path.dirname(cmd): # Filter command has no directory path so search filter directories. filtername = attrs.get('style') d = document.attributes.get('docdir') if d: found = findfilter(filtername, d, cmd) if not found: if USER_DIR: found = findfilter(filtername, USER_DIR, cmd) if not found: if localapp(): found = findfilter(filtername, APP_DIR, cmd) else: found = findfilter(filtername, CONF_DIR, cmd) else: if os.path.isfile(cmd): found = cmd else: message.warning('filter not found: %s' % cmd) if found: filter_cmd = '"' + found + '"' + mo.group('tail') if sys.platform == 'win32': # Windows doesn't like running scripts directly so explicitly # specify interpreter. if found: if cmd.endswith('.py'): filter_cmd = 'python ' + filter_cmd elif cmd.endswith('.rb'): filter_cmd = 'ruby ' + filter_cmd message.verbose('filtering: ' + filter_cmd) try: p = subprocess.Popen(filter_cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) output = p.communicate(os.linesep.join(lines))[0] except Exception: raise EAsciiDoc,'filter error: %s: %s' % (filter_cmd, sys.exc_info()[1]) if output: result = [s.rstrip() for s in output.split(os.linesep)] else: result = [] filter_status = p.wait() if filter_status: message.warning('filter non-zero exit code: %s: returned %d' % (filter_cmd, filter_status)) if lines and not result: message.warning('no output from filter: %s' % filter_cmd) return result def system(name, args, is_macro=False, attrs=None): """ Evaluate a system attribute ({name:args}) or system block macro (name::[args]). If is_macro is True then we are processing a system block macro otherwise it's a system attribute. The attrs dictionary is updated by the counter and set system attributes. NOTE: The include1 attribute is used internally by the include1::[] macro and is not for public use. """ if is_macro: syntax = '%s::[%s]' % (name,args) separator = '\n' else: syntax = '{%s:%s}' % (name,args) separator = writer.newline if name not in ('eval','eval3','sys','sys2','sys3','include','include1','counter','counter2','set','set2','template'): if is_macro: msg = 'illegal system macro name: %s' % name else: msg = 'illegal system attribute name: %s' % name message.warning(msg) return None if is_macro: s = subs_attrs(args) if s is None: message.warning('skipped %s: undefined attribute in: %s' % (name,args)) return None args = s if name != 'include1': message.verbose('evaluating: %s' % syntax) if safe() and name not in ('include','include1'): message.unsafe(syntax) return None result = None if name in ('eval','eval3'): try: result = eval(args) if result is True: result = '' elif result is False: result = None elif result is not None: result = str(result) except Exception: message.warning('%s: evaluation error' % syntax) elif name in ('sys','sys2','sys3'): result = '' fd,tmp = tempfile.mkstemp() os.close(fd) try: cmd = args cmd = cmd + (' > %s' % tmp) if name == 'sys2': cmd = cmd + ' 2>&1' if os.system(cmd): message.warning('%s: non-zero exit status' % syntax) try: if os.path.isfile(tmp): lines = [s.rstrip() for s in open(tmp)] else: lines = [] except Exception: raise EAsciiDoc,'%s: temp file read error' % syntax result = separator.join(lines) finally: if os.path.isfile(tmp): os.remove(tmp) elif name in ('counter','counter2'): mo = re.match(r'^(?P<attr>[^:]*?)(:(?P<seed>.*))?$', args) attr = mo.group('attr') seed = mo.group('seed') if seed and (not re.match(r'^\d+$', seed) and len(seed) > 1): message.warning('%s: illegal counter seed: %s' % (syntax,seed)) return None if not is_name(attr): message.warning('%s: illegal attribute name' % syntax) return None value = document.attributes.get(attr) if value: if not re.match(r'^\d+$', value) and len(value) > 1: message.warning('%s: illegal counter value: %s' % (syntax,value)) return None if re.match(r'^\d+$', value): expr = value + '+1' else: expr = 'chr(ord("%s")+1)' % value try: result = str(eval(expr)) except Exception: message.warning('%s: evaluation error: %s' % (syntax, expr)) else: if seed: result = seed else: result = '1' document.attributes[attr] = result if attrs is not None: attrs[attr] = result if name == 'counter2': result = '' elif name in ('set','set2'): mo = re.match(r'^(?P<attr>[^:]*?)(:(?P<value>.*))?$', args) attr = mo.group('attr') value = mo.group('value') if value is None: value = '' if attr.endswith('!'): attr = attr[:-1] value = None if not is_name(attr): message.warning('%s: illegal attribute name' % syntax) else: if attrs is not None: attrs[attr] = value if name != 'set2': # set2 only updates local attributes. document.attributes[attr] = value if value is None: result = None else: result = '' elif name == 'include': if not os.path.exists(args): message.warning('%s: file does not exist' % syntax) elif not is_safe_file(args): message.unsafe(syntax) else: result = [s.rstrip() for s in open(args)] if result: result = subs_attrs(result) result = separator.join(result) result = result.expandtabs(reader.tabsize) else: result = '' elif name == 'include1': result = separator.join(config.include1[args]) elif name == 'template': if not args in config.sections: message.warning('%s: template does not exist' % syntax) else: result = [] for line in config.sections[args]: line = subs_attrs(line) if line is not None: result.append(line) result = '\n'.join(result) else: assert False if result and name in ('eval3','sys3'): macros.passthroughs.append(result) result = '\x07' + str(len(macros.passthroughs)-1) + '\x07' return result def subs_attrs(lines, dictionary=None): """Substitute 'lines' of text with attributes from the global document.attributes dictionary and from 'dictionary' ('dictionary' entries take precedence). Return a tuple of the substituted lines. 'lines' containing undefined attributes are deleted. If 'lines' is a string then return a string. - Attribute references are substituted in the following order: simple, conditional, system. - Attribute references inside 'dictionary' entry values are substituted. """ def end_brace(text,start): """Return index following end brace that matches brace at start in text.""" assert text[start] == '{' n = 0 result = start for c in text[start:]: # Skip braces that are followed by a backslash. if result == len(text)-1 or text[result+1] != '\\': if c == '{': n = n + 1 elif c == '}': n = n - 1 result = result + 1 if n == 0: break return result if type(lines) == str: string_result = True lines = [lines] else: string_result = False if dictionary is None: attrs = document.attributes else: # Remove numbered document attributes so they don't clash with # attribute list positional attributes. attrs = {} for k,v in document.attributes.items(): if not re.match(r'^\d+$', k): attrs[k] = v # Substitute attribute references inside dictionary values. for k,v in dictionary.items(): if v is None: del dictionary[k] else: v = subs_attrs(str(v)) if v is None: del dictionary[k] else: dictionary[k] = v attrs.update(dictionary) # Substitute all attributes in all lines. result = [] for line in lines: # Make it easier for regular expressions. line = line.replace('\\{','{\\') line = line.replace('\\}','}\\') # Expand simple attributes ({name}). # Nested attributes not allowed. reo = re.compile(r'(?su)\{(?P<name>[^\\\W][-\w]*?)\}(?!\\)') pos = 0 while True: mo = reo.search(line,pos) if not mo: break s = attrs.get(mo.group('name')) if s is None: pos = mo.end() else: s = str(s) line = line[:mo.start()] + s + line[mo.end():] pos = mo.start() + len(s) # Expand conditional attributes. # Single name -- higher precedence. reo1 = re.compile(r'(?su)\{(?P<name>[^\\\W][-\w]*?)' \ r'(?P<op>\=|\?|!|#|%|@|\$)' \ r'(?P<value>.*?)\}(?!\\)') # Multiple names (n1,n2,... or n1+n2+...) -- lower precedence. reo2 = re.compile(r'(?su)\{(?P<name>[^\\\W][-\w'+OR+AND+r']*?)' \ r'(?P<op>\=|\?|!|#|%|@|\$)' \ r'(?P<value>.*?)\}(?!\\)') for reo in [reo1,reo2]: pos = 0 while True: mo = reo.search(line,pos) if not mo: break attr = mo.group() name = mo.group('name') if reo == reo2: if OR in name: sep = OR else: sep = AND names = [s.strip() for s in name.split(sep) if s.strip() ] for n in names: if not re.match(r'^[^\\\W][-\w]*$',n): message.error('illegal attribute syntax: %s' % attr) if sep == OR: # Process OR name expression: n1,n2,... for n in names: if attrs.get(n) is not None: lval = '' break else: lval = None else: # Process AND name expression: n1+n2+... for n in names: if attrs.get(n) is None: lval = None break else: lval = '' else: lval = attrs.get(name) op = mo.group('op') # mo.end() not good enough because '{x={y}}' matches '{x={y}'. end = end_brace(line,mo.start()) rval = line[mo.start('value'):end-1] UNDEFINED = '{zzzzz}' if lval is None: if op == '=': s = rval elif op == '?': s = '' elif op == '!': s = rval elif op == '#': s = UNDEFINED # So the line is dropped. elif op == '%': s = rval elif op in ('@','$'): s = UNDEFINED # So the line is dropped. else: assert False, 'illegal attribute: %s' % attr else: if op == '=': s = lval elif op == '?': s = rval elif op == '!': s = '' elif op == '#': s = rval elif op == '%': s = UNDEFINED # So the line is dropped. elif op in ('@','$'): v = re.split(r'(?<!\\):',rval) if len(v) not in (2,3): message.error('illegal attribute syntax: %s' % attr) s = '' elif not is_re('^'+v[0]+'$'): message.error('illegal attribute regexp: %s' % attr) s = '' else: v = [s.replace('\\:',':') for s in v] re_mo = re.match('^'+v[0]+'$',lval) if op == '@': if re_mo: s = v[1] # {<name>@<re>:<v1>[:<v2>]} else: if len(v) == 3: # {<name>@<re>:<v1>:<v2>} s = v[2] else: # {<name>@<re>:<v1>} s = '' else: if re_mo: if len(v) == 2: # {<name>$<re>:<v1>} s = v[1] elif v[1] == '': # {<name>$<re>::<v2>} s = UNDEFINED # So the line is dropped. else: # {<name>$<re>:<v1>:<v2>} s = v[1] else: if len(v) == 2: # {<name>$<re>:<v1>} s = UNDEFINED # So the line is dropped. else: # {<name>$<re>:<v1>:<v2>} s = v[2] else: assert False, 'illegal attribute: %s' % attr s = str(s) line = line[:mo.start()] + s + line[end:] pos = mo.start() + len(s) # Drop line if it contains unsubstituted {name} references. skipped = re.search(r'(?su)\{[^\\\W][-\w]*?\}(?!\\)', line) if skipped: trace('dropped line', line) continue; # Expand system attributes (eval has precedence). reos = [ re.compile(r'(?su)\{(?P<action>eval):(?P<expr>.*?)\}(?!\\)'), re.compile(r'(?su)\{(?P<action>[^\\\W][-\w]*?):(?P<expr>.*?)\}(?!\\)'), ] skipped = False for reo in reos: pos = 0 while True: mo = reo.search(line,pos) if not mo: break expr = mo.group('expr') action = mo.group('action') expr = expr.replace('{\\','{') expr = expr.replace('}\\','}') s = system(action, expr, attrs=dictionary) if dictionary is not None and action in ('counter','counter2','set','set2'): # These actions create and update attributes. attrs.update(dictionary) if s is None: # Drop line if the action returns None. skipped = True break line = line[:mo.start()] + s + line[mo.end():] pos = mo.start() + len(s) if skipped: break if not skipped: # Remove backslash from escaped entries. line = line.replace('{\\','{') line = line.replace('}\\','}') result.append(line) if string_result: if result: return '\n'.join(result) else: return None else: return tuple(result) def char_encoding(): encoding = document.attributes.get('encoding') if encoding: try: codecs.lookup(encoding) except LookupError,e: raise EAsciiDoc,str(e) return encoding def char_len(s): return len(char_decode(s)) east_asian_widths = {'W': 2, # Wide 'F': 2, # Full-width (wide) 'Na': 1, # Narrow 'H': 1, # Half-width (narrow) 'N': 1, # Neutral (not East Asian, treated as narrow) 'A': 1} # Ambiguous (s/b wide in East Asian context, # narrow otherwise, but that doesn't work) """Mapping of result codes from `unicodedata.east_asian_width()` to character column widths.""" def column_width(s): text = char_decode(s) if isinstance(text, unicode): width = 0 for c in text: width += east_asian_widths[unicodedata.east_asian_width(c)] return width else: return len(text) def char_decode(s): if char_encoding(): try: return s.decode(char_encoding()) except Exception: raise EAsciiDoc, \ "'%s' codec can't decode \"%s\"" % (char_encoding(), s) else: return s def char_encode(s): if char_encoding(): return s.encode(char_encoding()) else: return s def time_str(t): """Convert seconds since the Epoch to formatted local time string.""" t = time.localtime(t) s = time.strftime('%H:%M:%S',t) if time.daylight and t.tm_isdst == 1: result = s + ' ' + time.tzname[1] else: result = s + ' ' + time.tzname[0] # Attempt to convert the localtime to the output encoding. try: result = char_encode(result.decode(locale.getdefaultlocale()[1])) except Exception: pass return result def date_str(t): """Convert seconds since the Epoch to formatted local date string.""" t = time.localtime(t) return time.strftime('%Y-%m-%d',t) class Lex: """Lexical analysis routines. Static methods and attributes only.""" prev_element = None prev_cursor = None def __init__(self): raise AssertionError,'no class instances allowed' @staticmethod def next(): """Returns class of next element on the input (None if EOF). The reader is assumed to be at the first line following a previous element, end of file or line one. Exits with the reader pointing to the first line of the next element or EOF (leading blank lines are skipped).""" reader.skip_blank_lines() if reader.eof(): return None # Optimization: If we've already checked for an element at this # position return the element. if Lex.prev_element and Lex.prev_cursor == reader.cursor: return Lex.prev_element if AttributeEntry.isnext(): result = AttributeEntry elif AttributeList.isnext(): result = AttributeList elif BlockTitle.isnext() and not tables_OLD.isnext(): result = BlockTitle elif Title.isnext(): if AttributeList.style() == 'float': result = FloatingTitle else: result = Title elif macros.isnext(): result = macros.current elif lists.isnext(): result = lists.current elif blocks.isnext(): result = blocks.current elif tables_OLD.isnext(): result = tables_OLD.current elif tables.isnext(): result = tables.current else: if not paragraphs.isnext(): raise EAsciiDoc,'paragraph expected' result = paragraphs.current # Optimization: Cache answer. Lex.prev_cursor = reader.cursor Lex.prev_element = result return result @staticmethod def canonical_subs(options): """Translate composite subs values.""" if len(options) == 1: if options[0] == 'none': options = () elif options[0] == 'normal': options = config.subsnormal elif options[0] == 'verbatim': options = config.subsverbatim return options @staticmethod def subs_1(s,options): """Perform substitution specified in 'options' (in 'options' order).""" if not s: return s if document.attributes.get('plaintext') is not None: options = ('specialcharacters',) result = s options = Lex.canonical_subs(options) for o in options: if o == 'specialcharacters': result = config.subs_specialchars(result) elif o == 'attributes': result = subs_attrs(result) elif o == 'quotes': result = subs_quotes(result) elif o == 'specialwords': result = config.subs_specialwords(result) elif o in ('replacements','replacements2'): result = config.subs_replacements(result,o) elif o == 'macros': result = macros.subs(result) elif o == 'callouts': result = macros.subs(result,callouts=True) else: raise EAsciiDoc,'illegal substitution option: %s' % o trace(o, s, result) if not result: break return result @staticmethod def subs(lines,options): """Perform inline processing specified by 'options' (in 'options' order) on sequence of 'lines'.""" if not lines or not options: return lines options = Lex.canonical_subs(options) # Join lines so quoting can span multiple lines. para = '\n'.join(lines) if 'macros' in options: para = macros.extract_passthroughs(para) for o in options: if o == 'attributes': # If we don't substitute attributes line-by-line then a single # undefined attribute will drop the entire paragraph. lines = subs_attrs(para.split('\n')) para = '\n'.join(lines) else: para = Lex.subs_1(para,(o,)) if 'macros' in options: para = macros.restore_passthroughs(para) return para.splitlines() @staticmethod def set_margin(lines, margin=0): """Utility routine that sets the left margin to 'margin' space in a block of non-blank lines.""" # Calculate width of block margin. lines = list(lines) width = len(lines[0]) for s in lines: i = re.search(r'\S',s).start() if i < width: width = i # Strip margin width from all lines. for i in range(len(lines)): lines[i] = ' '*margin + lines[i][width:] return lines #--------------------------------------------------------------------------- # Document element classes parse AsciiDoc reader input and write DocBook writer # output. #--------------------------------------------------------------------------- class Document(object): # doctype property. def getdoctype(self): return self.attributes.get('doctype') def setdoctype(self,doctype): self.attributes['doctype'] = doctype doctype = property(getdoctype,setdoctype) # backend property. def getbackend(self): return self.attributes.get('backend') def setbackend(self,backend): if backend: backend = self.attributes.get('backend-alias-' + backend, backend) self.attributes['backend'] = backend backend = property(getbackend,setbackend) def __init__(self): self.infile = None # Source file name. self.outfile = None # Output file name. self.attributes = InsensitiveDict() self.level = 0 # 0 => front matter. 1,2,3 => sect1,2,3. self.has_errors = False # Set true if processing errors were flagged. self.has_warnings = False # Set true if warnings were flagged. self.safe = False # Default safe mode. def update_attributes(self,attrs=None): """ Set implicit attributes and attributes in 'attrs'. """ t = time.time() self.attributes['localtime'] = time_str(t) self.attributes['localdate'] = date_str(t) self.attributes['asciidoc-version'] = VERSION self.attributes['asciidoc-file'] = APP_FILE self.attributes['asciidoc-dir'] = APP_DIR if localapp(): self.attributes['asciidoc-confdir'] = APP_DIR else: self.attributes['asciidoc-confdir'] = CONF_DIR self.attributes['user-dir'] = USER_DIR if config.verbose: self.attributes['verbose'] = '' # Update with configuration file attributes. if attrs: self.attributes.update(attrs) # Update with command-line attributes. self.attributes.update(config.cmd_attrs) # Extract miscellaneous configuration section entries from attributes. if attrs: config.load_miscellaneous(attrs) config.load_miscellaneous(config.cmd_attrs) self.attributes['newline'] = config.newline # File name related attributes can't be overridden. if self.infile is not None: if self.infile and os.path.exists(self.infile): t = os.path.getmtime(self.infile) elif self.infile == '<stdin>': t = time.time() else: t = None if t: self.attributes['doctime'] = time_str(t) self.attributes['docdate'] = date_str(t) if self.infile != '<stdin>': self.attributes['infile'] = self.infile self.attributes['indir'] = os.path.dirname(self.infile) self.attributes['docfile'] = self.infile self.attributes['docdir'] = os.path.dirname(self.infile) self.attributes['docname'] = os.path.splitext( os.path.basename(self.infile))[0] if self.outfile: if self.outfile != '<stdout>': self.attributes['outfile'] = self.outfile self.attributes['outdir'] = os.path.dirname(self.outfile) if self.infile == '<stdin>': self.attributes['docname'] = os.path.splitext( os.path.basename(self.outfile))[0] ext = os.path.splitext(self.outfile)[1][1:] elif config.outfilesuffix: ext = config.outfilesuffix[1:] else: ext = '' if ext: self.attributes['filetype'] = ext self.attributes['filetype-'+ext] = '' def load_lang(self): """ Load language configuration file. """ lang = self.attributes.get('lang') if lang is None: filename = 'lang-en.conf' # Default language file. else: filename = 'lang-' + lang + '.conf' if config.load_from_dirs(filename): self.attributes['lang'] = lang # Reinstate new lang attribute. else: if lang is None: # The default language file must exist. message.error('missing conf file: %s' % filename, halt=True) else: message.warning('missing language conf file: %s' % filename) def set_deprecated_attribute(self,old,new): """ Ensures the 'old' name of an attribute that was renamed to 'new' is still honored. """ if self.attributes.get(new) is None: if self.attributes.get(old) is not None: self.attributes[new] = self.attributes[old] else: self.attributes[old] = self.attributes[new] def consume_attributes_and_comments(self,comments_only=False,noblanks=False): """ Returns True if one or more attributes or comments were consumed. If 'noblanks' is True then consumation halts if a blank line is encountered. """ result = False finished = False while not finished: finished = True if noblanks and not reader.read_next(): return result if blocks.isnext() and 'skip' in blocks.current.options: result = True finished = False blocks.current.translate() if noblanks and not reader.read_next(): return result if macros.isnext() and macros.current.name == 'comment': result = True finished = False macros.current.translate() if not comments_only: if AttributeEntry.isnext(): result = True finished = False AttributeEntry.translate() if AttributeList.isnext(): result = True finished = False AttributeList.translate() return result def parse_header(self,doctype,backend): """ Parses header, sets corresponding document attributes and finalizes document doctype and backend properties. Returns False if the document does not have a header. 'doctype' and 'backend' are the doctype and backend option values passed on the command-line, None if no command-line option was not specified. """ assert self.level == 0 # Skip comments and attribute entries that preceed the header. self.consume_attributes_and_comments() if doctype is not None: # Command-line overrides header. self.doctype = doctype elif self.doctype is None: # Was not set on command-line or in document header. self.doctype = DEFAULT_DOCTYPE # Process document header. has_header = (Title.isnext() and Title.level == 0 and AttributeList.style() != 'float') if self.doctype == 'manpage' and not has_header: message.error('manpage document title is mandatory',halt=True) if has_header: Header.parse() # Command-line entries override header derived entries. self.attributes.update(config.cmd_attrs) # DEPRECATED: revision renamed to revnumber. self.set_deprecated_attribute('revision','revnumber') # DEPRECATED: date renamed to revdate. self.set_deprecated_attribute('date','revdate') if doctype is not None: # Command-line overrides header. self.doctype = doctype if backend is not None: # Command-line overrides header. self.backend = backend elif self.backend is None: # Was not set on command-line or in document header. self.backend = DEFAULT_BACKEND else: # Has been set in document header. self.backend = self.backend # Translate alias in header. assert self.doctype in ('article','manpage','book'), 'illegal document type' return has_header def translate(self,has_header): if self.doctype == 'manpage': # Translate mandatory NAME section. if Lex.next() is not Title: message.error('name section expected') else: Title.translate() if Title.level != 1: message.error('name section title must be at level 1') if not isinstance(Lex.next(),Paragraph): message.error('malformed name section body') lines = reader.read_until(r'^$') s = ' '.join(lines) mo = re.match(r'^(?P<manname>.*?)\s+-\s+(?P<manpurpose>.*)$',s) if not mo: message.error('malformed name section body') self.attributes['manname'] = mo.group('manname').strip() self.attributes['manpurpose'] = mo.group('manpurpose').strip() names = [s.strip() for s in self.attributes['manname'].split(',')] if len(names) > 9: message.warning('to many manpage names') for i,name in enumerate(names): self.attributes['manname%d' % (i+1)] = name if has_header: # Do postponed substitutions (backend confs have been loaded). self.attributes['doctitle'] = Title.dosubs(self.attributes['doctitle']) if config.header_footer: hdr = config.subs_section('header',{}) writer.write(hdr,trace='header') if 'title' in self.attributes: del self.attributes['title'] self.consume_attributes_and_comments() if self.doctype in ('article','book'): # Translate 'preamble' (untitled elements between header # and first section title). if Lex.next() is not Title: stag,etag = config.section2tags('preamble') writer.write(stag,trace='preamble open') Section.translate_body() writer.write(etag,trace='preamble close') elif self.doctype == 'manpage' and 'name' in config.sections: writer.write(config.subs_section('name',{}), trace='name') else: self.process_author_names() if config.header_footer: hdr = config.subs_section('header',{}) writer.write(hdr,trace='header') if Lex.next() is not Title: Section.translate_body() # Process remaining sections. while not reader.eof(): if Lex.next() is not Title: raise EAsciiDoc,'section title expected' Section.translate() Section.setlevel(0) # Write remaining unwritten section close tags. # Substitute document parameters and write document footer. if config.header_footer: ftr = config.subs_section('footer',{}) writer.write(ftr,trace='footer') def parse_author(self,s): """ Return False if the author is malformed.""" attrs = self.attributes # Alias for readability. s = s.strip() mo = re.match(r'^(?P<name1>[^<>\s]+)' '(\s+(?P<name2>[^<>\s]+))?' '(\s+(?P<name3>[^<>\s]+))?' '(\s+<(?P<email>\S+)>)?$',s) if not mo: # Names that don't match the formal specification. if s: attrs['firstname'] = s return firstname = mo.group('name1') if mo.group('name3'): middlename = mo.group('name2') lastname = mo.group('name3') else: middlename = None lastname = mo.group('name2') firstname = firstname.replace('_',' ') if middlename: middlename = middlename.replace('_',' ') if lastname: lastname = lastname.replace('_',' ') email = mo.group('email') if firstname: attrs['firstname'] = firstname if middlename: attrs['middlename'] = middlename if lastname: attrs['lastname'] = lastname if email: attrs['email'] = email return def process_author_names(self): """ Calculate any missing author related attributes.""" attrs = self.attributes # Alias for readability. firstname = attrs.get('firstname','') middlename = attrs.get('middlename','') lastname = attrs.get('lastname','') author = attrs.get('author') initials = attrs.get('authorinitials') if author and not (firstname or middlename or lastname): self.parse_author(author) attrs['author'] = author.replace('_',' ') self.process_author_names() return if not author: author = '%s %s %s' % (firstname, middlename, lastname) author = author.strip() author = re.sub(r'\s+',' ', author) if not initials: initials = (char_decode(firstname)[:1] + char_decode(middlename)[:1] + char_decode(lastname)[:1]) initials = char_encode(initials).upper() names = [firstname,middlename,lastname,author,initials] for i,v in enumerate(names): v = config.subs_specialchars(v) v = subs_attrs(v) names[i] = v firstname,middlename,lastname,author,initials = names if firstname: attrs['firstname'] = firstname if middlename: attrs['middlename'] = middlename if lastname: attrs['lastname'] = lastname if author: attrs['author'] = author if initials: attrs['authorinitials'] = initials if author: attrs['authored'] = '' class Header: """Static methods and attributes only.""" REV_LINE_RE = r'^(\D*(?P<revnumber>.*?),)?(?P<revdate>.*?)(:\s*(?P<revremark>.*))?$' RCS_ID_RE = r'^\$Id: \S+ (?P<revnumber>\S+) (?P<revdate>\S+) \S+ (?P<author>\S+) (\S+ )?\$$' def __init__(self): raise AssertionError,'no class instances allowed' @staticmethod def parse(): assert Lex.next() is Title and Title.level == 0 attrs = document.attributes # Alias for readability. # Postpone title subs until backend conf files have been loaded. Title.translate(skipsubs=True) attrs['doctitle'] = Title.attributes['title'] document.consume_attributes_and_comments(noblanks=True) s = reader.read_next() mo = None if s: # Process first header line after the title that is not a comment # or an attribute entry. s = reader.read() mo = re.match(Header.RCS_ID_RE,s) if not mo: document.parse_author(s) document.consume_attributes_and_comments(noblanks=True) if reader.read_next(): # Process second header line after the title that is not a # comment or an attribute entry. s = reader.read() s = subs_attrs(s) if s: mo = re.match(Header.RCS_ID_RE,s) if not mo: mo = re.match(Header.REV_LINE_RE,s) document.consume_attributes_and_comments(noblanks=True) s = attrs.get('revnumber') if s: mo = re.match(Header.RCS_ID_RE,s) if mo: revnumber = mo.group('revnumber') if revnumber: attrs['revnumber'] = revnumber.strip() author = mo.groupdict().get('author') if author and 'firstname' not in attrs: document.parse_author(author) revremark = mo.groupdict().get('revremark') if revremark is not None: revremark = [revremark] # Revision remarks can continue on following lines. while reader.read_next(): if document.consume_attributes_and_comments(noblanks=True): break revremark.append(reader.read()) revremark = Lex.subs(revremark,['normal']) revremark = '\n'.join(revremark).strip() attrs['revremark'] = revremark revdate = mo.group('revdate') if revdate: attrs['revdate'] = revdate.strip() elif revnumber or revremark: # Set revision date to ensure valid DocBook revision. attrs['revdate'] = attrs['docdate'] document.process_author_names() if document.doctype == 'manpage': # manpage title formatted like mantitle(manvolnum). mo = re.match(r'^(?P<mantitle>.*)\((?P<manvolnum>.*)\)$', attrs['doctitle']) if not mo: message.error('malformed manpage title') else: mantitle = mo.group('mantitle').strip() mantitle = subs_attrs(mantitle) if mantitle is None: message.error('undefined attribute in manpage title') # mantitle is lowered only if in ALL CAPS if mantitle == mantitle.upper(): mantitle = mantitle.lower() attrs['mantitle'] = mantitle; attrs['manvolnum'] = mo.group('manvolnum').strip() class AttributeEntry: """Static methods and attributes only.""" pattern = None subs = None name = None name2 = None value = None attributes = {} # Accumulates all the parsed attribute entries. def __init__(self): raise AssertionError,'no class instances allowed' @staticmethod def isnext(): result = False # Assume not next. if not AttributeEntry.pattern: pat = document.attributes.get('attributeentry-pattern') if not pat: message.error("[attributes] missing 'attributeentry-pattern' entry") AttributeEntry.pattern = pat line = reader.read_next() if line: # Attribute entry formatted like :<name>[.<name2>]:[ <value>] mo = re.match(AttributeEntry.pattern,line) if mo: AttributeEntry.name = mo.group('attrname') AttributeEntry.name2 = mo.group('attrname2') AttributeEntry.value = mo.group('attrvalue') or '' AttributeEntry.value = AttributeEntry.value.strip() result = True return result @staticmethod def translate(): assert Lex.next() is AttributeEntry attr = AttributeEntry # Alias for brevity. reader.read() # Discard attribute entry from reader. while attr.value.endswith(' +'): if not reader.read_next(): break attr.value = attr.value[:-1] + reader.read().strip() if attr.name2 is not None: # Configuration file attribute. if attr.name2 != '': # Section entry attribute. section = {} # Some sections can have name! syntax. if attr.name in ('attributes','miscellaneous') and attr.name2[-1] == '!': section[attr.name] = [attr.name2] else: section[attr.name] = ['%s=%s' % (attr.name2,attr.value)] config.load_sections(section) config.load_miscellaneous(config.conf_attrs) else: # Markup template section attribute. if attr.name in config.sections: config.sections[attr.name] = [attr.value] else: message.warning('missing configuration section: %s' % attr.name) else: # Normal attribute. if attr.name[-1] == '!': # Names like name! undefine the attribute. attr.name = attr.name[:-1] attr.value = None # Strip white space and illegal name chars. attr.name = re.sub(r'(?u)[^\w\-_]', '', attr.name).lower() # Don't override most command-line attributes. if attr.name in config.cmd_attrs \ and attr.name not in ('trace','numbered'): return # Update document attributes with attribute value. if attr.value is not None: mo = re.match(r'^pass:(?P<attrs>.*)\[(?P<value>.*)\]$', attr.value) if mo: # Inline passthrough syntax. attr.subs = mo.group('attrs') attr.value = mo.group('value') # Passthrough. else: # Default substitution. # DEPRECATED: attributeentry-subs attr.subs = document.attributes.get('attributeentry-subs', 'specialcharacters,attributes') attr.subs = parse_options(attr.subs, SUBS_OPTIONS, 'illegal substitution option') attr.value = Lex.subs((attr.value,), attr.subs) attr.value = writer.newline.join(attr.value) document.attributes[attr.name] = attr.value elif attr.name in document.attributes: del document.attributes[attr.name] attr.attributes[attr.name] = attr.value class AttributeList: """Static methods and attributes only.""" pattern = None match = None attrs = {} def __init__(self): raise AssertionError,'no class instances allowed' @staticmethod def initialize(): if not 'attributelist-pattern' in document.attributes: message.error("[attributes] missing 'attributelist-pattern' entry") AttributeList.pattern = document.attributes['attributelist-pattern'] @staticmethod def isnext(): result = False # Assume not next. line = reader.read_next() if line: mo = re.match(AttributeList.pattern, line) if mo: AttributeList.match = mo result = True return result @staticmethod def translate(): assert Lex.next() is AttributeList reader.read() # Discard attribute list from reader. attrs = {} d = AttributeList.match.groupdict() for k,v in d.items(): if v is not None: if k == 'attrlist': v = subs_attrs(v) if v: parse_attributes(v, attrs) else: AttributeList.attrs[k] = v AttributeList.subs(attrs) AttributeList.attrs.update(attrs) @staticmethod def subs(attrs): '''Substitute single quoted attribute values normally.''' reo = re.compile(r"^'.*'$") for k,v in attrs.items(): if reo.match(str(v)): attrs[k] = Lex.subs_1(v[1:-1],SUBS_NORMAL) @staticmethod def style(): return AttributeList.attrs.get('style') or AttributeList.attrs.get('1') @staticmethod def consume(d): """Add attribute list to the dictionary 'd' and reset the list.""" if AttributeList.attrs: d.update(AttributeList.attrs) AttributeList.attrs = {} # Generate option attributes. if 'options' in d: options = parse_options(d['options'], (), 'illegal option name') for option in options: d[option+'-option'] = '' class BlockTitle: """Static methods and attributes only.""" title = None pattern = None def __init__(self): raise AssertionError,'no class instances allowed' @staticmethod def isnext(): result = False # Assume not next. line = reader.read_next() if line: mo = re.match(BlockTitle.pattern,line) if mo: BlockTitle.title = mo.group('title') result = True return result @staticmethod def translate(): assert Lex.next() is BlockTitle reader.read() # Discard title from reader. # Perform title substitutions. if not Title.subs: Title.subs = config.subsnormal s = Lex.subs((BlockTitle.title,), Title.subs) s = writer.newline.join(s) if not s: message.warning('blank block title') BlockTitle.title = s @staticmethod def consume(d): """If there is a title add it to dictionary 'd' then reset title.""" if BlockTitle.title: d['title'] = BlockTitle.title BlockTitle.title = None class Title: """Processes Header and Section titles. Static methods and attributes only.""" # Class variables underlines = ('==','--','~~','^^','++') # Levels 0,1,2,3,4. subs = () pattern = None level = 0 attributes = {} sectname = None section_numbers = [0]*len(underlines) dump_dict = {} linecount = None # Number of lines in title (1 or 2). def __init__(self): raise AssertionError,'no class instances allowed' @staticmethod def translate(skipsubs=False): """Parse the Title.attributes and Title.level from the reader. The real work has already been done by parse().""" assert Lex.next() in (Title,FloatingTitle) # Discard title from reader. for i in range(Title.linecount): reader.read() Title.setsectname() if not skipsubs: Title.attributes['title'] = Title.dosubs(Title.attributes['title']) @staticmethod def dosubs(title): """ Perform title substitutions. """ if not Title.subs: Title.subs = config.subsnormal title = Lex.subs((title,), Title.subs) title = writer.newline.join(title) if not title: message.warning('blank section title') return title @staticmethod def isnext(): lines = reader.read_ahead(2) return Title.parse(lines) @staticmethod def parse(lines): """Parse title at start of lines tuple.""" if len(lines) == 0: return False if len(lines[0]) == 0: return False # Title can't be blank. # Check for single-line titles. result = False for level in range(len(Title.underlines)): k = 'sect%s' % level if k in Title.dump_dict: mo = re.match(Title.dump_dict[k], lines[0]) if mo: Title.attributes = mo.groupdict() Title.level = level Title.linecount = 1 result = True break if not result: # Check for double-line titles. if not Title.pattern: return False # Single-line titles only. if len(lines) < 2: return False title,ul = lines[:2] title_len = column_width(title) ul_len = char_len(ul) if ul_len < 2: return False # Fast elimination check. if ul[:2] not in Title.underlines: return False # Length of underline must be within +-3 of title. if not ((ul_len-3 < title_len < ul_len+3) # Next test for backward compatibility. or (ul_len-3 < char_len(title) < ul_len+3)): return False # Check for valid repetition of underline character pairs. s = ul[:2]*((ul_len+1)/2) if ul != s[:ul_len]: return False # Don't be fooled by back-to-back delimited blocks, require at # least one alphanumeric character in title. if not re.search(r'(?u)\w',title): return False mo = re.match(Title.pattern, title) if mo: Title.attributes = mo.groupdict() Title.level = list(Title.underlines).index(ul[:2]) Title.linecount = 2 result = True # Check for expected pattern match groups. if result: if not 'title' in Title.attributes: message.warning('[titles] entry has no <title> group') Title.attributes['title'] = lines[0] for k,v in Title.attributes.items(): if v is None: del Title.attributes[k] try: Title.level += int(document.attributes.get('leveloffset','0')) except: pass Title.attributes['level'] = str(Title.level) return result @staticmethod def load(entries): """Load and validate [titles] section entries dictionary.""" if 'underlines' in entries: errmsg = 'malformed [titles] underlines entry' try: underlines = parse_list(entries['underlines']) except Exception: raise EAsciiDoc,errmsg if len(underlines) != len(Title.underlines): raise EAsciiDoc,errmsg for s in underlines: if len(s) !=2: raise EAsciiDoc,errmsg Title.underlines = tuple(underlines) Title.dump_dict['underlines'] = entries['underlines'] if 'subs' in entries: Title.subs = parse_options(entries['subs'], SUBS_OPTIONS, 'illegal [titles] subs entry') Title.dump_dict['subs'] = entries['subs'] if 'sectiontitle' in entries: pat = entries['sectiontitle'] if not pat or not is_re(pat): raise EAsciiDoc,'malformed [titles] sectiontitle entry' Title.pattern = pat Title.dump_dict['sectiontitle'] = pat if 'blocktitle' in entries: pat = entries['blocktitle'] if not pat or not is_re(pat): raise EAsciiDoc,'malformed [titles] blocktitle entry' BlockTitle.pattern = pat Title.dump_dict['blocktitle'] = pat # Load single-line title patterns. for k in ('sect0','sect1','sect2','sect3','sect4'): if k in entries: pat = entries[k] if not pat or not is_re(pat): raise EAsciiDoc,'malformed [titles] %s entry' % k Title.dump_dict[k] = pat # TODO: Check we have either a Title.pattern or at least one # single-line title pattern -- can this be done here or do we need # check routine like the other block checkers? @staticmethod def dump(): dump_section('titles',Title.dump_dict) @staticmethod def setsectname(): """ Set Title section name: If the first positional or 'template' attribute is set use it, next search for section title in [specialsections], if not found use default 'sect<level>' name. """ sectname = AttributeList.attrs.get('1') if sectname and sectname != 'float': Title.sectname = sectname elif 'template' in AttributeList.attrs: Title.sectname = AttributeList.attrs['template'] else: for pat,sect in config.specialsections.items(): mo = re.match(pat,Title.attributes['title']) if mo: title = mo.groupdict().get('title') if title is not None: Title.attributes['title'] = title.strip() else: Title.attributes['title'] = mo.group().strip() Title.sectname = sect break else: Title.sectname = 'sect%d' % Title.level @staticmethod def getnumber(level): """Return next section number at section 'level' formatted like 1.2.3.4.""" number = '' for l in range(len(Title.section_numbers)): n = Title.section_numbers[l] if l == 0: continue elif l < level: number = '%s%d.' % (number, n) elif l == level: number = '%s%d.' % (number, n + 1) Title.section_numbers[l] = n + 1 elif l > level: # Reset unprocessed section levels. Title.section_numbers[l] = 0 return number class FloatingTitle(Title): '''Floated titles are translated differently.''' @staticmethod def isnext(): return Title.isnext() and AttributeList.style() == 'float' @staticmethod def translate(): assert Lex.next() is FloatingTitle Title.translate() Section.set_id() AttributeList.consume(Title.attributes) template = 'floatingtitle' if template in config.sections: stag,etag = config.section2tags(template,Title.attributes) writer.write(stag,trace='floating title') else: message.warning('missing template section: [%s]' % template) class Section: """Static methods and attributes only.""" endtags = [] # Stack of currently open section (level,endtag) tuples. ids = [] # List of already used ids. def __init__(self): raise AssertionError,'no class instances allowed' @staticmethod def savetag(level,etag): """Save section end.""" Section.endtags.append((level,etag)) @staticmethod def setlevel(level): """Set document level and write open section close tags up to level.""" while Section.endtags and Section.endtags[-1][0] >= level: writer.write(Section.endtags.pop()[1],trace='section close') document.level = level @staticmethod def gen_id(title): """ The normalized value of the id attribute is an NCName according to the 'Namespaces in XML' Recommendation: NCName ::= NCNameStartChar NCNameChar* NCNameChar ::= NameChar - ':' NCNameStartChar ::= Letter | '_' NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' """ # Replace non-alpha numeric characters in title with underscores and # convert to lower case. base_ident = char_encode(re.sub(r'(?u)\W+', '_', char_decode(title)).strip('_').lower()) # Prefix the ID name with idprefix attribute or underscore if not # defined. Prefix ensures the ID does not clash with existing IDs. idprefix = document.attributes.get('idprefix','_') base_ident = idprefix + base_ident i = 1 while True: if i == 1: ident = base_ident else: ident = '%s_%d' % (base_ident, i) if ident not in Section.ids: Section.ids.append(ident) return ident else: ident = base_ident i += 1 @staticmethod def set_id(): if not document.attributes.get('sectids') is None \ and 'id' not in AttributeList.attrs: # Generate ids for sections. AttributeList.attrs['id'] = Section.gen_id(Title.attributes['title']) @staticmethod def translate(): assert Lex.next() is Title prev_sectname = Title.sectname Title.translate() if Title.level == 0 and document.doctype != 'book': message.error('only book doctypes can contain level 0 sections') if Title.level > document.level \ and 'basebackend-docbook' in document.attributes \ and prev_sectname in ('colophon','abstract', \ 'dedication','glossary','bibliography'): message.error('%s section cannot contain sub-sections' % prev_sectname) if Title.level > document.level+1: # Sub-sections of multi-part book level zero Preface and Appendices # are meant to be out of sequence. if document.doctype == 'book' \ and document.level == 0 \ and Title.level == 2 \ and prev_sectname in ('preface','appendix'): pass else: message.warning('section title out of sequence: ' 'expected level %d, got level %d' % (document.level+1, Title.level)) Section.set_id() Section.setlevel(Title.level) if 'numbered' in document.attributes: Title.attributes['sectnum'] = Title.getnumber(document.level) else: Title.attributes['sectnum'] = '' AttributeList.consume(Title.attributes) stag,etag = config.section2tags(Title.sectname,Title.attributes) Section.savetag(Title.level,etag) writer.write(stag,trace='section open: level %d: %s' % (Title.level, Title.attributes['title'])) Section.translate_body() @staticmethod def translate_body(terminator=Title): isempty = True next = Lex.next() while next and next is not terminator: if isinstance(terminator,DelimitedBlock) and next is Title: message.error('section title not permitted in delimited block') next.translate() next = Lex.next() isempty = False # The section is not empty if contains a subsection. if next and isempty and Title.level > document.level: isempty = False # Report empty sections if invalid markup will result. if isempty: if document.backend == 'docbook' and Title.sectname != 'index': message.error('empty section is not valid') class AbstractBlock: def __init__(self): # Configuration parameter names common to all blocks. self.CONF_ENTRIES = ('delimiter','options','subs','presubs','postsubs', 'posattrs','style','.*-style','template','filter') self.start = None # File reader cursor at start delimiter. self.name=None # Configuration file section name. # Configuration parameters. self.delimiter=None # Regular expression matching block delimiter. self.delimiter_reo=None # Compiled delimiter. self.template=None # template section entry. self.options=() # options entry list. self.presubs=None # presubs/subs entry list. self.postsubs=() # postsubs entry list. self.filter=None # filter entry. self.posattrs=() # posattrs entry list. self.style=None # Default style. self.styles=OrderedDict() # Each entry is a styles dictionary. # Before a block is processed it's attributes (from it's # attributes list) are merged with the block configuration parameters # (by self.merge_attributes()) resulting in the template substitution # dictionary (self.attributes) and the block's processing parameters # (self.parameters). self.attributes={} # The names of block parameters. self.PARAM_NAMES=('template','options','presubs','postsubs','filter') self.parameters=None # Leading delimiter match object. self.mo=None def short_name(self): """ Return the text following the last dash in the section name.""" i = self.name.rfind('-') if i == -1: return self.name else: return self.name[i+1:] def error(self, msg, cursor=None, halt=False): message.error('[%s] %s' % (self.name,msg), cursor, halt) def is_conf_entry(self,param): """Return True if param matches an allowed configuration file entry name.""" for s in self.CONF_ENTRIES: if re.match('^'+s+'$',param): return True return False def load(self,name,entries): """Update block definition from section 'entries' dictionary.""" self.name = name self.update_parameters(entries, self, all=True) def update_parameters(self, src, dst=None, all=False): """ Parse processing parameters from src dictionary to dst object. dst defaults to self.parameters. If all is True then copy src entries that aren't parameter names. """ dst = dst or self.parameters msg = '[%s] malformed entry %%s: %%s' % self.name def copy(obj,k,v): if isinstance(obj,dict): obj[k] = v else: setattr(obj,k,v) for k,v in src.items(): if not re.match(r'\d+',k) and not is_name(k): raise EAsciiDoc, msg % (k,v) if k == 'template': if not is_name(v): raise EAsciiDoc, msg % (k,v) copy(dst,k,v) elif k == 'filter': copy(dst,k,v) elif k == 'options': if isinstance(v,str): v = parse_options(v, (), msg % (k,v)) # Merge with existing options. v = tuple(set(dst.options).union(set(v))) copy(dst,k,v) elif k in ('subs','presubs','postsubs'): # Subs is an alias for presubs. if k == 'subs': k = 'presubs' if isinstance(v,str): v = parse_options(v, SUBS_OPTIONS, msg % (k,v)) copy(dst,k,v) elif k == 'delimiter': if v and is_re(v): copy(dst,k,v) else: raise EAsciiDoc, msg % (k,v) elif k == 'style': if is_name(v): copy(dst,k,v) else: raise EAsciiDoc, msg % (k,v) elif k == 'posattrs': v = parse_options(v, (), msg % (k,v)) copy(dst,k,v) else: mo = re.match(r'^(?P<style>.*)-style$',k) if mo: if not v: raise EAsciiDoc, msg % (k,v) style = mo.group('style') if not is_name(style): raise EAsciiDoc, msg % (k,v) d = {} if not parse_named_attributes(v,d): raise EAsciiDoc, msg % (k,v) if 'subs' in d: # Subs is an alias for presubs. d['presubs'] = d['subs'] del d['subs'] self.styles[style] = d elif all or k in self.PARAM_NAMES: copy(dst,k,v) # Derived class specific entries. def get_param(self,name,params=None): """ Return named processing parameter from params dictionary. If the parameter is not in params look in self.parameters. """ if params and name in params: return params[name] elif name in self.parameters: return self.parameters[name] else: return None def get_subs(self,params=None): """ Return (presubs,postsubs) tuple. """ presubs = self.get_param('presubs',params) postsubs = self.get_param('postsubs',params) return (presubs,postsubs) def dump(self): """Write block definition to stdout.""" write = lambda s: sys.stdout.write('%s%s' % (s,writer.newline)) write('['+self.name+']') if self.is_conf_entry('delimiter'): write('delimiter='+self.delimiter) if self.template: write('template='+self.template) if self.options: write('options='+','.join(self.options)) if self.presubs: if self.postsubs: write('presubs='+','.join(self.presubs)) else: write('subs='+','.join(self.presubs)) if self.postsubs: write('postsubs='+','.join(self.postsubs)) if self.filter: write('filter='+self.filter) if self.posattrs: write('posattrs='+','.join(self.posattrs)) if self.style: write('style='+self.style) if self.styles: for style,d in self.styles.items(): s = '' for k,v in d.items(): s += '%s=%r,' % (k,v) write('%s-style=%s' % (style,s[:-1])) def validate(self): """Validate block after the complete configuration has been loaded.""" if self.is_conf_entry('delimiter') and not self.delimiter: raise EAsciiDoc,'[%s] missing delimiter' % self.name if self.style: if not is_name(self.style): raise EAsciiDoc, 'illegal style name: %s' % self.style if not self.style in self.styles: if not isinstance(self,List): # Lists don't have templates. message.warning('[%s] \'%s\' style not in %s' % ( self.name,self.style,self.styles.keys())) # Check all styles for missing templates. all_styles_have_template = True for k,v in self.styles.items(): t = v.get('template') if t and not t in config.sections: # Defer check if template name contains attributes. if not re.search(r'{.+}',t): message.warning('missing template section: [%s]' % t) if not t: all_styles_have_template = False # Check we have a valid template entry or alternatively that all the # styles have templates. if self.is_conf_entry('template') and not 'skip' in self.options: if self.template: if not self.template in config.sections: # Defer check if template name contains attributes. if not re.search(r'{.+}',self.template): message.warning('missing template section: [%s]' % self.template) elif not all_styles_have_template: if not isinstance(self,List): # Lists don't have templates. message.warning('missing styles templates: [%s]' % self.name) def isnext(self): """Check if this block is next in document reader.""" result = False reader.skip_blank_lines() if reader.read_next(): if not self.delimiter_reo: # Cache compiled delimiter optimization. self.delimiter_reo = re.compile(self.delimiter) mo = self.delimiter_reo.match(reader.read_next()) if mo: self.mo = mo result = True return result def translate(self): """Translate block from document reader.""" if not self.presubs: self.presubs = config.subsnormal if reader.cursor: self.start = reader.cursor[:] def merge_attributes(self,attrs,params=[]): """ Use the current blocks attribute list (attrs dictionary) to build a dictionary of block processing parameters (self.parameters) and tag substitution attributes (self.attributes). 1. Copy the default parameters (self.*) to self.parameters. self.parameters are used internally to render the current block. Optional params array of additional parameters. 2. Copy attrs to self.attributes. self.attributes are used for template and tag substitution in the current block. 3. If a style attribute was specified update self.parameters with the corresponding style parameters; if there are any style parameters remaining add them to self.attributes (existing attribute list entries take precedence). 4. Set named positional attributes in self.attributes if self.posattrs was specified. 5. Finally self.parameters is updated with any corresponding parameters specified in attrs. """ def check_array_parameter(param): # Check the parameter is a sequence type. if not is_array(self.parameters[param]): message.error('malformed presubs attribute: %s' % self.parameters[param]) # Revert to default value. self.parameters[param] = getattr(self,param) params = list(self.PARAM_NAMES) + params self.attributes = {} if self.style: # If a default style is defined make it available in the template. self.attributes['style'] = self.style self.attributes.update(attrs) # Calculate dynamic block parameters. # Start with configuration file defaults. self.parameters = AttrDict() for name in params: self.parameters[name] = getattr(self,name) # Load the selected style attributes. posattrs = self.posattrs if posattrs and posattrs[0] == 'style': # Positional attribute style has highest precedence. style = self.attributes.get('1') else: style = None if not style: # Use explicit style attribute, fall back to default style. style = self.attributes.get('style',self.style) if style: if not is_name(style): message.error('illegal style name: %s' % style) style = self.style # Lists have implicit styles and do their own style checks. elif style not in self.styles and not isinstance(self,List): message.warning('missing style: [%s]: %s' % (self.name,style)) style = self.style if style in self.styles: self.attributes['style'] = style for k,v in self.styles[style].items(): if k == 'posattrs': posattrs = v elif k in params: self.parameters[k] = v elif not k in self.attributes: # Style attributes don't take precedence over explicit. self.attributes[k] = v # Set named positional attributes. for i,v in enumerate(posattrs): if str(i+1) in self.attributes: self.attributes[v] = self.attributes[str(i+1)] # Override config and style attributes with attribute list attributes. self.update_parameters(attrs) check_array_parameter('options') check_array_parameter('presubs') check_array_parameter('postsubs') class AbstractBlocks: """List of block definitions.""" PREFIX = '' # Conf file section name prefix set in derived classes. BLOCK_TYPE = None # Block type set in derived classes. def __init__(self): self.current=None self.blocks = [] # List of Block objects. self.default = None # Default Block. self.delimiters = None # Combined delimiters regular expression. def load(self,sections): """Load block definition from 'sections' dictionary.""" for k in sections.keys(): if re.match(r'^'+ self.PREFIX + r'.+$',k): d = {} parse_entries(sections.get(k,()),d) for b in self.blocks: if b.name == k: break else: b = self.BLOCK_TYPE() self.blocks.append(b) try: b.load(k,d) except EAsciiDoc,e: raise EAsciiDoc,'[%s] %s' % (k,str(e)) def dump(self): for b in self.blocks: b.dump() def isnext(self): for b in self.blocks: if b.isnext(): self.current = b return True; return False def validate(self): """Validate the block definitions.""" # Validate delimiters and build combined lists delimiter pattern. delimiters = [] for b in self.blocks: assert b.__class__ is self.BLOCK_TYPE b.validate() if b.delimiter: delimiters.append(b.delimiter) self.delimiters = re_join(delimiters) class Paragraph(AbstractBlock): def __init__(self): AbstractBlock.__init__(self) self.text=None # Text in first line of paragraph. def load(self,name,entries): AbstractBlock.load(self,name,entries) def dump(self): AbstractBlock.dump(self) write = lambda s: sys.stdout.write('%s%s' % (s,writer.newline)) write('') def isnext(self): result = AbstractBlock.isnext(self) if result: self.text = self.mo.groupdict().get('text') return result def translate(self): AbstractBlock.translate(self) attrs = self.mo.groupdict().copy() if 'text' in attrs: del attrs['text'] BlockTitle.consume(attrs) AttributeList.consume(attrs) self.merge_attributes(attrs) reader.read() # Discard (already parsed item first line). body = reader.read_until(paragraphs.terminators) body = [self.text] + list(body) presubs = self.parameters.presubs postsubs = self.parameters.postsubs if document.attributes.get('plaintext') is None: body = Lex.set_margin(body) # Move body to left margin. body = Lex.subs(body,presubs) template = self.parameters.template template = subs_attrs(template,attrs) stag = config.section2tags(template, self.attributes,skipend=True)[0] if self.parameters.filter: body = filter_lines(self.parameters.filter,body,self.attributes) body = Lex.subs(body,postsubs) etag = config.section2tags(template, self.attributes,skipstart=True)[1] # Write start tag, content, end tag. writer.write(dovetail_tags(stag,body,etag),trace='paragraph') class Paragraphs(AbstractBlocks): """List of paragraph definitions.""" BLOCK_TYPE = Paragraph PREFIX = 'paradef-' def __init__(self): AbstractBlocks.__init__(self) self.terminators=None # List of compiled re's. def initialize(self): self.terminators = [ re.compile(r'^\+$|^$'), re.compile(AttributeList.pattern), re.compile(blocks.delimiters), re.compile(tables.delimiters), re.compile(tables_OLD.delimiters), ] def load(self,sections): AbstractBlocks.load(self,sections) def validate(self): AbstractBlocks.validate(self) # Check we have a default paragraph definition, put it last in list. for b in self.blocks: if b.name == 'paradef-default': self.blocks.append(b) self.default = b self.blocks.remove(b) break else: raise EAsciiDoc,'missing section: [paradef-default]' class List(AbstractBlock): NUMBER_STYLES= ('arabic','loweralpha','upperalpha','lowerroman', 'upperroman') def __init__(self): AbstractBlock.__init__(self) self.CONF_ENTRIES += ('type','tags') self.PARAM_NAMES += ('tags',) # tabledef conf file parameters. self.type=None self.tags=None # Name of listtags-<tags> conf section. # Calculated parameters. self.tag=None # Current tags AttrDict. self.label=None # List item label (labeled lists). self.text=None # Text in first line of list item. self.index=None # Matched delimiter 'index' group (numbered lists). self.type=None # List type ('numbered','bulleted','labeled'). self.ordinal=None # Current list item ordinal number (1..) self.number_style=None # Current numbered list style ('arabic'..) def load(self,name,entries): AbstractBlock.load(self,name,entries) def dump(self): AbstractBlock.dump(self) write = lambda s: sys.stdout.write('%s%s' % (s,writer.newline)) write('type='+self.type) write('tags='+self.tags) write('') def validate(self): AbstractBlock.validate(self) tags = [self.tags] tags += [s['tags'] for s in self.styles.values() if 'tags' in s] for t in tags: if t not in lists.tags: self.error('missing section: [listtags-%s]' % t,halt=True) def isnext(self): result = AbstractBlock.isnext(self) if result: self.label = self.mo.groupdict().get('label') self.text = self.mo.groupdict().get('text') self.index = self.mo.groupdict().get('index') return result def translate_entry(self): assert self.type == 'labeled' entrytag = subs_tag(self.tag.entry, self.attributes) labeltag = subs_tag(self.tag.label, self.attributes) writer.write(entrytag[0],trace='list entry open') writer.write(labeltag[0],trace='list label open') # Write labels. while Lex.next() is self: reader.read() # Discard (already parsed item first line). writer.write_tag(self.tag.term, [self.label], self.presubs, self.attributes,trace='list term') if self.text: break writer.write(labeltag[1],trace='list label close') # Write item text. self.translate_item() writer.write(entrytag[1],trace='list entry close') def translate_item(self): if self.type == 'callout': self.attributes['coids'] = calloutmap.calloutids(self.ordinal) itemtag = subs_tag(self.tag.item, self.attributes) writer.write(itemtag[0],trace='list item open') # Write ItemText. text = reader.read_until(lists.terminators) if self.text: text = [self.text] + list(text) if text: writer.write_tag(self.tag.text, text, self.presubs, self.attributes,trace='list text') # Process explicit and implicit list item continuations. while True: continuation = reader.read_next() == '+' if continuation: reader.read() # Discard continuation line. while Lex.next() in (BlockTitle,AttributeList): # Consume continued element title and attributes. Lex.next().translate() if not continuation and BlockTitle.title: # Titled elements terminate the list. break next = Lex.next() if next in lists.open: break elif isinstance(next,List): next.translate() elif isinstance(next,Paragraph) and 'listelement' in next.options: next.translate() elif continuation: # This is where continued elements are processed. if next is Title: message.error('section title not allowed in list item',halt=True) next.translate() else: break writer.write(itemtag[1],trace='list item close') @staticmethod def calc_style(index): """Return the numbered list style ('arabic'...) of the list item index. Return None if unrecognized style.""" if re.match(r'^\d+[\.>]$', index): style = 'arabic' elif re.match(r'^[ivx]+\)$', index): style = 'lowerroman' elif re.match(r'^[IVX]+\)$', index): style = 'upperroman' elif re.match(r'^[a-z]\.$', index): style = 'loweralpha' elif re.match(r'^[A-Z]\.$', index): style = 'upperalpha' else: assert False return style @staticmethod def calc_index(index,style): """Return the ordinal number of (1...) of the list item index for the given list style.""" def roman_to_int(roman): roman = roman.lower() digits = {'i':1,'v':5,'x':10} result = 0 for i in range(len(roman)): digit = digits[roman[i]] # If next digit is larger this digit is negative. if i+1 < len(roman) and digits[roman[i+1]] > digit: result -= digit else: result += digit return result index = index[:-1] if style == 'arabic': ordinal = int(index) elif style == 'lowerroman': ordinal = roman_to_int(index) elif style == 'upperroman': ordinal = roman_to_int(index) elif style == 'loweralpha': ordinal = ord(index) - ord('a') + 1 elif style == 'upperalpha': ordinal = ord(index) - ord('A') + 1 else: assert False return ordinal def check_index(self): """Check calculated self.ordinal (1,2,...) against the item number in the document (self.index) and check the number style is the same as the first item (self.number_style).""" assert self.type in ('numbered','callout') if self.index: style = self.calc_style(self.index) if style != self.number_style: message.warning('list item style: expected %s got %s' % (self.number_style,style), offset=1) ordinal = self.calc_index(self.index,style) if ordinal != self.ordinal: message.warning('list item index: expected %s got %s' % (self.ordinal,ordinal), offset=1) def check_tags(self): """ Check that all necessary tags are present. """ tags = set(Lists.TAGS) if self.type != 'labeled': tags = tags.difference(['entry','label','term']) missing = tags.difference(self.tag.keys()) if missing: self.error('missing tag(s): %s' % ','.join(missing), halt=True) def translate(self): AbstractBlock.translate(self) if self.short_name() in ('bibliography','glossary','qanda'): message.deprecated('old %s list syntax' % self.short_name()) lists.open.append(self) attrs = self.mo.groupdict().copy() for k in ('label','text','index'): if k in attrs: del attrs[k] if self.index: # Set the numbering style from first list item. attrs['style'] = self.calc_style(self.index) BlockTitle.consume(attrs) AttributeList.consume(attrs) self.merge_attributes(attrs,['tags']) if self.type in ('numbered','callout'): self.number_style = self.attributes.get('style') if self.number_style not in self.NUMBER_STYLES: message.error('illegal numbered list style: %s' % self.number_style) # Fall back to default style. self.attributes['style'] = self.number_style = self.style self.tag = lists.tags[self.parameters.tags] self.check_tags() if 'width' in self.attributes: # Set horizontal list 'labelwidth' and 'itemwidth' attributes. v = str(self.attributes['width']) mo = re.match(r'^(\d{1,2})%?$',v) if mo: labelwidth = int(mo.group(1)) self.attributes['labelwidth'] = str(labelwidth) self.attributes['itemwidth'] = str(100-labelwidth) else: self.error('illegal attribute value: width="%s"' % v) stag,etag = subs_tag(self.tag.list, self.attributes) if stag: writer.write(stag,trace='list open') self.ordinal = 0 # Process list till list syntax changes or there is a new title. while Lex.next() is self and not BlockTitle.title: self.ordinal += 1 document.attributes['listindex'] = str(self.ordinal) if self.type in ('numbered','callout'): self.check_index() if self.type in ('bulleted','numbered','callout'): reader.read() # Discard (already parsed item first line). self.translate_item() elif self.type == 'labeled': self.translate_entry() else: raise AssertionError,'illegal [%s] list type' % self.name if etag: writer.write(etag,trace='list close') if self.type == 'callout': calloutmap.validate(self.ordinal) calloutmap.listclose() lists.open.pop() if len(lists.open): document.attributes['listindex'] = str(lists.open[-1].ordinal) class Lists(AbstractBlocks): """List of List objects.""" BLOCK_TYPE = List PREFIX = 'listdef-' TYPES = ('bulleted','numbered','labeled','callout') TAGS = ('list', 'entry','item','text', 'label','term') def __init__(self): AbstractBlocks.__init__(self) self.open = [] # A stack of the current and parent lists. self.tags={} # List tags dictionary. Each entry is a tags AttrDict. self.terminators=None # List of compiled re's. def initialize(self): self.terminators = [ re.compile(r'^\+$|^$'), re.compile(AttributeList.pattern), re.compile(lists.delimiters), re.compile(blocks.delimiters), re.compile(tables.delimiters), re.compile(tables_OLD.delimiters), ] def load(self,sections): AbstractBlocks.load(self,sections) self.load_tags(sections) def load_tags(self,sections): """ Load listtags-* conf file sections to self.tags. """ for section in sections.keys(): mo = re.match(r'^listtags-(?P<name>\w+)$',section) if mo: name = mo.group('name') if name in self.tags: d = self.tags[name] else: d = AttrDict() parse_entries(sections.get(section,()),d) for k in d.keys(): if k not in self.TAGS: message.warning('[%s] contains illegal list tag: %s' % (section,k)) self.tags[name] = d def validate(self): AbstractBlocks.validate(self) for b in self.blocks: # Check list has valid type. if not b.type in Lists.TYPES: raise EAsciiDoc,'[%s] illegal type' % b.name b.validate() def dump(self): AbstractBlocks.dump(self) for k,v in self.tags.items(): dump_section('listtags-'+k, v) class DelimitedBlock(AbstractBlock): def __init__(self): AbstractBlock.__init__(self) def load(self,name,entries): AbstractBlock.load(self,name,entries) def dump(self): AbstractBlock.dump(self) write = lambda s: sys.stdout.write('%s%s' % (s,writer.newline)) write('') def isnext(self): return AbstractBlock.isnext(self) def translate(self): AbstractBlock.translate(self) reader.read() # Discard delimiter. attrs = {} if self.short_name() != 'comment': BlockTitle.consume(attrs) AttributeList.consume(attrs) self.merge_attributes(attrs) options = self.parameters.options if 'skip' in options: reader.read_until(self.delimiter,same_file=True) elif safe() and self.name == 'blockdef-backend': message.unsafe('Backend Block') reader.read_until(self.delimiter,same_file=True) else: template = self.parameters.template template = subs_attrs(template,attrs) name = self.short_name()+' block' if 'sectionbody' in options: # The body is treated like a section body. stag,etag = config.section2tags(template,self.attributes) writer.write(stag,trace=name+' open') Section.translate_body(self) writer.write(etag,trace=name+' close') else: stag = config.section2tags(template,self.attributes,skipend=True)[0] body = reader.read_until(self.delimiter,same_file=True) presubs = self.parameters.presubs postsubs = self.parameters.postsubs body = Lex.subs(body,presubs) if self.parameters.filter: body = filter_lines(self.parameters.filter,body,self.attributes) body = Lex.subs(body,postsubs) # Write start tag, content, end tag. etag = config.section2tags(template,self.attributes,skipstart=True)[1] writer.write(dovetail_tags(stag,body,etag),trace=name) trace(self.short_name()+' block close',etag) if reader.eof(): self.error('missing closing delimiter',self.start) else: delimiter = reader.read() # Discard delimiter line. assert re.match(self.delimiter,delimiter) class DelimitedBlocks(AbstractBlocks): """List of delimited blocks.""" BLOCK_TYPE = DelimitedBlock PREFIX = 'blockdef-' def __init__(self): AbstractBlocks.__init__(self) def load(self,sections): """Update blocks defined in 'sections' dictionary.""" AbstractBlocks.load(self,sections) def validate(self): AbstractBlocks.validate(self) class Column: """Table column.""" def __init__(self, width=None, align_spec=None, style=None): self.width = width or '1' self.halign, self.valign = Table.parse_align_spec(align_spec) self.style = style # Style name or None. # Calculated attribute values. self.abswidth = None # 1.. (page units). self.pcwidth = None # 1..99 (percentage). class Cell: def __init__(self, data, span_spec=None, align_spec=None, style=None): self.data = data self.span, self.vspan = Table.parse_span_spec(span_spec) self.halign, self.valign = Table.parse_align_spec(align_spec) self.style = style self.reserved = False def __repr__(self): return '<Cell: %d.%d %s.%s %s "%s">' % ( self.span, self.vspan, self.halign, self.valign, self.style or '', self.data) def clone_reserve(self): """Return a clone of self to reserve vertically spanned cell.""" result = copy.copy(self) result.vspan = 1 result.reserved = True return result class Table(AbstractBlock): ALIGN = {'<':'left', '>':'right', '^':'center'} VALIGN = {'<':'top', '>':'bottom', '^':'middle'} FORMATS = ('psv','csv','dsv') SEPARATORS = dict( csv=',', dsv=r':|\n', # The count and align group matches are not exact. psv=r'((?<!\S)((?P<span>[\d.]+)(?P<op>[*+]))?(?P<align>[<\^>.]{,3})?(?P<style>[a-z])?)?\|' ) def __init__(self): AbstractBlock.__init__(self) self.CONF_ENTRIES += ('format','tags','separator') # tabledef conf file parameters. self.format='psv' self.separator=None self.tags=None # Name of tabletags-<tags> conf section. # Calculated parameters. self.abswidth=None # 1.. (page units). self.pcwidth = None # 1..99 (percentage). self.rows=[] # Parsed rows, each row is a list of Cells. self.columns=[] # List of Columns. @staticmethod def parse_align_spec(align_spec): """ Parse AsciiDoc cell alignment specifier and return 2-tuple with horizonatal and vertical alignment names. Unspecified alignments set to None. """ result = (None, None) if align_spec: mo = re.match(r'^([<\^>])?(\.([<\^>]))?$', align_spec) if mo: result = (Table.ALIGN.get(mo.group(1)), Table.VALIGN.get(mo.group(3))) return result @staticmethod def parse_span_spec(span_spec): """ Parse AsciiDoc cell span specifier and return 2-tuple with horizonatal and vertical span counts. Set default values (1,1) if not specified. """ result = (None, None) if span_spec: mo = re.match(r'^(\d+)?(\.(\d+))?$', span_spec) if mo: result = (mo.group(1) and int(mo.group(1)), mo.group(3) and int(mo.group(3))) return (result[0] or 1, result[1] or 1) def load(self,name,entries): AbstractBlock.load(self,name,entries) def dump(self): AbstractBlock.dump(self) write = lambda s: sys.stdout.write('%s%s' % (s,writer.newline)) write('format='+self.format) write('') def validate(self): AbstractBlock.validate(self) if self.format not in Table.FORMATS: self.error('illegal format=%s' % self.format,halt=True) self.tags = self.tags or 'default' tags = [self.tags] tags += [s['tags'] for s in self.styles.values() if 'tags' in s] for t in tags: if t not in tables.tags: self.error('missing section: [tabletags-%s]' % t,halt=True) if self.separator: # Evaluate escape characters. self.separator = literal_eval('"'+self.separator+'"') #TODO: Move to class Tables # Check global table parameters. elif config.pagewidth is None: self.error('missing [miscellaneous] entry: pagewidth') elif config.pageunits is None: self.error('missing [miscellaneous] entry: pageunits') def validate_attributes(self): """Validate and parse table attributes.""" # Set defaults. format = self.format tags = self.tags separator = self.separator abswidth = float(config.pagewidth) pcwidth = 100.0 for k,v in self.attributes.items(): if k == 'format': if v not in self.FORMATS: self.error('illegal %s=%s' % (k,v)) else: format = v elif k == 'tags': if v not in tables.tags: self.error('illegal %s=%s' % (k,v)) else: tags = v elif k == 'separator': separator = v elif k == 'width': if not re.match(r'^\d{1,3}%$',v) or int(v[:-1]) > 100: self.error('illegal %s=%s' % (k,v)) else: abswidth = float(v[:-1])/100 * config.pagewidth pcwidth = float(v[:-1]) # Calculate separator if it has not been specified. if not separator: separator = Table.SEPARATORS[format] if format == 'csv': if len(separator) > 1: self.error('illegal csv separator=%s' % separator) separator = ',' else: if not is_re(separator): self.error('illegal regular expression: separator=%s' % separator) self.parameters.format = format self.parameters.tags = tags self.parameters.separator = separator self.abswidth = abswidth self.pcwidth = pcwidth def get_tags(self,params): tags = self.get_param('tags',params) assert(tags and tags in tables.tags) return tables.tags[tags] def get_style(self,prefix): """ Return the style dictionary whose name starts with 'prefix'. """ if prefix is None: return None names = self.styles.keys() names.sort() for name in names: if name.startswith(prefix): return self.styles[name] else: self.error('missing style: %s*' % prefix) return None def parse_cols(self, cols, halign, valign): """ Build list of column objects from table 'cols', 'halign' and 'valign' attributes. """ # [<multiplier>*][<align>][<width>][<style>] COLS_RE1 = r'^((?P<count>\d+)\*)?(?P<align>[<\^>.]{,3})?(?P<width>\d+%?)?(?P<style>[a-z]\w*)?$' # [<multiplier>*][<width>][<align>][<style>] COLS_RE2 = r'^((?P<count>\d+)\*)?(?P<width>\d+%?)?(?P<align>[<\^>.]{,3})?(?P<style>[a-z]\w*)?$' reo1 = re.compile(COLS_RE1) reo2 = re.compile(COLS_RE2) cols = str(cols) if re.match(r'^\d+$',cols): for i in range(int(cols)): self.columns.append(Column()) else: for col in re.split(r'\s*,\s*',cols): mo = reo1.match(col) if not mo: mo = reo2.match(col) if mo: count = int(mo.groupdict().get('count') or 1) for i in range(count): self.columns.append( Column(mo.group('width'), mo.group('align'), self.get_style(mo.group('style'))) ) else: self.error('illegal column spec: %s' % col,self.start) # Set column (and indirectly cell) default alignments. for col in self.columns: col.halign = col.halign or halign or document.attributes.get('halign') or 'left' col.valign = col.valign or valign or document.attributes.get('valign') or 'top' # Validate widths and calculate missing widths. n = 0; percents = 0; props = 0 for col in self.columns: if col.width: if col.width[-1] == '%': percents += int(col.width[:-1]) else: props += int(col.width) n += 1 if percents > 0 and props > 0: self.error('mixed percent and proportional widths: %s' % cols,self.start) pcunits = percents > 0 # Fill in missing widths. if n < len(self.columns) and percents < 100: if pcunits: width = float(100 - percents)/float(len(self.columns) - n) else: width = 1 for col in self.columns: if not col.width: if pcunits: col.width = str(int(width))+'%' percents += width else: col.width = str(width) props += width # Calculate column alignment and absolute and percent width values. percents = 0 for col in self.columns: if pcunits: col.pcwidth = float(col.width[:-1]) else: col.pcwidth = (float(col.width)/props)*100 col.abswidth = self.abswidth * (col.pcwidth/100) if config.pageunits in ('cm','mm','in','em'): col.abswidth = '%.2f' % round(col.abswidth,2) else: col.abswidth = '%d' % round(col.abswidth) percents += col.pcwidth col.pcwidth = int(col.pcwidth) if round(percents) > 100: self.error('total width exceeds 100%%: %s' % cols,self.start) elif round(percents) < 100: self.error('total width less than 100%%: %s' % cols,self.start) def build_colspecs(self): """ Generate column related substitution attributes. """ cols = [] i = 1 for col in self.columns: colspec = self.get_tags(col.style).colspec if colspec: self.attributes['halign'] = col.halign self.attributes['valign'] = col.valign self.attributes['colabswidth'] = col.abswidth self.attributes['colpcwidth'] = col.pcwidth self.attributes['colnumber'] = str(i) s = subs_attrs(colspec, self.attributes) if not s: message.warning('colspec dropped: contains undefined attribute') else: cols.append(s) i += 1 if cols: self.attributes['colspecs'] = writer.newline.join(cols) def parse_rows(self, text): """ Parse the table source text into self.rows (a list of rows, each row is a list of Cells. """ reserved = {} # Reserved cells generated by rowspans. if self.parameters.format in ('psv','dsv'): colcount = len(self.columns) parsed_cells = self.parse_psv_dsv(text) ri = 0 # Current row index 0.. ci = 0 # Column counter 0..colcount row = [] i = 0 while True: resv = reserved.get(ri) and reserved[ri].get(ci) if resv: # We have a cell generated by a previous row span so # process it before continuing with the current parsed # cell. cell = resv else: if i >= len(parsed_cells): break # No more parsed or reserved cells. cell = parsed_cells[i] i += 1 if cell.vspan > 1: # Generate ensuing reserved cells spanned vertically by # the current cell. for j in range(1, cell.vspan): if not ri+j in reserved: reserved[ri+j] = {} reserved[ri+j][ci] = cell.clone_reserve() ci += cell.span if ci <= colcount: row.append(cell) if ci >= colcount: self.rows.append(row) ri += 1 row = [] ci = 0 elif self.parameters.format == 'csv': self.rows = self.parse_csv(text) else: assert True,'illegal table format' # Check for empty rows containing only reserved (spanned) cells. for ri,row in enumerate(self.rows): empty = True for cell in row: if not cell.reserved: empty = False break if empty: message.warning('table row %d: empty spanned row' % (ri+1)) # Check that all row spans match. for ri,row in enumerate(self.rows): row_span = 0 for cell in row: row_span += cell.span if ri == 0: header_span = row_span if row_span < header_span: message.warning('table row %d: does not span all columns' % (ri+1)) if row_span > header_span: message.warning('table row %d: exceeds columns span' % (ri+1)) def subs_rows(self, rows, rowtype='body'): """ Return a string of output markup from a list of rows, each row is a list of raw data text. """ tags = tables.tags[self.parameters.tags] if rowtype == 'header': rtag = tags.headrow elif rowtype == 'footer': rtag = tags.footrow else: rtag = tags.bodyrow result = [] stag,etag = subs_tag(rtag,self.attributes) for row in rows: result.append(stag) result += self.subs_row(row,rowtype) result.append(etag) return writer.newline.join(result) def subs_row(self, row, rowtype): """ Substitute the list of Cells using the data tag. Returns a list of marked up table cell elements. """ result = [] i = 0 for cell in row: if cell.reserved: # Skip vertically spanned placeholders. i += cell.span continue if i >= len(self.columns): break # Skip cells outside the header width. col = self.columns[i] self.attributes['halign'] = cell.halign or col.halign self.attributes['valign'] = cell.valign or col.valign self.attributes['colabswidth'] = col.abswidth self.attributes['colpcwidth'] = col.pcwidth self.attributes['colnumber'] = str(i+1) self.attributes['colspan'] = str(cell.span) self.attributes['colstart'] = self.attributes['colnumber'] self.attributes['colend'] = str(i+cell.span) self.attributes['rowspan'] = str(cell.vspan) self.attributes['morerows'] = str(cell.vspan-1) # Fill missing column data with blanks. if i > len(self.columns) - 1: data = '' else: data = cell.data if rowtype == 'header': # Use table style unless overriden by cell style. colstyle = cell.style else: # If the cell style is not defined use the column style. colstyle = cell.style or col.style tags = self.get_tags(colstyle) presubs,postsubs = self.get_subs(colstyle) data = [data] data = Lex.subs(data, presubs) data = filter_lines(self.get_param('filter',colstyle), data, self.attributes) data = Lex.subs(data, postsubs) if rowtype != 'header': ptag = tags.paragraph if ptag: stag,etag = subs_tag(ptag,self.attributes) text = '\n'.join(data).strip() data = [] for para in re.split(r'\n{2,}',text): data += dovetail_tags([stag],para.split('\n'),[etag]) if rowtype == 'header': dtag = tags.headdata elif rowtype == 'footer': dtag = tags.footdata else: dtag = tags.bodydata stag,etag = subs_tag(dtag,self.attributes) result = result + dovetail_tags([stag],data,[etag]) i += cell.span return result def parse_csv(self,text): """ Parse the table source text and return a list of rows, each row is a list of Cells. """ import StringIO import csv rows = [] rdr = csv.reader(StringIO.StringIO('\r\n'.join(text)), delimiter=self.parameters.separator, skipinitialspace=True) try: for row in rdr: rows.append([Cell(data) for data in row]) except Exception: self.error('csv parse error: %s' % row) return rows def parse_psv_dsv(self,text): """ Parse list of PSV or DSV table source text lines and return a list of Cells. """ def append_cell(data, span_spec, op, align_spec, style): op = op or '+' if op == '*': # Cell multiplier. span = Table.parse_span_spec(span_spec)[0] for i in range(span): cells.append(Cell(data, '1', align_spec, style)) elif op == '+': # Column spanner. cells.append(Cell(data, span_spec, align_spec, style)) else: self.error('illegal table cell operator') text = '\n'.join(text) separator = '(?msu)'+self.parameters.separator format = self.parameters.format start = 0 span = None op = None align = None style = None cells = [] data = '' for mo in re.finditer(separator,text): data += text[start:mo.start()] if data.endswith('\\'): data = data[:-1]+mo.group() # Reinstate escaped separators. else: append_cell(data, span, op, align, style) span = mo.groupdict().get('span') op = mo.groupdict().get('op') align = mo.groupdict().get('align') style = mo.groupdict().get('style') if style: style = self.get_style(style) data = '' start = mo.end() # Last cell follows final separator. data += text[start:] append_cell(data, span, op, align, style) # We expect a dummy blank item preceeding first PSV cell. if format == 'psv': if cells[0].data.strip() != '': self.error('missing leading separator: %s' % separator, self.start) else: cells.pop(0) return cells def translate(self): AbstractBlock.translate(self) reader.read() # Discard delimiter. # Reset instance specific properties. self.columns = [] self.rows = [] attrs = {} BlockTitle.consume(attrs) # Mix in document attribute list. AttributeList.consume(attrs) self.merge_attributes(attrs) self.validate_attributes() # Add global and calculated configuration parameters. self.attributes['pagewidth'] = config.pagewidth self.attributes['pageunits'] = config.pageunits self.attributes['tableabswidth'] = int(self.abswidth) self.attributes['tablepcwidth'] = int(self.pcwidth) # Read the entire table. text = reader.read_until(self.delimiter) if reader.eof(): self.error('missing closing delimiter',self.start) else: delimiter = reader.read() # Discard closing delimiter. assert re.match(self.delimiter,delimiter) if len(text) == 0: message.warning('[%s] table is empty' % self.name) return cols = attrs.get('cols') if not cols: # Calculate column count from number of items in first line. if self.parameters.format == 'csv': cols = text[0].count(self.parameters.separator) + 1 else: cols = 0 for cell in self.parse_psv_dsv(text[:1]): cols += cell.span self.parse_cols(cols, attrs.get('halign'), attrs.get('valign')) # Set calculated attributes. self.attributes['colcount'] = len(self.columns) self.build_colspecs() self.parse_rows(text) # The 'rowcount' attribute is used by the experimental LaTeX backend. self.attributes['rowcount'] = str(len(self.rows)) # Generate headrows, footrows, bodyrows. # Headrow, footrow and bodyrow data replaces same named attributes in # the table markup template. In order to ensure this data does not get # a second attribute substitution (which would interfere with any # already substituted inline passthroughs) unique placeholders are used # (the tab character does not appear elsewhere since it is expanded on # input) which are replaced after template attribute substitution. headrows = footrows = bodyrows = None if self.rows and 'header' in self.parameters.options: headrows = self.subs_rows(self.rows[0:1],'header') self.attributes['headrows'] = '\x07headrows\x07' self.rows = self.rows[1:] if self.rows and 'footer' in self.parameters.options: footrows = self.subs_rows( self.rows[-1:], 'footer') self.attributes['footrows'] = '\x07footrows\x07' self.rows = self.rows[:-1] if self.rows: bodyrows = self.subs_rows(self.rows) self.attributes['bodyrows'] = '\x07bodyrows\x07' table = subs_attrs(config.sections[self.parameters.template], self.attributes) table = writer.newline.join(table) # Before we finish replace the table head, foot and body place holders # with the real data. if headrows: table = table.replace('\x07headrows\x07', headrows, 1) if footrows: table = table.replace('\x07footrows\x07', footrows, 1) if bodyrows: table = table.replace('\x07bodyrows\x07', bodyrows, 1) writer.write(table,trace='table') class Tables(AbstractBlocks): """List of tables.""" BLOCK_TYPE = Table PREFIX = 'tabledef-' TAGS = ('colspec', 'headrow','footrow','bodyrow', 'headdata','footdata', 'bodydata','paragraph') def __init__(self): AbstractBlocks.__init__(self) # Table tags dictionary. Each entry is a tags dictionary. self.tags={} def load(self,sections): AbstractBlocks.load(self,sections) self.load_tags(sections) def load_tags(self,sections): """ Load tabletags-* conf file sections to self.tags. """ for section in sections.keys(): mo = re.match(r'^tabletags-(?P<name>\w+)$',section) if mo: name = mo.group('name') if name in self.tags: d = self.tags[name] else: d = AttrDict() parse_entries(sections.get(section,()),d) for k in d.keys(): if k not in self.TAGS: message.warning('[%s] contains illegal table tag: %s' % (section,k)) self.tags[name] = d def validate(self): AbstractBlocks.validate(self) # Check we have a default table definition, for i in range(len(self.blocks)): if self.blocks[i].name == 'tabledef-default': default = self.blocks[i] break else: raise EAsciiDoc,'missing section: [tabledef-default]' # Propagate defaults to unspecified table parameters. for b in self.blocks: if b is not default: if b.format is None: b.format = default.format if b.template is None: b.template = default.template # Check tags and propagate default tags. if not 'default' in self.tags: raise EAsciiDoc,'missing section: [tabletags-default]' default = self.tags['default'] for tag in ('bodyrow','bodydata','paragraph'): # Mandatory default tags. if tag not in default: raise EAsciiDoc,'missing [tabletags-default] entry: %s' % tag for t in self.tags.values(): if t is not default: if t.colspec is None: t.colspec = default.colspec if t.headrow is None: t.headrow = default.headrow if t.footrow is None: t.footrow = default.footrow if t.bodyrow is None: t.bodyrow = default.bodyrow if t.headdata is None: t.headdata = default.headdata if t.footdata is None: t.footdata = default.footdata if t.bodydata is None: t.bodydata = default.bodydata if t.paragraph is None: t.paragraph = default.paragraph # Use body tags if header and footer tags are not specified. for t in self.tags.values(): if not t.headrow: t.headrow = t.bodyrow if not t.footrow: t.footrow = t.bodyrow if not t.headdata: t.headdata = t.bodydata if not t.footdata: t.footdata = t.bodydata # Check table definitions are valid. for b in self.blocks: b.validate() def dump(self): AbstractBlocks.dump(self) for k,v in self.tags.items(): dump_section('tabletags-'+k, v) class Macros: # Default system macro syntax. SYS_RE = r'(?u)^(?P<name>[\\]?\w(\w|-)*?)::(?P<target>\S*?)' + \ r'(\[(?P<attrlist>.*?)\])$' def __init__(self): self.macros = [] # List of Macros. self.current = None # The last matched block macro. self.passthroughs = [] # Initialize default system macro. m = Macro() m.pattern = self.SYS_RE m.prefix = '+' m.reo = re.compile(m.pattern) self.macros.append(m) def load(self,entries): for entry in entries: m = Macro() m.load(entry) if m.name is None: # Delete undefined macro. for i,m2 in enumerate(self.macros): if m2.pattern == m.pattern: del self.macros[i] break else: message.warning('unable to delete missing macro: %s' % m.pattern) else: # Check for duplicates. for m2 in self.macros: if m2.pattern == m.pattern: message.verbose('macro redefinition: %s%s' % (m.prefix,m.name)) break else: self.macros.append(m) def dump(self): write = lambda s: sys.stdout.write('%s%s' % (s,writer.newline)) write('[macros]') # Dump all macros except the first (built-in system) macro. for m in self.macros[1:]: # Escape = in pattern. macro = '%s=%s%s' % (m.pattern.replace('=',r'\='), m.prefix, m.name) if m.subslist is not None: macro += '[' + ','.join(m.subslist) + ']' write(macro) write('') def validate(self): # Check all named sections exist. if config.verbose: for m in self.macros: if m.name and m.prefix != '+': m.section_name() def subs(self,text,prefix='',callouts=False): # If callouts is True then only callout macros are processed, if False # then all non-callout macros are processed. result = text for m in self.macros: if m.prefix == prefix: if callouts ^ (m.name != 'callout'): result = m.subs(result) return result def isnext(self): """Return matching macro if block macro is next on reader.""" reader.skip_blank_lines() line = reader.read_next() if line: for m in self.macros: if m.prefix == '#': if m.reo.match(line): self.current = m return m return False def match(self,prefix,name,text): """Return re match object matching 'text' with macro type 'prefix', macro name 'name'.""" for m in self.macros: if m.prefix == prefix: mo = m.reo.match(text) if mo: if m.name == name: return mo if re.match(name, mo.group('name')): return mo return None def extract_passthroughs(self,text,prefix=''): """ Extract the passthrough text and replace with temporary placeholders.""" self.passthroughs = [] for m in self.macros: if m.has_passthrough() and m.prefix == prefix: text = m.subs_passthroughs(text, self.passthroughs) return text def restore_passthroughs(self,text): """ Replace passthough placeholders with the original passthrough text.""" for i,v in enumerate(self.passthroughs): text = text.replace('\x07'+str(i)+'\x07', self.passthroughs[i]) return text class Macro: def __init__(self): self.pattern = None # Matching regular expression. self.name = '' # Conf file macro name (None if implicit). self.prefix = '' # '' if inline, '+' if system, '#' if block. self.reo = None # Compiled pattern re object. self.subslist = [] # Default subs for macros passtext group. def has_passthrough(self): return self.pattern.find(r'(?P<passtext>') >= 0 def section_name(self,name=None): """Return macro markup template section name based on macro name and prefix. Return None section not found.""" assert self.prefix != '+' if not name: assert self.name name = self.name if self.prefix == '#': suffix = '-blockmacro' else: suffix = '-inlinemacro' if name+suffix in config.sections: return name+suffix else: message.warning('missing macro section: [%s]' % (name+suffix)) return None def load(self,entry): e = parse_entry(entry) if e is None: # Only the macro pattern was specified, mark for deletion. self.name = None self.pattern = entry return if not is_re(e[0]): raise EAsciiDoc,'illegal macro regular expression: %s' % e[0] pattern, name = e if name and name[0] in ('+','#'): prefix, name = name[0], name[1:] else: prefix = '' # Parse passthrough subslist. mo = re.match(r'^(?P<name>[^[]*)(\[(?P<subslist>.*)\])?$', name) name = mo.group('name') if name and not is_name(name): raise EAsciiDoc,'illegal section name in macro entry: %s' % entry subslist = mo.group('subslist') if subslist is not None: # Parse and validate passthrough subs. subslist = parse_options(subslist, SUBS_OPTIONS, 'illegal subs in macro entry: %s' % entry) self.pattern = pattern self.reo = re.compile(pattern) self.prefix = prefix self.name = name self.subslist = subslist or [] def subs(self,text): def subs_func(mo): """Function called to perform macro substitution. Uses matched macro regular expression object and returns string containing the substituted macro body.""" # Check if macro reference is escaped. if mo.group()[0] == '\\': return mo.group()[1:] # Strip leading backslash. d = mo.groupdict() # Delete groups that didn't participate in match. for k,v in d.items(): if v is None: del d[k] if self.name: name = self.name else: if not 'name' in d: message.warning('missing macro name group: %s' % mo.re.pattern) return '' name = d['name'] section_name = self.section_name(name) if not section_name: return '' # If we're dealing with a block macro get optional block ID and # block title. if self.prefix == '#' and self.name != 'comment': AttributeList.consume(d) BlockTitle.consume(d) # Parse macro attributes. if 'attrlist' in d: if d['attrlist'] in (None,''): del d['attrlist'] else: if self.prefix == '': # Unescape ] characters in inline macros. d['attrlist'] = d['attrlist'].replace('\\]',']') parse_attributes(d['attrlist'],d) # Generate option attributes. if 'options' in d: options = parse_options(d['options'], (), '%s: illegal option name' % name) for option in options: d[option+'-option'] = '' # Substitute single quoted attribute values in block macros. if self.prefix == '#': AttributeList.subs(d) if name == 'callout': listindex =int(d['index']) d['coid'] = calloutmap.add(listindex) # The alt attribute is the first image macro positional attribute. if name == 'image' and '1' in d: d['alt'] = d['1'] # Unescape special characters in LaTeX target file names. if document.backend == 'latex' and 'target' in d and d['target']: if not '0' in d: d['0'] = d['target'] d['target']= config.subs_specialchars_reverse(d['target']) # BUG: We've already done attribute substitution on the macro which # means that any escaped attribute references are now unescaped and # will be substituted by config.subs_section() below. As a partial # fix have withheld {0} from substitution but this kludge doesn't # fix it for other attributes containing unescaped references. # Passthrough macros don't have this problem. a0 = d.get('0') if a0: d['0'] = chr(0) # Replace temporarily with unused character. body = config.subs_section(section_name,d) if len(body) == 0: result = '' elif len(body) == 1: result = body[0] else: if self.prefix == '#': result = writer.newline.join(body) else: # Internally processed inline macros use UNIX line # separator. result = '\n'.join(body) if a0: result = result.replace(chr(0), a0) return result return self.reo.sub(subs_func, text) def translate(self): """ Block macro translation.""" assert self.prefix == '#' s = reader.read() before = s if self.has_passthrough(): s = macros.extract_passthroughs(s,'#') s = subs_attrs(s) if s: s = self.subs(s) if self.has_passthrough(): s = macros.restore_passthroughs(s) if s: trace('macro block',before,s) writer.write(s) def subs_passthroughs(self, text, passthroughs): """ Replace macro attribute lists in text with placeholders. Substitute and append the passthrough attribute lists to the passthroughs list.""" def subs_func(mo): """Function called to perform inline macro substitution. Uses matched macro regular expression object and returns string containing the substituted macro body.""" # Don't process escaped macro references. if mo.group()[0] == '\\': return mo.group() d = mo.groupdict() if not 'passtext' in d: message.warning('passthrough macro %s: missing passtext group' % d.get('name','')) return mo.group() passtext = d['passtext'] if re.search('\x07\\d+\x07', passtext): message.warning('nested inline passthrough') return mo.group() if d.get('subslist'): if d['subslist'].startswith(':'): message.error('block macro cannot occur here: %s' % mo.group(), halt=True) subslist = parse_options(d['subslist'], SUBS_OPTIONS, 'illegal passthrough macro subs option') else: subslist = self.subslist passtext = Lex.subs_1(passtext,subslist) if passtext is None: passtext = '' if self.prefix == '': # Unescape ] characters in inline macros. passtext = passtext.replace('\\]',']') passthroughs.append(passtext) # Tabs guarantee the placeholders are unambiguous. result = ( text[mo.start():mo.start('passtext')] + '\x07' + str(len(passthroughs)-1) + '\x07' + text[mo.end('passtext'):mo.end()] ) return result return self.reo.sub(subs_func, text) class CalloutMap: def __init__(self): self.comap = {} # key = list index, value = callouts list. self.calloutindex = 0 # Current callout index number. self.listnumber = 1 # Current callout list number. def listclose(self): # Called when callout list is closed. self.listnumber += 1 self.calloutindex = 0 self.comap = {} def add(self,listindex): # Add next callout index to listindex map entry. Return the callout id. self.calloutindex += 1 # Append the coindex to a list in the comap dictionary. if not listindex in self.comap: self.comap[listindex] = [self.calloutindex] else: self.comap[listindex].append(self.calloutindex) return self.calloutid(self.listnumber, self.calloutindex) @staticmethod def calloutid(listnumber,calloutindex): return 'CO%d-%d' % (listnumber,calloutindex) def calloutids(self,listindex): # Retieve list of callout indexes that refer to listindex. if listindex in self.comap: result = '' for coindex in self.comap[listindex]: result += ' ' + self.calloutid(self.listnumber,coindex) return result.strip() else: message.warning('no callouts refer to list item '+str(listindex)) return '' def validate(self,maxlistindex): # Check that all list indexes referenced by callouts exist. for listindex in self.comap.keys(): if listindex > maxlistindex: message.warning('callout refers to non-existent list item ' + str(listindex)) #--------------------------------------------------------------------------- # Input stream Reader and output stream writer classes. #--------------------------------------------------------------------------- UTF8_BOM = '\xef\xbb\xbf' class Reader1: """Line oriented AsciiDoc input file reader. Processes include and conditional inclusion system macros. Tabs are expanded and lines are right trimmed.""" # This class is not used directly, use Reader class instead. READ_BUFFER_MIN = 10 # Read buffer low level. def __init__(self): self.f = None # Input file object. self.fname = None # Input file name. self.next = [] # Read ahead buffer containing # [filename,linenumber,linetext] lists. self.cursor = None # Last read() [filename,linenumber,linetext]. self.tabsize = 8 # Tab expansion number of spaces. self.parent = None # Included reader's parent reader. self._lineno = 0 # The last line read from file object f. self.current_depth = 0 # Current include depth. self.max_depth = 5 # Initial maxiumum allowed include depth. self.bom = None # Byte order mark (BOM). self.infile = None # Saved document 'infile' attribute. self.indir = None # Saved document 'indir' attribute. def open(self,fname): self.fname = fname message.verbose('reading: '+fname) if fname == '<stdin>': self.f = sys.stdin self.infile = None self.indir = None else: self.f = open(fname,'rb') self.infile = fname self.indir = os.path.dirname(fname) document.attributes['infile'] = self.infile document.attributes['indir'] = self.indir self._lineno = 0 # The last line read from file object f. self.next = [] # Prefill buffer by reading the first line and then pushing it back. if Reader1.read(self): if self.cursor[2].startswith(UTF8_BOM): self.cursor[2] = self.cursor[2][len(UTF8_BOM):] self.bom = UTF8_BOM self.unread(self.cursor) self.cursor = None def closefile(self): """Used by class methods to close nested include files.""" self.f.close() self.next = [] def close(self): self.closefile() self.__init__() def read(self, skip=False): """Read next line. Return None if EOF. Expand tabs. Strip trailing white space. Maintain self.next read ahead buffer. If skip=True then conditional exclusion is active (ifdef and ifndef macros).""" # Top up buffer. if len(self.next) <= self.READ_BUFFER_MIN: s = self.f.readline() if s: self._lineno = self._lineno + 1 while s: if self.tabsize != 0: s = s.expandtabs(self.tabsize) s = s.rstrip() self.next.append([self.fname,self._lineno,s]) if len(self.next) > self.READ_BUFFER_MIN: break s = self.f.readline() if s: self._lineno = self._lineno + 1 # Return first (oldest) buffer entry. if len(self.next) > 0: self.cursor = self.next[0] del self.next[0] result = self.cursor[2] # Check for include macro. mo = macros.match('+',r'^include[1]?$',result) if mo and not skip: # Parse include macro attributes. attrs = {} parse_attributes(mo.group('attrlist'),attrs) warnings = attrs.get('warnings', True) # Don't process include macro once the maximum depth is reached. if self.current_depth >= self.max_depth: return result # Perform attribute substitution on include macro file name. fname = subs_attrs(mo.group('target')) if not fname: return Reader1.read(self) # Return next input line. if self.fname != '<stdin>': fname = os.path.expandvars(os.path.expanduser(fname)) fname = safe_filename(fname, os.path.dirname(self.fname)) if not fname: return Reader1.read(self) # Return next input line. if not os.path.isfile(fname): if warnings: message.warning('include file not found: %s' % fname) return Reader1.read(self) # Return next input line. if mo.group('name') == 'include1': if not config.dumping: if fname not in config.include1: message.verbose('include1: ' + fname, linenos=False) # Store the include file in memory for later # retrieval by the {include1:} system attribute. config.include1[fname] = [ s.rstrip() for s in open(fname)] return '{include1:%s}' % fname else: # This is a configuration dump, just pass the macro # call through. return result # Clone self and set as parent (self assumes the role of child). parent = Reader1() assign(parent,self) self.parent = parent # Set attributes in child. if 'tabsize' in attrs: try: val = int(attrs['tabsize']) if not val >= 0: raise ValueError, "not >= 0" self.tabsize = val except ValueError: raise EAsciiDoc, 'illegal include macro tabsize argument' else: self.tabsize = config.tabsize if 'depth' in attrs: try: val = int(attrs['depth']) if not val >= 1: raise ValueError, "not >= 1" self.max_depth = self.current_depth + val except ValueError: raise EAsciiDoc, 'illegal include macro depth argument' # Process included file. message.verbose('include: ' + fname, linenos=False) self.open(fname) self.current_depth = self.current_depth + 1 result = Reader1.read(self) else: if not Reader1.eof(self): result = Reader1.read(self) else: result = None return result def eof(self): """Returns True if all lines have been read.""" if len(self.next) == 0: # End of current file. if self.parent: self.closefile() assign(self,self.parent) # Restore parent reader. document.attributes['infile'] = self.infile document.attributes['indir'] = self.indir return Reader1.eof(self) else: return True else: return False def read_next(self): """Like read() but does not advance file pointer.""" if Reader1.eof(self): return None else: return self.next[0][2] def unread(self,cursor): """Push the line (filename,linenumber,linetext) tuple back into the read buffer. Note that it's up to the caller to restore the previous cursor.""" assert cursor self.next.insert(0,cursor) class Reader(Reader1): """ Wraps (well, sought of) Reader1 class and implements conditional text inclusion.""" def __init__(self): Reader1.__init__(self) self.depth = 0 # if nesting depth. self.skip = False # true if we're skipping ifdef...endif. self.skipname = '' # Name of current endif macro target. self.skipto = -1 # The depth at which skipping is reenabled. def read_super(self): result = Reader1.read(self,self.skip) if result is None and self.skip: raise EAsciiDoc,'missing endif::%s[]' % self.skipname return result def read(self): result = self.read_super() if result is None: return None while self.skip: mo = macros.match('+',r'ifdef|ifndef|ifeval|endif',result) if mo: name = mo.group('name') target = mo.group('target') attrlist = mo.group('attrlist') if name == 'endif': self.depth -= 1 if self.depth < 0: raise EAsciiDoc,'mismatched macro: %s' % result if self.depth == self.skipto: self.skip = False if target and self.skipname != target: raise EAsciiDoc,'mismatched macro: %s' % result else: if name in ('ifdef','ifndef'): if not target: raise EAsciiDoc,'missing macro target: %s' % result if not attrlist: self.depth += 1 elif name == 'ifeval': if not attrlist: raise EAsciiDoc,'missing ifeval condition: %s' % result self.depth += 1 result = self.read_super() if result is None: return None mo = macros.match('+',r'ifdef|ifndef|ifeval|endif',result) if mo: name = mo.group('name') target = mo.group('target') attrlist = mo.group('attrlist') if name == 'endif': self.depth = self.depth-1 else: if not target and name in ('ifdef','ifndef'): raise EAsciiDoc,'missing macro target: %s' % result defined = is_attr_defined(target, document.attributes) if name == 'ifdef': if attrlist: if defined: return attrlist else: self.skip = not defined elif name == 'ifndef': if attrlist: if not defined: return attrlist else: self.skip = defined elif name == 'ifeval': if safe(): message.unsafe('ifeval invalid') raise EAsciiDoc,'ifeval invalid safe document' if not attrlist: raise EAsciiDoc,'missing ifeval condition: %s' % result cond = False attrlist = subs_attrs(attrlist) if attrlist: try: cond = eval(attrlist) except Exception,e: raise EAsciiDoc,'error evaluating ifeval condition: %s: %s' % (result, str(e)) message.verbose('ifeval: %s: %r' % (attrlist, cond)) self.skip = not cond if not attrlist or name == 'ifeval': if self.skip: self.skipto = self.depth self.skipname = target self.depth = self.depth+1 result = self.read() if result: # Expand executable block macros. mo = macros.match('+',r'eval|sys|sys2',result) if mo: action = mo.group('name') cmd = mo.group('attrlist') s = system(action, cmd, is_macro=True) if s is not None: self.cursor[2] = s # So we don't re-evaluate. result = s if result: # Unescape escaped system macros. if macros.match('+',r'\\eval|\\sys|\\sys2|\\ifdef|\\ifndef|\\endif|\\include|\\include1',result): result = result[1:] return result def eof(self): return self.read_next() is None def read_next(self): save_cursor = self.cursor result = self.read() if result is not None: self.unread(self.cursor) self.cursor = save_cursor return result def read_lines(self,count=1): """Return tuple containing count lines.""" result = [] i = 0 while i < count and not self.eof(): result.append(self.read()) return tuple(result) def read_ahead(self,count=1): """Same as read_lines() but does not advance the file pointer.""" result = [] putback = [] save_cursor = self.cursor try: i = 0 while i < count and not self.eof(): result.append(self.read()) putback.append(self.cursor) i = i+1 while putback: self.unread(putback.pop()) finally: self.cursor = save_cursor return tuple(result) def skip_blank_lines(self): reader.read_until(r'\s*\S+') def read_until(self,terminators,same_file=False): """Like read() but reads lines up to (but not including) the first line that matches the terminator regular expression, regular expression object or list of regular expression objects. If same_file is True then the terminating pattern must occur in the file the was being read when the routine was called.""" if same_file: fname = self.cursor[0] result = [] if not isinstance(terminators,list): if isinstance(terminators,basestring): terminators = [re.compile(terminators)] else: terminators = [terminators] while not self.eof(): save_cursor = self.cursor s = self.read() if not same_file or fname == self.cursor[0]: for reo in terminators: if reo.match(s): self.unread(self.cursor) self.cursor = save_cursor return tuple(result) result.append(s) return tuple(result) class Writer: """Writes lines to output file.""" def __init__(self): self.newline = '\r\n' # End of line terminator. self.f = None # Output file object. self.fname = None # Output file name. self.lines_out = 0 # Number of lines written. self.skip_blank_lines = False # If True don't output blank lines. def open(self,fname,bom=None): ''' bom is optional byte order mark. http://en.wikipedia.org/wiki/Byte-order_mark ''' self.fname = fname if fname == '<stdout>': self.f = sys.stdout else: self.f = open(fname,'wb+') message.verbose('writing: '+writer.fname,False) if bom: self.f.write(bom) self.lines_out = 0 def close(self): if self.fname != '<stdout>': self.f.close() def write_line(self, line=None): if not (self.skip_blank_lines and (not line or not line.strip())): self.f.write((line or '') + self.newline) self.lines_out = self.lines_out + 1 def write(self,*args,**kwargs): """Iterates arguments, writes tuple and list arguments one line per element, else writes argument as single line. If no arguments writes blank line. If argument is None nothing is written. self.newline is appended to each line.""" if 'trace' in kwargs and len(args) > 0: trace(kwargs['trace'],args[0]) if len(args) == 0: self.write_line() self.lines_out = self.lines_out + 1 else: for arg in args: if is_array(arg): for s in arg: self.write_line(s) elif arg is not None: self.write_line(arg) def write_tag(self,tag,content,subs=None,d=None,**kwargs): """Write content enveloped by tag. Substitutions specified in the 'subs' list are perform on the 'content'.""" if subs is None: subs = config.subsnormal stag,etag = subs_tag(tag,d) content = Lex.subs(content,subs) if 'trace' in kwargs: trace(kwargs['trace'],[stag]+content+[etag]) if stag: self.write(stag) if content: self.write(content) if etag: self.write(etag) #--------------------------------------------------------------------------- # Configuration file processing. #--------------------------------------------------------------------------- def _subs_specialwords(mo): """Special word substitution function called by Config.subs_specialwords().""" word = mo.re.pattern # The special word. template = config.specialwords[word] # The corresponding markup template. if not template in config.sections: raise EAsciiDoc,'missing special word template [%s]' % template if mo.group()[0] == '\\': return mo.group()[1:] # Return escaped word. args = {} args['words'] = mo.group() # The full match string is argument 'words'. args.update(mo.groupdict()) # Add other named match groups to the arguments. # Delete groups that didn't participate in match. for k,v in args.items(): if v is None: del args[k] lines = subs_attrs(config.sections[template],args) if len(lines) == 0: result = '' elif len(lines) == 1: result = lines[0] else: result = writer.newline.join(lines) return result class Config: """Methods to process configuration files.""" # Non-template section name regexp's. ENTRIES_SECTIONS= ('tags','miscellaneous','attributes','specialcharacters', 'specialwords','macros','replacements','quotes','titles', r'paradef-.+',r'listdef-.+',r'blockdef-.+',r'tabledef-.+', r'tabletags-.+',r'listtags-.+','replacements2', r'old_tabledef-.+') def __init__(self): self.sections = OrderedDict() # Keyed by section name containing # lists of section lines. # Command-line options. self.verbose = False self.header_footer = True # -s, --no-header-footer option. # [miscellaneous] section. self.tabsize = 8 self.textwidth = 70 # DEPRECATED: Old tables only. self.newline = '\r\n' self.pagewidth = None self.pageunits = None self.outfilesuffix = '' self.subsnormal = SUBS_NORMAL self.subsverbatim = SUBS_VERBATIM self.tags = {} # Values contain (stag,etag) tuples. self.specialchars = {} # Values of special character substitutions. self.specialwords = {} # Name is special word pattern, value is macro. self.replacements = OrderedDict() # Key is find pattern, value is #replace pattern. self.replacements2 = OrderedDict() self.specialsections = {} # Name is special section name pattern, value # is corresponding section name. self.quotes = OrderedDict() # Values contain corresponding tag name. self.fname = '' # Most recently loaded configuration file name. self.conf_attrs = {} # Attributes entries from conf files. self.cmd_attrs = {} # Attributes from command-line -a options. self.loaded = [] # Loaded conf files. self.include1 = {} # Holds include1::[] files for {include1:}. self.dumping = False # True if asciidoc -c option specified. def init(self, cmd): """ Check Python version and locate the executable and configuration files directory. cmd is the asciidoc command or asciidoc.py path. """ if float(sys.version[:3]) < MIN_PYTHON_VERSION: message.stderr('FAILED: Python 2.3 or better required') sys.exit(1) if not os.path.exists(cmd): message.stderr('FAILED: Missing asciidoc command: %s' % cmd) sys.exit(1) global APP_FILE APP_FILE = os.path.realpath(cmd) global APP_DIR APP_DIR = os.path.dirname(APP_FILE) global USER_DIR USER_DIR = userdir() if USER_DIR is not None: USER_DIR = os.path.join(USER_DIR,'.asciidoc') if not os.path.isdir(USER_DIR): USER_DIR = None def load_file(self, fname, dir=None, include=[], exclude=[]): """ Loads sections dictionary with sections from file fname. Existing sections are overlaid. The 'include' list contains the section names to be loaded. The 'exclude' list contains section names not to be loaded. Return False if no file was found in any of the locations. """ if dir: fname = os.path.join(dir, fname) # Sliently skip missing configuration file. if not os.path.isfile(fname): return False # Don't load conf files twice (local and application conf files are the # same if the source file is in the application directory). if os.path.realpath(fname) in self.loaded: return True rdr = Reader() # Reader processes system macros. message.linenos = False # Disable document line numbers. rdr.open(fname) message.linenos = None self.fname = fname reo = re.compile(r'(?u)^\[(?P<section>[^\W\d][\w-]*)\]\s*$') sections = OrderedDict() section,contents = '',[] while not rdr.eof(): s = rdr.read() if s and s[0] == '#': # Skip comment lines. continue if s[:2] == '\\#': # Unescape lines starting with '#'. s = s[1:] s = s.rstrip() found = reo.findall(s) if found: if section: # Store previous section. if section in sections \ and self.entries_section(section): if ''.join(contents): # Merge entries. sections[section] = sections[section] + contents else: del sections[section] else: sections[section] = contents section = found[0].lower() contents = [] else: contents.append(s) if section and contents: # Store last section. if section in sections \ and self.entries_section(section): if ''.join(contents): # Merge entries. sections[section] = sections[section] + contents else: del sections[section] else: sections[section] = contents rdr.close() if include: for s in set(sections) - set(include): del sections[s] if exclude: for s in set(sections) & set(exclude): del sections[s] attrs = {} self.load_sections(sections,attrs) if not include: # If all sections are loaded mark this file as loaded. self.loaded.append(os.path.realpath(fname)) document.update_attributes(attrs) # So they are available immediately. return True def load_sections(self,sections,attrs=None): """ Loads sections dictionary. Each dictionary entry contains a list of lines. Updates 'attrs' with parsed [attributes] section entries. """ # Delete trailing blank lines from sections. for k in sections.keys(): for i in range(len(sections[k])-1,-1,-1): if not sections[k][i]: del sections[k][i] elif not self.entries_section(k): break # Add/overwrite new sections. self.sections.update(sections) self.parse_tags() # Internally [miscellaneous] section entries are just attributes. d = {} parse_entries(sections.get('miscellaneous',()), d, unquote=True, allow_name_only=True) parse_entries(sections.get('attributes',()), d, unquote=True, allow_name_only=True) update_attrs(self.conf_attrs,d) if attrs is not None: attrs.update(d) d = {} parse_entries(sections.get('titles',()),d) Title.load(d) parse_entries(sections.get('specialcharacters',()),self.specialchars,escape_delimiter=False) parse_entries(sections.get('quotes',()),self.quotes) self.parse_specialwords() self.parse_replacements() self.parse_replacements('replacements2') self.parse_specialsections() paragraphs.load(sections) lists.load(sections) blocks.load(sections) tables_OLD.load(sections) tables.load(sections) macros.load(sections.get('macros',())) def get_load_dirs(self): """ Return list of well known paths with conf files. """ result = [] if localapp(): # Load from folders in asciidoc executable directory. result.append(APP_DIR) else: # Load from global configuration directory. result.append(CONF_DIR) # Load configuration files from ~/.asciidoc if it exists. if USER_DIR is not None: result.append(USER_DIR) return result def find_in_dirs(self, filename, dirs=None): """ Find conf files from dirs list. Return list of found file paths. Return empty list if not found in any of the locations. """ result = [] if dirs is None: dirs = self.get_load_dirs() for d in dirs: f = os.path.join(d,filename) if os.path.isfile(f): result.append(f) return result def load_from_dirs(self, filename, dirs=None, include=[]): """ Load conf file from dirs list. If dirs not specified try all the well known locations. Return False if no file was sucessfully loaded. """ count = 0 for f in self.find_in_dirs(filename,dirs): if self.load_file(f, include=include): count += 1 return count != 0 def load_backend(self, dirs=None): """ Load the backend configuration files from dirs list. If dirs not specified try all the well known locations. Return True if a backend conf file was found. """ if dirs is None: dirs = self.get_load_dirs() loaded = False conf = document.backend + '.conf' conf2 = document.backend + '-' + document.doctype + '.conf' # First search for filter backends. for d in [os.path.join(d, 'backends', document.backend) for d in dirs]: if self.load_file(conf,d): loaded = True self.load_file(conf2,d) if not loaded: # Search in the normal locations. for d in dirs: if self.load_file(conf,d): loaded = True self.load_file(conf2,d) return loaded def load_filters(self, dirs=None): """ Load filter configuration files from 'filters' directory in dirs list. If dirs not specified try all the well known locations. """ if dirs is None: dirs = self.get_load_dirs() for d in dirs: # Load filter .conf files. filtersdir = os.path.join(d,'filters') for dirpath,dirnames,filenames in os.walk(filtersdir): for f in filenames: if re.match(r'^.+\.conf$',f): self.load_file(f,dirpath) def find_config_dir(self, *dirnames): """ Return path of configuration directory. Try all the well known locations. Return None if directory not found. """ for d in [os.path.join(d, *dirnames) for d in self.get_load_dirs()]: if os.path.isdir(d): return d return None def set_theme_attributes(self): theme = document.attributes.get('theme') if theme and 'themedir' not in document.attributes: themedir = config.find_config_dir('themes', theme) if themedir: document.attributes['themedir'] = themedir iconsdir = os.path.join(themedir, 'icons') if 'data-uri' in document.attributes and os.path.isdir(iconsdir): document.attributes['iconsdir'] = iconsdir else: message.warning('missing theme: %s' % theme, linenos=False) def load_miscellaneous(self,d): """Set miscellaneous configuration entries from dictionary 'd'.""" def set_if_int_gt_zero(name, d): if name in d: try: val = int(d[name]) if not val > 0: raise ValueError, "not > 0" if val > 0: setattr(self, name, val) except ValueError: raise EAsciiDoc, 'illegal [miscellaneous] %s entry' % name set_if_int_gt_zero('tabsize', d) set_if_int_gt_zero('textwidth', d) # DEPRECATED: Old tables only. if 'pagewidth' in d: try: val = float(d['pagewidth']) self.pagewidth = val except ValueError: raise EAsciiDoc, 'illegal [miscellaneous] pagewidth entry' if 'pageunits' in d: self.pageunits = d['pageunits'] if 'outfilesuffix' in d: self.outfilesuffix = d['outfilesuffix'] if 'newline' in d: # Convert escape sequences to their character values. self.newline = literal_eval('"'+d['newline']+'"') if 'subsnormal' in d: self.subsnormal = parse_options(d['subsnormal'],SUBS_OPTIONS, 'illegal [%s] %s: %s' % ('miscellaneous','subsnormal',d['subsnormal'])) if 'subsverbatim' in d: self.subsverbatim = parse_options(d['subsverbatim'],SUBS_OPTIONS, 'illegal [%s] %s: %s' % ('miscellaneous','subsverbatim',d['subsverbatim'])) def validate(self): """Check the configuration for internal consistancy. Called after all configuration files have been loaded.""" message.linenos = False # Disable document line numbers. # Heuristic to validate that at least one configuration file was loaded. if not self.specialchars or not self.tags or not lists: raise EAsciiDoc,'incomplete configuration files' # Check special characters are only one character long. for k in self.specialchars.keys(): if len(k) != 1: raise EAsciiDoc,'[specialcharacters] ' \ 'must be a single character: %s' % k # Check all special words have a corresponding inline macro body. for macro in self.specialwords.values(): if not is_name(macro): raise EAsciiDoc,'illegal special word name: %s' % macro if not macro in self.sections: message.warning('missing special word macro: [%s]' % macro) # Check all text quotes have a corresponding tag. for q in self.quotes.keys()[:]: tag = self.quotes[q] if not tag: del self.quotes[q] # Undefine quote. else: if tag[0] == '#': tag = tag[1:] if not tag in self.tags: message.warning('[quotes] %s missing tag definition: %s' % (q,tag)) # Check all specialsections section names exist. for k,v in self.specialsections.items(): if not v: del self.specialsections[k] elif not v in self.sections: message.warning('missing specialsections section: [%s]' % v) paragraphs.validate() lists.validate() blocks.validate() tables_OLD.validate() tables.validate() macros.validate() message.linenos = None def entries_section(self,section_name): """ Return True if conf file section contains entries, not a markup template. """ for name in self.ENTRIES_SECTIONS: if re.match(name,section_name): return True return False def dump(self): """Dump configuration to stdout.""" # Header. hdr = '' hdr = hdr + '#' + writer.newline hdr = hdr + '# Generated by AsciiDoc %s for %s %s.%s' % \ (VERSION,document.backend,document.doctype,writer.newline) t = time.asctime(time.localtime(time.time())) hdr = hdr + '# %s%s' % (t,writer.newline) hdr = hdr + '#' + writer.newline sys.stdout.write(hdr) # Dump special sections. # Dump only the configuration file and command-line attributes. # [miscellanous] entries are dumped as part of the [attributes]. d = {} d.update(self.conf_attrs) d.update(self.cmd_attrs) dump_section('attributes',d) Title.dump() dump_section('quotes',self.quotes) dump_section('specialcharacters',self.specialchars) d = {} for k,v in self.specialwords.items(): if v in d: d[v] = '%s "%s"' % (d[v],k) # Append word list. else: d[v] = '"%s"' % k dump_section('specialwords',d) dump_section('replacements',self.replacements) dump_section('replacements2',self.replacements2) dump_section('specialsections',self.specialsections) d = {} for k,v in self.tags.items(): d[k] = '%s|%s' % v dump_section('tags',d) paragraphs.dump() lists.dump() blocks.dump() tables_OLD.dump() tables.dump() macros.dump() # Dump remaining sections. for k in self.sections.keys(): if not self.entries_section(k): sys.stdout.write('[%s]%s' % (k,writer.newline)) for line in self.sections[k]: sys.stdout.write('%s%s' % (line,writer.newline)) sys.stdout.write(writer.newline) def subs_section(self,section,d): """Section attribute substitution using attributes from document.attributes and 'd'. Lines containing undefinded attributes are deleted.""" if section in self.sections: return subs_attrs(self.sections[section],d) else: message.warning('missing section: [%s]' % section) return () def parse_tags(self): """Parse [tags] section entries into self.tags dictionary.""" d = {} parse_entries(self.sections.get('tags',()),d) for k,v in d.items(): if v is None: if k in self.tags: del self.tags[k] elif v == '': self.tags[k] = (None,None) else: mo = re.match(r'(?P<stag>.*)\|(?P<etag>.*)',v) if mo: self.tags[k] = (mo.group('stag'), mo.group('etag')) else: raise EAsciiDoc,'[tag] %s value malformed' % k def tag(self, name, d=None): """Returns (starttag,endtag) tuple named name from configuration file [tags] section. Raise error if not found. If a dictionary 'd' is passed then merge with document attributes and perform attribute substitution on tags.""" if not name in self.tags: raise EAsciiDoc, 'missing tag: %s' % name stag,etag = self.tags[name] if d is not None: # TODO: Should we warn if substitution drops a tag? if stag: stag = subs_attrs(stag,d) if etag: etag = subs_attrs(etag,d) if stag is None: stag = '' if etag is None: etag = '' return (stag,etag) def parse_specialsections(self): """Parse specialsections section to self.specialsections dictionary.""" # TODO: This is virtually the same as parse_replacements() and should # be factored to single routine. d = {} parse_entries(self.sections.get('specialsections',()),d,unquote=True) for pat,sectname in d.items(): pat = strip_quotes(pat) if not is_re(pat): raise EAsciiDoc,'[specialsections] entry ' \ 'is not a valid regular expression: %s' % pat if sectname is None: if pat in self.specialsections: del self.specialsections[pat] else: self.specialsections[pat] = sectname def parse_replacements(self,sect='replacements'): """Parse replacements section into self.replacements dictionary.""" d = OrderedDict() parse_entries(self.sections.get(sect,()), d, unquote=True) for pat,rep in d.items(): if not self.set_replacement(pat, rep, getattr(self,sect)): raise EAsciiDoc,'[%s] entry in %s is not a valid' \ ' regular expression: %s' % (sect,self.fname,pat) @staticmethod def set_replacement(pat, rep, replacements): """Add pattern and replacement to replacements dictionary.""" pat = strip_quotes(pat) if not is_re(pat): return False if rep is None: if pat in replacements: del replacements[pat] else: replacements[pat] = strip_quotes(rep) return True def subs_replacements(self,s,sect='replacements'): """Substitute patterns from self.replacements in 's'.""" result = s for pat,rep in getattr(self,sect).items(): result = re.sub(pat, rep, result) return result def parse_specialwords(self): """Parse special words section into self.specialwords dictionary.""" reo = re.compile(r'(?:\s|^)(".+?"|[^"\s]+)(?=\s|$)') for line in self.sections.get('specialwords',()): e = parse_entry(line) if not e: raise EAsciiDoc,'[specialwords] entry in %s is malformed: %s' \ % (self.fname,line) name,wordlist = e if not is_name(name): raise EAsciiDoc,'[specialwords] name in %s is illegal: %s' \ % (self.fname,name) if wordlist is None: # Undefine all words associated with 'name'. for k,v in self.specialwords.items(): if v == name: del self.specialwords[k] else: words = reo.findall(wordlist) for word in words: word = strip_quotes(word) if not is_re(word): raise EAsciiDoc,'[specialwords] entry in %s ' \ 'is not a valid regular expression: %s' \ % (self.fname,word) self.specialwords[word] = name def subs_specialchars(self,s): """Perform special character substitution on string 's'.""" """It may seem like a good idea to escape special characters with a '\' character, the reason we don't is because the escape character itself then has to be escaped and this makes including code listings problematic. Use the predefined {amp},{lt},{gt} attributes instead.""" result = '' for ch in s: result = result + self.specialchars.get(ch,ch) return result def subs_specialchars_reverse(self,s): """Perform reverse special character substitution on string 's'.""" result = s for k,v in self.specialchars.items(): result = result.replace(v, k) return result def subs_specialwords(self,s): """Search for word patterns from self.specialwords in 's' and substitute using corresponding macro.""" result = s for word in self.specialwords.keys(): result = re.sub(word, _subs_specialwords, result) return result def expand_templates(self,entries): """Expand any template::[] macros in a list of section entries.""" result = [] for line in entries: mo = macros.match('+',r'template',line) if mo: s = mo.group('attrlist') if s in self.sections: result += self.expand_templates(self.sections[s]) else: message.warning('missing section: [%s]' % s) result.append(line) else: result.append(line) return result def expand_all_templates(self): for k,v in self.sections.items(): self.sections[k] = self.expand_templates(v) def section2tags(self, section, d={}, skipstart=False, skipend=False): """Perform attribute substitution on 'section' using document attributes plus 'd' attributes. Return tuple (stag,etag) containing pre and post | placeholder tags. 'skipstart' and 'skipend' are used to suppress substitution.""" assert section is not None if section in self.sections: body = self.sections[section] else: message.warning('missing section: [%s]' % section) body = () # Split macro body into start and end tag lists. stag = [] etag = [] in_stag = True for s in body: if in_stag: mo = re.match(r'(?P<stag>.*)\|(?P<etag>.*)',s) if mo: if mo.group('stag'): stag.append(mo.group('stag')) if mo.group('etag'): etag.append(mo.group('etag')) in_stag = False else: stag.append(s) else: etag.append(s) # Do attribute substitution last so {brkbar} can be used to escape |. # But don't do attribute substitution on title -- we've already done it. title = d.get('title') if title: d['title'] = chr(0) # Replace with unused character. if not skipstart: stag = subs_attrs(stag, d) if not skipend: etag = subs_attrs(etag, d) # Put the {title} back. if title: stag = map(lambda x: x.replace(chr(0), title), stag) etag = map(lambda x: x.replace(chr(0), title), etag) d['title'] = title return (stag,etag) #--------------------------------------------------------------------------- # Deprecated old table classes follow. # Naming convention is an _OLD name suffix. # These will be removed from future versions of AsciiDoc def join_lines_OLD(lines): """Return a list in which lines terminated with the backslash line continuation character are joined.""" result = [] s = '' continuation = False for line in lines: if line and line[-1] == '\\': s = s + line[:-1] continuation = True continue if continuation: result.append(s+line) s = '' continuation = False else: result.append(line) if continuation: result.append(s) return result class Column_OLD: """Table column.""" def __init__(self): self.colalign = None # 'left','right','center' self.rulerwidth = None self.colwidth = None # Output width in page units. class Table_OLD(AbstractBlock): COL_STOP = r"(`|'|\.)" # RE. ALIGNMENTS = {'`':'left', "'":'right', '.':'center'} FORMATS = ('fixed','csv','dsv') def __init__(self): AbstractBlock.__init__(self) self.CONF_ENTRIES += ('template','fillchar','format','colspec', 'headrow','footrow','bodyrow','headdata', 'footdata', 'bodydata') # Configuration parameters. self.fillchar=None self.format=None # 'fixed','csv','dsv' self.colspec=None self.headrow=None self.footrow=None self.bodyrow=None self.headdata=None self.footdata=None self.bodydata=None # Calculated parameters. self.underline=None # RE matching current table underline. self.isnumeric=False # True if numeric ruler. self.tablewidth=None # Optional table width scale factor. self.columns=[] # List of Columns. # Other. self.check_msg='' # Message set by previous self.validate() call. def load(self,name,entries): AbstractBlock.load(self,name,entries) """Update table definition from section entries in 'entries'.""" for k,v in entries.items(): if k == 'fillchar': if v and len(v) == 1: self.fillchar = v else: raise EAsciiDoc,'malformed table fillchar: %s' % v elif k == 'format': if v in Table_OLD.FORMATS: self.format = v else: raise EAsciiDoc,'illegal table format: %s' % v elif k == 'colspec': self.colspec = v elif k == 'headrow': self.headrow = v elif k == 'footrow': self.footrow = v elif k == 'bodyrow': self.bodyrow = v elif k == 'headdata': self.headdata = v elif k == 'footdata': self.footdata = v elif k == 'bodydata': self.bodydata = v def dump(self): AbstractBlock.dump(self) write = lambda s: sys.stdout.write('%s%s' % (s,writer.newline)) write('fillchar='+self.fillchar) write('format='+self.format) if self.colspec: write('colspec='+self.colspec) if self.headrow: write('headrow='+self.headrow) if self.footrow: write('footrow='+self.footrow) write('bodyrow='+self.bodyrow) if self.headdata: write('headdata='+self.headdata) if self.footdata: write('footdata='+self.footdata) write('bodydata='+self.bodydata) write('') def validate(self): AbstractBlock.validate(self) """Check table definition and set self.check_msg if invalid else set self.check_msg to blank string.""" # Check global table parameters. if config.textwidth is None: self.check_msg = 'missing [miscellaneous] textwidth entry' elif config.pagewidth is None: self.check_msg = 'missing [miscellaneous] pagewidth entry' elif config.pageunits is None: self.check_msg = 'missing [miscellaneous] pageunits entry' elif self.headrow is None: self.check_msg = 'missing headrow entry' elif self.footrow is None: self.check_msg = 'missing footrow entry' elif self.bodyrow is None: self.check_msg = 'missing bodyrow entry' elif self.headdata is None: self.check_msg = 'missing headdata entry' elif self.footdata is None: self.check_msg = 'missing footdata entry' elif self.bodydata is None: self.check_msg = 'missing bodydata entry' else: # No errors. self.check_msg = '' def isnext(self): return AbstractBlock.isnext(self) def parse_ruler(self,ruler): """Parse ruler calculating underline and ruler column widths.""" fc = re.escape(self.fillchar) # Strip and save optional tablewidth from end of ruler. mo = re.match(r'^(.*'+fc+r'+)([\d\.]+)$',ruler) if mo: ruler = mo.group(1) self.tablewidth = float(mo.group(2)) self.attributes['tablewidth'] = str(float(self.tablewidth)) else: self.tablewidth = None self.attributes['tablewidth'] = '100.0' # Guess whether column widths are specified numerically or not. if ruler[1] != self.fillchar: # If the first column does not start with a fillchar then numeric. self.isnumeric = True elif ruler[1:] == self.fillchar*len(ruler[1:]): # The case of one column followed by fillchars is numeric. self.isnumeric = True else: self.isnumeric = False # Underlines must be 3 or more fillchars. self.underline = r'^' + fc + r'{3,}$' splits = re.split(self.COL_STOP,ruler)[1:] # Build self.columns. for i in range(0,len(splits),2): c = Column_OLD() c.colalign = self.ALIGNMENTS[splits[i]] s = splits[i+1] if self.isnumeric: # Strip trailing fillchars. s = re.sub(fc+r'+$','',s) if s == '': c.rulerwidth = None else: try: val = int(s) if not val > 0: raise ValueError, 'not > 0' c.rulerwidth = val except ValueError: raise EAsciiDoc, 'malformed ruler: bad width' else: # Calculate column width from inter-fillchar intervals. if not re.match(r'^'+fc+r'+$',s): raise EAsciiDoc,'malformed ruler: illegal fillchars' c.rulerwidth = len(s)+1 self.columns.append(c) # Fill in unspecified ruler widths. if self.isnumeric: if self.columns[0].rulerwidth is None: prevwidth = 1 for c in self.columns: if c.rulerwidth is None: c.rulerwidth = prevwidth prevwidth = c.rulerwidth def build_colspecs(self): """Generate colwidths and colspecs. This can only be done after the table arguments have been parsed since we use the table format.""" self.attributes['cols'] = len(self.columns) # Calculate total ruler width. totalwidth = 0 for c in self.columns: totalwidth = totalwidth + c.rulerwidth if totalwidth <= 0: raise EAsciiDoc,'zero width table' # Calculate marked up colwidths from rulerwidths. for c in self.columns: # Convert ruler width to output page width. width = float(c.rulerwidth) if self.format == 'fixed': if self.tablewidth is None: # Size proportional to ruler width. colfraction = width/config.textwidth else: # Size proportional to page width. colfraction = width/totalwidth else: # Size proportional to page width. colfraction = width/totalwidth c.colwidth = colfraction * config.pagewidth # To page units. if self.tablewidth is not None: c.colwidth = c.colwidth * self.tablewidth # Scale factor. if self.tablewidth > 1: c.colwidth = c.colwidth/100 # tablewidth is in percent. # Build colspecs. if self.colspec: cols = [] i = 0 for c in self.columns: i += 1 self.attributes['colalign'] = c.colalign self.attributes['colwidth'] = str(int(c.colwidth)) self.attributes['colnumber'] = str(i + 1) s = subs_attrs(self.colspec,self.attributes) if not s: message.warning('colspec dropped: contains undefined attribute') else: cols.append(s) self.attributes['colspecs'] = writer.newline.join(cols) def split_rows(self,rows): """Return a two item tuple containing a list of lines up to but not including the next underline (continued lines are joined ) and the tuple of all lines after the underline.""" reo = re.compile(self.underline) i = 0 while not reo.match(rows[i]): i = i+1 if i == 0: raise EAsciiDoc,'missing table rows' if i >= len(rows): raise EAsciiDoc,'closing [%s] underline expected' % self.name return (join_lines_OLD(rows[:i]), rows[i+1:]) def parse_rows(self, rows, rtag, dtag): """Parse rows list using the row and data tags. Returns a substituted list of output lines.""" result = [] # Source rows are parsed as single block, rather than line by line, to # allow the CSV reader to handle multi-line rows. if self.format == 'fixed': rows = self.parse_fixed(rows) elif self.format == 'csv': rows = self.parse_csv(rows) elif self.format == 'dsv': rows = self.parse_dsv(rows) else: assert True,'illegal table format' # Substitute and indent all data in all rows. stag,etag = subs_tag(rtag,self.attributes) for row in rows: result.append(' '+stag) for data in self.subs_row(row,dtag): result.append(' '+data) result.append(' '+etag) return result def subs_row(self, data, dtag): """Substitute the list of source row data elements using the data tag. Returns a substituted list of output table data items.""" result = [] if len(data) < len(self.columns): message.warning('fewer row data items then table columns') if len(data) > len(self.columns): message.warning('more row data items than table columns') for i in range(len(self.columns)): if i > len(data) - 1: d = '' # Fill missing column data with blanks. else: d = data[i] c = self.columns[i] self.attributes['colalign'] = c.colalign self.attributes['colwidth'] = str(int(c.colwidth)) self.attributes['colnumber'] = str(i + 1) stag,etag = subs_tag(dtag,self.attributes) # Insert AsciiDoc line break (' +') where row data has newlines # ('\n'). This is really only useful when the table format is csv # and the output markup is HTML. It's also a bit dubious in that it # assumes the user has not modified the shipped line break pattern. subs = self.get_subs()[0] if 'replacements' in subs: # Insert line breaks in cell data. d = re.sub(r'(?m)\n',r' +\n',d) d = d.split('\n') # So writer.newline is written. else: d = [d] result = result + [stag] + Lex.subs(d,subs) + [etag] return result def parse_fixed(self,rows): """Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.""" result = [] for row in rows: data = [] start = 0 # build an encoded representation row = char_decode(row) for c in self.columns: end = start + c.rulerwidth if c is self.columns[-1]: # Text in last column can continue forever. # Use the encoded string to slice, but convert back # to plain string before further processing data.append(char_encode(row[start:]).strip()) else: data.append(char_encode(row[start:end]).strip()) start = end result.append(data) return result def parse_csv(self,rows): """Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.""" import StringIO import csv result = [] rdr = csv.reader(StringIO.StringIO('\r\n'.join(rows)), skipinitialspace=True) try: for row in rdr: result.append(row) except Exception: raise EAsciiDoc,'csv parse error: %s' % row return result def parse_dsv(self,rows): """Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.""" separator = self.attributes.get('separator',':') separator = literal_eval('"'+separator+'"') if len(separator) != 1: raise EAsciiDoc,'malformed dsv separator: %s' % separator # TODO If separator is preceeded by an odd number of backslashes then # it is escaped and should not delimit. result = [] for row in rows: # Skip blank lines if row == '': continue # Unescape escaped characters. row = literal_eval('"'+row.replace('"','\\"')+'"') data = row.split(separator) data = [s.strip() for s in data] result.append(data) return result def translate(self): message.deprecated('old tables syntax') AbstractBlock.translate(self) # Reset instance specific properties. self.underline = None self.columns = [] attrs = {} BlockTitle.consume(attrs) # Add relevant globals to table substitutions. attrs['pagewidth'] = str(config.pagewidth) attrs['pageunits'] = config.pageunits # Mix in document attribute list. AttributeList.consume(attrs) # Validate overridable attributes. for k,v in attrs.items(): if k == 'format': if v not in self.FORMATS: raise EAsciiDoc, 'illegal [%s] %s: %s' % (self.name,k,v) self.format = v elif k == 'tablewidth': try: self.tablewidth = float(attrs['tablewidth']) except Exception: raise EAsciiDoc, 'illegal [%s] %s: %s' % (self.name,k,v) self.merge_attributes(attrs) # Parse table ruler. ruler = reader.read() assert re.match(self.delimiter,ruler) self.parse_ruler(ruler) # Read the entire table. table = [] while True: line = reader.read_next() # Table terminated by underline followed by a blank line or EOF. if len(table) > 0 and re.match(self.underline,table[-1]): if line in ('',None): break; if line is None: raise EAsciiDoc,'closing [%s] underline expected' % self.name table.append(reader.read()) # EXPERIMENTAL: The number of lines in the table, requested by Benjamin Klum. self.attributes['rows'] = str(len(table)) if self.check_msg: # Skip if table definition was marked invalid. message.warning('skipping %s table: %s' % (self.name,self.check_msg)) return # Generate colwidths and colspecs. self.build_colspecs() # Generate headrows, footrows, bodyrows. # Headrow, footrow and bodyrow data replaces same named attributes in # the table markup template. In order to ensure this data does not get # a second attribute substitution (which would interfere with any # already substituted inline passthroughs) unique placeholders are used # (the tab character does not appear elsewhere since it is expanded on # input) which are replaced after template attribute substitution. headrows = footrows = [] bodyrows,table = self.split_rows(table) if table: headrows = bodyrows bodyrows,table = self.split_rows(table) if table: footrows,table = self.split_rows(table) if headrows: headrows = self.parse_rows(headrows, self.headrow, self.headdata) headrows = writer.newline.join(headrows) self.attributes['headrows'] = '\x07headrows\x07' if footrows: footrows = self.parse_rows(footrows, self.footrow, self.footdata) footrows = writer.newline.join(footrows) self.attributes['footrows'] = '\x07footrows\x07' bodyrows = self.parse_rows(bodyrows, self.bodyrow, self.bodydata) bodyrows = writer.newline.join(bodyrows) self.attributes['bodyrows'] = '\x07bodyrows\x07' table = subs_attrs(config.sections[self.template],self.attributes) table = writer.newline.join(table) # Before we finish replace the table head, foot and body place holders # with the real data. if headrows: table = table.replace('\x07headrows\x07', headrows, 1) if footrows: table = table.replace('\x07footrows\x07', footrows, 1) table = table.replace('\x07bodyrows\x07', bodyrows, 1) writer.write(table,trace='table') class Tables_OLD(AbstractBlocks): """List of tables.""" BLOCK_TYPE = Table_OLD PREFIX = 'old_tabledef-' def __init__(self): AbstractBlocks.__init__(self) def load(self,sections): AbstractBlocks.load(self,sections) def validate(self): # Does not call AbstractBlocks.validate(). # Check we have a default table definition, for i in range(len(self.blocks)): if self.blocks[i].name == 'old_tabledef-default': default = self.blocks[i] break else: raise EAsciiDoc,'missing section: [OLD_tabledef-default]' # Set default table defaults. if default.format is None: default.subs = 'fixed' # Propagate defaults to unspecified table parameters. for b in self.blocks: if b is not default: if b.fillchar is None: b.fillchar = default.fillchar if b.format is None: b.format = default.format if b.template is None: b.template = default.template if b.colspec is None: b.colspec = default.colspec if b.headrow is None: b.headrow = default.headrow if b.footrow is None: b.footrow = default.footrow if b.bodyrow is None: b.bodyrow = default.bodyrow if b.headdata is None: b.headdata = default.headdata if b.footdata is None: b.footdata = default.footdata if b.bodydata is None: b.bodydata = default.bodydata # Check all tables have valid fill character. for b in self.blocks: if not b.fillchar or len(b.fillchar) != 1: raise EAsciiDoc,'[%s] missing or illegal fillchar' % b.name # Build combined tables delimiter patterns and assign defaults. delimiters = [] for b in self.blocks: # Ruler is: # (ColStop,(ColWidth,FillChar+)?)+, FillChar+, TableWidth? b.delimiter = r'^(' + Table_OLD.COL_STOP \ + r'(\d*|' + re.escape(b.fillchar) + r'*)' \ + r')+' \ + re.escape(b.fillchar) + r'+' \ + '([\d\.]*)$' delimiters.append(b.delimiter) if not b.headrow: b.headrow = b.bodyrow if not b.footrow: b.footrow = b.bodyrow if not b.headdata: b.headdata = b.bodydata if not b.footdata: b.footdata = b.bodydata self.delimiters = re_join(delimiters) # Check table definitions are valid. for b in self.blocks: b.validate() if config.verbose: if b.check_msg: message.warning('[%s] table definition: %s' % (b.name,b.check_msg)) # End of deprecated old table classes. #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- # filter and theme plugin commands. #--------------------------------------------------------------------------- import shutil, zipfile def die(msg): message.stderr(msg) sys.exit(1) def unzip(zip_file, destdir): """ Unzip Zip file to destination directory. Throws exception if error occurs. """ zipo = zipfile.ZipFile(zip_file, 'r') try: for zi in zipo.infolist(): outfile = zi.filename if not outfile.endswith('/'): d, outfile = os.path.split(outfile) directory = os.path.normpath(os.path.join(destdir, d)) if not os.path.isdir(directory): os.makedirs(directory) outfile = os.path.join(directory, outfile) perms = (zi.external_attr >> 16) & 0777 message.verbose('extracting: %s' % outfile) if perms == 0: # Zip files created under Window do not include permissions. fh = os.open(outfile, os.O_CREAT | os.O_WRONLY) else: fh = os.open(outfile, os.O_CREAT | os.O_WRONLY, perms) try: os.write(fh, zipo.read(zi.filename)) finally: os.close(fh) finally: zipo.close() class Plugin: """ --filter and --theme option commands. """ CMDS = ('install','remove','list') type = None # 'filter' or 'theme'. @staticmethod def get_dir(): """ Return plugins path (.asciidoc/filters or .asciidoc/themes) in user's home direcory or None if user home not defined. """ result = userdir() if result: result = os.path.join(result, '.asciidoc', Plugin.type+'s') return result @staticmethod def install(args): """ Install plugin Zip file. args[0] is plugin zip file path. args[1] is optional destination plugins directory. """ if len(args) not in (1,2): die('invalid number of arguments: --%s install %s' % (Plugin.type, ' '.join(args))) zip_file = args[0] if not os.path.isfile(zip_file): die('file not found: %s' % zip_file) reo = re.match(r'^\w+',os.path.split(zip_file)[1]) if not reo: die('file name does not start with legal %s name: %s' % (Plugin.type, zip_file)) plugin_name = reo.group() if len(args) == 2: plugins_dir = args[1] if not os.path.isdir(plugins_dir): die('directory not found: %s' % plugins_dir) else: plugins_dir = Plugin.get_dir() if not plugins_dir: die('user home directory is not defined') plugin_dir = os.path.join(plugins_dir, plugin_name) if os.path.exists(plugin_dir): die('%s is already installed: %s' % (Plugin.type, plugin_dir)) try: os.makedirs(plugin_dir) except Exception,e: die('failed to create %s directory: %s' % (Plugin.type, str(e))) try: unzip(zip_file, plugin_dir) except Exception,e: die('failed to extract %s: %s' % (Plugin.type, str(e))) @staticmethod def remove(args): """ Delete plugin directory. args[0] is plugin name. args[1] is optional plugin directory (defaults to ~/.asciidoc/<plugin_name>). """ if len(args) not in (1,2): die('invalid number of arguments: --%s remove %s' % (Plugin.type, ' '.join(args))) plugin_name = args[0] if not re.match(r'^\w+$',plugin_name): die('illegal %s name: %s' % (Plugin.type, plugin_name)) if len(args) == 2: d = args[1] if not os.path.isdir(d): die('directory not found: %s' % d) else: d = Plugin.get_dir() if not d: die('user directory is not defined') plugin_dir = os.path.join(d, plugin_name) if not os.path.isdir(plugin_dir): die('cannot find %s: %s' % (Plugin.type, plugin_dir)) try: message.verbose('removing: %s' % plugin_dir) shutil.rmtree(plugin_dir) except Exception,e: die('failed to delete %s: %s' % (Plugin.type, str(e))) @staticmethod def list(args): """ List all plugin directories (global and local). """ for d in [os.path.join(d, Plugin.type+'s') for d in config.get_load_dirs()]: if os.path.isdir(d): for f in os.walk(d).next()[1]: message.stdout(os.path.join(d,f)) #--------------------------------------------------------------------------- # Application code. #--------------------------------------------------------------------------- # Constants # --------- APP_FILE = None # This file's full path. APP_DIR = None # This file's directory. USER_DIR = None # ~/.asciidoc # Global configuration files directory (set by Makefile build target). CONF_DIR = '/etc/asciidoc' HELP_FILE = 'help.conf' # Default (English) help file. # Globals # ------- document = Document() # The document being processed. config = Config() # Configuration file reader. reader = Reader() # Input stream line reader. writer = Writer() # Output stream line writer. message = Message() # Message functions. paragraphs = Paragraphs() # Paragraph definitions. lists = Lists() # List definitions. blocks = DelimitedBlocks() # DelimitedBlock definitions. tables_OLD = Tables_OLD() # Table_OLD definitions. tables = Tables() # Table definitions. macros = Macros() # Macro definitions. calloutmap = CalloutMap() # Coordinates callouts and callout list. trace = Trace() # Implements trace attribute processing. ### Used by asciidocapi.py ### # List of message strings written to stderr. messages = message.messages def asciidoc(backend, doctype, confiles, infile, outfile, options): """Convert AsciiDoc document to DocBook document of type doctype The AsciiDoc document is read from file object src the translated DocBook file written to file object dst.""" def load_conffiles(include=[], exclude=[]): # Load conf files specified on the command-line and by the conf-files attribute. files = document.attributes.get('conf-files','') files = [f.strip() for f in files.split('|') if f.strip()] files += confiles if files: for f in files: if os.path.isfile(f): config.load_file(f, include=include, exclude=exclude) else: raise EAsciiDoc,'missing configuration file: %s' % f try: if doctype not in (None,'article','manpage','book'): raise EAsciiDoc,'illegal document type' # Set processing options. for o in options: if o == '-c': config.dumping = True if o == '-s': config.header_footer = False if o == '-v': config.verbose = True document.update_attributes() if '-e' not in options: # Load asciidoc.conf files in two passes: the first for attributes # the second for everything. This is so that locally set attributes # available are in the global asciidoc.conf if not config.load_from_dirs('asciidoc.conf',include=['attributes']): raise EAsciiDoc,'configuration file asciidoc.conf missing' load_conffiles(include=['attributes']) config.load_from_dirs('asciidoc.conf') if infile != '<stdin>': indir = os.path.dirname(infile) config.load_file('asciidoc.conf', indir, include=['attributes','titles','specialchars']) else: load_conffiles(include=['attributes','titles','specialchars']) document.update_attributes() # Check the infile exists. if infile != '<stdin>': if not os.path.isfile(infile): raise EAsciiDoc,'input file %s missing' % infile document.infile = infile AttributeList.initialize() # Open input file and parse document header. reader.tabsize = config.tabsize reader.open(infile) has_header = document.parse_header(doctype,backend) # doctype is now finalized. document.attributes['doctype-'+document.doctype] = '' config.set_theme_attributes() # Load backend configuration files. if '-e' not in options: f = document.backend + '.conf' if not config.load_backend(): raise EAsciiDoc,'missing backend conf file: %s' % f # backend is now known. document.attributes['backend-'+document.backend] = '' document.attributes[document.backend+'-'+document.doctype] = '' doc_conffiles = [] if '-e' not in options: # Load filters and language file. config.load_filters() document.load_lang() if infile != '<stdin>': # Load local conf files (files in the source file directory). config.load_file('asciidoc.conf', indir) config.load_backend([indir]) config.load_filters([indir]) # Load document specific configuration files. f = os.path.splitext(infile)[0] doc_conffiles = [ f for f in (f+'.conf', f+'-'+document.backend+'.conf') if os.path.isfile(f) ] for f in doc_conffiles: config.load_file(f) load_conffiles() # Build asciidoc-args attribute. args = '' # Add custom conf file arguments. for f in doc_conffiles + confiles: args += ' --conf-file "%s"' % f # Add command-line and header attributes. attrs = {} attrs.update(AttributeEntry.attributes) attrs.update(config.cmd_attrs) if 'title' in attrs: # Don't pass the header title. del attrs['title'] for k,v in attrs.items(): if v: args += ' --attribute "%s=%s"' % (k,v) else: args += ' --attribute "%s"' % k document.attributes['asciidoc-args'] = args # Build outfile name. if outfile is None: outfile = os.path.splitext(infile)[0] + '.' + document.backend if config.outfilesuffix: # Change file extension. outfile = os.path.splitext(outfile)[0] + config.outfilesuffix document.outfile = outfile # Document header attributes override conf file attributes. document.attributes.update(AttributeEntry.attributes) document.update_attributes() # Configuration is fully loaded. config.expand_all_templates() # Check configuration for consistency. config.validate() paragraphs.initialize() lists.initialize() if config.dumping: config.dump() else: writer.newline = config.newline try: writer.open(outfile, reader.bom) try: document.translate(has_header) # Generate the output. finally: writer.close() finally: reader.closefile() except KeyboardInterrupt: raise except Exception,e: # Cleanup. if outfile and outfile != '<stdout>' and os.path.isfile(outfile): os.unlink(outfile) # Build and print error description. msg = 'FAILED: ' if reader.cursor: msg = message.format('', msg) if isinstance(e, EAsciiDoc): message.stderr('%s%s' % (msg,str(e))) else: if __name__ == '__main__': message.stderr(msg+'unexpected error:') message.stderr('-'*60) traceback.print_exc(file=sys.stderr) message.stderr('-'*60) else: message.stderr('%sunexpected error: %s' % (msg,str(e))) sys.exit(1) def usage(msg=''): if msg: message.stderr(msg) show_help('default', sys.stderr) def show_help(topic, f=None): """Print help topic to file object f.""" if f is None: f = sys.stdout # Select help file. lang = config.cmd_attrs.get('lang') if lang and lang != 'en': help_file = 'help-' + lang + '.conf' else: help_file = HELP_FILE # Print [topic] section from help file. config.load_from_dirs(help_file) if len(config.sections) == 0: # Default to English if specified language help files not found. help_file = HELP_FILE config.load_from_dirs(help_file) if len(config.sections) == 0: message.stderr('no help topics found') sys.exit(1) n = 0 for k in config.sections: if re.match(re.escape(topic), k): n += 1 lines = config.sections[k] if n == 0: if topic != 'topics': message.stderr('help topic not found: [%s] in %s' % (topic, help_file)) message.stderr('available help topics: %s' % ', '.join(config.sections.keys())) sys.exit(1) elif n > 1: message.stderr('ambiguous help topic: %s' % topic) else: for line in lines: print >>f, line ### Used by asciidocapi.py ### def execute(cmd,opts,args): """ Execute asciidoc with command-line options and arguments. cmd is asciidoc command or asciidoc.py path. opts and args conform to values returned by getopt.getopt(). Raises SystemExit if an error occurs. Doctests: 1. Check execution: >>> import StringIO >>> infile = StringIO.StringIO('Hello *{author}*') >>> outfile = StringIO.StringIO() >>> opts = [] >>> opts.append(('--backend','html4')) >>> opts.append(('--no-header-footer',None)) >>> opts.append(('--attribute','author=Joe Bloggs')) >>> opts.append(('--out-file',outfile)) >>> execute(__file__, opts, [infile]) >>> print outfile.getvalue() <p>Hello <strong>Joe Bloggs</strong></p> >>> """ config.init(cmd) if len(args) > 1: usage('To many arguments') sys.exit(1) backend = None doctype = None confiles = [] outfile = None options = [] help_option = False for o,v in opts: if o in ('--help','-h'): help_option = True #DEPRECATED: --unsafe option. if o == '--unsafe': document.safe = False if o == '--safe': document.safe = True if o == '--version': print('asciidoc %s' % VERSION) sys.exit(0) if o in ('-b','--backend'): backend = v # config.cmd_attrs['backend'] = v if o in ('-c','--dump-conf'): options.append('-c') if o in ('-d','--doctype'): doctype = v # config.cmd_attrs['doctype'] = v if o in ('-e','--no-conf'): options.append('-e') if o in ('-f','--conf-file'): confiles.append(v) if o in ('-n','--section-numbers'): o = '-a' v = 'numbered' if o in ('-a','--attribute'): e = parse_entry(v, allow_name_only=True) if not e: usage('Illegal -a option: %s' % v) sys.exit(1) k,v = e # A @ suffix denotes don't override existing document attributes. if v and v[-1] == '@': document.attributes[k] = v[:-1] else: config.cmd_attrs[k] = v if o in ('-o','--out-file'): outfile = v if o in ('-s','--no-header-footer'): options.append('-s') if o in ('-v','--verbose'): options.append('-v') if help_option: if len(args) == 0: show_help('default') else: show_help(args[-1]) sys.exit(0) if len(args) == 0 and len(opts) == 0: usage() sys.exit(0) if len(args) == 0: usage('No source file specified') sys.exit(1) # if not backend: # usage('No --backend option specified') # sys.exit(1) stdin,stdout = sys.stdin,sys.stdout try: infile = args[0] if infile == '-': infile = '<stdin>' elif isinstance(infile, str): infile = os.path.abspath(infile) else: # Input file is file object from API call. sys.stdin = infile infile = '<stdin>' if outfile == '-': outfile = '<stdout>' elif isinstance(outfile, str): outfile = os.path.abspath(outfile) elif outfile is None: if infile == '<stdin>': outfile = '<stdout>' else: # Output file is file object from API call. sys.stdout = outfile outfile = '<stdout>' # Do the work. asciidoc(backend, doctype, confiles, infile, outfile, options) if document.has_errors: sys.exit(1) finally: sys.stdin,sys.stdout = stdin,stdout if __name__ == '__main__': # Process command line options. import getopt try: #DEPRECATED: --unsafe option. opts,args = getopt.getopt(sys.argv[1:], 'a:b:cd:ef:hno:svw:', ['attribute=','backend=','conf-file=','doctype=','dump-conf', 'help','no-conf','no-header-footer','out-file=', 'section-numbers','verbose','version','safe','unsafe', 'doctest','filter=','theme=']) except getopt.GetoptError: message.stderr('illegal command options') sys.exit(1) opt_names = [opt[0] for opt in opts] if '--doctest' in opt_names: # Run module doctests. import doctest options = doctest.NORMALIZE_WHITESPACE + doctest.ELLIPSIS failures,tries = doctest.testmod(optionflags=options) if failures == 0: message.stderr('All doctests passed') sys.exit(0) else: sys.exit(1) # Look for plugin management commands. count = 0 for o,v in opts: if o in ('-b','--backend','--filter','--theme'): if o == '-b': o = '--backend' plugin = o[2:] cmd = v if plugin == 'backend' and cmd not in Plugin.CMDS: # --backend is setting document backend. continue count += 1 if count > 1: die('--backend, --filter and --theme options are mutually exclusive') if count == 1: # Execute plugin management commands. if not cmd: die('missing --%s command' % plugin) if cmd not in Plugin.CMDS: die('illegal --%s command: %s' % (plugin, cmd)) Plugin.type = plugin config.init(sys.argv[0]) config.verbose = bool(set(['-v','--verbose']) & set(opt_names)) getattr(Plugin,cmd)(args) else: # Execute asciidoc. try: execute(sys.argv[0],opts,args) except KeyboardInterrupt: sys.exit(1)
Python
#!/usr/bin/env python """ asciidocapi - AsciiDoc API wrapper class. The AsciiDocAPI class provides an API for executing asciidoc. Minimal example compiles `mydoc.txt` to `mydoc.html`: import asciidocapi asciidoc = asciidocapi.AsciiDocAPI() asciidoc.execute('mydoc.txt') - Full documentation in asciidocapi.txt. - See the doctests below for more examples. Doctests: 1. Check execution: >>> import StringIO >>> infile = StringIO.StringIO('Hello *{author}*') >>> outfile = StringIO.StringIO() >>> asciidoc = AsciiDocAPI() >>> asciidoc.options('--no-header-footer') >>> asciidoc.attributes['author'] = 'Joe Bloggs' >>> asciidoc.execute(infile, outfile, backend='html4') >>> print outfile.getvalue() <p>Hello <strong>Joe Bloggs</strong></p> >>> asciidoc.attributes['author'] = 'Bill Smith' >>> infile = StringIO.StringIO('Hello _{author}_') >>> outfile = StringIO.StringIO() >>> asciidoc.execute(infile, outfile, backend='docbook') >>> print outfile.getvalue() <simpara>Hello <emphasis>Bill Smith</emphasis></simpara> 2. Check error handling: >>> import StringIO >>> asciidoc = AsciiDocAPI() >>> infile = StringIO.StringIO('---------') >>> outfile = StringIO.StringIO() >>> asciidoc.execute(infile, outfile) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "asciidocapi.py", line 189, in execute raise AsciiDocError(self.messages[-1]) AsciiDocError: ERROR: <stdin>: line 1: [blockdef-listing] missing closing delimiter Copyright (C) 2009 Stuart Rackham. Free use of this software is granted under the terms of the GNU General Public License (GPL). """ import sys,os,re,imp API_VERSION = '0.1.2' MIN_ASCIIDOC_VERSION = '8.4.1' # Minimum acceptable AsciiDoc version. def find_in_path(fname, path=None): """ Find file fname in paths. Return None if not found. """ if path is None: path = os.environ.get('PATH', '') for dir in path.split(os.pathsep): fpath = os.path.join(dir, fname) if os.path.isfile(fpath): return fpath else: return None class AsciiDocError(Exception): pass class Options(object): """ Stores asciidoc(1) command options. """ def __init__(self, values=[]): self.values = values[:] def __call__(self, name, value=None): """Shortcut for append method.""" self.append(name, value) def append(self, name, value=None): if type(value) in (int,float): value = str(value) self.values.append((name,value)) class Version(object): """ Parse and compare AsciiDoc version numbers. Instance attributes: string: String version number '<major>.<minor>[.<micro>][suffix]'. major: Integer major version number. minor: Integer minor version number. micro: Integer micro version number. suffix: Suffix (begins with non-numeric character) is ignored when comparing. Doctest examples: >>> Version('8.2.5') < Version('8.3 beta 1') True >>> Version('8.3.0') == Version('8.3. beta 1') True >>> Version('8.2.0') < Version('8.20') True >>> Version('8.20').major 8 >>> Version('8.20').minor 20 >>> Version('8.20').micro 0 >>> Version('8.20').suffix '' >>> Version('8.20 beta 1').suffix 'beta 1' """ def __init__(self, version): self.string = version reo = re.match(r'^(\d+)\.(\d+)(\.(\d+))?\s*(.*?)\s*$', self.string) if not reo: raise ValueError('invalid version number: %s' % self.string) groups = reo.groups() self.major = int(groups[0]) self.minor = int(groups[1]) self.micro = int(groups[3] or '0') self.suffix = groups[4] or '' def __cmp__(self, other): result = cmp(self.major, other.major) if result == 0: result = cmp(self.minor, other.minor) if result == 0: result = cmp(self.micro, other.micro) return result class AsciiDocAPI(object): """ AsciiDoc API class. """ def __init__(self, asciidoc_py=None): """ Locate and import asciidoc.py. Initialize instance attributes. """ self.options = Options() self.attributes = {} self.messages = [] # Search for the asciidoc command file. # Try ASCIIDOC_PY environment variable first. cmd = os.environ.get('ASCIIDOC_PY') if cmd: if not os.path.isfile(cmd): raise AsciiDocError('missing ASCIIDOC_PY file: %s' % cmd) elif asciidoc_py: # Next try path specified by caller. cmd = asciidoc_py if not os.path.isfile(cmd): raise AsciiDocError('missing file: %s' % cmd) else: # Try shell search paths. for fname in ['asciidoc.py','asciidoc.pyc','asciidoc']: cmd = find_in_path(fname) if cmd: break else: # Finally try current working directory. for cmd in ['asciidoc.py','asciidoc.pyc','asciidoc']: if os.path.isfile(cmd): break else: raise AsciiDocError('failed to locate asciidoc') self.cmd = os.path.realpath(cmd) self.__import_asciidoc() def __import_asciidoc(self, reload=False): ''' Import asciidoc module (script or compiled .pyc). See http://groups.google.com/group/asciidoc/browse_frm/thread/66e7b59d12cd2f91 for an explanation of why a seemingly straight-forward job turned out quite complicated. ''' if os.path.splitext(self.cmd)[1] in ['.py','.pyc']: sys.path.insert(0, os.path.dirname(self.cmd)) try: try: if reload: import __builtin__ # Because reload() is shadowed. __builtin__.reload(self.asciidoc) else: import asciidoc self.asciidoc = asciidoc except ImportError: raise AsciiDocError('failed to import ' + self.cmd) finally: del sys.path[0] else: # The import statement can only handle .py or .pyc files, have to # use imp.load_source() for scripts with other names. try: imp.load_source('asciidoc', self.cmd) import asciidoc self.asciidoc = asciidoc except ImportError: raise AsciiDocError('failed to import ' + self.cmd) if Version(self.asciidoc.VERSION) < Version(MIN_ASCIIDOC_VERSION): raise AsciiDocError( 'asciidocapi %s requires asciidoc %s or better' % (API_VERSION, MIN_ASCIIDOC_VERSION)) def execute(self, infile, outfile=None, backend=None): """ Compile infile to outfile using backend format. infile can outfile can be file path strings or file like objects. """ self.messages = [] opts = Options(self.options.values) if outfile is not None: opts('--out-file', outfile) if backend is not None: opts('--backend', backend) for k,v in self.attributes.items(): if v == '' or k[-1] in '!@': s = k elif v is None: # A None value undefines the attribute. s = k + '!' else: s = '%s=%s' % (k,v) opts('--attribute', s) args = [infile] # The AsciiDoc command was designed to process source text then # exit, there are globals and statics in asciidoc.py that have # to be reinitialized before each run -- hence the reload. self.__import_asciidoc(reload=True) try: try: self.asciidoc.execute(self.cmd, opts.values, args) finally: self.messages = self.asciidoc.messages[:] except SystemExit, e: if e.code: raise AsciiDocError(self.messages[-1]) if __name__ == "__main__": """ Run module doctests. """ import doctest options = doctest.NORMALIZE_WHITESPACE + doctest.ELLIPSIS doctest.testmod(optionflags=options)
Python
#!/usr/bin/python # # Copyright 2011 Google Inc. All Rights Reserved. # # 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. import os import glob import pygame import sys import os.path import urllib2 import BaseHTTPServer import mmap import cStringIO import base64 import subprocess import re paused = False # For image inspection image_number = None # Scanimage starts counting at 1 book_dimensions = None # (top, bottom, side) in pixels fullscreen = True # Easier to debug in a window suppressions = set() # Pages we don't want to keep left_offset = 593 # Hardware sensor position in pixels right_offset = 150 # Hardware sensor position in pixels dpi = 300 # Hardware resolution def blue(): """Original scansation blue, handed down from antiquity.""" return (70, 120, 173) def clearscreen(screen): """And G-d said, 'Let there be blue light!'""" screen.fill(blue()) def get_epsilon(screen): """How much to separate page image from center of display.""" return screen.get_width() / 100 def render_text(screen, msg, position): """Write messages to screen, such as the image number.""" pos = [0, 0] font = pygame.font.SysFont('Courier', 28, bold=True) color = blue() if image_number in suppressions: color = pygame.Color('red') for line in msg.split("\n"): if len(line) > 0: text = font.render(line.rstrip('\r'), 1, (255, 255, 255)) background = pygame.Surface(text.get_size()) background.fill(color) if position == "upperright": pos[0] = screen.get_width() - text.get_width() screen.blit(background, pos) screen.blit(text, pos) pygame.display.update(pygame.Rect(pos, text.get_size())) pos[1] += 30 color = blue() def read_ppm_header(fp, filename): """Read dimensions and headersize from a PPM file.""" headersize = 0 magic_number = fp.readline() if magic_number != "P6\n": raise TypeError("Hey! Not a ppm image file: %s" % filename) headersize += len(magic_number) comment = fp.readline() if comment[0] == "#": headersize += len(comment) dimensions = fp.readline() else: dimensions = comment headersize += len(dimensions) max_value = fp.readline() if max_value != "255\n": raise ValueError("I only work with 8 bits per color channel") headersize += len(max_value) w = int(dimensions.split(" ")[0]) h = int(dimensions.split(" ")[1]) return (w, h), headersize def scale_to_crop_coord(scale_coord, scale_size, crop_size, epsilon): """Scale images are displayed 2-up in the screen.""" w2 = pygame.display.Info().current_w // 2 is_left = scale_coord[0] < w2 if is_left: x0 = w2 - epsilon - scale_size[0] else: x0 = w2 + epsilon x = (scale_coord[0] - x0) * crop_size[0] // scale_size[0] y = scale_coord[1] * crop_size[1] // scale_size[1] if is_left: x = crop_size[0] - x return (x, y), is_left def crop_to_full_coord(crop_coord, is_left): """We always crop out saddle, and usually crop to book page.""" x, y = crop_coord if book_dimensions: (top, bottom, side) = book_dimensions y += top if is_left: y += left_offset else: y += right_offset return x, y def process_image(h, filename, is_left): """Return both screen resolution and scan resolution images.""" kSaddleHeight = 3600 # scan pixels f = open(filename, "r+b") dimensions, headersize = read_ppm_header(f, filename) map = mmap.mmap(f.fileno(), 0) image = pygame.image.frombuffer(buffer(map, headersize), dimensions, 'RGB') unused, y = crop_to_full_coord((0, 0), is_left) if book_dimensions: (top, bottom, side) = book_dimensions wh = (side, bottom - top) else: wh = (image.get_width(), kSaddleHeight) rect = pygame.Rect((0, y), wh) crop = image.subsurface(rect) w = image.get_width() * h // kSaddleHeight scale = pygame.transform.smoothscale(crop, (w, h)) if is_left: scale = pygame.transform.flip(scale, True, False) return scale, crop def clip_image_number(playground): """Only show images that exist.""" global image_number if image_number < 1: # scanimage starts counting at 1 image_number = 1 while image_number > 1: filename = os.path.join(playground, '%06d.pnm' % image_number) if os.path.exists(filename): break image_number -= 2 def get_book_dimensions(playground): """User saved book dimensions in some earlier run.""" global book_dimensions try: for line in open(os.path.join(playground, "book_dimensions")).readlines(): if line[0] != "#": book_dimensions = [int(x) for x in line.split(",")] except IOError: pass def unset_book_dimensions(playground): global book_dimensions if book_dimensions: book_dimensions = None os.unlink(os.path.join(playground, "book_dimensions")) def set_book_dimensions(click, epsilon, crop_size, scale_size, playground): """User has dragged mouse to specify book position in image.""" global book_dimensions down = list(click[0]) up = list(click[1]) min_book_dimension = 30 # screen pixels w2 = pygame.display.Info().current_w // 2 down[0] = abs(w2 - down[0]) + w2 up[0] = abs(w2 - up[0]) + w2 if min(abs(down[1] - up[1]), abs(up[0] - w2)) < min_book_dimension: return side = max(down[0], up[0]) - w2 - epsilon top = min(down[1], up[1]) bottom = max(down[1], up[1]) side = min(side, scale_size[0]) side = side * crop_size[0] // scale_size[0] top = top * crop_size[1] // scale_size[1] bottom = bottom * crop_size[1] // scale_size[1] book_dimensions = (top, bottom, side) f = open(os.path.join(playground, "book_dimensions"), "wb") f.write("#top,bottom,side\n%s,%s,%s\n" % book_dimensions) f.close() def zoom(screen, click, scale_a, scale_b, crop_a, crop_b): """Given a mouseclick, zoom in on the region.""" coord, is_left = scale_to_crop_coord(click, scale_a.get_size(), crop_a.get_size(), get_epsilon(screen)) if is_left: crop = crop_a else: crop = crop_b size = pygame.display.Info().current_w // 3 dst = (click[0] - size, click[1] - size) rect = pygame.Rect((coord[0] - size, coord[1] - size), (2 * size, 2 * size)) if is_left: tmp = pygame.Surface((2 * size, 2 * size)) tmp.blit(crop, (0,0), rect) tmp2 = pygame.transform.flip(tmp, True, False) screen.blit(tmp2, dst) else: screen.blit(crop, dst, rect) def draw(screen, image_number, scale_a, scale_b, paused): """Draw the page images on screen.""" w2 = screen.get_width() // 2 render_text(screen, "%s" % str(image_number).ljust(4), "upperleft") render_text(screen, "%s" % str(image_number + 1).rjust(4), "upperright") epsilon = get_epsilon(screen) render_text(screen, "\n ", "upperleft") screen.blit(scale_a, (w2 - scale_a.get_width() - epsilon, 0)) screen.blit(scale_b, (w2 + epsilon, 0)) if paused: render_text(screen, "\nPAUSE", "upperleft") def create_new_pdf(playground, width, height): import reportlab.rl_config from reportlab.pdfgen.canvas import Canvas pdf = Canvas(os.path.join(playground, "book.pdf"), pagesize=(width, height), pageCompression=1) pdf.setCreator('cheesegrater') pdf.setTitle(os.path.basename(playground)) load_font() return pdf def export_pdf(playground, screen): """Create a PDF file fit for human consumption""" if book_dimensions == None: return width = book_dimensions[2] * 72 / dpi height = (book_dimensions[1] - book_dimensions[0]) * 72 / dpi pdf = create_new_pdf(playground, width, height) jpegs = glob.glob(os.path.join(playground, '*.jpg')) jpegs.sort(reverse=True) # Switch to reading order counter = 0 for jpeg in jpegs: msg = "Exporting PDF %d/%d" % (counter, len(jpegs) - 1) render_text(screen, msg, "upperright") counter += 1 number = int(os.path.basename(jpeg).split('-')[0]) if number in suppressions or (number - 1) in suppressions: continue pdf.drawImage(jpeg, 0, 0, width=width, height=height) add_text_layer(pdf, jpeg, height) pdf.showPage() pdf.save() render_text(screen, " " * len(msg), "upperright") def add_text_layer(pdf, jpeg, height): """Draw an invisible text layer for OCR data""" from xml.etree.ElementTree import ElementTree, ParseError p = re.compile('bbox((\s+\d+){4})') hocrfile = os.path.splitext(jpeg)[0] + ".html" hocr = ElementTree() try: hocr.parse(hocrfile) except ParseError: print("Parse error for %s" % hocrfile) # Tesseract bug fixed Aug 16, 2012 return except IOError: return # Tesseract not installed; user doesn't want OCR for line in hocr.findall(".//%sspan"%('')): if line.attrib['class'] != 'ocr_line': continue coords = p.search(line.attrib['title']).group(1).split() # Heuristic - we assume 30% of line bounding box is descenders b = float(coords[3]) - 0.3 * (float(coords[3]) - float(coords[1])) base = height - b * 72 / dpi for word in line: if word.attrib['class'] != 'ocr_word' or word.text is None: continue default_width = pdf.stringWidth(word.text.strip(), 'invisible', 8) if default_width <= 0: continue coords = p.search(word.attrib['title']).group(1).split() left = float(coords[0]) * 72 / dpi right = float(coords[2]) * 72 / dpi text = pdf.beginText() text.setTextRenderMode(3) # double invisible text.setFont('invisible', 8) text.setTextOrigin(left, base) text.setHorizScale(100.0 * (right - left) / default_width) text.textLine(word.text.strip()) pdf.drawText(text) def save_jpeg(screen, crop_a, crop_b, playground, image_number): """Save cropped images in reading order.""" a = pygame.transform.flip(crop_a, True, False) p1 = write_jpeg(screen, playground, a, image_number) p2 = write_jpeg(screen, playground, crop_b, image_number + 1) return (p1, p2) def write_jpeg(screen, playground, img, number): """Write JPEG image if not already there, plus remove any old cruft""" if book_dimensions: d = book_dimensions stem = "%06d-%s-%s-%s" % (number, d[0], d[1], d[2]) else: return hocrs = glob.glob(os.path.join(playground, '%06d-*.html' % number)) jpegs = glob.glob(os.path.join(playground, '%06d-*.jpg' % number)) for file in hocrs + jpegs: if os.path.splitext(os.path.basename(file))[0] != stem: os.remove(file) jpeg = os.path.join(playground, stem + ".jpg") if not os.path.exists(jpeg): pygame.image.save(img, jpeg) p = None hocr = os.path.join(playground, stem) if os.path.exists(hocr + ".html"): msg = "\n\n\n " else: msg = "\n\n\nOCR" try: p = subprocess.Popen(['tesseract', jpeg, hocr, 'hocr']) except OSError: pass # Tesseract not installed; user doesn't want OCR if number % 2 == 0: render_text(screen, msg, "upperleft") else: render_text(screen, msg, "upperright") return p def get_bibliography(barcode): """Hit up Google Books for bibliographic data. Thanks, Leonid.""" if barcode[0:3] == "978": url = ("http://books.google.com/books/download/" "?vid=isbn%s&output=enw&source=cheese" % barcode[0:13]) try: bib = urllib2.urlopen(url, None, 2).read() except urllib2.URLError, e: if hasattr(e, 'reason'): excuse = e.reason elif hasattr(e, 'code'): excuse = "HTTP return code %d\n" % e.code excuse += BaseHTTPServer.BaseHTTPRequestHandler.responses[e.code][0] return "Error looking up barcode: %s\n\n%s" % (barcode.split("_")[0], excuse) return bib return "Unknown Barcode: %s" % barcode.split("_")[0] def splashscreen(screen, barcode): """Like opening credits in a movie, but more useful.""" clearscreen(screen) render_text(screen, "Looking up barcode: %s" % barcode.split("_")[0], "upperleft") clearscreen(screen) render_text(screen, get_bibliography(barcode), "upperleft") pygame.display.update() render_text(screen, ("\n\n\n\n\n\n\n\n\n\n" "H,? = help\n" "MOUSE = crop | mosaic | zoom\n" "ARROWS = navigation\n" "PgUp/PgDn/Home/End = navigation!\n" "\n" "S = screenshot\n" "Q,ESC = quit\n" "\n" "E = export to pdf\n" "DELETE,BACKSPACE = delete\n" "U = uncrop\n" "F11,F = fullscreen\n" "P,SPACE = pause\n" ), "upperleft") clearscreen(screen) pygame.time.wait(2000) def get_suppressions(playground): """Read list of suppressed images from file""" global suppressions try: for line in open(os.path.join(playground, "suppressions")).readlines(): if line[0] != "#": suppressions = set([int(x) for x in line.split(",")]) except IOError: pass def set_suppressions(playground, image_number): """Toggle supression for the supplied image pair, persistantly""" global suppressions if image_number in suppressions: suppressions.remove(image_number) else: suppressions.add(image_number) filename = os.path.join(playground, "suppressions") f = open(filename, "wb") f.write("#Suppressed image pairs indicated by left image number\n") f.write(str(suppressions).strip('set([])')) f.write("\n"); f.close() def handle_key_event(screen, event, playground, barcode, mosaic_click, fullsize): """I find it easier to deal with keystrokes mostly in one place.""" global image_number global paused global fullscreen newscreen = None if event.key == pygame.K_ESCAPE or event.key == pygame.K_q: pygame.quit() sys.exit() elif event.key == pygame.K_SPACE or event.key == pygame.K_p: paused = not paused elif event.key == pygame.K_e: export_pdf(playground, screen) elif event.key == pygame.K_DELETE or event.key == pygame.K_BACKSPACE: set_suppressions(playground, image_number) elif event.key == pygame.K_F11 or event.key == pygame.K_f: fullscreen = not fullscreen set_pygame_window(fullsize, fullscreen) newscreen = pygame.display.get_surface() clearscreen(newscreen) elif event.key == pygame.K_LEFT or event.key == pygame.K_UP: image_number -= 2 paused = True elif event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN: image_number += 2 paused = True elif event.key == pygame.K_PAGEUP: image_number -= 10 paused = True elif event.key == pygame.K_PAGEDOWN: image_number += 10 paused = True elif event.key == pygame.K_HOME: image_number = 1 paused = True elif event.key == pygame.K_END: pnms = glob.glob(os.path.join(playground, '*.pnm')) pnms.sort(reverse=True) candidate = int(os.path.splitext(os.path.basename(pnms[0]))[0]) image_number = candidate - 1 + candidate % 2 # left page paused = True elif event.key == pygame.K_u: unset_book_dimensions(playground) elif event.key == pygame.K_s: filename = "screenshot-" + barcode + "-" + str(image_number) + ".jpg" pygame.image.save(screen, filename); render_text(screen, filename, "upperright") pygame.time.wait(2000) render_text(screen, " " * len(filename), "upperright") elif event.key == pygame.K_h or event.key == pygame.K_QUESTION: splashscreen(screen, barcode) pygame.time.wait(3000) clip_image_number(playground) if mosaic_click: clearscreen(screen) return newscreen def render(playground, screen, paused, image_number): """Calculate and draw entire screen, including book images.""" filename_a = os.path.join(playground, '%06d.pnm' % image_number) filename_b = os.path.join(playground, '%06d.pnm' % (image_number + 1)) h = screen.get_height() scale_a, crop_a = process_image(h, filename_a, True) scale_b, crop_b = process_image(h, filename_b, False) draw(screen, image_number, scale_a, scale_b, paused) pygame.display.set_caption("%d %s" % (image_number, os.path.basename(playground))) pygame.display.update() return crop_a, crop_b, scale_a, scale_b, image_number def mosaic_dimensions(screen): """Reduce some cut-n-past code.""" columns = 10 rows = 20 h = screen.get_height() // rows size = (2 * h, h) windowsize = 2 * rows * columns start = max(1, image_number - windowsize + 2) return size, windowsize, start, columns def navigate_mosaic(playground, screen, click): """Click on a mosaic tile, jump to that page.""" global image_number clearscreen(screen) size, unused, start, columns = mosaic_dimensions(screen) if click[0] > columns * size[0]: return x, y = click[0] // size[0], click[1] // size[1] candidate = start + 2 * (columns * y + x) filename = os.path.join(playground, '%06d.pnm' % candidate) if os.path.exists(filename): image_number = candidate def render_mosaic(screen, playground, click, scale_size, crop_size, image_number): """Useful for seeing lots of page numbers at once.""" crop_coord, is_left = scale_to_crop_coord(click, scale_size, crop_size, get_epsilon(screen)) full_coord = crop_to_full_coord(crop_coord, is_left) size, windowsize, start, columns = mosaic_dimensions(screen) if not is_left: start += 1 for i in range(start, start + windowsize, 2): x = ((i - start) // 2) % columns y = ((i - start) // 2) // columns filename = os.path.join(playground, '%06d.pnm' % i) if not os.path.exists(filename): break f = open(filename, "r+b") map = mmap.mmap(f.fileno(), 0) dimensions, headersize = read_ppm_header(f, filename) image = pygame.image.frombuffer(buffer(map, headersize), dimensions, 'RGB') src = full_coord[0] - 3 * size[0] // 2, full_coord[1] - 3 * size[1] // 2 rect = pygame.Rect(src, (size[0] * 3, size[1] * 3)) crop = image.subsurface(rect) scale = pygame.transform.smoothscale(crop, size) if is_left: scale = pygame.transform.flip(scale, True, False) dst = (size[0] * x, size[1] * y) dirty = pygame.Rect(dst, size) if is_left: left_image_number = i else: left_image_number = i - 1 screen.blit(scale, dst) if left_image_number in suppressions: red = pygame.Surface(scale.get_size()) red.fill(pygame.Color('red')) red.set_alpha(128) screen.blit(red, dst) map.close() f.close() pygame.display.update(dirty) def get_beep(): """Not having as external file makes life easier for sysadmins.""" wav = """ UklGRigCAABXQVZFZm10IBAAAAABAAEAESsAACJWAAACABAAZGF0YQQCAAA01jVaF1f2WGJW1FoN U5hhMcMxoKCoiqhcogiwOJTK/zxqak9fXHxWrFYcXv08rZtQrhShk6wBoXaudZtGPcZdBlcnVqdc N09Tatf//pN7sKKhmKkypwui3sBzZJhP+V5tUfBeq09XZALB36Fnp1mp7KEksGWUXv/eappOVV1n VdhX41w7Pm6ai6/hn7yt5Z+Cr3uaLD71XMJXgVU4XbpOu2qE/z2UT7C9oYupM6cVosvAjGR5Tx9f QVEgX3hPimTQwA+iOqeEqcKhS7BBlIH/vmq2TjxdfVXGV/FcMD53moWv45+8reOfhq92mjE+71zI V3xVPF22Tr9qf/9ClEuwwqGFqTinEKLQwItkd08gX0JRHl96T4pkzsASojenhanDoUuwQJSC/7xq uE48XXxVx1fxXC4+epqCr+afuq3kn4Wvd5oxPu9cx1d9VTtduE6+an7/RZRGsMihfqk/pwui1MCG ZHxPG19HURpffU+HZNHAEKI4p4apwKFPsDuUh/+2asJOLl2NVbNXBV0cPouaca/5n6Wt+p9wr4ma Ij77XMFXfFVDXalO0mpm/2OUILD2oUipgKe+oSzBImTtT6FeyFGTXghQ+mNgwYGhw6cCqTmi5K+W lED/5WqsTiddtVVnV3pdej1bm3OuJKFNrH+hv61knCI8GF+PVbVXG1uUUIZp4f4= """ f = cStringIO.StringIO(base64.decodestring(wav)) return pygame.mixer.Sound(f) def set_pygame_window(size, fullscreen): """Apply fullscreen or windowed user interface""" if fullscreen: return pygame.display.set_mode(size, pygame.FULLSCREEN) pygame.display.set_mode((size[0] // 2, size[1] // 2), pygame.RESIZABLE) def main(argv1): """Display scanned images as they are created.""" playground = argv1.rstrip('/') barcode = os.path.basename(playground) pygame.init() global image_number global paused global book_dimensions last_drawn_image_number = 0 get_book_dimensions(playground) get_suppressions(playground) try: beep = get_beep() except: pass fullsize = (pygame.display.Info().current_w, pygame.display.Info().current_h) set_pygame_window(fullsize, fullscreen) screen = pygame.display.get_surface() pygame.display.set_caption("%s" % os.path.basename(playground)) splashscreen(screen, barcode) scale_a = None # prevent crash if keypress during opening splashscreen image_number = 1 pygame.time.set_timer(pygame.USEREVENT, 50) shadow = pygame.Surface(screen.get_size()) shadow.set_alpha(128) shadow.fill((0, 0, 0)) mosaic_click = None # Don't mode me in, bro! p1, p2 = None, None busy = False while True: for event in [ pygame.event.wait() ]: if event.type == pygame.MOUSEBUTTONDOWN: busy = True pygame.event.clear(pygame.USEREVENT) if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: if mosaic_click or book_dimensions: continue leftdownclick = event.pos oldscreen = screen.copy() shadowscreen = screen.copy() shadowscreen.blit(shadow, (0, 0)) screen.blit(shadowscreen, (0, 0)) prevroi = pygame.Rect(event.pos, (0, 0)) pygame.display.update() elif event.type == pygame.MOUSEMOTION and event.buttons[0] == 1: if book_dimensions or mosaic_click: continue x = abs(event.pos[0] - screen.get_width() // 2) pos = (screen.get_width() // 2 - x, min(leftdownclick[1], event.pos[1])) roi = pygame.Rect(pos, (2 * x, abs(leftdownclick[1] - event.pos[1]))) dirty = roi.union(prevroi) prevroi = roi.copy() screen.blit(shadowscreen, dirty.topleft, area = dirty) screen.blit(oldscreen, roi.topleft, area = roi) pygame.display.update(dirty) elif event.type == pygame.MOUSEBUTTONUP and event.button == 1: if mosaic_click: navigate_mosaic(playground, screen, event.pos) last_drawn_image_number = None mosaic_click = None elif not book_dimensions: oldscreen = None leftclick = (leftdownclick, event.pos) set_book_dimensions(leftclick, get_epsilon(screen), crop_a.get_size(), scale_a.get_size(), playground) clearscreen(screen) crop_a, crop_b, scale_a, scale_b, last_drawn_image_number = \ render(playground, screen, paused, image_number) busy = False elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3: draw(screen, image_number, scale_a, scale_b, paused) zoom(screen, event.pos, scale_a, scale_b, crop_a, crop_b) pygame.display.update() elif event.type == pygame.MOUSEBUTTONUP and event.button == 3: mosaic_click = None clearscreen(screen) draw(screen, image_number, scale_a, scale_b, paused) pygame.display.update() busy = False elif event.type == pygame.MOUSEBUTTONUP and event.button == 2: mosaic_click = event.pos if image_number != last_drawn_image_number: crop_a, crop_b, scale_a, scale_b, last_drawn_image_number = \ render(playground, screen, paused, image_number) try: render_mosaic(screen, playground, mosaic_click, scale_a.get_size(), crop_a.get_size(), image_number) except ValueError: mosaic_click = None paused = True busy = False elif event.type == pygame.QUIT: pygame.quit() sys.exit() elif mosaic_click and \ event.type == pygame.KEYDOWN and \ (event.key == pygame.K_PAGEUP or event.key == pygame.K_PAGEDOWN): unused, windowsize, start, unused = mosaic_dimensions(screen) if event.key == pygame.K_PAGEUP: image_number = start - 2 elif event.key == pygame.K_PAGEDOWN: image_number = start + windowsize + windowsize - 2 clip_image_number(playground) clearscreen(screen) if image_number != last_drawn_image_number: crop_a, crop_b, scale_a, scale_b, last_drawn_image_number = \ render(playground, screen, paused, image_number) render_mosaic(screen, playground, mosaic_click, scale_a.get_size(), crop_a.get_size(), image_number) elif event.type == pygame.KEYDOWN: newscreen = handle_key_event(screen, event, playground, barcode, mosaic_click, fullsize) mosaic_click = None last_drawn_image_number = None if newscreen: screen = newscreen clearscreen(screen) elif event.type == pygame.VIDEORESIZE: screen = pygame.display.set_mode(event.size, pygame.RESIZABLE) clearscreen(screen) last_drawn_image_number = None elif event.type == pygame.USEREVENT: if busy: continue if p1 and p1.poll() != None: p1 = None render_text(screen, "\n\n\n ", "upperleft") if p2 and p2.poll() != None: p2 = None render_text(screen, "\n\n\n ", "upperright") if not (paused or p1 or p2): image_number += 2 clip_image_number(playground) if image_number != last_drawn_image_number: try: crop_a, crop_b, scale_a, scale_b, last_drawn_image_number = \ render(playground, screen, paused, image_number) p1, p2 = save_jpeg(screen, crop_a, crop_b, playground, image_number) if not paused: try: beep.play() except: pass except IOError: pass pygame.event.clear(pygame.USEREVENT) # Glyphless variation of vedaal's invisible font retrieved from # http://www.angelfire.com/pr/pgpf/if.html, which says: # 'Invisible font' is unrestricted freeware. Enjoy, Improve, Distribute freely def load_font(): font = """ AAEAAAANAIAAAwBQRkZUTVJ1oasAAAlUAAAAHEdERUYAMAAEAAAJNAAAACBPUy8yvX2H2QAAAVgAAAB WY21hcAANA5YAAAG4AAABOmdhc3D//wADAAAJLAAAAAhnbHlmAAAAAAAAAvwAAAAAaGVhZPfIBVkAAA DcAAAANmhoZWEKHQJZAAABFAAAACRobXR4CAAAAAAAAbAAAAAIbG9jYQAAAAAAAAL0AAAACG1heHAEY gAxAAABOAAAACBuYW1lwzbcaAAAAvwAAAYIcG9zdP8tAJgAAAkEAAAAKAABAAAAAQAA7vU91l8PPPUA CwgAAAAAAMxU4C4AAAAAzFTgLgAAAAAAAAAAAAAACAACAAAAAAAAAAEAAAnY+lcAQwgAAAAAAAAAAAE AAAAAAAAAAAAAAAAAAAABAAEAAAADAAAAAAAAAAAAAgAQAC8AQgAABAwAAAAAAAAAAQH0AZAABQAIBZ oFMwAAARsFmgUzAAAD0QBmAhIAAAIAAAAAAAAAAACgAAKvUAB4+wAAAAAAAAAASEwgIABA//8AAAXT/ lEBMwNyBA9gAAGf3/cAAAAACAAAAAAAAAAAAAADAAAAAwAAABwAAQAAAAAANAADAAEAAAAcAAQAGAAA AAIAAgAAAAD//wAA//8AAQAAAAABBgAAAQAAAAAAAAABAgAAAAIAAAAAAAAAAAAAAAAAAAABAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAoAeY AAQAAAAAAAAA0AGoAAQAAAAAAAQAJALMAAQAAAAAAAgAHAM0AAQAAAAAAAwAWAQMAAQAAAAAABAAJAS 4AAQAAAAAABQAwAZoAAQAAAAAABgAJAd8AAQAAAAAACgBAAmsAAwABBAMAAgAMAqwAAwABBAUAAgAQA roAAwABBAYAAgAMAswAAwABBAcAAgAQAtoAAwABBAgAAgAQAuwAAwABBAkAAABoAAAAAwABBAkAAQAS AJ8AAwABBAkAAgAOAL0AAwABBAkAAwAsANUAAwABBAkABAASARoAAwABBAkABQBgATgAAwABBAkABgA SAcsAAwABBAkACgCAAekAAwABBAoAAgAMAv4AAwABBAsAAgAQAwwAAwABBAwAAgAMAx4AAwABBA4AAg AMAywAAwABBBAAAgAOAzoAAwABBBMAAgASA0oAAwABBBQAAgAMA14AAwABBBUAAgAQA2wAAwABBBYAA gAMA34AAwABBBkAAgAOA4wAAwABBBsAAgAQA5wAAwABBB0AAgAMA64AAwABBB8AAgAMA7wAAwABBCQA AgAOA8oAAwABBC0AAgAOA9oAAwABCAoAAgAMA+oAAwABCBYAAgAMA/gAAwABDAoAAgAMBAYAAwABDAw AAgAMBBQAVAB5AHAAZQBmAGEAYwBlACAAqQAgACgAeQBvAHUAcgAgAGMAbwBtAHAAYQBuAHkAKQAuAC AAMgAwADAANQAuACAAQQBsAGwAIABSAGkAZwBoAHQAcwAgAFIAZQBzAGUAcgB2AGUAZAAAVHlwZWZhY 2UgqSAoeW91ciBjb21wYW55KS4gMjAwNS4gQWxsIFJpZ2h0cyBSZXNlcnZlZAAAaQBuAHYAaQBzAGkA YgBsAGUAAGludmlzaWJsZQAAUgBlAGcAdQBsAGEAcgAAUmVndWxhcgAAaQBuAHYAaQBzAGkAYgBsAGU AOgBWAGUAcgBzAGkAbwBuACAAMQAuADAAMAAAaW52aXNpYmxlOlZlcnNpb24gMS4wMAAAaQBuAHYAaQ BzAGkAYgBsAGUAAGludmlzaWJsZQAAVgBlAHIAcwBpAG8AbgAgADEALgAwADAAIABTAGUAcAB0AGUAb QBiAGUAcgAgADEAMwAsACAAMgAwADAANQAsACAAaQBuAGkAdABpAGEAbAAgAHIAZQBsAGUAYQBzAGUA AFZlcnNpb24gMS4wMCBTZXB0ZW1iZXIgMTMsIDIwMDUsIGluaXRpYWwgcmVsZWFzZQAAaQBuAHYAaQB zAGkAYgBsAGUAAGludmlzaWJsZQAAVABoAGkAcwAgAGYAbwBuAHQAIAB3AGEAcwAgAGMAcgBlAGEAdA BlAGQAIAB1AHMAaQBuAGcAIABGAG8AbgB0ACAAQwByAGUAYQB0AG8AcgAgADUALgAwACAAZgByAG8Ab QAgAEgAaQBnAGgALQBMAG8AZwBpAGMALgBjAG8AbQAAVGhpcyBmb250IHdhcyBjcmVhdGVkIHVzaW5n IEZvbnQgQ3JlYXRvciA1LjAgZnJvbSBIaWdoLUxvZ2ljLmNvbQAATgBvAHIAbQBhAGwAAABvAGIAeQE NAGUAagBuAOkAAABuAG8AcgBtAGEAbAAAAFMAdABhAG4AZABhAHIAZAAAA5oDsQO9A78DvQO5A7oDrA AAAE4AbwByAG0AYQBsAAAATgBvAHIAbQBhAGEAbABpAAAATgBvAHIAbQBhAGwAAABOAG8AcgBtAOEAb AAAAE4AbwByAG0AYQBsAGUAAABTAHQAYQBuAGQAYQBhAHIAZAAAAE4AbwByAG0AYQBsAAAATgBvAHIA bQBhAGwAbgB5AAAATgBvAHIAbQBhAGwAAAQeBDEESwRHBD0ESwQ5AAAATgBvAHIAbQDhAGwAbgBlAAA ATgBvAHIAbQBhAGwAAABOAG8AcgBtAGEAbAAAAE4AYQB2AGEAZABuAG8AAABBAHIAcgB1AG4AdABhAA AATgBvAHIAbQBhAGwAAABOAG8AcgBtAGEAbAAAAE4AbwByAG0AYQBsAAAATgBvAHIAbQBhAGwAAAACA AAAAAAA/ycAlgAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAABAAIAAAAB//8AAgABAAAADgAAABgAAAAA AAIAAQABAAIAAQAEAAAAAgAAAAAAAQAAAADG1C6ZAAAAAL9MkvAAAAAAzFTgIQ== """ ttf = cStringIO.StringIO(base64.decodestring(font)) from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('invisible', ttf)) if __name__ == "__main__": if len(sys.argv) == 1: print("Usage: %s <imgdir>\n" % os.path.basename(sys.argv[0])) else: main(sys.argv[1])
Python
# -*- coding: utf-8 -*- #! /usr/bin/env python from PySide.QtCore import Qt _ADD, _DELETE, _INSERT = range(3) _ROOT, _DEPTH, _WIDTH = range(3) def int_to_checkstate(i): i = int(i) return { 0 : Qt.CheckState.Unchecked, 1 : Qt.CheckState.PartiallyChecked, 2 : Qt.CheckState.Checked, }.get(i, Qt.CheckState.Unchecked) def checkstate_to_int(c): return { Qt.CheckState.Unchecked: 0, Qt.CheckState.PartiallyChecked: 1, Qt.CheckState.Checked: 2, }.get(c, 0) def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") s = s.replace("&quot;", "\"") # this has to be last: s = s.replace("&amp;", "&") return s def create_dirs(dir): if not os.path.exists(dir): os.mkdir(dir) if not os.path.exists(dir + "/cur"): os.mkdir(dir + "/cur") if not os.path.exists(dir + "/new"): os.mkdir(dir + "/new") if not os.path.exists(dir + "/tmp"): os.mkdir(dir + "/tmp") # Create Maildir++ folder marker file(dir + "/maildirfolder", "w").close() class Node(object): def __init__(self, id = 0, title = '', checked = False, expanded = True, parent = None): self.id = id self.parent = parent self.title = title self.checked = checked self.expanded = expanded class Tree(object): def __init__(self): self.nodes = [] def get_index(self, id): for index, node in enumerate(self.nodes): if node.identifier == id: break return index def create_node(self, id, title = '', checked = False, parent = None): node = Node(id, title) self.nodes.append(node) return node def __getitem__(self, key): return self.nodes[self.get_index(key)] def __setitem__(self, key, item): self.nodes[self.get_index(key)] = item def __len__(self): return len(self.nodes) def __contains__(self, identifier): return [node.identifier for node in self.nodes if node.identifier is identifier] if __name__ == "__main__": tree = Tree() tree.create_node(1, "harry") # root node tree.create_node(3, "jane", parent = 1) tree.create_node(4, "bill", parent = 1) tree.create_node(5, "joe", parent = 3) tree.create_node(6, "diane", parent = 3) tree.create_node(7, "george", parent = 6) tree.create_node(8, "mary", parent = 6) tree.create_node(9, "jill", parent = 7) tree.create_node(10, "carol", parent = 8) tree.create_node(11, "grace", parent = 9) tree.create_node(12, "mark", parent = 3) print("="*80) tree.show("harry") print("="*80) for node in tree.expand_tree("harry", mode = _WIDTH): print(node) print("="*80)
Python
# -*- coding: utf-8 -*- from PySide import QtCore, QtGui, QtWebKit from operator import attrgetter from config import * from utils import unescape #from post_widget import PostView class QWorker(QtCore.QThread): signal = QtCore.Signal(str) signal_update_status_bar = QtCore.Signal(tuple) signal_update_progress_bar = QtCore.Signal(int) fill_tree_signal = QtCore.Signal(int, int, tuple, int) def __init__(self, parent = None): QtCore.QThread.__init__(self, parent) self.func = None self.data = None self.exc = None self.exiting = False self.UL_THREADS = UL_THREADS self.parent = parent self.forum = parent.forum self.args = () self.kwargs = {} self.disabled_ids = [] self.signal.connect(self.parent.on_finished) self.signal_update_status_bar.connect(self.parent.update_status_bar) self.signal_update_progress_bar.connect(self.parent.update_progress_bar) self.fill_tree_signal.connect(self.parent.add_tree_item) if self.parent._update_target == UPDATE_ALL: self.disabled_ids = [] elif self.parent._update_target == UPDATE_SELECTED: self.disabled_ids = [id for id, item in self.parent._forum_cache.items() if not item.checked] elif self.parent._update_target == UPDATE_UNSELECTED: self.disabled_ids = [id for id, item in self.parent._forum_cache.items() if item.checked] #self.disabled_ids = [42, 91] #print self.disabled_ids def work(self, func, *args, **kwargs): self.func = attrgetter(func)(self) self.args = args self.kwargs = kwargs self.start() def _update_threads(self): for id, f_title in self.UL_THREADS.iteritems(): if id in self.disabled_ids: continue f_data = (0, f_title), self.fill_tree_signal.emit(0, id, f_data, TOP_LEVEL) forums = self.forum.get_forums_list() i = 100 - len(forums) # TODO: later... self.signal_update_progress_bar.emit(i) for f in forums: f_id, f_title, f_answers, f_bluetime, f_lastauthor, f_threads, f_parentid = f f_id = int(f_id) f_parentid = int(f_parentid) if f_parentid in self.disabled_ids or f_id in self.disabled_ids: continue f_title = unicode(unescape(f_title), FORUM_ENCODING) #print f_parentid, f_id, f_title, self.disabled_ids t_data = (0, f_title), (1, f_threads), (2, f_answers), (3, f_bluetime) self.fill_tree_signal.emit(f_parentid, f_id, t_data, FORUM) for t in self.forum.get_threads_list(f_id): t_id, t_title, t_bluetime, t_open1, t_open2, t_answers, t_author, t_author_id, t_lastauthor, t_lastauthor_id, t_undertitle = t #print t_id, unicode(unescape(t_title), FORUM_ENCODING), t_bluetime, t_open1, t_open2, t_answers, unicode(unescape(t_author), FORUM_ENCODING), t_author_id, t_lastauthor_id, unicode(unescape(t_undertitle), FORUM_ENCODING) t_id = int(t_id) if t_id in self.disabled_ids: continue t_title = unicode(unescape(t_title), FORUM_ENCODING) if t_undertitle: t_title += " (%s)" % unicode(unescape(t_undertitle), FORUM_ENCODING) self.signal_update_status_bar.emit((t_title, 0)) t_data = (0, t_title), (2, t_answers), (3, t_bluetime) self.fill_tree_signal.emit(f_id, t_id, t_data, THREAD) i += 1 self.signal_update_progress_bar.emit(i) self.signal_update_progress_bar.emit(100) self.signal_update_status_bar.emit(('Ready', 0)) def run(self): try: self.data = self.func(*self.args, **self.kwargs) except Exception, e: self.signal.emit(e.message) else: self.signal.emit('') def __del__(self): self.exiting = True self.wait()
Python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'untitled.ui' # # Created: Mon Apr 23 15:15:26 2012 # by: pyside-uic 0.2.13 running on PySide 1.1.0 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui, QtWebKit from list_widget import ListWidget import os class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1212, 888) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) MainWindow.setMinimumSize(QtCore.QSize(800, 600)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setDockNestingEnabled(False) self.centralwidget = QtGui.QWidget(MainWindow) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth()) self.centralwidget.setSizePolicy(sizePolicy) self.centralwidget.setMinimumSize(QtCore.QSize(800, 600)) self.centralwidget.setAutoFillBackground(False) self.centralwidget.setObjectName("centralwidget") self.gridLayoutWidget = QtGui.QWidget(self.centralwidget) self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 1231, 761)) self.gridLayoutWidget.setObjectName("gridLayoutWidget") self.gridLayout = QtGui.QGridLayout(self.gridLayoutWidget) self.gridLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.tab_widget = QtGui.QTabWidget(self.gridLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tab_widget.sizePolicy().hasHeightForWidth()) self.tab_widget.setSizePolicy(sizePolicy) self.tab_widget.setMinimumSize(QtCore.QSize(800, 600)) self.tab_widget.setTabsClosable(True) self.tab_widget.setObjectName("tab_widget") self.tab = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tab.sizePolicy().hasHeightForWidth()) self.tab.setSizePolicy(sizePolicy) self.tab.setObjectName("tab") self.gridLayoutWidget_7 = QtGui.QWidget(self.tab) self.gridLayoutWidget_7.setGeometry(QtCore.QRect(10, 10, 1121, 611)) self.gridLayoutWidget_7.setObjectName("gridLayoutWidget_7") self.gridLayout_7 = QtGui.QGridLayout(self.gridLayoutWidget_7) self.gridLayout_7.setSizeConstraint(QtGui.QLayout.SetMaximumSize) self.gridLayout_7.setContentsMargins(8, 8, 8, 8) self.gridLayout_7.setSpacing(8) self.gridLayout_7.setContentsMargins(0, 0, 0, 0) self.gridLayout_7.setObjectName("gridLayout_7") self.progressBar = QtGui.QProgressBar(self.gridLayoutWidget_7) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth()) self.progressBar.setSizePolicy(sizePolicy) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName("progressBar") self.gridLayout_7.addWidget(self.progressBar, 1, 0, 1, 1) self.tree_widget = QtGui.QTreeWidget(self.gridLayoutWidget_7) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tree_widget.sizePolicy().hasHeightForWidth()) self.tree_widget.setSizePolicy(sizePolicy) self.tree_widget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.tree_widget.setColumnCount(5) self.tree_widget.setObjectName("tree_widget") self.tree_widget.headerItem().setText(0, "Тема") self.gridLayout_7.addWidget(self.tree_widget, 0, 0, 1, 1) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setContentsMargins(8, 8, 8, 8) self.verticalLayout.setObjectName("verticalLayout") self.get_forums_button = QtGui.QPushButton(self.gridLayoutWidget_7) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.get_forums_button.sizePolicy().hasHeightForWidth()) self.get_forums_button.setSizePolicy(sizePolicy) self.get_forums_button.setMinimumSize(QtCore.QSize(250, 0)) self.get_forums_button.setObjectName("get_forums_button") self.verticalLayout.addWidget(self.get_forums_button) self.update_target = QtGui.QVBoxLayout() self.update_target.setObjectName("update_target") self.get_all_rb = QtGui.QRadioButton(self.gridLayoutWidget_7) self.get_all_rb.setChecked(True) self.get_all_rb.setObjectName("get_all_rb") self.update_target.addWidget(self.get_all_rb) self.get_selected_rb = QtGui.QRadioButton(self.gridLayoutWidget_7) self.get_selected_rb.setObjectName("get_selected_rb") self.update_target.addWidget(self.get_selected_rb) self.get_unselected_rb = QtGui.QRadioButton(self.gridLayoutWidget_7) self.get_unselected_rb.setObjectName("get_unselected_rb") self.update_target.addWidget(self.get_unselected_rb) self.verticalLayout.addLayout(self.update_target) self.line_2 = QtGui.QFrame(self.gridLayoutWidget_7) self.line_2.setFrameShape(QtGui.QFrame.HLine) self.line_2.setFrameShadow(QtGui.QFrame.Sunken) self.line_2.setObjectName("line_2") self.verticalLayout.addWidget(self.line_2) self.check_on_startup_cb = QtGui.QCheckBox(self.gridLayoutWidget_7) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.check_on_startup_cb.sizePolicy().hasHeightForWidth()) self.check_on_startup_cb.setSizePolicy(sizePolicy) self.check_on_startup_cb.setObjectName("check_on_startup_cb") self.verticalLayout.addWidget(self.check_on_startup_cb) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.reload_interval_sb = QtGui.QSpinBox(self.gridLayoutWidget_7) self.reload_interval_sb.setObjectName("reload_interval_sb") self.horizontalLayout.addWidget(self.reload_interval_sb) self.label = QtGui.QLabel(self.gridLayoutWidget_7) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setMargin(0) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.horizontalLayout.setStretch(1, 10) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setContentsMargins(8, 8, 8, 8) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label_3 = QtGui.QLabel(self.gridLayoutWidget_7) self.label_3.setObjectName("label_3") self.horizontalLayout_3.addWidget(self.label_3) self.lcd_number_forums = QtGui.QLCDNumber(self.gridLayoutWidget_7) self.lcd_number_forums.setDigitCount(4) self.lcd_number_forums.setSegmentStyle(QtGui.QLCDNumber.Flat) self.lcd_number_forums.setObjectName("lcd_number_forums") self.horizontalLayout_3.addWidget(self.lcd_number_forums) self.verticalLayout.addLayout(self.horizontalLayout_3) self.line = QtGui.QFrame(self.gridLayoutWidget_7) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName("line") self.verticalLayout.addWidget(self.line) self.hide_to_tray_cb = QtGui.QCheckBox(self.gridLayoutWidget_7) self.hide_to_tray_cb.setObjectName("hide_to_tray_cb") self.verticalLayout.addWidget(self.hide_to_tray_cb) self.line_3 = QtGui.QFrame(self.gridLayoutWidget_7) self.line_3.setFrameShape(QtGui.QFrame.HLine) self.line_3.setFrameShadow(QtGui.QFrame.Sunken) self.line_3.setObjectName("line_3") self.verticalLayout.addWidget(self.line_3) self.get_posts_button = QtGui.QPushButton(self.gridLayoutWidget_7) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.get_posts_button.sizePolicy().hasHeightForWidth()) self.get_posts_button.setSizePolicy(sizePolicy) self.get_posts_button.setObjectName("get_posts_button") self.verticalLayout.addWidget(self.get_posts_button) self.horizontalLayout_9 = QtGui.QHBoxLayout() self.horizontalLayout_9.setObjectName("horizontalLayout_9") self.reload_posts_interval_sb = QtGui.QSpinBox(self.gridLayoutWidget_7) self.reload_posts_interval_sb.setObjectName("reload_posts_interval_sb") self.horizontalLayout_9.addWidget(self.reload_posts_interval_sb) self.label_9 = QtGui.QLabel(self.gridLayoutWidget_7) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label_9.sizePolicy().hasHeightForWidth()) self.label_9.setSizePolicy(sizePolicy) self.label_9.setMargin(0) self.label_9.setObjectName("label_9") self.horizontalLayout_9.addWidget(self.label_9) self.horizontalLayout_9.setStretch(1, 10) self.verticalLayout.addLayout(self.horizontalLayout_9) self.horizontalLayout_8 = QtGui.QHBoxLayout() self.horizontalLayout_8.setContentsMargins(8, 8, 8, 8) self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.label_8 = QtGui.QLabel(self.gridLayoutWidget_7) self.label_8.setObjectName("label_8") self.horizontalLayout_8.addWidget(self.label_8) self.lcd_number_posts = QtGui.QLCDNumber(self.gridLayoutWidget_7) self.lcd_number_posts.setDigitCount(4) self.lcd_number_posts.setSegmentStyle(QtGui.QLCDNumber.Flat) self.lcd_number_posts.setObjectName("lcd_number_posts") self.horizontalLayout_8.addWidget(self.lcd_number_posts) self.verticalLayout.addLayout(self.horizontalLayout_8) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem) self.gridLayout_7.addLayout(self.verticalLayout, 0, 1, 1, 1) self.gridLayout_7.setColumnStretch(0, 10) self.tab_widget.addTab(self.tab, "") self.tab_2 = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tab_2.sizePolicy().hasHeightForWidth()) self.tab_2.setSizePolicy(sizePolicy) self.tab_2.setObjectName("tab_2") self.gridLayoutWidget_2 = QtGui.QWidget(self.tab_2) self.gridLayoutWidget_2.setGeometry(QtCore.QRect(30, 10, 1071, 671)) self.gridLayoutWidget_2.setObjectName("gridLayoutWidget_2") self.gridLayout_2 = QtGui.QGridLayout(self.gridLayoutWidget_2) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setObjectName("gridLayout_2") self.subscribe_listWidget = QtGui.QListWidget(self.gridLayoutWidget_2) self.subscribe_listWidget.setObjectName("subscribe_listWidget") self.gridLayout_2.addWidget(self.subscribe_listWidget, 0, 0, 4, 1) self.subscribe_listWidget11 = ListWidget(self.gridLayoutWidget_2) self.subscribe_listWidget11.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.gridLayout_2.addWidget(self.subscribe_listWidget11, 0, 1, 2, 1) self.subscribed_view = QtWebKit.QWebView() self.subscribed_view.setHtml('') path = os.getcwd() self.subscribed_view.settings().setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile(path + "/css_2.css")) self.gridLayout_2.addWidget(self.subscribed_view, 2, 1, 1, 1) self.update_subscribed_button = QtGui.QPushButton(self.gridLayoutWidget_2) self.update_subscribed_button.setObjectName("update_subscribed_button") self.gridLayout_2.addWidget(self.update_subscribed_button, 4, 1, 1, 1) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.reload_interval_subscription_sb = QtGui.QSpinBox(self.gridLayoutWidget_2) self.reload_interval_subscription_sb.setObjectName("reload_interval_subscription_sb") self.horizontalLayout_2.addWidget(self.reload_interval_subscription_sb) self.label_2 = QtGui.QLabel(self.gridLayoutWidget_2) self.label_2.setObjectName("label_2") self.horizontalLayout_2.addWidget(self.label_2) self.lcd_number_subscription = QtGui.QLCDNumber(self.gridLayoutWidget_2) self.lcd_number_subscription.setObjectName("lcd_number_subscription") self.horizontalLayout_2.addWidget(self.lcd_number_subscription) self.horizontalLayout_2.setStretch(1, 1) self.gridLayout_2.addLayout(self.horizontalLayout_2, 4, 0, 1, 1) self.gridLayout_2.setColumnStretch(1, 1) self.gridLayout_2.setRowStretch(0, 1) self.tab_widget.addTab(self.tab_2, "") self.gridLayout.addWidget(self.tab_widget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1212, 27)) self.menubar.setObjectName("menubar") self.menu = QtGui.QMenu(self.menubar) self.menu.setObjectName("menu") MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.statusbar.sizePolicy().hasHeightForWidth()) self.statusbar.setSizePolicy(sizePolicy) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.action = QtGui.QAction(MainWindow) self.action.setObjectName("action") self.menu.addAction(self.action) self.menubar.addAction(self.menu.menuAction()) self.retranslateUi(MainWindow) self.tab_widget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "FER Fetcher", None, QtGui.QApplication.UnicodeUTF8)) self.tree_widget.headerItem().setText(2, QtGui.QApplication.translate("MainWindow", "Ответов", None, QtGui.QApplication.UnicodeUTF8)) self.get_forums_button.setToolTip(QtGui.QApplication.translate("MainWindow", "Если не знаете, что делать, жмите сюда.", None, QtGui.QApplication.UnicodeUTF8)) self.get_forums_button.setText(QtGui.QApplication.translate("MainWindow", "Обновить темы форума", None, QtGui.QApplication.UnicodeUTF8)) #self.get_all_rb.setToolTip(QtGui.QApplication.translate("MainWindow", "Не работает", None, QtGui.QApplication.UnicodeUTF8)) self.get_all_rb.setText(QtGui.QApplication.translate("MainWindow", "Обновлять всё", None, QtGui.QApplication.UnicodeUTF8)) #self.get_selected_rb.setToolTip(QtGui.QApplication.translate("MainWindow", "Не работает", None, QtGui.QApplication.UnicodeUTF8)) self.get_selected_rb.setText(QtGui.QApplication.translate("MainWindow", "Только выделенное", None, QtGui.QApplication.UnicodeUTF8)) #self.get_unselected_rb.setToolTip(QtGui.QApplication.translate("MainWindow", "Не работает", None, QtGui.QApplication.UnicodeUTF8)) self.get_unselected_rb.setText(QtGui.QApplication.translate("MainWindow", "Кроме выделенного", None, QtGui.QApplication.UnicodeUTF8)) self.check_on_startup_cb.setText(QtGui.QApplication.translate("MainWindow", "Обновлять при запуске", None, QtGui.QApplication.UnicodeUTF8)) self.reload_interval_sb.setToolTip(QtGui.QApplication.translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:14pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Интервал обновления в минутах.</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Если <span style=\" font-weight:600;\">0</span> - не обновлять.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.label.setToolTip(QtGui.QApplication.translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:14pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Интервал обновления в минутах.</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Если <span style=\" font-weight:600;\">0</span> - не обновлять.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", "Интервал обновления", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("MainWindow", "Обновление через", None, QtGui.QApplication.UnicodeUTF8)) self.hide_to_tray_cb.setText(QtGui.QApplication.translate("MainWindow", "Сворачивать в трей", None, QtGui.QApplication.UnicodeUTF8)) self.get_posts_button.setText(QtGui.QApplication.translate("MainWindow", "Обновить открытые threads", None, QtGui.QApplication.UnicodeUTF8)) self.label_8.setText(QtGui.QApplication.translate("MainWindow", "Обновление через", None, QtGui.QApplication.UnicodeUTF8)) self.reload_posts_interval_sb.setToolTip(QtGui.QApplication.translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:14pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Интервал обновления в минутах.</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Если <span style=\" font-weight:600;\">0</span> - не обновлять.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.label_9.setToolTip(QtGui.QApplication.translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:14pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Интервал обновления в минутах.</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Если <span style=\" font-weight:600;\">0</span> - не обновлять.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.label_9.setText(QtGui.QApplication.translate("MainWindow", "Интервал обновления", None, QtGui.QApplication.UnicodeUTF8)) self.tab_widget.setTabText(self.tab_widget.indexOf(self.tab), QtGui.QApplication.translate("MainWindow", "Список Форумов", None, QtGui.QApplication.UnicodeUTF8)) __sortingEnabled = self.subscribe_listWidget.isSortingEnabled() self.subscribe_listWidget.setSortingEnabled(False) self.subscribe_listWidget.setSortingEnabled(__sortingEnabled) self.update_subscribed_button.setText(QtGui.QApplication.translate("MainWindow", "Обновить", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setToolTip(QtGui.QApplication.translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:14pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Интервал обновления в минутах.</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Если <span style=\" font-weight:600;\">0</span> - не обновлять.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Интервал обновления", None, QtGui.QApplication.UnicodeUTF8)) self.tab_widget.setTabText(self.tab_widget.indexOf(self.tab_2), QtGui.QApplication.translate("MainWindow", "Подписка", None, QtGui.QApplication.UnicodeUTF8)) self.menu.setTitle(QtGui.QApplication.translate("MainWindow", "Меню", None, QtGui.QApplication.UnicodeUTF8)) self.action.setText(QtGui.QApplication.translate("MainWindow", "Выход", None, QtGui.QApplication.UnicodeUTF8)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
Python
# -*- coding: utf-8 -*- #! /usr/bin/env python from PySide import QtCore, QtGui, QtWebKit from PySide.QtCore import SIGNAL, QSettings, QSize, QPoint, QAbstractListModel, QModelIndex, Qt from PySide.QtWebKit import QWebSettings import logging, time, os from pprint import pprint from datetime import datetime from ui_auto import Ui_MainWindow from worker import QWorker, unescape from config import * from utils import * from fer_fetcher import Fer logger = logging.getLogger('fer_fetcher') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('fer_fetcher.log') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.ERROR) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) # t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle # f_id, f_title, f_answers, f_bluetime, f_lastauthor, f_threads, f_parentid # t_id, t_title, t_bluetime, t_open1, t_open2, t_answers, t_author, t_author_id, t_lastauthor, t_lastauthor_id, t_undertitle webSettings = QWebSettings.globalSettings() webSettings.setFontFamily(QWebSettings.FixedFont, FixedFont) webSettings.setFontFamily(QWebSettings.StandardFont, FixedFont) _initial_dict = {'item_id': 0, 'title': '', 'parent_id': 0, 'threads': 0, 'answers': 0, 'checked': 0, 'subscribed': 0, 'timestamp': 0, } class Item(object): #def __init__(self, item_id = 0, title = '', parent_id = 0, ): def __init__(self, _dict): self.__dict__.update(_initial_dict) self.__dict__.update(_dict) def __repr__(self): return u'<%s:%s>' % (self.item_id, self.parent_id) def __unicode__(self): return u'<%s:%s: %s>' % (self.item_id, self.parent_id, self.title) def _data(self): t = [(0, self.title)] if self.threads: t += (1, str(self.threads)), if self.answers: t += (2, str(self.answers)), if self.timestamp: t += (3, str(self.timestamp)), return t class CountDown(QtCore.QThread): def __init__(self, parent = None, interval = 0): QtCore.QThread.__init__(self, parent) self.interval = interval self.timer = QtCore.QTimer(self) self.connect(self.timer, SIGNAL("timeout()"), self.update) def run(self): self.timer.start(1000) def set_interval(self, interval): self.interval = self.i = interval self.emit(SIGNAL('update_countdown(int)'), self.i / 1000) def update(self): self.emit(SIGNAL('update_countdown(int)'), self.i / 1000) if self.i == 0: self.i = self.interval #self.timer.stop() self.i -= 1000 class TreeWidgetItem(QtGui.QTreeWidgetItem): def __init__(self, parent): QtGui.QTreeWidgetItem.__init__(self, parent) self.item_id = 0 self.parent_id = 0 class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent = None, menu = None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) if not menu: menu = QtGui.QMenu(parent) exitAction = menu.addAction("Exit") self.setContextMenu(menu) class Main(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) logger.info('creating an instance of QtGui.QMainWindow') self.ul_threads = {} self.open_threads = {} self.subscribe_widgets = {} self.forum = Fer() self.forum.authorize() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.centralwidget.setLayout(self.ui.gridLayout) self.ui.tab.setLayout(self.ui.gridLayout_7) self.ui.tab_2.setLayout(self.ui.gridLayout_2) self.radio_button_group = QtGui.QButtonGroup(self.ui.update_target) for i, button in enumerate((self.ui.get_all_rb, self.ui.get_selected_rb, self.ui.get_unselected_rb)): self.radio_button_group.addButton(button) self.radio_button_group.setId(button, i) self.radio_button_group.buttonClicked.connect(self.radio_activateInput) self.read_settings() self.create_context_menu() self.ui.check_on_startup_cb.stateChanged.connect(self.write_settings) self.ui.reload_interval_sb.valueChanged.connect(self.change_interval) self.ui.reload_posts_interval_sb.valueChanged.connect(self.change_posts_interval) self.ui.reload_interval_subscription_sb.valueChanged.connect(self.change_subscribed_update_interval) self.ui.hide_to_tray_cb.stateChanged.connect(self.write_settings) QtCore.QObject.connect(self.ui.tab_widget, SIGNAL('tabCloseRequested(int)'), self.close_tab) self.ui.subscribe_listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.ui.subscribe_listWidget.customContextMenuRequested.connect(self.subscribe_context_menu) self.ui.subscribe_listWidget.currentItemChanged.connect(self.view_subscribed_thread) self.ui.subscribe_listWidget11.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.ui.subscribe_listWidget11.customContextMenuRequested.connect(self.subscribe_context_menu) self.ui.tree_widget.customContextMenuRequested.connect(self.tree_context_menu) self.ui.tree_widget.setColumnWidth(0, 400) self.ui.tree_widget.resizeEvent = self.on_tree_resize self.ui.tree_widget.itemChanged.connect(self.on_tree_widget_item_changed) self.ui.tree_widget.doubleClicked.connect(self.open_thread) self.ui.get_forums_button.clicked.connect(self.update_threads) self.ui.get_posts_button.clicked.connect(self.update_posts) self.ui.update_subscribed_button.clicked.connect(self.update_subscribed) #self.connect(self.ui.pushButton_2, SIGNAL('clicked()'), self.open_thread) self.ui.action.triggered.connect(QtGui.qApp.quit) self.trayIcon = SystemTrayIcon(QtGui.QIcon("icon.ico"), self, self.ui.menu) self.trayIcon.show() self.trayIcon.activated.connect(self.__icon_activated) self.init_tree_widget() self.init_subscribe_widget() if RESTORE_OPENED_THREADS and self.open_threads_list: for thread_id in self.open_threads_list: self.open_thread(thread_id) if int(self.settings.value("MainWindow/check_on_startup_cb", 0)): self.update_threads() self.update_interval = int(self.settings.value("MainWindow/reload_interval_sb", 0)) self.forums_timer = QtCore.QTimer() self.forums_timer.timeout.connect(self.update_threads) self.lcd_timer = CountDown() self.ui.lcd_number_forums.connect(self.lcd_timer, SIGNAL('update_countdown(int)'), self.ui.lcd_number_forums, QtCore.SLOT('display(int)')) if self.update_interval: self.forums_timer.start(1000 * 60 * self.update_interval) self.lcd_timer.set_interval(1000 * 60 * self.update_interval) self.lcd_timer.start() self.update_interval = int(self.settings.value("MainWindow/reload_posts_interval_sb", 0)) self.posts_timer = QtCore.QTimer() self.posts_timer.timeout.connect(self.update_posts) self.lcd_posts_timer = CountDown() self.ui.lcd_number_posts.connect(self.lcd_posts_timer, SIGNAL('update_countdown(int)'), self.ui.lcd_number_posts, QtCore.SLOT('display(int)')) if self.update_interval: self.posts_timer.start(1000 * 60 * self.update_interval) self.lcd_posts_timer.set_interval(1000 * 60 * self.update_interval) self.lcd_posts_timer.start() self.update_interval = int(self.settings.value("MainWindow/reload_interval_subscription_sb", 0)) self.subscribed_timer = QtCore.QTimer() self.subscribed_timer.timeout.connect(self.update_subscribed) self.lcd_subscribed_timer = CountDown() self.ui.lcd_number_subscription.connect(self.lcd_subscribed_timer, SIGNAL('update_countdown(int)'), self.ui.lcd_number_subscription, QtCore.SLOT('display(int)')) if self.update_interval: self.subscribed_timer.start(1000 * 60 * self.update_interval) self.lcd_subscribed_timer.set_interval(1000 * 60 * self.update_interval) self.lcd_subscribed_timer.start() def radio_activateInput(self, button): self.update_target = self.radio_button_group.checkedId() self.settings.setValue("MainWindow/update_target", self.radio_button_group.checkedId()) def on_tree_resize(self, event): self.ui.tree_widget.setColumnWidth(0, self.ui.tree_widget.width() - 410) self.ui.tree_widget.setColumnWidth(1, 100) self.ui.tree_widget.setColumnWidth(2, 100) self.ui.tree_widget.setColumnWidth(3, 1) self.ui.tree_widget.setColumnWidth(4, 200) def close_tab(self, index): if index > 1: # let's leave main tabs # let's store thread_ids in tabs' ObjectNames del self.open_threads[int(self.ui.tab_widget.currentWidget().objectName())] self.ui.tab_widget.removeTab(index); def update_threads(self): if not self.ui.get_forums_button.isEnabled(): return logger.info('Updating threads...') self.ui.get_forums_button.setEnabled(0) self.forums_thread = QWorker(self) self.forums_thread.work('_update_threads') @QtCore.Slot(str) def on_finished(self, error): self.ui.get_forums_button.setEnabled(1) if error: logger.error(error) def on_tree_widget_item_changed(self, item, column): self._forum_cache[item.item_id].checked = checkstate_to_int(item.checkState(0)) # TODO move color settings to config if self._forum_cache[item.item_id].subscribed: item.setBackground(0, QtGui.QColor(138, 43, 226)) elif checkstate_to_int(item.checkState(0)): item.setBackground(0, QtGui.QColor(152, 251, 152)) else: item.setBackground(0, QtGui.QColor(255, 255, 255)) @QtCore.Slot(int, int, tuple, int) def add_tree_item(self, parent_id, item_id, item_data, level = 0): #pprint(self.ul_threads) if parent_id: parent = self.ul_threads[parent_id] else: parent = self.ui.tree_widget self.ui.tree_widget.itemChanged.disconnect(self.on_tree_widget_item_changed) if self.ul_threads.has_key(item_id): item = self.ul_threads[item_id] else: item = TreeWidgetItem(parent) item.item_id = item_id item.parent_id = parent_id threads = 0 answers = 0 timestamp = 0 for column, value in item_data: item.setText(column, value) if column == 0: title = value elif column == 1: threads = value elif column == 2: answers = value elif column == 3: timestamp = value item.setText(4, datetime.fromtimestamp(int(timestamp)).strftime(DATE_TIME_FORMAT)) checked = Qt.CheckState.Unchecked if self._forum_cache.has_key(item_id): checked = self._forum_cache[item_id].checked elif self._forum_cache.has_key(parent_id): checked = self._forum_cache[parent_id].checked item.setCheckState(0, int_to_checkstate(checked)) # TODO move color settings to config if checked: item.setBackground(0, QtGui.QColor(152, 251, 152)) subscribed = 0 if self._forum_cache.has_key(item_id): subscribed = self._forum_cache[item_id].subscribed if subscribed: item.setBackground(0, QtGui.QColor(138, 43, 226)) self.ul_threads[item_id] = item #if item_id not in self._forum_cache.keys(): cache_item = Item({'item_id': item_id, 'title': title, 'parent_id': parent_id, 'threads': threads, 'answers': answers, 'checked': checkstate_to_int(checked), 'subscribed': subscribed, 'level': level, 'timestamp': timestamp, 'date': datetime.fromtimestamp(int(timestamp)).strftime(DATE_TIME_FORMAT), }) self._forum_cache[item_id] = cache_item self.ui.tree_widget.itemChanged.connect(self.on_tree_widget_item_changed) self.ui.tree_widget.sortItems(3, QtCore.Qt.SortOrder.DescendingOrder) @QtCore.Slot(int) def update_progress_bar(self, progress): self.ui.progressBar.setValue(progress) self.ui.progressBar.repaint() @QtCore.Slot(tuple) def update_status_bar(self, message): self.ui.statusbar.showMessage(message[0]) self.ui.statusbar.repaint() def create_context_menu(self): self.popMenu = QtGui.QMenu(self) self.popMenu.addAction(u'Открыть', self.open_thread) self.popMenu.addSeparator() self.popMenu.addAction(u'Подписаться', self.subscribe) self.popMenu.addAction(u'Отписаться', self.unsubscribe) #self.popMenu.addSeparator() #self.popMenu.addAction(QtGui.QAction('something', self)) self.posts_popMenu = QtGui.QMenu(self) self.posts_popMenu.addAction(u'Игнорировать', self.ignore) self.subscribe_popMenu = QtGui.QMenu(self) self.subscribe_popMenu.addAction(u'Отписаться', self.unsubscribe1) def subscribe_context_menu(self, point): item = self.ui.subscribe_listWidget.itemAt(point) if item: self.subscribe_popMenu.exec_(self.ui.subscribe_listWidget.mapToGlobal(point)) def tree_context_menu(self, point): item = self.ui.tree_widget.itemAt(point) if item and not item.childCount(): self.popMenu.exec_(self.ui.tree_widget.mapToGlobal(point)) def posts_list_context_menu(self, point): thread_id = int(self.ui.tab_widget.currentWidget().objectName()) list_widget = self.open_threads[thread_id][0] item = list_widget.itemAt(point) if item: self.posts_popMenu.exec_(list_widget.mapToGlobal(point)) def ignore(self): thread_id = int(self.ui.tab_widget.currentWidget().objectName()) list_widget = self.open_threads[thread_id][0] user_id = list_widget.currentItem().user_id self.ignore_list.append(user_id) rows = range(list_widget.count()) rows.reverse() for row in rows: item = list_widget.item(row) if item and item.user_id == user_id: list_widget.takeItem(row) def open_thread(self, thread_id = 0): if not thread_id in self._forum_cache.keys(): thread_id = self.ui.tree_widget.currentItem().item_id if self._forum_cache[thread_id].level != THREAD: return posts_list, t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle = self.forum.get_posts_list(thread_id) t_title = unicode(unescape(t_title), FORUM_ENCODING) t_undertitle = unicode(unescape(t_undertitle), FORUM_ENCODING) tab = QtGui.QWidget() # let's store thread_ids in tabs' ObjectNames tab.setObjectName("%s" % thread_id) grid_layout_widget = QtGui.QWidget(tab) layout = QtGui.QGridLayout(grid_layout_widget) layout.setColumnStretch(1, 10) label = QtGui.QLabel() label.setText("%s %s" % (t_title, t_undertitle)) layout.addWidget(label, 0, 0, 1, 2) listWidget = QtGui.QListWidget() listWidget.currentItemChanged.connect(self.view_post) for post in posts_list: if len(post) == 4: post_id, user, user_id, timestamp = post else: post_id, user, user_id, timestamp, avatar_url = post if user_id in self.ignore_list: continue item = QtGui.QListWidgetItem(unicode(user, FORUM_ENCODING)) item.id = post_id item.thread_id = thread_id item.user_id = user_id listWidget.addItem(item) layout.addWidget(listWidget, 1, 0, 3, 1) view = QtWebKit.QWebView() path = os.getcwd() view.settings().setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile(path + "/css_2.css")) self.open_threads[thread_id] = (listWidget, view) layout.addWidget(view, 1, 1, 1, 1) textEdit = QtGui.QTextEdit(grid_layout_widget) layout.addWidget(textEdit, 2, 1, 1, 1) post_button = QtGui.QPushButton(u"Отправить") layout.addWidget(post_button, 3, 1, 1, 1) tab.setLayout(layout) listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) listWidget.customContextMenuRequested.connect(self.posts_list_context_menu) listWidget.setCurrentItem(item) index = self.ui.tab_widget.addTab(tab, t_title) self.ui.tab_widget.setCurrentIndex(index) def view_post(self, current, previous): post_id = current.id thread_id = current.thread_id listWidget, view = self.open_threads[thread_id] post = self.forum.get_posts(post_id)[0] HTML = unicode(post.post_text, FORUM_ENCODING) attach = '' if post.attach: attach = "%suploads/%s" % (SITE_URL, post.attach) HTML = """%s<br><img src="%s"><br><br><a href="%st/%s/p/%s" target="_blank">post's URL</a> %s""" %\ (HTML, attach, SITE_URL, thread_id, post_id, datetime.fromtimestamp(int(post.timestamp)).strftime(DATE_TIME_FORMAT)) view.setTextSizeMultiplier(HTML_ZOOM_FACTOR) view.setHtml(HTML) def view_subscribed_post(self, current, previous): post_id = current.id thread_id = current.thread_id post = self.forum.get_posts(post_id)[0] HTML = unicode(post.post_text, FORUM_ENCODING) attach = '' if post.attach: attach = """<img src="%suploads/%s">""" % (SITE_URL, post.attach) HTML = """%s<br>%s<br><br><a href="%st/%s/p/%s" target="_blank">URL</a> %s""" %\ (HTML, attach, SITE_URL, thread_id, post_id, datetime.fromtimestamp(int(post.timestamp)).strftime(DATE_TIME_FORMAT)) self.ui.subscribed_view.setTextSizeMultiplier(HTML_ZOOM_FACTOR) self.ui.subscribed_view.setHtml(HTML) def view_subscribed_thread(self, current, previous): self.ui.subscribe_listWidget11.currentItemChanged.connect(self.view_subscribed_post) self.ui.subscribe_listWidget11.currentItemChanged.disconnect(self.view_subscribed_post) self.ui.subscribe_listWidget11.set_items(self._subscribe_cache[current.item_id][2]) self.ui.subscribe_listWidget11.currentItemChanged.connect(self.view_subscribed_post) def update_subscribed(self): for item_id, v in self._subscribe_cache.items(): posts_list, t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle = self.forum.get_posts_list(item_id) text, last_post_id, posts = v for post in posts_list: post_id = post[0] user = post[1] user_id = post[2] if user_id in self.ignore_list: continue # TODO no need to process the whole list if post_id > last_post_id: item = Item({'item_id': post_id, 'title': unicode(user, FORUM_ENCODING), 'parent_id': item_id, }) posts.append(item) self._subscribe_cache[item_id] = [text, post_id, posts] def update_posts(self): for thread_id, value in self.open_threads.items(): listWidget, web_view = value listWidget.currentItemChanged.disconnect(self.view_post) posts_list, t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle = self.forum.get_posts_list(thread_id) last_post_id = listWidget.item(listWidget.count() - 1).id for post in posts_list: post_id = post[0] user = post[1] user_id = post[2] if user_id in self.ignore_list: continue # TODO no need to process the whole list if post_id > last_post_id: item = QtGui.QListWidgetItem(unicode(user, FORUM_ENCODING)) item.id = post_id item.thread_id = thread_id listWidget.addItem(item) listWidget.currentItemChanged.connect(self.view_post) def subscribe(self): item_id = self.ui.tree_widget.currentItem().item_id if self._subscribe_cache.has_key(item_id): return self._forum_cache[item_id].subscribed = 1 item = self.ul_threads[item_id] item.setBackground(0, QtGui.QColor(138, 43, 226)) subscribe_item = QtGui.QListWidgetItem(item.text(0)) subscribe_item.item_id = item_id self.ui.subscribe_listWidget.addItem(subscribe_item) self._subscribe_cache[item_id] = (item.text(0), 0, []) def unsubscribe(self): item_id = self.ui.tree_widget.currentItem().item_id if not self._subscribe_cache.has_key(item_id): return self._forum_cache[item_id].subscribed = 0 item = self.ul_threads[item_id] item.setBackground(0, QtGui.QColor(255, 255, 255)) for item in self.ui.subscribe_listWidget.findItems(self._subscribe_cache[item_id][0], QtCore.Qt.MatchWildcard): self.ui.subscribe_listWidget.takeItem(self.ui.subscribe_listWidget.row(item)) del self._subscribe_cache[item_id] def unsubscribe1(self): item_id = self.ui.subscribe_listWidget.currentItem().item_id if not self._subscribe_cache.has_key(item_id): return self._forum_cache[item_id].subscribed = 0 item = self.ul_threads[item_id] item.setBackground(0, QtGui.QColor(255, 255, 255)) for item in self.ui.subscribe_listWidget.findItems(self._subscribe_cache[item_id][0], QtCore.Qt.MatchWildcard): self.ui.subscribe_listWidget.takeItem(self.ui.subscribe_listWidget.row(item)) del self._subscribe_cache[item_id] def keyPressEvent(self, e): if e.key() == QtCore.Qt.Key_Escape: self.hide() def closeEvent(self, event): if self.ui.hide_to_tray_cb.checkState(): self.write_settings() event.ignore() self.hide() else: quit_msg = "Are you sure you want to exit the program?" reply = QtGui.QMessageBox.question(self, 'Message', quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.write_settings() event.accept() else: event.ignore() def change_interval(self): self.update_interval = self.ui.reload_interval_sb.value() * 1000 * 60 self.forums_timer.stop() self.lcd_timer.timer.stop() self.lcd_timer.set_interval(self.update_interval) if self.update_interval: self.forums_timer.setInterval(self.update_interval) self.forums_timer.start() self.lcd_timer.timer.start(1000) self.settings.setValue("MainWindow/reload_interval_sb", self.ui.reload_interval_sb.value()) def change_posts_interval(self): self.update_interval = self.ui.reload_posts_interval_sb.value() * 1000 * 60 self.posts_timer.stop() self.lcd_posts_timer.timer.stop() self.lcd_posts_timer.set_interval(self.update_interval) if self.update_interval: self.posts_timer.setInterval(self.update_interval) self.posts_timer.start() self.lcd_posts_timer.timer.start(1000) self.settings.setValue("MainWindow/reload_posts_interval_sb", self.ui.reload_posts_interval_sb.value()) def change_subscribed_update_interval(self): self.update_interval = self.ui.reload_interval_subscription_sb.value() * 1000 * 60 self.subscribed_timer.stop() self.lcd_subscribed_timer.timer.stop() self.lcd_subscribed_timer.set_interval(self.update_interval) if self.update_interval: self.subscribed_timer.setInterval(self.update_interval) self.subscribed_timer.start() self.lcd_subscribed_timer.timer.start(1000) self.settings.setValue("MainWindow/reload_interval_subscription_sb", self.ui.reload_interval_subscription_sb.value()) def init_subscribe_widget(self): for item_id, v in self._subscribe_cache.items(): text, last_post_id, posts = v subscribe_item = QtGui.QListWidgetItem(text) subscribe_item.item_id = item_id self.ui.subscribe_listWidget.addItem(subscribe_item) def init_tree_widget(self): self.ui.tree_widget.setColumnCount(5) self.ui.tree_widget.setHeaderLabels([u'Форумы', u'Тем', u'Постов', u'', u'Дата']) #pprint(self._forum_cache) for level in range(4): for key, value in self._forum_cache.iteritems(): if value.level == level: self.add_tree_item(value.parent_id, key, value._data(), level) def write_settings(self): logger.info('Writting settings') self.settings = QSettings(AUTHOR, APP_NAME) #self.settings = QSettings("settings.ini", QSettings.IniFormat) self.settings.beginGroup("MainWindow") self.settings.setValue("size", self.size()) self.settings.setValue("pos", self.pos()) self.settings.setValue("check_on_startup_cb", self.ui.check_on_startup_cb.checkState()) self.settings.setValue("hide_to_tray_cb", self.ui.hide_to_tray_cb.checkState()) self.settings.setValue("reload_interval_sb", self.ui.reload_interval_sb.value()) self.settings.setValue("reload_posts_interval_sb", self.ui.reload_posts_interval_sb.value()) self.settings.setValue("reload_interval_subscription_sb", self.ui.reload_interval_subscription_sb.value()) self.settings.setValue("update_target", self.radio_button_group.checkedId()) self.settings.endGroup() self.settings.setValue("_timestamp", self._bluetime) self.settings.setValue("_forum_cache", self._forum_cache) self.settings.setValue("_subscribe_cache", self._subscribe_cache) self.settings.setValue("_open_threads_list", self.open_threads.keys()) self.settings.setValue("_ignore_list", self.ignore_list) def read_settings(self): self.settings = QSettings(AUTHOR, APP_NAME) #self.settings = QSettings("settings.ini", QSettings.IniFormat) self.settings.beginGroup("MainWindow") self.resize(self.settings.value("size", QSize(800, 600))) self.move(self.settings.value("pos", QPoint(200, 200))) self.ui.check_on_startup_cb.setCheckState(int_to_checkstate(self.settings.value("check_on_startup_cb", 0))) self.ui.hide_to_tray_cb.setCheckState(int_to_checkstate(self.settings.value("hide_to_tray_cb", 0))) self.ui.reload_interval_sb.setValue(int(self.settings.value("reload_interval_sb", 0))) self.ui.reload_posts_interval_sb.setValue(int(self.settings.value("reload_posts_interval_sb", 0))) self.ui.reload_interval_subscription_sb.setValue(int(self.settings.value("reload_interval_subscription_sb", 0))) self._update_target = int(self.settings.value("update_target", 0)) self.radio_button_group.button(self._update_target).setChecked(1) self.settings.endGroup() self._bluetime = self.settings.value("_timestamp", 0) self._forum_cache = self.settings.value("_forum_cache", {}) self._subscribe_cache = self.settings.value("_subscribe_cache", {}) self.open_threads_list = self.settings.value("_open_threads_list", []) self.ignore_list = self.settings.value("_ignore_list", []) if not self.ignore_list: self.ignore_list = [0] #pprint(self._forum_cache) if not self._forum_cache: self._forum_cache = {} for item_id, title in UL_THREADS.iteritems(): item = Item({'title': title, 'item_id': item_id, 'level': TOP_LEVEL}) self._forum_cache[item_id] = item def __icon_activated(self, reason): if reason == QtGui.QSystemTrayIcon.Trigger: if self.isActiveWindow(): self.hide() else: self.show() if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = Main() MainWindow.show() sys.exit(app.exec_())
Python
# -*- coding: utf-8 -*- #! /usr/bin/env python import sys, re, os import urllib2, urllib, cookielib import logging import xml.etree.ElementTree as ET from config import * from utils import * logger = logging.getLogger('fer_fetcher') #Post: post_id, thread_title, author, author_id, timestamp, forum_id, thread_id, unknown, thread_undertitle _initial_dict = {'post_id': 0, 'post_text': '', 'thread_title': '', 'thread_undertitle': '', 'author': '', 'attach': '', 'author_id': 0, 'forum_id': 0, 'thread_id': 0, 'timestamp': 0, } class Post(object): def __init__(self, _dict): self.__dict__.update(_initial_dict) for k in _initial_dict.keys(): self.__dict__[k] = _dict[k] def __repr__(self): return u'<%s:%s>' % (self.post_id, self.timestamp) def __unicode__(self): return u'<%s:%s: %s>' % (self.post_id, self.author, self.post_text) class Fer(): def __init__(self): #if not os.path.exists(MAILDIR): os.mkdir(MAILDIR) self.data = urllib.urlencode(LOGIN_VALUES) self.cookies = cookielib.CookieJar() self.opener = urllib2.build_opener( urllib2.HTTPRedirectHandler(), urllib2.HTTPHandler(debuglevel=0), urllib2.HTTPSHandler(debuglevel=0), urllib2.HTTPCookieProcessor(self.cookies)) def authorize(self): logger.info('Authorization start') response = self.opener.open(LOGIN_URL, self.data) the_page = response.read() http_headers = response.info() logger.info('Authorization done') def get_forums_list(self): logger.info('Get forums ...') forums_list = [] response = self.opener.open(FORUMLIST_URL) data = response.read() # TODO: make xml parser, add error handler r = re.compile('<plist>(.*)</plist>') try: # TODO: make error catching for line in r.findall(data)[0].split('<|> <br>'): if line: forums_list.append(line.split('<|>')) #if line: print unicode(unescape(line), FORUM_ENCODING) r = re.compile('<bluetime>(.*)</bluetime>') bluetime = r.findall(data)[0] logger.info('Get forums done') except: return [] if READ_PJ: forums_list.append(['164', u'ПЖ 2.0'.encode(FORUM_ENCODING), '0', bluetime, 'xxx', '0', '36']) return forums_list def get_threads_list(self, forum_id): logger.info('Get threads , forum_id = %s...' % forum_id) threads_list = [] response = self.opener.open(THREADLIST_URL % forum_id) data = response.read() # TODO: make xml parser, add error handler r = re.compile('<plist>(.*)</plist>') if 'error' in data: return [] for line in r.findall(data)[0].split('<br>'): if line: threads_list.append(line.split('<|>')) r = re.compile('<bluetime>(.*)</bluetime>') bluetime = r.findall(data) logger.info('Get threads done') return threads_list def get_posts_list(self, thread_id): logger.info('Get posts , thread_id = %s...' % thread_id) posts_list = [] response = self.opener.open(POSTLIST_URL % thread_id) data = response.read() # TODO: make xml parser, add error handler r = re.compile('<pinfo>(.*)</pinfo>', flags = re.S) #print POSTLIST_URL % thread_id #print data t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle = r.findall(data)[0].split('<|>') r = re.compile('<plist>(.*)</plist>') for line in r.findall(data)[0].split('<br>'): if line: posts_list.append(line.split('<|>')) r = re.compile('<bluetime>(.*)</bluetime>') bluetime = r.findall(data) logger.info('Get posts done') return posts_list, t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle def get_posts(self, post_id, backlimit = 1): logger.info('Get posts, start post_id = %s...' % post_id) posts_list = [] response = self.opener.open(POSTS_URL % (post_id, backlimit)) data = response.read() # TODO: make xml parser, add error handler #print POSTS_URL % (post_id, backlimit) #print data r = re.compile('<xpost>(.*?)</xpost>', flags = re.S) for line in r.findall(data): r1 = re.compile('<hdr>(.*)</hdr>', flags = re.S) r2 = re.compile('<posttext>(.*)</posttext>', flags = re.S) r3 = re.compile('<attach>(.*)</attach>', flags = re.S) post_id, thread_title, author, author_id, timestamp, forum_id, thread_id, unknown, thread_undertitle = r1.findall(line)[0].split('<|>') post_text = r2.findall(line)[0] if r3.findall(line): attach = r3.findall(line)[0] post = Post(locals()) posts_list.append(post) logger.info('Get posts done') return posts_list if __name__ == "__main__": forum = Fer() forum.authorize() #print forum.get_forums_list() #print forum.get_threads_list('164') #print forum.get_posts_list('190953') print forum.get_posts('32194446', 1) for id, f_title in UL_THREADS.iteritems(): if id !=36: continue f_data = ((0, f_title), ) forums = forum.get_forums_list() for f in forums: f_id, f_title, f_answers, f_bluetime, f_lastauthor, f_threads, f_parentid = f #print '---', unicode(unescape(f_title), FORUM_ENCODING) f_id = int(f_id) f_parentid = int(f_parentid) f_title = unicode(unescape(f_title), FORUM_ENCODING) if f_id not in (42, 91): continue for t in forum.get_threads_list(f_id): t_id, t_title, t_bluetime, t_open1, t_open2, t_answers, t_author, t_author_id, t_lastauthor, t_lastauthor_id, t_undertitle = t t_id = int(t_id) t_title = unicode(unescape(t_title), FORUM_ENCODING) #if t_id in disabled_ids: continue if t_undertitle: t_title+= "(%s)" % unicode(unescape(t_undertitle), FORUM_ENCODING) #print t_title
Python
# -*- coding: utf-8 -*- ### Access information USERNAME = '' PASSWORD = '' AUYH_KEY = '' #SITE_URL='http://forum.exler.ru/' SITE_URL='http://club443.ru/' FORUMLIST_URL= SITE_URL + 'ib_client/cltp2z01.php?forumlist=1' THREADLIST_URL= SITE_URL + 'ib_client/cltp2z01.php?forum=%s&tlimit=100' POSTLIST_URL= SITE_URL + 'ib_client/cltp2z01.php?thread=%s&llimit=65530' POSTS_URL= SITE_URL + 'ib_client/cltp6z02.php?mpost=%s&backlimit=%d' LOGIN_URL = SITE_URL + 'index.php?act=Login&CODE=01' LOGOUT_URL = SITE_URL + 'index.php?act=Login&CODE=03' FINDUSER_URL= SITE_URL + 'ib_client/cltp3z01.php?pa=finduser&user=%s' MAILDIR = 'FER_MAILDIR' DATABASE = 'db/fer.db' FORUM_CACHE = 'db/_forum_cache.db' # Form fields (maybe not needed) USERNAME_FIELD = 'UserName' PASS_FIELD = 'PassWord' COOKIEDATE = 1 LOGIN_VALUES = {USERNAME_FIELD : USERNAME, PASS_FIELD : PASSWORD, 'CookieDate': COOKIEDATE} FORUM_ENCODING = 'cp1251' AUTHOR = 'fvk' APP_NAME = 'FER Fetcher' # TODO: get upperlevel forums from ib api UL_THREADS = {59: u'Форумная болтология', 36: u'Обсуждения', 67: u'Кино, ТВ, видео', 60: u'Культура и искусство', 64: u'Взаимоотношения, семья и дом', 65: u'Компьютеры и цифровая техника', 24: u'Сайт и форум Exler.ru', 61: u'I don\'t know'} READ_PJ = True RESTORE_OPENED_THREADS = True TOP_LEVEL, FORUM, THREAD, POST = range(4) UPDATE_ALL, UPDATE_SELECTED, UPDATE_UNSELECTED = range(3) CHECKED_ITEM_BGCOLOR = 152, 251, 152 DATE_TIME_FORMAT = "%Y-%m-%d %H:%M" HTML_ZOOM_FACTOR = 1.5 FixedFont = 'monospace' StandardFont = 'Arial'
Python
# -*- coding: utf-8 -*- #! /usr/bin/env python from PySide import QtCore, QtGui class ListWidget(QtGui.QListWidget): def __init__(self, parent): super(ListWidget, self).__init__(parent) def set_items(self, items): if self.count(): for i in range(self.count()): self.takeItem(i) for i in items: item = QtGui.QListWidgetItem(i.title) item.id = i.item_id item.thread_id = i.parent_id self.addItem(item) if items: self.setCurrentItem(item) def keyPressEvent(self, event): super(ListWidget, self).keyPressEvent(event) if event.key() == QtCore.Qt.Key_Delete: self._del_item() def _del_item(self): for item in self.selectedItems(): self.takeItem(self.row(item))
Python
# Para hacer el ejecutable: # python setup.py py2exe # "Creador de instalador para PyAfipWs" __author__ = "Mariano Reingart (mariano@nsis.com.ar)" __copyright__ = "Copyright (C) 2008 Mariano Reingart" from distutils.core import setup import py2exe import sys # includes for py2exe includes=['email.generator', 'email.iterators', 'email.message', 'email.utils'] opts = { 'py2exe': { 'includes':includes, 'optimize':2} } setup( name = "PyAfipWs", com_server = ["pyafipws"], console=['rece.py', 'receb.py', 'recex.py', 'rg1361.py', 'wsaa.py', 'wsfex.py', 'wsbfe.py'], options=opts, )
Python
{'application':{'type':'Application', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'bgTemplate', 'title':u'Aplicativo Factura Electr\xf3nica (PyRece)', 'size':(592, 487), 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', 'name':'menuConsultas', 'label':u'Consultas', 'items': [ {'type':'MenuItem', 'name':'menuConsultasLastCBTE', 'label':u'\xdalt. Cbte.', }, {'type':'MenuItem', 'name':'menuConsultasLastID', 'label':u'\xdalt. ID', }, {'type':'MenuItem', 'name':'menuConsultasGetCAE', 'label':u'Recuperar CAE', }, ] }, {'type':'Menu', 'name':'menuAyuda', 'label':u'Ayuda', 'items': [ {'type':'MenuItem', 'name':'menuAyudaInstructivo', 'label':u'Instructivo', }, {'type':'MenuItem', 'name':'menuAyudaAcercaDe', 'label':u'Acerca de', }, {'type':'MenuItem', 'name':'menuAyudaLimpiar', 'label':u'Limpiar estado', }, ] }, ] }, 'components': [ {'type':'StaticText', 'name':'lblWebservice', 'position':(18, 10), 'text':u'Webservice:', }, {'type':'Choice', 'name':'cboWebservice', 'position':(82, 5), 'size':(69, -1), 'items':[u'wsfe', u'wsfev1', u'wsfex'], }, {'type':'Button', 'name':'btnGrabar', 'position':(504, 4), 'size':(60, -1), 'label':u'Grabar', }, {'type':'Button', 'name':'btnMarcarTodo', 'position':(292, 163), 'label':u'Marcar Todo', 'toolTip':u'Seleccionar todas las facturas', }, {'type':'Button', 'name':'btnAutorizarLote', 'position':(188, 163), 'label':u'Autorizar Lote', 'toolTip':u'Obtener CAE para todas las facturas', }, {'type':'Button', 'name':'btnPrevisualizar', 'position':(395, 163), 'label':u'Previsualizar', }, {'type':'Button', 'name':'btnAutenticar', 'position':(20, 163), 'label':u'Autenticar', 'toolTip':u'Iniciar Sesin en la AFIP', }, {'type':'TextArea', 'name':'txtEstado', 'position':(20, 243), 'size':(534, 212), 'font':{'faceName': u'Sans', 'family': 'sansSerif', 'size': 8}, 'text':u'\n', }, {'type':'StaticText', 'name':'lblProgreso', 'position':(20, 194), 'text':u'Progreso:', }, {'type':'StaticText', 'name':'lblEstado', 'position':(22, 219), 'text':u'Estado:', }, {'type':'Button', 'name':'btnEnviar', 'position':(490, 163), 'size':(60, -1), 'label':u'Enviar', 'toolTip':u'Generar y enviar mails', }, {'type':'Button', 'name':'btnExaminar', 'position':(370, 4), 'size':(69, -1), 'label':u'Examinar', }, {'type':'TextField', 'name':'txtArchivo', 'position':(197, 5), 'size':(167, -1), 'text':u'facturas.csv', }, {'type':'StaticText', 'name':'lblArchivo', 'position':(155, 10), 'text':u'Archivo:', }, {'type':'Button', 'name':'btnCargar', 'position':(443, 4), 'size':(60, -1), 'label':u'Cargar', }, {'type':'Button', 'name':'btnAutorizar', 'position':(104, 163), 'label':u'Autorizar', 'toolTip':u'Obtener CAE por cada factura', }, {'type':'MultiColumnList', 'name':'lvwListado', 'position':(18, 53), 'size':(537, 106), 'backgroundColor':(255, 255, 255, 255), 'columnHeadings':[], 'font':{'faceName': u'Tahoma', 'family': 'sansSerif', 'size': 8}, 'items':[], 'maxColumns':1000, 'rules':1, }, {'type':'StaticText', 'name':'lblFacturas', 'position':(18, 35), 'size':(117, -1), 'text':u'Facturas:', }, {'type':'Gauge', 'name':'pbProgreso', 'position':(89, 195), 'size':(477, 16), 'backgroundColor':(209, 194, 182, 255), 'layout':'horizontal', 'max':100, 'value':0, }, ] # end components } # end background ] # end backgrounds } }
Python
import wsaa import os,sys from subprocess import Popen, PIPE from base64 import b64encode def sign_tra(tra,cert,privatekey): "Firmar PKCS#7 el TRA y devolver CMS (recortando los headers SMIME)" # Firmar el texto (tra) out = Popen(["openssl", "smime", "-sign", "-signer", cert, "-inkey", privatekey, "-outform","DER", "-out", "cms.bin" , "-nodetach"], stdin=PIPE,stdout=PIPE).communicate(tra)[0] out = open("cms.bin","rb").read() return b64encode(out) tra = wsaa.create_tra("wsfex") print tra cms = sign_tra(tra,"reingart.crt","reingart.key") print cms open("tra.cms","w").write(cms) ta = wsaa.call_wsaa(cms) print ta open("TA.xml","w").write(ta)
Python
#!/usr/bin/python # -*- coding: latin-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 3, 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 MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. "Manejo de XML simple" __author__ = "Mariano Reingart (mariano@nsis.com.ar)" __copyright__ = "Copyright (C) 2008/009 Mariano Reingart" __license__ = "LGPL 3.0" __version__ = "1.0" import xml.dom.minidom DEBUG = False class SimpleXMLElement(object): "Clase para Manejo simple de XMLs (simil PHP)" def __init__(self, text = None, elements = None, document = None, namespace = None, prefix=None): self.__ns = namespace self.__prefix = prefix if text: try: self.__document = xml.dom.minidom.parseString(text) except: if DEBUG: print text raise self.__elements = [self.__document.documentElement] else: self.__elements = elements self.__document = document def addChild(self,tag,text=None,ns=True): if not ns or not self.__ns: if DEBUG: print "adding %s ns %s %s" % (tag, self.__ns,ns) element = self.__document.createElement(tag) else: if DEBUG: print "adding %s ns %s %s" % (tag, self.__ns,ns) element = self.__document.createElementNS(self.__ns, "%s:%s" % (self.__prefix, tag)) if text: if isinstance(text, unicode): element.appendChild(self.__document.createTextNode(text)) else: element.appendChild(self.__document.createTextNode(str(text))) self.__element.appendChild(element) return SimpleXMLElement( elements=[element], document=self.__document, namespace=self.__ns, prefix=self.__prefix) def asXML(self,filename=None): return self.__document.toxml('UTF-8') def __getattr__(self,tag): try: if self.__ns: if DEBUG: print "searching %s by ns=%s" % (tag,self.__ns) elements = self.__elements[0].getElementsByTagNameNS(self.__ns, tag) if not self.__ns or not elements: if DEBUG: print "searching %s " % (tag) elements = self.__elements[0].getElementsByTagName(tag) if not elements: if DEBUG: print self.__elements[0].toxml() raise AttributeError("Sin elementos") return SimpleXMLElement( elements=elements, document=self.__document, namespace=self.__ns, prefix=self.__prefix) except AttributeError, e: raise AttributeError("Tag not found: %s (%s)" % (tag, str(e))) def __iter__(self): "Iterate over xml tags" try: for __element in self.__elements: yield SimpleXMLElement( elements=[__element], document=self.__document, namespace=self.__ns, prefix=self.__prefix) except: raise def __getitem__(self,item): "Return xml attribute" return getattr(self.__element, item) def __contains__( self, item): return self.__element.getElementsByTagName(item) def __unicode__(self): return self.__element.childNodes[0].data def __str__(self): if self.__element.childNodes: rc = "" for node in self.__element.childNodes: if node.nodeType == node.TEXT_NODE: rc = rc + node.data.encode("utf8","ignore") return rc return '' def __repr__(self): return repr(self.__str__()) def __int__(self): return int(self.__str__()) def __float__(self): try: return float(self.__str__()) except: raise IndexError(self.__element.toxml()) __element = property(lambda self: self.__elements[0]) if __name__ == "__main__": span = SimpleXMLElement('<span><a href="google.com">google</a><prueba><i>1</i><float>1.5</float></prueba></span>') print str(span.a) print int(span.prueba.i) print float(span.prueba.float) span = SimpleXMLElement('<span><a href="google.com">google</a><a>yahoo</a><a>hotmail</a></span>') for a in span.a: print str(a) span.addChild('a','altavista') print span.asXML()
Python
# Para hacer el ejecutable: # python setup.py py2exe # """ __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2005/04/05 18:44:54 $" """ __author__ = "Mariano Reingart (mariano@nsis.com.ar)" __copyright__ = "Copyright (C) 2008 Mariano Reingart" from distutils.core import setup import py2exe import sys if sys.platform == 'darwin': import py2app buildstyle = 'app' else: import py2exe buildstyle = 'windows' # find pythoncard resources, to add as 'data_files' import os pycard_resources=[] for filename in os.listdir('.'): if filename.find('.rsrc.')>-1: pycard_resources+=[filename] # includes for py2exe includes=[] for comp in ['button','image','staticbox','radiogroup', 'imagebutton', 'statictext','textarea','textfield','passwordfield', 'checkbox', 'tree','multicolumnlist','list','gauge','choice', ]: includes += ['PythonCard.components.'+comp] print 'includes',includes includes+=['email.generator', 'email.iterators', 'email.message', 'email.utils'] opts = { 'py2exe': { 'includes':includes, 'optimize':2} } setup( name = "PyRece", data_files = [ (".", pycard_resources), (".",["logo.png",]) ], options=opts, **{buildstyle: ["pyrece.py"], 'console': [{"script": "pyrece.py", "dest_base": "pyrece_consola"}] } )
Python
#!/usr/bin/python # -*- coding: latin-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 3, 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 MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. "Py2Exe extension to build NSIS Installers" # Based on py2exe/samples/extending/setup.py: # "A setup script showing how to extend py2exe." # Copyright (c) 2000-2008 Thomas Heller, Mark Hammond, Jimmy Retzlaff __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2011 Mariano Reingart" __license__ = "GPL 3.0" import os import sys from py2exe.build_exe import py2exe nsi_base_script = """\ ; base.nsi ; WARNING: This script has been created by py2exe. Changes to this script ; will be overwritten the next time py2exe is run! XPStyle on Page license Page directory ;Page components Page instfiles RequestExecutionLevel admin LoadLanguageFile "${NSISDIR}\Contrib\Language files\English.nlf" LoadLanguageFile "${NSISDIR}\Contrib\Language files\Spanish.nlf" # set license page LicenseText "" LicenseData "licencia.txt" LicenseForceSelection checkbox ; use the default string for the directory page. DirText "" Name "%(description)s" OutFile "%(out_file)s" ;SetCompress off ; disable compression (testing) SetCompressor /SOLID lzma ;InstallDir %(install_dir)s InstallDir $PROGRAMFILES\%(install_dir)s InstallDirRegKey HKLM "Software\%(reg_key)s" "Install_Dir" Section %(name)s ; uninstall old version ReadRegStr $R0 HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s" "UninstallString" StrCmp $R0 "" notistalled ExecWait '$R0 /S _?=$INSTDIR' notistalled: SectionIn RO SetOutPath $INSTDIR File /r dist\*.* WriteRegStr HKLM SOFTWARE\%(reg_key)s "Install_Dir" "$INSTDIR" ; Write the uninstall keys for Windows WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s" "DisplayName" "%(description)s (solo eliminar)" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s" "UninstallString" "$INSTDIR\Uninst.exe" WriteUninstaller "Uninst.exe" ;To Register a DLL RegDLL "$INSTDIR\%(com_server)s" SectionEnd Section "Uninstall" ;To Unregister a DLL UnRegDLL "$INSTDIR\%(com_server)s" ;Delete Files ;Delete Uninstaller And Unistall Registry Entries Delete "$INSTDIR\Uninst.exe" DeleteRegKey HKEY_LOCAL_MACHINE "SOFTWARE\%(reg_key)s" DeleteRegKey HKEY_LOCAL_MACHINE "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\%(reg_key)s" RMDir "$INSTDIR" SectionEnd ;-------------------------------- Function .onInit ;Language selection dialog Push "" Push ${LANG_ENGLISH} Push English Push ${LANG_SPANISH} Push Spanish Push A ; A means auto count languages ; for the auto count to work the first empty push (Push "") must remain LangDLL::LangDialog "Installer Language" "Please select the language of the installer" Pop $LANGUAGE StrCmp $LANGUAGE "cancel" 0 +2 Abort FunctionEnd """ class build_installer(py2exe): # This class first builds the exe file(s), then creates a Windows installer. # You need NSIS (Nullsoft Scriptable Install System) for it. def run(self): # Clean up os.system("del /S /Q dist") # First, let py2exe do it's work. py2exe.run(self) lib_dir = self.lib_dir dist_dir = self.dist_dir comserver_files = self.comserver_files metadata = self.distribution.metadata # create the Installer, using the files py2exe has created. script = NSISScript(metadata, lib_dir, dist_dir, self.windows_exe_files, self.lib_files, comserver_files) print "*** creating the nsis script***" script.create() print "*** compiling the nsis script***" script.compile() # Note: By default the final setup.exe will be in an Output subdirectory. class NSISScript: def __init__(self, metadata, lib_dir, dist_dir, windows_exe_files = [], lib_files = [], comserver_files = []): self.lib_dir = lib_dir self.dist_dir = dist_dir if not self.dist_dir[-1] in "\\/": self.dist_dir += "\\" self.name = metadata.get_name() self.description = metadata.get_name() self.version = metadata.get_version() self.windows_exe_files = [self.chop(p) for p in windows_exe_files] self.lib_files = [self.chop(p) for p in lib_files] self.comserver_files = [self.chop(p) for p in comserver_files if p.lower().endswith(".dll")] def chop(self, pathname): assert pathname.startswith(self.dist_dir) return pathname[len(self.dist_dir):] def create(self, pathname="base.nsi"): self.pathname = pathname ofi = self.file = open(pathname, "w") ofi.write(nsi_base_script % { 'name': self.name, 'description': "%s version %s" % (self.description, self.version), 'version': self.version, 'install_dir': self.name, 'reg_key': self.name, 'out_file': "instalador-%s-%s.exe" % (self.name, self.version), 'com_server': self.comserver_files[0], }) def compile(self, pathname="base.nsi"): os.startfile(pathname, 'compile')
Python
# Para hacer el ejecutable: # python setup.py py2exe # "Creador de instalador para PyAfipWs (WSMTXCA)" __author__ = "Mariano Reingart (mariano@nsis.com.ar)" __copyright__ = "Copyright (C) 2010 Mariano Reingart" from distutils.core import setup import py2exe import glob, sys # includes for py2exe includes=['email.generator', 'email.iterators', 'email.message', 'email.utils'] # don't pull in all this MFC stuff used by the makepy UI. excludes=["pywin", "pywin.dialogs", "pywin.dialogs.list", "win32ui"] opts = { 'py2exe': { 'includes':includes, 'optimize':2, 'excludes': excludes, }} data_files = [ (".", ["wsfev1_wsdl.xml","wsfev1_wsdl_homo.xml", "licencia.txt"]), ("cache", glob.glob("cache/*")), ] import wsfev1 from nsis import build_installer setup( name="WSFEV1", version=wsfev1.__version__ + (wsfev1.HOMO and '-homo' or '-full'), description="Interfaz PyAfipWs WSFEv1 %s", long_description=wsfev1.__doc__, author="Mariano Reingart", author_email="reingart@gmail.com", url="http://www.sistemasagiles.com.ar", license="GNU GPL v3", com_server = ["wsfev1"], console=['wsfev1.py', 'rece1.py', 'wsaa.py'], options=opts, data_files = data_files, cmdclass = {"py2exe": build_installer} )
Python
#!/usr/bin/env python # $Header: //info.ravenbrook.com/project/jili/version/1.1/code/spacepar.py#1 $ # Python 2.3.3 # Tool to analyse and correct all the errors of the form # "'(' is preceded with whitespace" produced by the Checkstyle tool. # it does this by processing the style.txt file output by Checkstyle. # Currently falls over (with an assert) if a line of source has more # than one violation. import re import sys import fileinput currentfilename = None currentfileinput = None def windtoend(fi) : '''Copies the remainder of fi to sys.stdout and then closes both streams.''' while True : l = fi.readline() if l == '' : break sys.stdout.write(l) sys.stdout.close() fi.close() def getfileinput(name) : global currentfilename global currentfileinput if currentfilename == name : return currentfileinput if currentfileinput : windtoend(currentfileinput) currentfileinput = fileinput.input(name, inplace=1) currentfilename = name return currentfileinput def doit(inp) : '''Take a file object as input. The input is the text report produced by Checkstyle. It is processed for violations.''' filename = None for l in inp.xreadlines() : if re.search(r"'\(' is preceded with whitespace", l) : m = re.search(r'^(.*?):(.*?):(.*?):', l) assert m != None filename = m.group(1) lineno = int(m.group(2)) # The column number is, by inspection of a typical line from # style.txt, the column number of the '(' character, starting from # 1 being the leftmost column. columnno = int(m.group(3)) fi = getfileinput(filename) while 1 : x = fi.readline() if fi.lineno() >= lineno : break sys.stdout.write(x) assert fi.lineno() == lineno, (filename + ' ' + str(fi.lineno()) + ' ' + str(lineno)) old = x firstpart = x[0:columnno-1] lastpart = x[columnno-1:] firstpart = firstpart.rstrip() x = firstpart + lastpart sys.stdout.write(x) windtoend(getfileinput(filename)) # close the last one. def main() : doit(sys.stdin) main()
Python
#!/usr/bin/env python # $Header: //info.ravenbrook.com/project/jili/version/1.1/code/addpackage.py#1 $ # Created using python 2.3.3 documentation as reference. # Add package declaration to java files import fileinput import sys def doit(name) : f = fileinput.input(name, inplace=1) packaged = False while True : l = f.readline() if l == '' : break sys.stdout.write(l) if not packaged and l == '\n' : sys.stdout.write('package mnj.lua;\n') packaged = True f.close() def main() : for name in sys.argv[1:] : doit(name) main()
Python
#!/usr/bin/env python # $Header: //info.ravenbrook.com/project/jili/version/1.1/code/brace.py#1 $ # Python 2.3.3 # Script to move braces import os import re import string import sys # See [JLS2] 3.9 javaKeyword = [ 'abstract', 'default', 'if', 'private', 'this', 'boolean', 'do', 'implements', 'protected', 'throw', 'break', 'double', 'import', 'public', 'throws', 'byte', 'else', 'instanceof', 'return', 'transient', 'case', 'extends', 'int', 'short', 'try', 'catch', 'final', 'interface', 'static', 'void', 'char', 'finally', 'long', 'strictfp', 'volatile', 'class', 'float', 'native', 'super', 'while', 'const', 'for', 'new', 'switch', 'continue', 'goto', 'package', 'synchronized', ] def javaKeywordP(x) : return x in javaKeyword def doit(f, out) : '''Process input file object f and emit to output file object out.''' n = 1 b = None # line to use for column position of '{' methodDecl = False for l in f.xreadlines() : field = l.split() # Find and fix '} else ...' and similar if (re.search(r'^[\t ]*}', l) and len(field) > 1 and javaKeywordP(field[1]) and field[1] != 'while') : # :todo: split line and emit m = re.match(r'^([\t ]*)}[\t *](.*)$', l) out.write(m.group(1) + '}\n') newl = m.group(1) + m.group(2) + '\n' l = newl field = l.split() firstWord='' if len(field) > 0 : firstWord = re.search(r'^[a-zA-Z_0-9]*', field[0]).group() # We store a line in b (which will be used for making the white # space on the new line that has just '{'). We store the line if it # begins with a keyword or we thinking we are starting a method # declaration. # The RE for starting a method decl is # just matching exactly 2 spaces at the beginning of a line and is # very brittle. if javaKeywordP(firstWord) and not methodDecl : b = l if re.search(r'^ [^\t ]', l) : b = l methodDecl = True suffix = '' # Find a '{' that is not on a line of its own. Any trailing # comments on the same line as '{' get preserved on their original # line. Only the '{' moves to a new line of its own. if re.search(r'[^\t ].*{[\t ]*((//.*)|(/\*.*))?$', l) : m = re.search(r'^(.*){(.*?)$', l) l = m.group(1) + ' ' + m.group(2) + '\n' l = l.rstrip() + '\n' if b == None : b = l suffix = re.search(r'^[\t ]*', b).group() + '{\n' b = None methodDecl = False out.write(l) out.write(suffix) n += 1 def perfile(name) : outname = name + '.out' out = file(outname, 'w') doit(open(name), out) out.close() os.rename(outname, name) def main() : for file in sys.argv[1:] : perfile(file) main()
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * curr_file_name = 'A-large-practice' #curr_file_name = 'A-small-practice' #curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): M, V = map(int, input_lines.pop(0).split(' ')) b = [] for j in range((M-1) / 2): temp = map(int, input_lines.pop(0).split(' ')) temp.append(-1) b.append(temp) for j in range((M+1) / 2): b.append([-1, 0, int(input_lines.pop(0))]) case_inputs.append([M, V, b]) return case_inputs def get_parent(index): return (index-1)/2 def get_children(index): return [index*2+1, index*2+2] def proc_nodes(G, v0, v1): if G == 0: return v0 | v1 if G == 1: return v0 & v1 return -1 def to_desire(b, idx, d): if b[idx][2] == d: return 0 # is leaf and not equal to desire: impossible if b[idx][0] < 0: return 100000000 ch = get_children(idx) r1 = 0 # OR if b[idx][0] == 0: if d == 0: r1 = to_desire(b, ch[0], 0) + to_desire(b, ch[1], 0) #if d == 1: else: r1 = min(to_desire(b, ch[0], 1), to_desire(b, ch[1], 1)) # AND #if b[idx][0] == 1: else: if d == 1: r1 = to_desire(b, ch[0], 1) + to_desire(b, ch[1], 1) #if d == 0: else: r1 = min(to_desire(b, ch[0], 0), to_desire(b, ch[1], 0)) if b[idx][1] == 0: return r1 # change gate r2 = 0 # OR if b[idx][0] == 1: if d == 0: r2 = to_desire(b, ch[0], 0) + to_desire(b, ch[1], 0) #if d == 1: else: r2 = min(to_desire(b, ch[0], 1), to_desire(b, ch[1], 1)) # AND #if b[idx][0] == 0: else: if d == 1: r2 = to_desire(b, ch[0], 1) + to_desire(b, ch[1], 1) #if d == 0: else: r2 = min(to_desire(b, ch[0], 0), to_desire(b, ch[1], 0)) r2 += 1 # if r1 > r2: # print idx, 'changed' return min(r1, r2) def process_func(func_input): #print func_input M, V, b = func_input p = len(b) - 1 while p > 0: pp = get_parent(p) b[pp][2] = proc_nodes(b[pp][0], b[p][2], b[p-1][2]) p -= 2 print b r = to_desire(b, 0, V) if r >= 100000000: r = 'IMPOSSIBLE' return r run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name) #print proc_nodes(1, 1, 0)
Python
''' Created on 19/05/2014 @author: dingliangl ''' from cj_lib import * from properties import * import math import fractions curr_file_name = 'A-large-practice' #curr_file_name = 'A-small-practice' #curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): N, M = map(int, input_lines.pop(0).split(' ')) oep = [] for i in range(M): oep.append(map(int, input_lines.pop(0).split(' '))) case_inputs.append([N, M, oep]) return case_inputs def calc_fee(o, e, p, N): if o == e: return 0 x = e-o return (N*x - x*(x-1)/2) * p def calc_total_fee(oep, N): f = 0 for s in oep: f += calc_fee(s[0], s[1], s[2], N) return f def process_func(func_input): N, M, oep = func_input inout = dict() for s in oep: o,e,p = s if not inout.has_key(o): inout[o] = [0, 0] if not inout.has_key(e): inout[e] = [0, 0] inout[o][0] += p inout[e][1] += p #print inout removingk = [] for k in sorted(inout.keys()): if inout[k][0] == inout[k][1]: removingk.append(k) continue x = min(inout[k][0], inout[k][1]) inout[k][0] -= x inout[k][1] -= x for k in removingk: del inout[k] #print inout fakeoep = [] inoutseq = [] for k in sorted(inout.keys()): inoutseq.append([k, inout[k][0] - inout[k][1], 0, 0]) #print inoutseq removingk = [] for i in range(len(inoutseq)): if inoutseq[i][1] == 0: removingk.append(i) for i in removingk[::-1]: inoutseq.pop(i) curr = 0 for io in inoutseq: curr += io[1] io[2] = curr io[3] = 0 if len(inoutseq) > 0: minc = -1 for i in range(len(inoutseq) - 2, -1, -1): if minc < 0 or minc > inoutseq[i][2]: minc = inoutseq[i][2] inoutseq[i][3] = minc #print inoutseq while inoutseq != []: #print inoutseq down = [] for i in range(len(inoutseq))[::-1]: io = inoutseq[i] if io[1] < 0: down = io break #down = inoutseq[-1] up = [] for io in inoutseq: if io[3] > 0 and io[1] > 0: up = io break p = min(-down[1], up[1], up[3]) down[1] += p up[1] -= p fakeoep.append([up[0], down[0], p]) #print inoutseq #print fakeoep[-1] removingk = [] for i in range(len(inoutseq)): if inoutseq[i][1] == 0: removingk.append(i) for i in removingk[::-1]: inoutseq.pop(i) curr = 0 for io in inoutseq: curr += io[1] io[2] = curr io[3] = 0 if len(inoutseq) > 0: minc = -1 for i in range(len(inoutseq)-1)[::-1]: if minc < 0 or minc > inoutseq[i][2]: minc = inoutseq[i][2] inoutseq[i][3] = minc fo = calc_total_fee(oep, N) ff = calc_total_fee(fakeoep, N) return (fo-ff)%1000002013 run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)
Python
''' Created on 23/05/2014 @author: dingliangl ''' from cj_lib import * from properties import * import math import fractions #curr_file_name = '-large-practice' #curr_file_name = '-small-practice' curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): case_inputs.append(map(int, input_lines.pop(0).split(' '))) return case_inputs def process_func(func_input): N, P = func_input return 0 run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name) print int2bin(10, 4) print bin2int('11110') print bin2int(list('11110')) print bin2int([1,1,1,1,0])
Python
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * import math import fractions #curr_file_name = 'A-large-practice' #curr_file_name = 'A-small-practice' curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): input1 = input_lines.pop(0).split(' ') print input1 t = int(input1.pop(0)) input2 = [] for j in range(t): c = input1.pop(0) p = int(input1.pop(0)) input2.append([c, p]) case_inputs.append(input2) return case_inputs def process_func(func_input): print func_input seq = func_input o = [0, 1] b = [0, 1] t = 0 for s in seq: c = [] if s[0] == 'O': c = o else: c = b d = int(math.fabs(c[1] - s[1])) #print d, t, c c[0] += d c[1] = s[1] if t > c[0]: c[0] = t else: t = c[0] t += 1 c[0] += 1 #print s[0], c #print o, b return t run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)
Python
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * import math import fractions curr_file_name = 'B-large-practice' #curr_file_name = 'B-small-practice' #curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): input = input_lines.pop(0).split(' ') C = int(input.pop(0)) comb = [] for i in range(C): comb.append(list(input.pop(0))) D = int(input.pop(0)) oppo = [] for i in range(D): oppo.append(list(input.pop(0))) N = int(input.pop(0)) cast = list(input.pop(0)) case_inputs.append([comb, oppo, cast]) return case_inputs def process_func(func_input): print func_input comb, oppo, cast = func_input cd = dict() od = dict() for c in comb: if not cd.has_key(c[0]): cd[c[0]] = [] cd[c[0]].append([c[1], c[2]]) if not cd.has_key(c[1]): cd[c[1]] = [] cd[c[1]].append([c[0], c[2]]) for o in oppo: if not od.has_key(o[0]): od[o[0]] = [] od[o[0]].append(o[1]) if not od.has_key(o[1]): od[o[1]] = [] od[o[1]].append(o[0]) print cd, od elem = [] while cast != []: print cast, elem e = cast.pop(0) if len(elem) == 0: elem.append(e) else: combed = False if cd.has_key(e): cl = cd[e] for l in cl: if elem[-1] == l[0]: elem.pop(-1) cast.insert(0, l[1]) combed = True break if not combed: oppoed = False if od.has_key(e): ol = od[e] for l in ol: if l in elem: elem = [] oppoed = True break if not oppoed: elem.append(e) return '[' + ', '.join(elem) + ']' run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)
Python
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * import math import fractions #curr_file_name = '-large-practice' #curr_file_name = '-small-practice' curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): case_inputs.append([]) return case_inputs def process_func(func_input): print func_input return 0 run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)
Python
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * import math import fractions curr_file_name = 'D-large-practice' #curr_file_name = 'D-small-practice' #curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) #for a sequence with N elements, there are N! different permutations #record T(i, N) as the number of permutations that have i and only i elements in right places (as sorted) #e.g. for 4 elements sequence [1,2,3,4], there are 6 permutations with 2 and only 2 elements in right places: #1 2 4 3 #1 3 2 4 #1 4 3 2 #2 1 3 4 #3 2 1 4 #4 2 3 1 #thus T(2, 4) = 6 #assume T(0, 0) = 1, easy to have: # #1) for 1 <= i <= N, T(i, N) = C(i, N) * T(0, N-i) (e.g for N = 6, i = 3: in case there are 3 elements just #in right places, we need to pick a combination of any 3 different elements ( C(3, 6) ), assume these 3 #elements are in places and the other 3 elements are not in place, then for each combination, it's equivalent #to 3 elements sequence that has no element in right place) # #2) for i = 0, T(0, N) = N! - (Sigma|i = 1~N (T(i, N))) (Excluding all cases with i > 0, the rest cases are #of i == 0.) # #Then we can easily calculate T with any small enough i and N. # #for N element sequence (with no element in place), assume the expect number of hit-the-table is Xn (assume X0 = 0) # #from the initial status, after 1 hit, the sequence might be changed to: #still N elements not in place (total case number: T(0, N)): need another Xn hits in average; #1 elements in place (total case number: T(1, N)): N-1 elements not in places, need another Xn-1 hits in average; #2 elements in places (total case number: T(1, N)): another Xn-2 hits; # #as there is already 1 hit happened, we have the average hit number is: #(Sigma|i=0~N (T(i, N) * (Xn-i + 1))) / N! (the total number of all cases) #== Xn! #as we already have all T(i, N) and X0, we can then easily calculate all Xn when N is small enough # # #Not finished! Observe X2 == 2, X3 == 3, X4 == 4 ... #Could be Xn == N? worth try! #and it works! def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): input_lines.pop(0) case_inputs.append(map(int, input_lines.pop(0).split(' '))) return case_inputs def process_func(func_input): print func_input seq = func_input sseq = sorted(seq) N = 0 for i in range(len(seq)): if seq[i] != sseq[i]: N += 1 return float(N) run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)
Python
''' Created on Dec 12, 2012 @author: dingliangl ''' # store some common properties that might be relative to local environment, so # leave svn peace. default_file_name = 'test' default_input_file_path = r'G:\Project\codejam_inout_2\test.in' default_output_file_path = r'G:\Project\codejam_inout_2\test.out' default_working_folder = 'G:\\Project\\codejam_inout_2\\' curr_working_folder = 'G:\\Project\\codejam_inout_2\\' #default_input_file_path = r'G:\Project\Codejam_inout\test.in' #default_output_file_path = r'G:\Project\Codejam_inout\test.out' #default_working_folder = 'G:\\Project\\Codejam_inout\\' # #curr_working_folder = 'G:\\Project\\Codejam_inout\\2008\\q\\'
Python
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * import math import fractions curr_file_name = 'C-large-practice' #curr_file_name = 'C-small-practice' #curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): input_lines.pop(0) case_inputs.append(map(int, input_lines.pop(0).split(' '))) return case_inputs def process_func(func_input): print func_input candy = func_input xor = 0 for c in candy: xor ^= c if xor != 0: return 'NO' return sum(candy) - min(candy) run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)
Python
''' CodeJam Python Lib for Festony, By Festony Created on 2012-12-12 @author: festony ''' import time import inspect import os.path import shutil import properties from properties import * __all__ = [ \ 'run_proc', \ 'accumulate', \ 'get_full', \ 'get_perm', \ 'get_comb', \ 'gen_prime', \ 'get_prime_list', \ 'int2bin', \ 'bin2int', \ ] print_details = True def print_detailed_info(info): if print_details: print info def check_input(working_folder, file_name, func): in_path = working_folder + file_name + '.in' out_path = working_folder + file_name + '.out' r = [in_path, out_path, working_folder] if file_name.find('test') >= 0: return r full_source_path = inspect.getsourcefile(func) source_file_name = full_source_path.split('\\')[-1][:-3] first_separator_index = source_file_name.find('_') if first_separator_index < 0: return r in_year_str = source_file_name[:first_separator_index] in_year = -1 try: in_year = int(in_year_str) except ValueError: return r if in_year < 2007 or in_year > 2020: return r source_file_name = source_file_name[first_separator_index+1:] first_separator_index = source_file_name.find('_') if first_separator_index < 0: return r in_round = source_file_name[:first_separator_index] source_file_name = source_file_name[first_separator_index+1:] question = source_file_name[0] if len(source_file_name) > 1 and source_file_name[1] != '_': return r if not question.isalpha() or question != question.upper(): return r moved_in_folder = working_folder + in_year_str + "\\" + in_round + "\\" if not os.path.isdir(moved_in_folder): os.makedirs(moved_in_folder) new_in_path = moved_in_folder + file_name + '.in' new_out_path = moved_in_folder + file_name + '.out' new_r = [new_in_path, new_out_path, moved_in_folder] if os.path.isfile(new_in_path): return new_r if os.path.isfile(in_path): shutil.move(in_path, new_in_path) return new_r return r def run_proc(func, input_dividing_func, working_folder=default_working_folder, file_name=default_file_name): '''Run the function multiple times for cases. Process time for each run / all runs are tracked. 1) need to provide the function to process each case, the function should take a list as raw func_input; 2) an input_dividing_func should be provided to break func_input lines into func_input lists for each case. ''' in_path = working_folder + file_name + '.in' out_path = working_folder + file_name + '.out' in_path, out_path, working_folder = check_input(working_folder, file_name, func) inputfile = open(in_path, 'r') raw_input_str = inputfile.read() inputfile.close() input_lines = map(lambda x:x.rstrip('\r\n'), raw_input_str.split('\n')) inputs = input_dividing_func(input_lines) r = '' case_total_num = len(inputs) print_detailed_info('{0} cases in total.'.format(case_total_num)) start_time_overall = time.clock() for i, func_input in enumerate(inputs): case_num = i + 1 print_detailed_info('Case {0}:'.format(case_num)) start_time_single_case = time.clock() r += 'Case #%d: %s\n' % (case_num, str(func(func_input))) print_detailed_info("Process time: %g sec(s)" % \ (time.clock() - start_time_single_case,)) print_detailed_info("Overall process time till now: %g sec(s)" % \ (time.clock() - start_time_overall,)) end_time_overall = time.clock() print(r) print("Overall process time: %g sec(s)" % \ (end_time_overall - start_time_overall,)) outputfile = open(out_path, 'w') outputfile.write(r) outputfile.close() if not ('practice' in file_name or 'test' in file_name): shutil.copy(inspect.getsourcefile(run_proc), working_folder) shutil.copy(inspect.getsourcefile(properties), working_folder) shutil.copy(inspect.getsourcefile(func), working_folder) return r # commonly used functions def accumulate(l): r = l[:] for i in range(1, len(r)): r[i] += r[i-1] return r def get_full(k): r = [] k1 = 0 for i in range(k): if r == []: for j in range(k): r.append([j]) else: l = len(r) for j in range(l): temp = r.pop(0) for j1 in range(k): temp2 = temp + [j1] r.append(temp2) return r def get_perm(k, n): if k == 0: return [] r = [] if k == 1: for i in range(n): r.append([i]) return r r1 = get_perm(k-1, n) r = [] for p in r1: for j in range(max(p)+1, n): for i in range(k): temp = p[:] temp.insert(i, j) r.append(temp) return r def get_comb(k, n): ''' get k items out of total n ''' if k == 0: return [] r = [] if k == 1: for i in range(n): r.append([i]) return r r1 = get_comb(k-1, n) for sr in r1: for i in range(sr[-1] + 1, n): if i not in sr: temp = sr[:] temp.append(i) r.append(temp) return r def is_dividable(n, prime_list): for p in prime_list: if n % p == 0: return True return False def gen_prime(n): r = [2] i = 3 while i <= n: if not is_dividable(i, r): r.append(i) i += 2 return r def get_prime_list(): f = open('prime_list.txt', 'r') prime_list = eval(f.read()) return prime_list def int2bin(n, N = None): bn = bin(n)[2:] if N == None or N <= len(bn): return map(int, list(bn)) else: return map(int, list(bn.zfill(N))) def bin2int(bn): return int(''.join(map(str, list(bn))), 2) # Test if __name__ == '__main__': def test_process_func(func_input): print 'func_input:', func_input return 0 # Set test case input file f = open(default_working_folder + default_file_name + '.in', 'r') old_content = f.read() f.close() f = open(default_working_folder + default_file_name + '.in', 'w') f.write('''4 5 Yeehaw NSM Dont Ask B9 Googol 10 Yeehaw Yeehaw Googol B9 Googol NSM B9 NSM Dont Ask Googol 5 Yeehaw NSM Dont Ask B9 Googol 7 Googol Dont Ask NSM NSM Yeehaw Yeehaw Googol 4 Zol Zolz Zollz Zolzz 0 0 3 'AZ' 'BZ' 'CZ' ''') f.close() def test_input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): engine_num = int(input_lines.pop(0)) engines = input_lines[:engine_num] del input_lines[:engine_num] query_num = int(input_lines.pop(0)) queries = input_lines[:query_num] del input_lines[:query_num] case_inputs.append([engines, queries]) return case_inputs run_proc(test_process_func, test_input_dividing_func) # restore file used in test case back to its original content. f = open(default_working_folder + default_file_name + '.in', 'w') f.write(old_content) f.close()
Python
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * import math import fractions #curr_file_name = '-large-practice' #curr_file_name = '-small-practice' curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): case_inputs.append([]) return case_inputs def process_func(func_input): print func_input return 0 run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)
Python
''' Created on Dec 12, 2012 @author: dingliangl ''' # store some common properties that might be relative to local environment, so # leave svn peace. default_file_name = 'test' default_input_file_path = r'D:\CodeJam\inout\test.in' default_output_file_path = r'D:\CodeJam\inout\test.out' default_working_folder = 'D:\\CodeJam\\inout\\' curr_working_folder = 'D:\\CodeJam\\inout\\' #default_input_file_path = r'G:\Project\Codejam_inout\test.in' #default_output_file_path = r'G:\Project\Codejam_inout\test.out' #default_working_folder = 'G:\\Project\\Codejam_inout\\' # #curr_working_folder = 'G:\\Project\\Codejam_inout\\2008\\q\\' # #curr_working_folder = 'G:\\Project\\Codejam_inout\\'
Python
''' CodeJam Python Lib for Festony, By Festony Created on 2012-12-12 @author: festony ''' import time import inspect import os.path import shutil import properties from properties import * __all__ = [ \ 'run_proc', \ 'accumulate', \ 'get_full', \ 'get_perm', \ 'get_comb', \ 'gen_prime', \ 'get_prime_list', \ 'int2bin', \ 'bin2int', \ ] print_details = True def print_detailed_info(info): if print_details: print info def check_input(working_folder, file_name, func): in_path = working_folder + file_name + '.in' out_path = working_folder + file_name + '.out' r = [in_path, out_path, working_folder] if file_name.find('test') >= 0: return r full_source_path = inspect.getsourcefile(func) source_file_name = full_source_path.split('\\')[-1][:-3] first_separator_index = source_file_name.find('_') if first_separator_index < 0: return r in_year_str = source_file_name[:first_separator_index] in_year = -1 try: in_year = int(in_year_str) except ValueError: return r if in_year < 2007 or in_year > 2020: return r source_file_name = source_file_name[first_separator_index+1:] first_separator_index = source_file_name.find('_') if first_separator_index < 0: return r in_round = source_file_name[:first_separator_index] source_file_name = source_file_name[first_separator_index+1:] question = source_file_name[0] if len(source_file_name) > 1 and source_file_name[1] != '_': return r if not question.isalpha() or question != question.upper(): return r moved_in_folder = working_folder + in_year_str + "\\" + in_round + "\\" if not os.path.isdir(moved_in_folder): os.makedirs(moved_in_folder) new_in_path = moved_in_folder + file_name + '.in' new_out_path = moved_in_folder + file_name + '.out' new_r = [new_in_path, new_out_path, moved_in_folder] if os.path.isfile(new_in_path): return new_r if os.path.isfile(in_path): shutil.move(in_path, new_in_path) return new_r return r def run_proc(func, input_dividing_func, working_folder=default_working_folder, file_name=default_file_name): '''Run the function multiple times for cases. Process time for each run / all runs are tracked. 1) need to provide the function to process each case, the function should take a list as raw func_input; 2) an input_dividing_func should be provided to break func_input lines into func_input lists for each case. ''' in_path = working_folder + file_name + '.in' out_path = working_folder + file_name + '.out' in_path, out_path, working_folder = check_input(working_folder, file_name, func) inputfile = open(in_path, 'r') raw_input_str = inputfile.read() inputfile.close() input_lines = map(lambda x:x.rstrip('\r\n'), raw_input_str.split('\n')) inputs = input_dividing_func(input_lines) r = '' case_total_num = len(inputs) print_detailed_info('{0} cases in total.'.format(case_total_num)) start_time_overall = time.clock() for i, func_input in enumerate(inputs): case_num = i + 1 print_detailed_info('Case {0}:'.format(case_num)) start_time_single_case = time.clock() r += 'Case #%d: %s\n' % (case_num, str(func(func_input))) print_detailed_info("Process time: %g sec(s)" % \ (time.clock() - start_time_single_case,)) print_detailed_info("Overall process time till now: %g sec(s)" % \ (time.clock() - start_time_overall,)) end_time_overall = time.clock() print(r) print("Overall process time: %g sec(s)" % \ (end_time_overall - start_time_overall,)) outputfile = open(out_path, 'w') outputfile.write(r) outputfile.close() if not ('practice' in file_name or 'test' in file_name): shutil.copy(inspect.getsourcefile(run_proc), working_folder) shutil.copy(inspect.getsourcefile(properties), working_folder) shutil.copy(inspect.getsourcefile(func), working_folder) return r # commonly used functions def accumulate(l): r = l[:] for i in range(1, len(r)): r[i] += r[i-1] return r def get_full(k): r = [] k1 = 0 for i in range(k): if r == []: for j in range(k): r.append([j]) else: l = len(r) for j in range(l): temp = r.pop(0) for j1 in range(k): temp2 = temp + [j1] r.append(temp2) return r def get_perm(k, n): if k == 0: return [] r = [] if k == 1: for i in range(n): r.append([i]) return r r1 = get_perm(k-1, n) r = [] for p in r1: for j in range(max(p)+1, n): for i in range(k): temp = p[:] temp.insert(i, j) r.append(temp) return r def get_comb(k, n): ''' get k items out of total n ''' if k == 0: return [] r = [] if k == 1: for i in range(n): r.append([i]) return r r1 = get_comb(k-1, n) for sr in r1: for i in range(sr[-1] + 1, n): if i not in sr: temp = sr[:] temp.append(i) r.append(temp) return r def is_dividable(n, prime_list): for p in prime_list: if n % p == 0: return True return False def gen_prime(n): r = [2] i = 3 while i <= n: if not is_dividable(i, r): r.append(i) i += 2 return r def get_prime_list(): f = open('prime_list.txt', 'r') prime_list = eval(f.read()) return prime_list def int2bin(n, N = None): bn = bin(n)[2:] if N == None or N <= len(bn): return map(int, list(bn)) else: return map(int, list(bn.zfill(N))) def bin2int(bn): return int(''.join(map(str, list(bn))), 2) # Test if __name__ == '__main__': def test_process_func(func_input): print 'func_input:', func_input return 0 # Set test case input file f = open(default_working_folder + default_file_name + '.in', 'r') old_content = f.read() f.close() f = open(default_working_folder + default_file_name + '.in', 'w') f.write('''4 5 Yeehaw NSM Dont Ask B9 Googol 10 Yeehaw Yeehaw Googol B9 Googol NSM B9 NSM Dont Ask Googol 5 Yeehaw NSM Dont Ask B9 Googol 7 Googol Dont Ask NSM NSM Yeehaw Yeehaw Googol 4 Zol Zolz Zollz Zolzz 0 0 3 'AZ' 'BZ' 'CZ' ''') f.close() def test_input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): engine_num = int(input_lines.pop(0)) engines = input_lines[:engine_num] del input_lines[:engine_num] query_num = int(input_lines.pop(0)) queries = input_lines[:query_num] del input_lines[:query_num] case_inputs.append([engines, queries]) return case_inputs run_proc(test_process_func, test_input_dividing_func) # restore file used in test case back to its original content. f = open(default_working_folder + default_file_name + '.in', 'w') f.write(old_content) f.close()
Python
''' Created on 2014-4-4 @author: festony '''
Python
''' Created on 2014-4-4 @author: festony ''' class AmebaDiv1: def count(self, X): U = list(set(X)) S = U[:] for ini in U: s = ini for x in X: if x == s: s += x if s in S: S.remove(s) return len(S) class LongLongTripDiv1: def isAble(self, N, A, B, D, T): paths = [] for i in range(len(A)): if A[i] == 0: p = [i] curr = B[i] paths.append([p, curr]) elif B[i] == 0: p = [i] curr = A[i] paths.append([p, curr]) print paths fpaths = [] while paths != []: path = paths.pop(0) p = path[0] curr = path[1] if len(p) == len(A): fpaths.append(path[0]) continue #print p, curr updated = False for i in range(len(A)): if i in p: continue if A[i] == curr: updated = True newp = p[:] newp.append(i) newcurr = B[i] paths.append([newp, newcurr]) elif B[i] == curr: updated = True newp = p[:] newp.append(i) newcurr = A[i] paths.append([newp, newcurr]) if updated == False: fpaths.append(path[0]) print paths print fpaths if fpaths == []: return "Impossible" paths = [] for p in fpaths: path = [] cities = [0] curr = 0 for r in p: a = A[r] b = B[r] if a == curr: cities.append(b) curr = b elif b == curr: cities.append(a) curr = a path.append(r) if curr == N-1: paths.append([path[:], cities[:]]) print paths if paths == []: return "Impossible" t_cities = {} for p in paths: t = 0 for r in p[0]: t += D[r] if t_cities.has_key(t): for c in p[1]: t_cities[t].add(c) else: t_cities[t] = set(p[1]) print t_cities t_roads = {} for t in t_cities.keys(): if not t_roads.has_key(t): t_roads[t] = set([]) for c in t_cities[t]: for i in range(len(A)): if A[i] == c or B[i] == c: t_roads[t].add(i) print t_roads t_rl = {} for t in t_roads.keys(): if not t_rl.has_key(t): t_rl[t] = set([]) for r in t_roads[t]: t_rl[t].add(D[r]) print t_rl for t in t_rl.keys(): if t > T: continue if t == T: return "Possible" rest = T - t if rest % 2 == 1: continue rest /= 2 print rest facts = sorted(list(t_rl[t]), reverse = True) print facts for f in facts: rest %= f print 'r', r if rest == 0: return "Possible" if rest == 0: return "Possible" return "Impossible" l = LongLongTripDiv1() #N = 6 #A = [0,0,0,1,2,1,2,2,3,4] #B = [1,2,3,2,3,5,5,4,4,5] #D = [1,1,1,1,2,1,2,2,3,4] #T = 10000 N = 3 A = [0, 0, 1] B = [2, 1, 2] D = [7, 6, 5] T = 25 print l.isAble(N, A, B, D, T)
Python
''' Created on 2014-4-4 @author: festony ''' class MinimumSquare: def getMaxSquareSide(self, x, y): minx = min(x) maxx = max(x) miny = min(y) maxy = max(y) disx = maxx - minx disy = maxy - miny dis = max(disx, disy) return dis + 2 def testSquareContainsKAtP(self, x, y, K, s, p): N = len(x) clbx = p[0] clby = p[1] crtx = clbx + s crty = clby + s c = 0 for i in range(N): if x[i] > clbx and x[i] < crtx and y[i] > clby and y[i] < crty: c += 1 return c >= K def testSquareContainsK(self, x, y, K, s): minx = min(x) maxx = max(x) miny = min(y) maxy = max(y) startp = [minx - 1, miny - 1] endp = [maxx + 1, maxy + 1] for ix in x: for iy in y: p = [ix - 1, iy - 1] if self.testSquareContainsKAtP(x, y, K, s, p): return True # p = [ix - 1, iy - s + 1] # if self.testSquareContainsKAtP(x, y, K, s, p): # return True # p = [ix - s + 1, iy - 1] # if self.testSquareContainsKAtP(x, y, K, s, p): # return True # p = [ix - s + 1, iy - s + 1] # if self.testSquareContainsKAtP(x, y, K, s, p): # return True return False def minArea(self, x, y, K): down = 2 up = self.getMaxSquareSide(x, y) mid = (up + down) / 2 while up - down > 1: if self.testSquareContainsK(x, y, K, mid): up = mid mid = (up + down) / 2 else: down = mid mid = (up + down) / 2 return up * up
Python
''' Created on 17/03/2014 @author: dingliangl ''' class SurroundingGameEasy: def isDom(self, x, y, s): if s[y][x]: return True if x > 0 and not s[y][x-1]: return False if x < len(s[0]) - 1 and not s[y][x+1]: return False if y > 0 and not s[y-1][x]: return False if y < len(s) - 1 and not s[y+1][x]: return False return True def score(self, cost, benefit, stone): c = [] for cs in cost: ln = [] for ch in list(cs): ln.append(int(ch)) c.append(ln) b = [] for bs in benefit: ln = [] for ch in list(bs): ln.append(int(ch)) b.append(ln) s = [] for ss in stone: ln = [] for ch in list(ss): ln.append(ch=='o') s.append(ln) score = 0 print len(s) for y in range(len(s)): for x in range(len(s[0])): print y, x if self.isDom(x, y, s): score += b[y][x] if s[y][x]: score -= c[y][x] return score s = SurroundingGameEasy() cost = ["4362","4321"] benefit = ["5329","5489"] stone = ["...o","..o."] #print s.score(cost, benefit, stone) class Stamp: def paint_seg(self, seg, l): lseg = list(seg) r = 0 while lseg != []: while lseg != [] and lseg[0] == '*': lseg.pop(0) while lseg != [] and lseg[0] != '*': r += 1 if len(lseg) >= l: lseg = lseg[l:] else: lseg = [] return r def paint(self, board, stampCost, pushCost): smaxl = min(map(len, board)) r = [] for l in range(1, smaxl+1): t = 0 for seg in board: t += self.paint_seg(seg, l) if t == 0: r.append(0) break r.append(stampCost * l + pushCost * t) return min(r) def gen_paint_meth(self, dcolor, colorord): cl = list(dcolor) first = [] second = [] third = [] for ch in cl: # if ch == colorord[0] or ch == '*': # first.append('1') # else: # first.append('*') if ch == colorord[0] or ch == '*': first.append('1') else: first.append('*') if ch == colorord[0]: second.append(' ') elif ch == colorord[1]: second.append('1') elif ch == colorord[2] or ch == '*': second.append('*') if ch == colorord[0] or ch == colorord[1]: third.append(' ') elif ch == [2]: third.append('1') else: third.append('*') #bs = [first, second, third] r = map(lambda x:filter(lambda y:y!='',(''.join(x)).split(' ')), [first, second, third]) #print r return r def getMinimumCost(self, desiredColor, stampCost, pushCost): allcolorord = ['RGB', 'RBG', 'GRB', 'GBR', 'BRG', 'BGR'] r = [] for co in allcolorord: s = self.gen_paint_meth(desiredColor, co) sub = 0 for ss in s: sub += self.paint(ss, stampCost, pushCost) r.append(sub) print r return 0 s = Stamp() desiredColor = '*R*RG*G*GR*RGG*G*GGR***RR*GG' stampCost = 7 pushCost = 1 print s.getMinimumCost(desiredColor, stampCost, pushCost) #print s.paint_seg('1**1*1', 3) #[f,s,t] = s.gen_paint_meth(list("*R*RG*G*GR*RGG*G*GGR***RR*GG"), 'RGB') # print f,s,t # print filter(lambda x:x!='',s.split(' ')) # print f.split(' ')
Python
#!/usr/bin/env python # # Small Python utility that reads an ABAQUS file and creates an image of the # model. # # ABAQUS entities supported: # Shells: # S4, S4R, S4RS, S3, S3R, S3RS, M3D4, M3D4R, M3D3, S8R, S8R5, M3D8, # M3D8R, M3D6, SFM3D4, SFM3D4R, SFM3D3 # Bars: # B31, CONN3D2 # Solids: TODO # # This utility requires the Python Imaging Library (PIL). It has been # tested with PIL 1.1.6. You can get PIL at: # http://www.pythonware.com/products/pil/ # # Images are created in PNG and EPS formats. Other formats supported by PIL can # also be implemented. # # Writen by: Michalis Giannakidis, mgiannakidis@gmail.com # See README for details. """ usage: %prog [options] filename Read an ABAQUS file in memory. Save an image with the model's contents. """ __author__ = 'Michalis Giannakidis' __version__ = '0.2' #============================================================================== # if PIL is not site installed, download it and provide the path to it here: _PATH_TO_PIL_LIBRARY = '/home/mgiann/Imaging-1.1.6/PIL' # angle (in degrees) between shells to consider as features _FEATURE_ANGLE = 40 #============================================================================== import os import re import optparse import math import random import sys try: import Image, ImageDraw, ImageFont except ImportError: sys.path.append( _PATH_TO_PIL_LIBRARY ) import Image, ImageDraw, ImageFont #============================================================================== # angle between facets to consider as feature Costheta_feature = math.cos(_FEATURE_ANGLE * math.pi / 180.) # rotation of the view to take image, in degrees Rot_view_x = -45 Rot_view_y = 0 Rot_view_z = 30 # default width for images Width = 400 #============================================================================== def nnormal(nodes): if nodes[3] == None: d1x = nodes[1].x - nodes[0].x d1y = nodes[1].y - nodes[0].y d1z = nodes[1].z - nodes[0].z d2x = nodes[2].x - nodes[0].x d2y = nodes[2].y - nodes[0].y d2z = nodes[2].z - nodes[0].z else: d1x = nodes[2].x - nodes[0].x d1y = nodes[2].y - nodes[0].y d1z = nodes[2].z - nodes[0].z d2x = nodes[3].x - nodes[1].x d2y = nodes[3].y - nodes[1].y d2z = nodes[3].z - nodes[1].z dx = d1y*d2z - d1z*d2y dy = d1z*d2x - d1x*d2z dz = d1x*d2y - d1y*d2x dd = math.sqrt(dx*dx+dy*dy+dz*dz) if dd: dx = dx/dd dy = dy/dd dz = dz/dd else: dx = 0. dy = 0. dz = 0. return dx, dy, dz #============================================================================== class Node(object): __slots__ = ('id', 'x', 'y', 'z') def __init__(self, id, xc = 0., yc = 0., zc = 0.): self.id = id self.x = xc self.y = yc self.z = zc def populate(self): return True #============================================================================== class Element(object): __slots__ = ('id', 'prop') def __init__(self, id, prop): self.id = id self.prop = prop # FIXME populate for Element.... check if prop is compatible. def populate(self): sec_arr = entities_array('PROP') if sec_arr.has_key(self.prop): self.prop = sec_arr[self.prop] self.prop.elements.append(self) else: self.prop = None return True class Shell(Element): __slots__ = ('nn') def __init__(self, id, n1, n2, n3, n4, prop = None): Element.__init__(self, id, prop) self.nn = [ n1, n2, n3, n4 ] def nodes(self): return self.nn def nodes_num(self): if self.nn[3] == None: return 3 return 4 def populate(self): if not Element.populate(self): return False try: nodes = entities_array('NODE') self.nn[0] = nodes[self.nn[0]] self.nn[1] = nodes[self.nn[1]] self.nn[2] = nodes[self.nn[2]] if self.nn[3]: self.nn[3] = nodes[self.nn[3]] else: self.nn[3] = None return True except KeyError: return False class Bar(Element): __slots__ = ('nn') def __init__(self, id, n1, n2, prop = None): Element.__init__(self, id, prop) self.nn = [ n1, n2 ] def nodes(self): return self.nn def nodes_num(self): return 2 def populate(self): if not Element.populate(self): return False try: nodes = entities_array('NODE') self.nn[0] = nodes[self.nn[0]] self.nn[1] = nodes[self.nn[1]] return True except KeyError: return False #============================================================================== class Section(object): __slots__ = ('id', 'name', 'type', 'elements', 'feature_lines') def __init__(self, id, name, type): self.id = id self.name = name self.type = type self.elements = [] self.feature_lines = None def populate(self): return True def calc_feature_lines(self): if not self.type == 'SHELL': return if self.feature_lines: return self.feature_lines = [] edges_shells = [] for elem in self.elements: nodes = elem.nn nodes_num = elem.nodes_num() for i in range(0, nodes_num): n1, n2 = nodes[i%nodes_num], nodes[(i+1)%nodes_num] if n1 < n2: nmin = n1 nmax = n2 else: nmin = n2 nmax = n1 edges_shells.append( (nmin, nmax, elem) ) edges_shells.sort() tot_len = len(edges_shells) i = 0 k = 0 while i < tot_len: n1, n2 = edges_shells[i][0], edges_shells[i][1] j = i+1 while j < tot_len and \ (edges_shells[j][0],edges_shells[j][1]) == (n1, n2): j = j + 1 gap = j - i #gap = 1 if gap == 2: d1x, d1y, d1z = nnormal(edges_shells[i][2].nn) d2x, d2y, d2z = nnormal(edges_shells[i+1][2].nn) costheta = d1x*d2x + d1y*d2y + d1z*d2z if costheta < Costheta_feature: # feature angle #self.feature_lines.append((n1, n2)) edges_shells[k] = edges_shells[i] k = k + 1 elif gap > 0: #self.feature_lines.append((n1, n2)) edges_shells[k] = edges_shells[i] k = k + 1 i = j edges_shells = edges_shells[:k] self.feature_lines = [ (n1, n2) for n1, n2, elem in edges_shells ] #for n1, n2, elem in edges_shells: # self.feature_lines.append((n1, n2)) del edges_shells return #============================================================================== def cmp_abaqus_names(x, y): x = x.replace(' ', '').upper() y = y.replace(' ', '').upper() return cmp(x, y) #============================================================================== class AbaqusReader: MAX_ABQ_FIELDS = 16 def __init__(self, fname): self.filename = fname self.file = open(self.filename, 'rb') self.file_list = [ self.file ] self.current_line_num = 0 self.end_of_file_reached = False self.prop_name_to_id = {} self.ivals = [ 0 ] * AbaqusReader.MAX_ABQ_FIELDS self.fvals = [ 0. ] * AbaqusReader.MAX_ABQ_FIELDS self.svals = [ '' ] * AbaqusReader.MAX_ABQ_FIELDS def __del__(self): map(file.close, self.file_list) def del_unused_after_input(self): del self.prop_name_to_id self.prop_name_to_id = None abaqus_keyword_pattern = re.compile('^\*[A-Za-z ]+') abaqus_keyword_pattern_fast = re.compile('^\*[A-Za-z]') @staticmethod def l_is_keyword(line): #m = AbaqusReader.abaqus_keyword_pattern_fast.match(line) #if not m: return None if line and line[0] != '*': return None m = AbaqusReader.abaqus_keyword_pattern.match(line) if not m: return None return m.group(0).upper() @staticmethod def l_is_comment(line): if line[:2] == '**': return True else: return False param_pairs_pattern = re.compile('([A-Za-z][\w ]*)(=([\w;\./ -]*)|)') @staticmethod def decode_keyword_line(line): #k, p = decode_keyword_line("*ELEMENT, TYPE=LALALA, V=wwwww, V2=0.2, WW") # FIXME read parameters spanning lines keyword = AbaqusReader.l_is_keyword(line) param_pairs = line.split(',') parameters = {} for param_pair in param_pairs[1:]: param_pair = param_pair.strip() m = AbaqusReader.param_pairs_pattern.match(param_pair) if m: if m.group(3): parameters[m.group(1).strip().upper()] = \ m.group(3).strip() else: parameters[m.group(1).strip().upper()] = None return keyword, parameters def decode_data_line(self, line, min_num_vals = MAX_ABQ_FIELDS): vals = line.split(',') nfields = len(vals) for i, val in enumerate(vals): is_number = True try: self.fvals[i] = float(val) except ValueError: is_number = False self.ivals[i] = int(self.fvals[i]) if not is_number: self.svals[i] = val.strip() i = i + 1 while i < min_num_vals: self.ivals[i] = 0 self.fvals[i] = 0. self.svals[i] = '' i = i + 1 return nfields def readline(self): self.current_line = self.file.readline() # skip comments.... while AbaqusReader.l_is_comment(self.current_line): self.current_line = self.file.readline() if self.current_line: self.current_line = self.current_line.rstrip() self.current_line_num = self.current_line_num + 1 return True else: file = self.file_list.pop() file.close() if len(self.file_list) == 0: self.end_of_file_reached = True return False self.file = self.file_list[-1] return True def read_include(self, keyword, parameters): keyword, parameters = self.decode_keyword_line(self.current_line) if parameters.has_key('INPUT'): filename = parameters['INPUT'] if not os.path.isabs(self.filename): filename = os.path.join(os.path.dirname(self.filename),filename) if os.path.isfile(filename): file = open(filename, 'rb') if file: self.file_list.append(file) self.file = file else: print '*INCLUDE %s is missing' % filename return 0 def dummy_read_keyword(self): while self.readline(): if AbaqusReader.l_is_keyword(self.current_line): return 1 #print self.current_line return 0 def prop_id_from_name(self, prop_name): if not self.prop_name_to_id.has_key(prop_name): self.prop_name_to_id[prop_name] = \ len(self.prop_name_to_id) + 1 return self.prop_name_to_id[prop_name] def read_nodes(self, keyword, parameters): # ar.current_line contains *NODE. n_arr = entities_array('NODE') while self.readline(): if AbaqusReader.l_is_keyword(self.current_line): return 1 self.decode_data_line(self.current_line, 4) id = self.ivals[0] if id > 0: if not n_arr.has_key(id): n_arr[id] = Node(id, self.fvals[1], self.fvals[2], self.fvals[3]) else: print "Node id: %d already exists" % id else: print "Node id: %d is invalid" % id return 0 def read_shells(self, keyword, parameters, is_tria): if parameters.has_key('ELSET'): prop = self.prop_id_from_name(parameters['ELSET']) else: prop = None sh_arr = entities_array('SHELL') while self.readline(): if AbaqusReader.l_is_keyword(self.current_line): return 1 self.decode_data_line(self.current_line, 5) id = self.ivals[0] n1 = self.ivals[1] n2 = self.ivals[2] n3 = self.ivals[3] n4 = self.ivals[4] if is_tria: n4 = 0 if id > 0 and n1 > 0 and n2 > 0 and n3 > 0 and n4 >= 0: if not sh_arr.has_key(id): sh_arr[id] = Shell(id, n1, n2, n3, n4, prop) else: print "Shell id: %d already exists" % id return 0 def read_shells3(self, keyword, parameters): return self.read_shells(keyword, parameters, True) def read_shells4(self, keyword, parameters): return self.read_shells(keyword, parameters, False) def read_bars(self, keyword, parameters): if parameters.has_key('ELSET'): prop = self.prop_id_from_name(parameters['ELSET']) else: prop = None bar_arr = entities_array('BAR') while self.readline(): if AbaqusReader.l_is_keyword(self.current_line): return 1 self.decode_data_line(self.current_line, 3) id = self.ivals[0] n1 = self.ivals[1] n2 = self.ivals[2] if id > 0 and n1 > 0 and n2 > 0: if not bar_arr.has_key(id): bar_arr[id] = Bar(id, n1, n2, prop) else: print "Bar id: %d already exists" % id return 0 def read_section(self, keyword, parameters): if parameters.has_key('ELSET'): prop = parameters['ELSET'] id = self.prop_id_from_name(parameters['ELSET']) sec = Section(id, prop, self.properties_to_element_types[keyword]) sec_arr = entities_array('PROP') if not sec_arr.has_key(id): sec_arr[id] = sec else: sec.type = self.properties_to_element_types[keyword] #print 'Section: %s already exists' % \ # parameters['ELSET'] while self.readline(): if self.l_is_keyword(self.current_line): return 1 #skip all datalines... return 0 def read_keyword(self, keyword): keyword, parameters = self.decode_keyword_line(self.current_line) if self.keywords_library_read_fun.has_key(keyword): print 'reading %s' % keyword reader = self.keywords_library_read_fun[keyword] try: return reader(self, keyword, parameters) except TypeError: for p, pval, rfun in reader: if parameters.has_key(p) and\ parameters[p] == pval: return rfun(self, keyword, parameters) print 'skipping, %s %s=%s' % \ (keyword, p, parameters[p]) else: print 'skipping %s' % keyword return self.dummy_read_keyword() #====================================================================== keywords_library_read_fun = { '*NODE' : read_nodes, '*INCLUDE' : read_include, '*ELEMENT' : ( ( 'TYPE', 'S4', read_shells4 ), ( 'TYPE', 'S4R', read_shells4 ), ( 'TYPE', 'S4RS', read_shells4 ), ( 'TYPE', 'S3', read_shells3 ), ( 'TYPE', 'S3R', read_shells3 ), ( 'TYPE', 'S3RS', read_shells3 ), ( 'TYPE', 'M3D4', read_shells4 ), ( 'TYPE', 'M3D4R', read_shells4 ), ( 'TYPE', 'M3D3', read_shells3 ), ( 'TYPE', 'S8R', read_shells4 ), ( 'TYPE', 'S8R5', read_shells4 ), ( 'TYPE', 'M3D8', read_shells4 ), ( 'TYPE', 'M3D8R', read_shells4 ), ( 'TYPE', 'M3D6', read_shells3 ), # Joke: surfaces are shells! ( 'TYPE', 'SFM3D4', read_shells4 ), ( 'TYPE', 'SFM3D4R', read_shells4 ), ( 'TYPE', 'SFM3D3', read_shells4 ), ( 'TYPE', 'B31', read_bars ), ( 'TYPE', 'CONN3D2', read_bars ), ), '*SHELL SECTION' : read_section, '*MEMBRANE SECTION' : read_section, '*SURFACE SECTION' : read_section, '*SOLID SECTION' : read_section, '*BEAM SECTION' : read_section, '*BEAM GENERAL SECTION' : read_section, '*CONNECTOR SECTION' : read_section, } properties_to_element_types = { '*SHELL SECTION' : 'SHELL', '*MEMBRANE SECTION' : 'SHELL', '*SURFACE SECTION' : 'SHELL', '*SOLID SECTION' : 'SOLID', # Trusses also.... '*BEAM SECTION' : 'BAR', '*BEAM GENERAL SECTION' : 'BAR', '*CONNECTOR SECTION' : 'BAR', } def read_file(self): st = True keyword_line_pending = 0 while st: if not keyword_line_pending: st = self.readline() keyword_line_pending = 0 keyword = AbaqusReader.l_is_keyword(self.current_line) if keyword: keyword_line_pending = self.read_keyword(keyword) if self.end_of_file_reached: break if not keyword_line_pending: pass #print "Unread line: %d: `%s'" % \ # (self.current_line_num, self.current_line) self.del_unused_after_input() #============================================================================== def entities_array(keyword): return sup_keywords_library[keyword] #============================================================================== # elements can all go to the same array, as properties. # but, since we will not create any new elements, let's have them separate for # now sup_keywords_library = { 'NODE': {}, 'SHELL': {}, 'BAR': {}, 'PROP': {}, } #============================================================================== def populate_group(ent_dict): to_del = [ id for id, ent in ent_dict.iteritems() if not ent.populate() ] map( ent_dict.pop, to_del ) def populate_entities(): map( populate_group, sup_keywords_library.values() ) #============================================================================== def read_abaqus_file(filename): ar = AbaqusReader(filename) ar.read_file() del ar #============================================================================== class ScreenView(object): def __init__(self, width): from math import sin, cos, pi a = Rot_view_x*pi/180 # x axis rot b = Rot_view_y*pi/180 # y axis rot c = Rot_view_z*pi/180 # z axis rot self.dxx = cos(c)*cos(b) self.dxy = -sin(c)*cos(b) self.dxz = sin(b) self.dyx = cos(c)*sin(b)*sin(a) + sin(c)*cos(a) self.dyy = cos(c)*cos(a) - sin(c)*sin(b)*sin(a) self.dyz = -cos(b)*sin(a) self.dzx = sin(c)*sin(a) - cos(c)*sin(b)*cos(a) self.dzy = sin(c)*sin(b)*cos(a) + sin(a)*cos(c) self.dzz = cos(b)*cos(a) self.width = width self.height = width/math.sqrt(2) self.xmin = 10e9 self.ymin = 10e9 self.zmin = 10e9 self.xmax = -10e9 self.ymax = -10e9 self.zmax = -10e9 self.xm = 0 self.ym = 0 self.scale = 1 def view_bounds(self): for id, sec in entities_array('PROP').iteritems(): for elem in sec.elements: nodes = elem.nn num_n = elem.nodes_num() for n in nodes[:num_n]: nx, ny, nz = self.from_global(n.x, n.y, n.z) if nx < self.xmin: self.xmin = nx elif nx > self.xmax: self.xmax = nx if ny < self.ymin: self.ymin = ny elif ny > self.ymax: self.ymax = ny if nz < self.zmin: self.zmin = nz elif nz > self.zmax: self.zmax = nz dx = (self.xmax - self.xmin) dy = (self.ymax - self.ymin) sx = float(self.width)/float(dx) sy = float(self.height)/float(dy) self.scale = min(sx, sy) self.scale = self.scale*0.95 self.xm = self.xmin-dx*0.025 # 0.95 + 0.025*2 = 1 self.ym = self.ymin-dy*0.025 xoffs = self.width - dx*self.scale/0.95 if xoffs > 0: self.xm = self.xm - xoffs/(2*self.scale) yoffs = self.height - dy*self.scale/0.95 if yoffs > 0: self.ym = self.ym - yoffs/(2*self.scale) def from_global(self, x, y, z): xn = self.dxx * x + self.dxy * y + self.dxz * z yn = self.dyx * x + self.dyy * y + self.dyz * z zn = self.dzx * x + self.dzy * y + self.dzz * z return xn, yn, zn def to_image(self, x, y, z): x, y = (x-self.xm)*self.scale, (y-self.ym)*self.scale return x, self.height - y def from_global_to_image(self, x, y, z): x, y, z = self.from_global(x, y, z) x, y = self.to_image(x, y, z) return x, y def edge_mid_z_key(self, e): x, y, z1 = self.from_global(e[0].x, e[0].y, e[0].z) x, y, z2 = self.from_global(e[1].x, e[1].y, e[1].z) zm = (z1 + z2) * 0.5 return zm def print_vec(self): print '----------------------' print self.dxx, self.dxy, self.dxz print self.dyx, self.dyy, self.dyz print self.dzx, self.dzy, self.dzz print '----------------------' pass #============================================================================== def write_vrml(filename): try: file = open(filename, 'wb') except IOError: print 'Cannot write to file %s' % filename return n_arr = entities_array("NODE") # FIXME Implement vrml output. file.write('#VRML V2.0 utf8\n') file.close() #============================================================================== def random_color(): r, g, b = random.randrange(1, 255), \ random.randrange(1, 255), random.randrange(1, 255) return r, g, b #============================================================================== def write_image(image_fname_format, width): transp = 255 sv = ScreenView(width) #sv.print_vec() sv.view_bounds(); img = Image.new('RGB', (int(sv.width), int(sv.height)), \ (255,255,255, 0) ) img.info['Creator']= 'femio' draw = ImageDraw.Draw(img) font = ImageFont.load_default() # draw cord al = 20 #axis len xn = sv.dxx * 1 + sv.dxy * 0 + sv.dxz * 0 yn = sv.dyx * 1 + sv.dyy * 0 + sv.dyz * 0 draw.line((0 + al , sv.height - al, al*xn +al, sv.height - al*yn - al),\ fill=(255, 0, 0, 255), width=2) xn = sv.dxx * 2 + sv.dxy * 0 + sv.dxz * 0 yn = sv.dyx * 2 + sv.dyy * 0 + sv.dyz * 0 draw.text((al*xn +al, sv.height - al*yn - al),\ 'x', font=font, fill=(255, 0, 0, 255)) xn = sv.dxx * 0 + sv.dxy * 1 + sv.dxz * 0 yn = sv.dyx * 0 + sv.dyy * 1 + sv.dyz * 0 draw.line((0 + al , sv.height - al, al*xn +al, sv.height - al*yn - al),\ fill=(0, 255, 0, 255), width=2) xn = sv.dxx * 0 + sv.dxy * 2 + sv.dxz * 0 yn = sv.dyx * 0 + sv.dyy * 2 + sv.dyz * 0 draw.text((al*xn +al, sv.height - al*yn - al),\ 'y', font=font, fill=(0, 255, 0, 255)) xn = sv.dxx * 0 + sv.dxy * 0 + sv.dxz * 1 yn = sv.dyx * 0 + sv.dyy * 0 + sv.dyz * 1 draw.line((0 + al , sv.height - al, al*xn +al, sv.height - al*yn - al),\ fill=(0, 0, 255, 255), width=2) xn = sv.dxx * 0 + sv.dxy * 0 + sv.dxz * 2 yn = sv.dyx * 0 + sv.dyy * 0 + sv.dyz * 2 draw.text((al*xn +al, sv.height - al*yn - al),\ 'z', font=font, fill=(0, 0, 255, 255)) model_edges = [] color_map = {} for id, sec in entities_array('PROP').iteritems(): color_map[id] = random_color() if sec.feature_lines: model_edges.extend( [ (e[0], e[1], id) for e in sec.feature_lines ] ) del sec.feature_lines sec.feature_lines = None elif sec.type == 'BAR': for bar in sec.elements: nn = bar.nn model_edges.append((nn[0], nn[1], id)) model_edges.sort(key=sv.edge_mid_z_key) for n1, n2, id in model_edges: r, g, b = color_map[id] x1, y1 = sv.from_global_to_image(n1.x, n1.y, n1.z) x2, y2 = sv.from_global_to_image(n2.x, n2.y, n2.z) draw.line((x1, y1, x2, y2), fill=(r, g, b, transp)) del draw for fname, format in image_fname_format: img.save(fname, format) #============================================================================== def reader(): # args parsing parser = optparse.OptionParser(usage=__doc__.strip(), version='%prog '+ __version__) parser.add_option('-v', '--output-vrml', action="store", metavar='ouptut_file', dest="ouptut_vrml_filename", help='write model in VRML format to file') parser.add_option('-p', '--output-png', action="store", metavar='ouptut_file', dest="ouptut_png_filename", help='write model in PNG format to file') parser.add_option('-e', '--output-eps', action="store", metavar='ouptut_file', dest="ouptut_eps_filename", help='write model in EPS format to file') parser.add_option('-w', '--width', action="store", metavar='view_width', dest="view_width", help='width of the image to create in pixels (default %d)' % Width) opts, args = parser.parse_args() if len(args) == 0: raise SystemExit('Error: no input file has been specified') filename = args[0] if not os.path.isfile(filename): raise SystemExit('Error: not a valid filename') # args parsing read_abaqus_file(filename) # done with reading... print "done with reading" populate_entities() print "done with populate_entities" print 'NODES: %d' % len(entities_array('NODE')) print 'SHELLS: %d' % len(entities_array('SHELL')) print 'BARS: %d' % len(entities_array('BAR')) print 'PROPS: %d' % len(entities_array('PROP')) for id, sec in entities_array('PROP').iteritems(): #print '%d: %s, %s: %d' % (id, sec.name, sec.type, \ # len(sec.elements)) sec.calc_feature_lines() width = Width if opts.view_width: if float(opts.view_width) > 0: width = float(opts.view_width) image_formats = [] if opts.ouptut_png_filename: image_formats.append((opts.ouptut_png_filename, 'PNG')) if opts.ouptut_eps_filename: image_formats.append((opts.ouptut_eps_filename, 'EPS')) print 'Please wait. Creating Images...' if len( image_formats ): write_image(image_formats, width) if opts.ouptut_vrml_filename: write_vrml(opts.ouptut_vrml_filename) #============================================================================== if __name__ == "__main__": reader()
Python
import os, time class MyException(Exception): pass def passing(*args): pass def sleeping(s): time.sleep(s) os.environ['ROBOT_THREAD_TESTING'] = str(s) return s def returning(arg): return arg def failing(msg='xxx'): raise MyException, msg if os.name == 'java': from java.lang import Error def java_failing(msg='zzz'): raise Error(msg)
Python
#!/usr/bin/env python """Helper script to run all Robot Framework's unit tests. usage: run_utest.py [options] options: -q, --quiet Minimal output -v, --verbose Verbose output -d, --doc Show test's doc string instead of name and class (implies verbosity) -h, --help Show help """ import unittest import os import sys import re import getopt base = os.path.abspath(os.path.normpath(os.path.split(sys.argv[0])[0])) for path in [ "../src", "../src/robot/libraries", "../src/robot", "../atest/testresources/testlibs" ]: path = os.path.join(base, path.replace('/', os.sep)) if path not in sys.path: sys.path.insert(0, path) testfile = re.compile("^test_.*\.py$", re.IGNORECASE) def get_tests(directory=None): if directory is None: directory = base sys.path.append(directory) tests = [] modules = [] for name in os.listdir(directory): if name.startswith("."): continue fullname = os.path.join(directory, name) if os.path.isdir(fullname): tests.extend(get_tests(fullname)) elif testfile.match(name): modname = os.path.splitext(name)[0] modules.append(__import__(modname)) tests.extend([ unittest.defaultTestLoader.loadTestsFromModule(module) for module in modules ]) return tests def parse_args(argv): docs = 0 verbosity = 1 try: options, args = getopt.getopt(argv, 'hH?vqd', ['help','verbose','quiet','doc']) if len(args) != 0: raise getopt.error, 'no arguments accepted, got %s' % (args) except getopt.error, err: usage_exit(err) for opt, value in options: if opt in ('-h','-H','-?','--help'): usage_exit() if opt in ('-q','--quit'): verbosity = 0 if opt in ('-v', '--verbose'): verbosity = 2 if opt in ('-d', '--doc'): docs = 1 verbosity = 2 return docs, verbosity def usage_exit(msg=None): print __doc__ if msg is None: rc = 251 else: print '\nError:', msg rc = 252 sys.exit(rc) if __name__ == '__main__': docs, vrbst = parse_args(sys.argv[1:]) tests = get_tests() suite = unittest.TestSuite(tests) runner = unittest.TextTestRunner(descriptions=docs, verbosity=vrbst) result = runner.run(suite) rc = len(result.failures) + len(result.errors) if rc > 250: rc = 250 sys.exit(rc)
Python
import os THIS_PATH = os.path.dirname(__file__) GOLDEN_OUTPUT = os.path.join(THIS_PATH, 'golden_suite', 'output.xml') GOLDEN_OUTPUT2 = os.path.join(THIS_PATH, 'golden_suite', 'output2.xml') GOLDEN_JS = os.path.join(THIS_PATH, 'golden_suite', 'expected.js')
Python
#!/usr/bin/env python import fileinput import os import sys import robot from robot.result.jsparser import create_datamodel_from BASEDIR = os.path.dirname(__file__) def run_robot(outputdirectory, testdata, loglevel='INFO'): robot.run(testdata, log='NONE', report='NONE', tagstatlink=['force:http://google.com:<kuukkeli&gt;', 'i*:http://%1/:Title of i%1'], tagdoc=['test:this_is_*my_bold*_test', 'IX:*Combined* & escaped <&lt; tag doc'], tagstatcombine=['fooANDi*:zap', 'i?:IX'], critical=[], noncritical=[], outputdir=outputdirectory, loglevel=loglevel) def create_jsdata(output_xml_file, target): model = create_datamodel_from(output_xml_file) model.set_settings({'logURL': 'log.html', 'reportURL': 'report.html', 'background': {'fail': 'DeepPink'}}) with open(target, 'w') as output: model.write_to(output) def replace_all(file,searchExp,replaceExp): for line in fileinput.input(file, inplace=1): if searchExp in line: line = line.replace(searchExp,replaceExp) sys.stdout.write(line) def create(input, target, targetName, loglevel='INFO'): run_robot(BASEDIR, input, loglevel) create_jsdata('output.xml', target) replace_all(target, 'window.output', 'window.' + targetName) if __name__ == '__main__': create('Suite.txt', 'Suite.js', 'suiteOutput') create('SetupsAndTeardowns.txt', 'SetupsAndTeardowns.js', 'setupsAndTeardownsOutput') create('Messages.txt', 'Messages.js', 'messagesOutput') create('teardownFailure', 'TeardownFailure.js', 'teardownFailureOutput') create(os.path.join('teardownFailure', 'PassingFailing.txt'), 'PassingFailing.js', 'passingFailingOutput') create('TestsAndKeywords.txt', 'TestsAndKeywords.js', 'testsAndKeywordsOutput') create('.', 'allData.js', 'allDataOutput')
Python
import os import sys from distutils.sysconfig import get_python_lib def egg_preinstall(temp_robot_path, scripts): """Updates platform specific startup scripts. Run as part of the easy_install egg creation procedure. This is the only way to get the scripts updated when the easy_install is used. Updates the scripts before the egg is created and therefore the created egg cannot be used at any other machine unless the Python and Jython installations are exactly equal. """ major, minor = sys.version_info[0:2] version = os.path.basename(temp_robot_path) version = version.replace('-', '_').replace('_', '-', 1) egg_name = '%s-py%s.%s.egg' % (version, major, minor) robot_dir = os.path.join(_find_easy_install_dir() or get_python_lib(), egg_name, 'robot') _update_scripts(scripts, temp_robot_path, robot_dir) def generic_install(script_names, script_dir, robot_dir): """Updates given startup scripts. Run as part of the generic installation procedure from 'setup.py' after running 'python setyp.py install'. """ _update_scripts(script_names, script_dir, robot_dir) def windows_binary_install(): """Updates start-up scripts. Executed as the last part of Windows binary installation started by running 'robotframework-<version>.win32.exe'. """ scripts = ['pybot.bat','jybot.bat', 'rebot.bat'] script_dir = os.path.join(sys.prefix, 'Scripts') robot_dir = _get_installation_dir() python_exe = os.path.join(sys.prefix, 'python.exe') # sys.executable doesn't work here try: _update_scripts(scripts, script_dir, robot_dir, python_exe) print '\nInstallation was successful. Happy Roboting!' except Exception, err: print '\nRunning post-install script failed: %s' % err print 'Robot Framework start-up scripts may not work correctly.' def windows_binary_uninstall(): """Deletes Jython compiled files ('*$py.class') This function is executed as part of the Windows binary uninstallation started from 'Add/Remove Programs'. Uninstaller deletes files only if installer has created them and also deletes directories only if they are empty. Thus compiled files created by Jython must be deleted separately. """ for base, dirs, files in os.walk(_get_installation_dir()): for name in files: if name.endswith('$py.class'): path = os.path.join(base, name) try: os.remove(path) except Exception, err: print "Failed to remove Jython compiled file '%s': %s" \ % (path, str(err)) def _find_easy_install_dir(): """Returns the installation directory that easy_install will actually use. This is a workaround because: 1. distutils.sysconfig.get_python_lib() is not aware of easy_install way of managing installation paths. 2. easy_install doesn't pass its install_dir as a command line argument to the setup script. """ try: import inspect f = inspect.currentframe() try: while True: if f is None: return instance = f.f_locals.get("self") if instance and hasattr(instance, "install_dir"): return getattr(instance, "install_dir") f = f.f_back finally: del f except Exception, err: print "Failed to retrieve easy_install_dir: %s" % str(err) def _get_installation_dir(): """Returns installation location. Works also with easy_install.""" try: import robot except ImportError: # Workaround for Windows installer problem with Python 2.6.1 # http://code.google.com/p/robotframework/issues/detail?id=196 class FakeModule: def __getattr__(self, name): raise RuntimeError('Fake module set by robot_postinstall.py') sys.modules['urllib'] = FakeModule() import robot return os.path.dirname(os.path.abspath(robot.__file__)) def _update_scripts(scripts, script_dir, robot_dir, python_exe=sys.executable): print 'Creating Robot Framework runner scripts...' print 'Installation directory:', robot_dir if os.name != 'java': jython_exe, how_found = _find_jython() print 'Python executable:', python_exe print 'Jython executable: %s (%s)' % (jython_exe, how_found) else: jython_exe = python_exe print 'Jython executable:', jython_exe for script in scripts: path = os.path.join(script_dir, script) content = _read(path) for pattern, replace in [ ('[ROBOT_DIR]', robot_dir), ('[PYTHON_EXECUTABLE]', python_exe), ('[JYTHON_EXECUTABLE]', jython_exe) ]: content = content.replace(pattern, replace) _write(path, content) name = os.path.splitext(os.path.basename(script))[0].capitalize() print '%s script: %s' % (name, path) def _read(path): reader = open(path) content = reader.read() reader.close() return content def _write(path, content): os.chmod(path, 0755) writer = open(path, 'w') writer.write(content) writer.close() def _find_jython(): """Tries to find path to Jython and returns it and how it was found. First Jython is searched from PATH, then checked is JYTHON_HOME set and finally Jython installation directory is searched from the system. """ jyexe, search_dirs = _get_platform_jython_search_items() env1, env2 = os.sep == '/' and ('$','') or ('%','%') if _jython_in_path(jyexe): return jyexe, 'in %sPATH%s' % (env1, env2) elif _is_jython_dir(os.environ.get('JYTHON_HOME','notset'), jyexe): jyexe = os.path.join(os.environ['JYTHON_HOME'], jyexe) return jyexe, 'from %sJYTHON_HOME%s' % (env1, env2) return _search_jython_from_dirs(search_dirs, jyexe) def _get_platform_jython_search_items(): """Returns Jython executable and a list of dirs where to search it""" if os.name == 'nt': return 'jython.bat', ['C:\\', 'D:\\'] elif sys.platform.count('cygwin'): return 'jython.bat', ['/cygdrive/c', '/cygdrive/d'] else: return 'jython', ['/usr/local','/opt'] def _jython_in_path(jyexe): out = os.popen('%s --version 2>&1' % jyexe ) found = out.read().startswith('Jython 2.') out.close() return found def _search_jython_from_dirs(search_dirs, jyexe, recursions=1, raise_unless_found=False): excl_dirs = ['WINNT','RECYCLER'] # no need to search from these for dir in search_dirs: try: dirs = [ os.path.join(dir,item) for item in os.listdir(dir) if item not in excl_dirs ] except: # may not have rights to read the dir etc. continue dirs = [ item for item in dirs if os.path.isdir(item) ] matches = [ item for item in dirs if _is_jython_dir(item, jyexe) ] if len(matches) > 0: # if multiple matches, the last one probably the latest version return os.path.join(dir, matches[-1], jyexe), 'found from system' if recursions > 0: try: return _search_jython_from_dirs(dirs, jyexe, recursions-1, True) except ValueError: pass if raise_unless_found: raise ValueError, 'not found' return jyexe, 'default value' def _is_jython_dir(dir, jyexe): if not os.path.basename(os.path.normpath(dir)).lower().startswith('jython'): return False try: items = os.listdir(dir) except: # may not have rights to read the dir etc. return False return jyexe in items and 'jython.jar' in items if __name__ == '__main__': # This is executed when run as a post-install script for Windows binary # distribution. Executed both when installed and when uninstalled from # Add/Remove Programs. For more details see # 5.3 Creating Windows Installers # http://docs.python.org/dist/postinstallation-script.html # # If installation is done using 'easy_install', this script is not run # automatically. It is possible to run this script manually without # arguments to update start-up scripts in that case. if len(sys.argv) < 2 or sys.argv[1] == '-install': windows_binary_install() elif sys.argv[1] == '-remove': windows_binary_uninstall()
Python
#!/usr/bin/env python import sys import os from distutils.core import setup import robot_postinstall execfile(os.path.join(os.path.dirname(__file__),'src','robot','version.py')) # Maximum width in Windows installer seems to be 70 characters -------| DESCRIPTION = """ Robot Framework is a generic test automation framework for acceptance testing and acceptance test-driven development (ATDD). It has easy-to-use tabular test data syntax and utilizes the keyword-driven testing approach. Its testing capabilities can be extended by test libraries implemented either with Python or Java, and users can create new keywords from existing ones using the same syntax that is used for creating test cases. """[1:-1] CLASSIFIERS = """ Development Status :: 5 - Production/Stable License :: OSI Approved :: Apache Software License Operating System :: OS Independent Programming Language :: Python Topic :: Software Development :: Testing """[1:-1] PACKAGES = ['robot', 'robot.api', 'robot.common', 'robot.conf', 'robot.libraries', 'robot.output', 'robot.parsing', 'robot.result', 'robot.running', 'robot.utils', 'robot.variables'] SCRIPT_NAMES = ['pybot', 'jybot', 'rebot'] if os.name == 'java': SCRIPT_NAMES.remove('pybot') def main(): inst_scripts = [ os.path.join('src','bin',name) for name in SCRIPT_NAMES ] if 'bdist_wininst' in sys.argv: inst_scripts = [ script+'.bat' for script in inst_scripts ] inst_scripts.append('robot_postinstall.py') elif os.sep == '\\': inst_scripts = [ script+'.bat' for script in inst_scripts ] if 'bdist_egg' in sys.argv: package_path = os.path.dirname(sys.argv[0]) robot_postinstall.egg_preinstall(package_path, inst_scripts) # Let distutils take care of most of the setup dist = setup( name = 'robotframework', version = get_version(sep='-'), author = 'Robot Framework Developers', author_email = 'robotframework-devel@googlegroups.com', url = 'http://robotframework.org', license = 'Apache License 2.0', description = 'A generic test automation framework', long_description = DESCRIPTION, keywords = 'robotframework testing testautomation atdd', platforms = 'any', classifiers = CLASSIFIERS.splitlines(), package_dir = {'': 'src'}, package_data = {'robot': ['webcontent/*.html', 'webcontent/*.css', 'webcontent/*js', 'webcontent/lib/*.js']}, packages = PACKAGES, scripts = inst_scripts, ) if 'install' in sys.argv: absnorm = lambda path: os.path.abspath(os.path.normpath(path)) script_dir = absnorm(dist.command_obj['install_scripts'].install_dir) module_dir = absnorm(dist.command_obj['install_lib'].install_dir) robot_dir = os.path.join(module_dir, 'robot') script_names = [ os.path.basename(name) for name in inst_scripts ] robot_postinstall.generic_install(script_names, script_dir, robot_dir) if __name__ == "__main__": main()
Python
#!/usr/bin/env python """A script for running Robot Framework's acceptance tests. Usage: run_atests.py interpreter [options] datasource(s) Data sources are paths to directories or files under `robot` folder. Available options are the same that can be used with Robot Framework. See its help (e.g. `pybot --help`) for more information. The specified interpreter is used by acceptance tests under `robot` to run test cases under `testdata`. It can be simply `python` or `jython` (if they are in PATH) or to a path a selected interpreter (e.g. `/usr/bin/python26`). Note that this script itself must always be executed with Python. Examples: $ atest/run_atests.py python --test example atest/robot $ atest/run_atests.py /usr/bin/jython25 atest/robot/tags/tag_doc.txt """ import signal import subprocess import os.path import shutil import glob import sys from zipfile import ZipFile, ZIP_DEFLATED CURDIR = os.path.dirname(os.path.abspath(__file__)) RESULTDIR = os.path.join(CURDIR, 'results') sys.path.insert(0, os.path.join(CURDIR, '..', 'src')) import robot ARGUMENTS = ' '.join(''' --doc RobotSPFrameworkSPacceptanceSPtests --reporttitle RobotSPFrameworkSPTestSPReport --logtitle RobotSPFrameworkSPTestSPLog --metadata Interpreter:%(INTERPRETER)s --metadata Platform:%(PLATFORM)s --variable INTERPRETER:%(INTERPRETER)s --variable STANDALONE_JYTHON:NO --pythonpath %(PYTHONPATH)s --include %(RUNNER)s --outputdir %(OUTPUTDIR)s --output output.xml --report report.html --log log.html --escape space:SP --escape star:STAR --escape paren1:PAR1 --escape paren2:PAR2 --critical regression --noncritical to_be_clarified --noncritical static_html_checks --SuiteStatLevel 3 --TagStatCombine jybotNOTpybot --TagStatCombine pybotNOTjybot --TagStatExclude pybot --TagStatExclude jybot '''.strip().splitlines()) def atests(interpreter, *params): if os.path.isdir(RESULTDIR): shutil.rmtree(RESULTDIR) runner = ('jython' in os.path.basename(interpreter) and 'jybot' or 'pybot') args = ARGUMENTS % { 'PYTHONPATH' : os.path.join(CURDIR, 'resources'), 'OUTPUTDIR' : RESULTDIR, 'INTERPRETER': interpreter, 'PLATFORM': sys.platform, 'RUNNER': runner } if os.name == 'nt': args += ' --exclude nonwindows' if sys.platform == 'darwin' and runner == 'pybot': args += ' --exclude nonmacpython' runner = os.path.join(os.path.dirname(robot.__file__), 'runner.py') command = '%s %s %s %s' % (sys.executable, runner, args, ' '.join(params)) print 'Running command\n%s\n' % command sys.stdout.flush() signal.signal(signal.SIGINT, signal.SIG_IGN) return subprocess.call(command.split()) def buildbot(interpreter, *params): params = '--log NONE --report NONE --SplitOutputs 1'.split() + list(params) rc = atests(interpreter, *params) zippath = os.path.join(RESULTDIR, 'outputs.zip') zipfile = ZipFile(zippath, 'w', compression=ZIP_DEFLATED) for output in glob.glob(os.path.join(RESULTDIR, '*.xml')): zipfile.write(output, os.path.basename(output)) zipfile.close() print 'Archive:', zippath return rc if __name__ == '__main__': if len(sys.argv) == 1 or '--help' in sys.argv: print __doc__ rc = 251 elif sys.argv[1] == 'buildbot': rc = buildbot(*sys.argv[2:]) else: rc = atests(*sys.argv[1:]) sys.exit(rc)
Python
import subprocess import os import signal import ctypes import time class ProcessManager(object): def __init__(self): self._process = None self._stdout = '' self._stderr = '' def start_process(self, *args): args = args[0].split() + list(args[1:]) self._process = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE) self._stdout = '' self._stderr = '' def send_terminate(self, signal_name): if os.name != 'nt': os.kill(self._process.pid, getattr(signal, signal_name)) else: self._set_handler_to_ignore_one_sigint() ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, 0) def _set_handler_to_ignore_one_sigint(self): orig_handler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, lambda signum, frame: signal.signal(signal.SIGINT, orig_handler)) def get_stdout(self): self.wait_until_finished() return self._stdout def get_stderr(self): self.wait_until_finished() return self._stderr def log_stdout_and_stderr(self): print "stdout: ", self._process.stdout.read() print "stderr: ", self._process.stderr.read() def wait_until_finished(self): if self._process.returncode is None: self._stdout, self._stderr = self._process.communicate() def busy_sleep(self, seconds): max_time = time.time() + int(seconds) while time.time() < max_time: pass def get_jython_path(self): jython_home = os.getenv('JYTHON_HOME') if not jython_home: raise RuntimeError('This test requires JYTHON_HOME environment variable to be set.') return '%s -Dpython.home=%s -classpath %s org.python.util.jython' \ % (self._get_java(), jython_home, self._get_classpath(jython_home)) def _get_java(self): java_home = os.getenv('JAVA_HOME') if not java_home: return 'java' if java_home.startswith('"') and java_home.endswith('"'): java_home = java_home[1:-1] return os.path.join(java_home, 'bin', 'java') def _get_classpath(self, jython_home): jython_jar = os.path.join(jython_home, 'jython.jar') return jython_jar + os.pathsep + os.getenv('CLASSPATH','')
Python
from robot.libraries.BuiltIn import BuiltIn BIN = BuiltIn() def start_keyword(*args): if BIN.get_variables()['${TESTNAME}'] == 'Listener Using BuiltIn': BIN.set_test_variable('${SET BY LISTENER}', 'quux')
Python
import os import tempfile import time class ListenAll: ROBOT_LISTENER_API_VERSION = '2' def __init__(self, *path): if not path: path = os.path.join(tempfile.gettempdir(), 'listen_all.txt') else: path = ':'.join(path) self.outfile = open(path, 'w') def start_suite(self, name, attrs): metastr = ' '.join(['%s: %s' % (k, v) for k, v in attrs['metadata'].items()]) self.outfile.write("SUITE START: %s '%s' [%s]\n" % (name, attrs['doc'], metastr)) def start_test(self, name, attrs): tags = [ str(tag) for tag in attrs['tags'] ] self.outfile.write("TEST START: %s '%s' %s\n" % (name, attrs['doc'], tags)) def start_keyword(self, name, attrs): args = [ str(arg) for arg in attrs['args'] ] self.outfile.write("KW START: %s %s\n" % (name, args)) def log_message(self, message): msg, level = self._check_message_validity(message) if level != 'TRACE' and 'Traceback' not in msg: self.outfile.write('LOG MESSAGE: [%s] %s\n' % (level, msg)) def message(self, message): msg, level = self._check_message_validity(message) if 'Settings' in msg: self.outfile.write('Got settings on level: %s\n' % level) def _check_message_validity(self, message): if message['html'] not in ['yes', 'no']: self.outfile.write('Log message has invalid `html` attribute %s' % message['html']) if not message['timestamp'].startswith(str(time.localtime()[0])): self.outfile.write('Log message has invalid timestamp %s' % message['timestamp']) return message['message'], message['level'] def end_keyword(self, name, attrs): self.outfile.write("KW END: %s\n" % (attrs['status'])) def end_test(self, name, attrs): if attrs['status'] == 'PASS': self.outfile.write('TEST END: PASS\n') else: self.outfile.write("TEST END: %s %s\n" % (attrs['status'], attrs['message'])) def end_suite(self, name, attrs): self.outfile.write('SUITE END: %s %s\n' % (attrs['status'], attrs['statistics'])) def output_file(self, path): self._out_file('Output', path) def summary_file(self, path): self._out_file('Summary', path) def report_file(self, path): self._out_file('Report', path) def log_file(self, path): self._out_file('Log', path) def debug_file(self, path): self._out_file('Debug', path) def _out_file(self, name, path): assert os.path.isabs(path) self.outfile.write('%s: %s\n' % (name, os.path.basename(path))) def close(self): self.outfile.write('Closing...\n') self.outfile.close()
Python