Revert "Reformatted all code to match PEP8, optimized imports."

This reverts commit 244be6b

Signed-off-by: Dan Yeaw <dan@yeaw.me>
This commit is contained in:
Dan Yeaw 2018-09-21 10:24:45 -04:00
parent d09cc1d23f
commit 8b686cd62e
No known key found for this signature in database
GPG Key ID: 77A923EF537B61A4
19 changed files with 465 additions and 422 deletions

View File

@ -8,15 +8,17 @@
# All configuration values have a default; values that are commented out # All configuration values have a default; values that are commented out
# serve to show the default. # serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory, # If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the # add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here. # documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.')) #sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ----------------------------------------------------- # -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here. # If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0' #needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions # Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
@ -29,7 +31,7 @@ templates_path = ['_templates']
source_suffix = '.txt' source_suffix = '.txt'
# The encoding of source files. # The encoding of source files.
# source_encoding = 'utf-8-sig' #source_encoding = 'utf-8-sig'
# The master toctree document. # The master toctree document.
master_doc = 'contents' master_doc = 'contents'
@ -49,37 +51,37 @@ release = '0.17.1'
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
# language = None #language = None
# There are two options for replacing |today|: either, you set today to some # There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used: # non-false value, then it is used:
# today = '' #today = ''
# Else, today_fmt is used as the format for a strftime call. # Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y' #today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
exclude_patterns = ['_build'] exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents. # The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None #default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text. # If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True #add_function_parentheses = True
# If true, the current module name will be prepended to all description # If true, the current module name will be prepended to all description
# unit titles (such as .. function::). # unit titles (such as .. function::).
# add_module_names = True #add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the # If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default. # output. They are ignored by default.
# show_authors = False #show_authors = False
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx' pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting. # A list of ignored prefixes for module index sorting.
# modindex_common_prefix = [] #modindex_common_prefix = []
# -- Options for HTML output --------------------------------------------------- # -- Options for HTML output ---------------------------------------------------
@ -91,26 +93,26 @@ html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme # Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the # further. For a list of options available for each theme, see the
# documentation. # documentation.
# html_theme_options = {} #html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory. # Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = [] #html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to # The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation". # "<project> v<release> documentation".
# html_title = None #html_title = None
# A shorter title for the navigation bar. Default is the same as html_title. # A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None #html_short_title = None
# The name of an image file (relative to this directory) to place at the top # The name of an image file (relative to this directory) to place at the top
# of the sidebar. # of the sidebar.
# html_logo = None #html_logo = None
# The name of an image file (within the static path) to use as favicon of the # The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
# html_favicon = None #html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,
@ -119,85 +121,86 @@ html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format. # using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y' #html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to # If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities. # typographically correct entities.
# html_use_smartypants = True #html_use_smartypants = True
# Custom sidebar templates, maps document names to template names. # Custom sidebar templates, maps document names to template names.
# html_sidebars = {} #html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to # Additional templates that should be rendered to pages, maps page names to
# template names. # template names.
# html_additional_pages = {} #html_additional_pages = {}
# If false, no module index is generated. # If false, no module index is generated.
# html_domain_indices = True #html_domain_indices = True
# If false, no index is generated. # If false, no index is generated.
# html_use_index = True #html_use_index = True
# If true, the index is split into individual pages for each letter. # If true, the index is split into individual pages for each letter.
# html_split_index = False #html_split_index = False
# If true, links to the reST sources are added to the pages. # If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True #html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True #html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True #html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will # If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the # contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served. # base URL from which the finished HTML is served.
# html_use_opensearch = '' #html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml"). # This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None #html_file_suffix = None
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'Gaphordoc' htmlhelp_basename = 'Gaphordoc'
# -- Options for LaTeX output -------------------------------------------------- # -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4'). # The paper size ('letter' or 'a4').
# latex_paper_size = 'letter' #latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt'). # The font size ('10pt', '11pt' or '12pt').
# latex_font_size = '10pt' #latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples # Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]). # (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [ latex_documents = [
('contents', 'Gaphor.tex', u'Gaphor Documentation', ('contents', 'Gaphor.tex', u'Gaphor Documentation',
u'Gaphor development team', 'manual'), u'Gaphor development team', 'manual'),
] ]
# The name of an image file (relative to this directory) to place at the top of # The name of an image file (relative to this directory) to place at the top of
# the title page. # the title page.
# latex_logo = None #latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts, # For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters. # not chapters.
# latex_use_parts = False #latex_use_parts = False
# If true, show page references after internal links. # If true, show page references after internal links.
# latex_show_pagerefs = False #latex_show_pagerefs = False
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
# latex_show_urls = False #latex_show_urls = False
# Additional stuff for the LaTeX preamble. # Additional stuff for the LaTeX preamble.
# latex_preamble = '' #latex_preamble = ''
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
# latex_appendices = [] #latex_appendices = []
# If false, no module index is generated. # If false, no module index is generated.
# latex_domain_indices = True #latex_domain_indices = True
# -- Options for manual page output -------------------------------------------- # -- Options for manual page output --------------------------------------------

View File

@ -3,21 +3,21 @@
"""This script list classes and optionally attributes from UML model """This script list classes and optionally attributes from UML model
created with Gaphor.""" created with Gaphor."""
import optparse
import sys import sys
import optparse
import gaphor.UML as UML
from gaphor import Application from gaphor import Application
import gaphor.UML as UML
# Setup command line options. #Setup command line options.
usage = 'usage: %prog [options] file.gaphor' usage = 'usage: %prog [options] file.gaphor'
parser = optparse.OptionParser(usage=usage) parser = optparse.OptionParser(usage=usage)
parser.add_option('-a', \ parser.add_option('-a',\
'--attributes', \ '--attributes',\
dest='attrs', \ dest='attrs',\
action='store_true', \ action='store_true',\
help='Print class attributes') help='Print class attributes')
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
@ -26,25 +26,26 @@ if len(args) != 1:
parser.print_help() parser.print_help()
sys.exit(1) sys.exit(1)
# The model file to load. #The model file to load.
model = args[0] model = args[0]
# Create the Gaphor application object. #Create the Gaphor application object.
Application.init() Application.init()
# Get services we need. #Get services we need.
element_factory = Application.get_service('element_factory') element_factory = Application.get_service('element_factory')
file_manager = Application.get_service('file_manager') file_manager = Application.get_service('file_manager')
# Load model from file. #Load model from file.
file_manager.load(model) file_manager.load(model)
# Find all classes using factory select. #Find all classes using factory select.
for cls in element_factory.select(lambda e: e.isKindOf(UML.Class)): for cls in element_factory.select(lambda e: e.isKindOf(UML.Class)):
print 'Found class %s' % cls.name print 'Found class %s' % cls.name
if options.attrs: if options.attrs:
for attr in cls.ownedAttribute: for attr in cls.ownedAttribute:
print ' Attribute: %s' % attr.name print ' Attribute: %s' % attr.name

View File

@ -14,9 +14,8 @@ the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools. This file can also be run as a script to install or upgrade setuptools.
""" """
import sys import sys
DEFAULT_VERSION = "0.6c11" DEFAULT_VERSION = "0.6c11"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = { md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
@ -64,28 +63,23 @@ md5_data = {
} }
import sys, os import sys, os
try: from hashlib import md5
try: except ImportError: from md5 import md5
from hashlib import md5
except ImportError:
from md5 import md5
def _validate_md5(egg_name, data): def _validate_md5(egg_name, data):
if egg_name in md5_data: if egg_name in md5_data:
digest = md5(data).hexdigest() digest = md5(data).hexdigest()
if digest != md5_data[egg_name]: if digest != md5_data[egg_name]:
print >> sys.stderr, ( print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)" "md5 validation of %s failed! (Possible download problem?)"
% egg_name % egg_name
) )
sys.exit(2) sys.exit(2)
return data return data
def use_setuptools( def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15 download_delay=15
): ):
"""Automatically find/download setuptools and make it available on sys.path """Automatically find/download setuptools and make it available on sys.path
@ -99,39 +93,34 @@ def use_setuptools(
an attempt to abort the calling script. an attempt to abort the calling script.
""" """
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download(): def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay) egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg) sys.path.insert(0, egg)
import setuptools; import setuptools; setuptools.bootstrap_install_from = egg
setuptools.bootstrap_install_from = egg
try: try:
import pkg_resources import pkg_resources
except ImportError: except ImportError:
return do_download() return do_download()
try: try:
pkg_resources.require("setuptools>=" + version); pkg_resources.require("setuptools>="+version); return
return
except pkg_resources.VersionConflict, e: except pkg_resources.VersionConflict, e:
if was_imported: if was_imported:
print >> sys.stderr, ( print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n" "The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n" "can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'." " a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)" "\n\n(Currently using %r)"
) % (version, e.args[0]) ) % (version, e.args[0])
sys.exit(2) sys.exit(2)
else: else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download() return do_download()
except pkg_resources.DistributionNotFound: except pkg_resources.DistributionNotFound:
return do_download() return do_download()
def download_setuptools( def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay=15 delay = 15
): ):
"""Download setuptools from a specified location and return its filename """Download setuptools from a specified location and return its filename
@ -140,8 +129,8 @@ def download_setuptools(
with a '/'). `to_dir` is the directory where the egg will be downloaded. with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt. `delay` is the number of seconds to pause before an actual download attempt.
""" """
import urllib2 import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version, sys.version[:3]) egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name) saveto = os.path.join(to_dir, egg_name)
src = dst = None src = dst = None
@ -163,23 +152,54 @@ I will start the download in %d seconds.
and place it in this directory before rerunning this script.) and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""", ---------------------------------------------------------------------------""",
version, download_base, delay, url version, download_base, delay, url
); ); from time import sleep; sleep(delay)
from time import sleep;
sleep(delay)
log.warn("Downloading %s", url) log.warn("Downloading %s", url)
src = urllib2.urlopen(url) src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file # Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted. # if the download is interrupted.
data = _validate_md5(egg_name, src.read()) data = _validate_md5(egg_name, src.read())
dst = open(saveto, "wb"); dst = open(saveto,"wb"); dst.write(data)
dst.write(data)
finally: finally:
if src: src.close() if src: src.close()
if dst: dst.close() if dst: dst.close()
return os.path.realpath(saveto) return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION): def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall""" """Install or upgrade setuptools and EasyInstall"""
try: try:
@ -188,21 +208,21 @@ def main(argv, version=DEFAULT_VERSION):
egg = None egg = None
try: try:
egg = download_setuptools(version, delay=0) egg = download_setuptools(version, delay=0)
sys.path.insert(0, egg) sys.path.insert(0,egg)
from setuptools.command.easy_install import main from setuptools.command.easy_install import main
return main(list(argv) + [egg]) # we're done here return main(list(argv)+[egg]) # we're done here
finally: finally:
if egg and os.path.exists(egg): if egg and os.path.exists(egg):
os.unlink(egg) os.unlink(egg)
else: else:
if setuptools.__version__ == '0.0.1': if setuptools.__version__ == '0.0.1':
print >> sys.stderr, ( print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n" "You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script." "remove it from your system entirely before rerunning this script."
) )
sys.exit(2) sys.exit(2)
req = "setuptools>=" + version req = "setuptools>="+version
import pkg_resources import pkg_resources
try: try:
pkg_resources.require(req) pkg_resources.require(req)
@ -211,17 +231,16 @@ def main(argv, version=DEFAULT_VERSION):
from setuptools.command.easy_install import main from setuptools.command.easy_install import main
except ImportError: except ImportError:
from easy_install import main from easy_install import main
main(list(argv) + [download_setuptools(delay=0)]) main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit sys.exit(0) # try to force an exit
else: else:
if argv: if argv:
from setuptools.command.easy_install import main from setuptools.command.easy_install import main
main(argv) main(argv)
else: else:
print "Setuptools version", version, "or greater has been installed." print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames): def update_md5(filenames):
"""Update our built-in md5 registry""" """Update our built-in md5 registry"""
@ -229,7 +248,7 @@ def update_md5(filenames):
for name in filenames: for name in filenames:
base = os.path.basename(name) base = os.path.basename(name)
f = open(name, 'rb') f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest() md5_data[base] = md5(f.read()).hexdigest()
f.close() f.close()
@ -239,23 +258,27 @@ def update_md5(filenames):
import inspect import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__]) srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); f = open(srcfile, 'rb'); src = f.read(); f.close()
src = f.read();
f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src) match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match: if not match:
print >> sys.stderr, "Internal error!" print >>sys.stderr, "Internal error!"
sys.exit(2) sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):] src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile, 'w') f = open(srcfile,'w')
f.write(src) f.write(src)
f.close() f.close()
if __name__ == '__main__': if __name__=='__main__':
if len(sys.argv) > 2 and sys.argv[1] == '--md5update': if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:]) update_md5(sys.argv[2:])
else: else:
main(sys.argv[1:]) main(sys.argv[1:])

View File

@ -1,7 +1,6 @@
import os import os
import sys import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# from . import uml2 as UML #from . import uml2 as UML
# from .diagram import Diagram #from .diagram import Diagram

View File

@ -21,7 +21,6 @@
Recursive attribute access functions. Recursive attribute access functions.
""" """
def rgetattr(obj, attr): def rgetattr(obj, attr):
""" """
Get named attribute from an object, i.e. getattr(obj, 'a.a') is Get named attribute from an object, i.e. getattr(obj, 'a.a') is
@ -75,4 +74,5 @@ def rsetattr(obj, attr, val):
obj = getattr(obj, name) obj = getattr(obj, name)
setattr(obj, attrs[-1], val) setattr(obj, attrs[-1], val)
# vim:sw=4:et:ai # vim:sw=4:et:ai

View File

@ -15,3 +15,4 @@ Plugins can be registered in Gaphor by declaring them as service entry point::
There is a thin line between a service and a plugin. A service typically performs some basic need for the applications (such as the element factory or the undo mechanism). A plugin is more of an add-on. For example a plugin can depend on external libraries or provide a cross-over function between two applications. There is a thin line between a service and a plugin. A service typically performs some basic need for the applications (such as the element factory or the undo mechanism). A plugin is more of an add-on. For example a plugin can depend on external libraries or provide a cross-over function between two applications.
""" """

View File

@ -408,7 +408,7 @@ __file__
""" """
pythonbuiltinfunctions = pythonbuiltinfunctions_txt.split() pythonbuiltinfunctions = pythonbuiltinfunctions_txt.split()
javakeywords_txt = """ javakeywords_txt = """
abstract abstract
boolean boolean
break break
@ -464,7 +464,11 @@ strictfp
""" """
javakeywords = javakeywords_txt.split() javakeywords = javakeywords_txt.split()
delphikeywords_txt = """
delphikeywords_txt = """
And And
Array Array
As As
@ -522,8 +526,7 @@ With
Xor Xor
""" """
delphikeywords = delphikeywords_txt.split() delphikeywords = delphikeywords_txt.split()
delphikeywords = [x.lower() for x in delphikeywords = [ x.lower() for x in delphikeywords ] # delphi is case insensitive, so convert everything to lowercase for comparisons
delphikeywords] # delphi is case insensitive, so convert everything to lowercase for comparisons
# See Token.py in \python2x\Lib # See Token.py in \python2x\Lib
@ -586,3 +589,4 @@ TILDE = 32
VBAR = 18 VBAR = 18
VBAREQUAL = 43 VBAREQUAL = 43
""" """

View File

@ -7,8 +7,8 @@ dependencies.
VERSION = '0.17.1' VERSION = '0.17.1'
import os
import sys import sys
sys.path.insert(0, '.') sys.path.insert(0, '.')
from ez_setup import use_setuptools from ez_setup import use_setuptools
@ -16,9 +16,10 @@ from ez_setup import use_setuptools
use_setuptools() use_setuptools()
from setuptools import setup, find_packages from setuptools import setup, find_packages
# try: from distutils.cmd import Command
# from sphinx.setup_command import BuildDoc #try:
# except ImportError, e: #from sphinx.setup_command import BuildDoc
#except ImportError, e:
# print 'No Sphynx found' # print 'No Sphynx found'
from utils.command.build_mo import build_mo from utils.command.build_mo import build_mo
@ -27,24 +28,25 @@ from utils.command.build_uml import build_uml
from utils.command.install_lib import install_lib from utils.command.install_lib import install_lib
from utils.command.run import run from utils.command.run import run
LINGUAS = ['ca', 'es', 'fr', 'nl', 'sv'] LINGUAS = [ 'ca', 'es', 'fr', 'nl', 'sv' ]
# Wrap setuptools' build_py command, so we're sure build_uml is performed # Wrap setuptools' build_py command, so we're sure build_uml is performed
# before the build_py code. # before the build_py code.
from setuptools.command.build_py import build_py from setuptools.command.build_py import build_py
class build_py_with_sub_commands(build_py): class build_py_with_sub_commands(build_py):
def run(self): def run(self):
for cmd_name in self.get_sub_commands(): for cmd_name in self.get_sub_commands():
self.run_command(cmd_name) self.run_command(cmd_name)
build_py.run(self) build_py.run(self)
build_py_with_sub_commands.sub_commands.append(('build_uml', None)) build_py_with_sub_commands.sub_commands.append(('build_uml', None))
setup( setup(
name='gaphor', name='gaphor',
version=VERSION, version=VERSION,
@ -58,7 +60,7 @@ Gaphor is a UML modeling tool written in Python.
It uses the GTK+ environment for user interaction. It uses the GTK+ environment for user interaction.
""", """,
classifiers=[ classifiers = [
'Development Status :: 5 - Production/Stable', 'Development Status :: 5 - Production/Stable',
'Environment :: X11 Applications :: GTK', 'Environment :: X11 Applications :: GTK',
'Intended Audience :: Developers', 'Intended Audience :: Developers',
@ -74,37 +76,37 @@ It uses the GTK+ environment for user interaction.
'Topic :: Software Development :: Documentation', 'Topic :: Software Development :: Documentation',
], ],
keywords='model modeling modelling uml diagram python tool', keywords = 'model modeling modelling uml diagram python tool',
packages=find_packages(exclude=['ez_setup', 'utils*']), packages = find_packages(exclude=['ez_setup', 'utils*']),
include_package_data=True, include_package_data = True,
install_requires=[ install_requires = [
# 'PyGTK >= 2.8.0', - Exclude, since it will not build anyway # 'PyGTK >= 2.8.0', - Exclude, since it will not build anyway
'gaphas >= 0.7.2', 'gaphas >= 0.7.2',
'etk.docking >= 0.2', 'etk.docking >= 0.2',
'zope.component >= 3.4.0', # - won't compile on windows. 'zope.component >= 3.4.0', # - won't compile on windows.
], ],
zip_safe=False, zip_safe = False,
# test_suite = 'nose.collector', #test_suite = 'nose.collector',
entry_points={ entry_points = {
'console_scripts': [ 'console_scripts': [
'gaphor = gaphor:main', 'gaphor = gaphor:main',
'gaphorconvert = gaphor.tools.gaphorconvert:main', 'gaphorconvert = gaphor.tools.gaphorconvert:main',
], ],
'gaphor.services': [ 'gaphor.services': [
'component_registry = gaphor.services.componentregistry:ZopeComponentRegistry', 'component_registry = gaphor.services.componentregistry:ZopeComponentRegistry',
# 'event_dispatcher = gaphor.services.eventdispatcher:EventDispatcher', #'event_dispatcher = gaphor.services.eventdispatcher:EventDispatcher',
'adapter_loader = gaphor.services.adapterloader:AdapterLoader', 'adapter_loader = gaphor.services.adapterloader:AdapterLoader',
'properties = gaphor.services.properties:Properties', 'properties = gaphor.services.properties:Properties',
'undo_manager = gaphor.services.undomanager:UndoManager', 'undo_manager = gaphor.services.undomanager:UndoManager',
'element_factory = gaphor.UML.elementfactory:ElementFactoryService', 'element_factory = gaphor.UML.elementfactory:ElementFactoryService',
'file_manager = gaphor.services.filemanager:FileManager', 'file_manager = gaphor.services.filemanager:FileManager',
# 'backup_service = gaphor.services.backupservice:BackupService', #'backup_service = gaphor.services.backupservice:BackupService',
'diagram_export_manager = gaphor.services.diagramexportmanager:DiagramExportManager', 'diagram_export_manager = gaphor.services.diagramexportmanager:DiagramExportManager',
'action_manager = gaphor.services.actionmanager:ActionManager', 'action_manager = gaphor.services.actionmanager:ActionManager',
'ui_manager = gaphor.services.actionmanager:UIManager', 'ui_manager = gaphor.services.actionmanager:UIManager',
@ -112,17 +114,17 @@ It uses the GTK+ environment for user interaction.
'copy = gaphor.services.copyservice:CopyService', 'copy = gaphor.services.copyservice:CopyService',
'sanitizer = gaphor.services.sanitizerservice:SanitizerService', 'sanitizer = gaphor.services.sanitizerservice:SanitizerService',
'element_dispatcher = gaphor.services.elementdispatcher:ElementDispatcher', 'element_dispatcher = gaphor.services.elementdispatcher:ElementDispatcher',
# 'property_dispatcher = gaphor.services.propertydispatcher:PropertyDispatcher', #'property_dispatcher = gaphor.services.propertydispatcher:PropertyDispatcher',
'xmi_export = gaphor.plugins.xmiexport:XMIExport', 'xmi_export = gaphor.plugins.xmiexport:XMIExport',
'diagram_layout = gaphor.plugins.diagramlayout:DiagramLayout', 'diagram_layout = gaphor.plugins.diagramlayout:DiagramLayout',
'pynsource = gaphor.plugins.pynsource:PyNSource', 'pynsource = gaphor.plugins.pynsource:PyNSource',
# 'check_metamodel = gaphor.plugins.checkmetamodel:CheckModelWindow', #'check_metamodel = gaphor.plugins.checkmetamodel:CheckModelWindow',
# 'live_object_browser = gaphor.plugins.liveobjectbrowser:LiveObjectBrowser', #'live_object_browser = gaphor.plugins.liveobjectbrowser:LiveObjectBrowser',
'alignment = gaphor.plugins.alignment:Alignment', 'alignment = gaphor.plugins.alignment:Alignment',
'help = gaphor.services.helpservice:HelpService', 'help = gaphor.services.helpservice:HelpService',
], ],
'gaphor.uicomponents': [ 'gaphor.uicomponents': [
# 'mainwindow = gaphor.ui.mainwindow:MainWindow', #'mainwindow = gaphor.ui.mainwindow:MainWindow',
'namespace = gaphor.ui.mainwindow:Namespace', 'namespace = gaphor.ui.mainwindow:Namespace',
'toolbox = gaphor.ui.mainwindow:Toolbox', 'toolbox = gaphor.ui.mainwindow:Toolbox',
'consolewindow = gaphor.ui.consolewindow:ConsoleWindow', 'consolewindow = gaphor.ui.consolewindow:ConsoleWindow',
@ -130,32 +132,32 @@ It uses the GTK+ environment for user interaction.
], ],
}, },
cmdclass={ cmdclass = {
'build_py': build_py_with_sub_commands, 'build_py': build_py_with_sub_commands,
'build_uml': build_uml, 'build_uml': build_uml,
# 'build_doc': BuildDoc, #'build_doc': BuildDoc,
'build_mo': build_mo, 'build_mo': build_mo,
'build_pot': build_pot, 'build_pot': build_pot,
'install_lib': install_lib, 'install_lib': install_lib,
'run': run, 'run': run,
}, },
setup_requires=[ setup_requires = [
# 'Sphinx >= 1.0.6', #'Sphinx >= 1.0.6',
'nose >= 0.10.4', 'nose >= 0.10.4',
'setuptools-git >= 0.3.4' 'setuptools-git >= 0.3.4'
], ],
test_suite='nose.collector', test_suite = 'nose.collector',
options=dict( options = dict(
build_pot=dict( build_pot = dict(
all_linguas=','.join(LINGUAS), all_linguas = ','.join(LINGUAS),
), ),
build_mo=dict( build_mo = dict(
all_linguas=','.join(LINGUAS), all_linguas = ','.join(LINGUAS),
), ),
), ),
) )
# vim:sw=4:et:ai # vim:sw=4:et:ai

View File

@ -11,9 +11,9 @@ import sys
sys.path.append("..") sys.path.append("..")
done = [object] from gaphor.UML import *
done = [ object ]
def print_vars(cls): def print_vars(cls):
global done global done
done.append(cls) done.append(cls)
@ -22,9 +22,8 @@ def print_vars(cls):
for key in dict.keys(): for key in dict.keys():
print "\t" + key + ":", str(dict[key]) print "\t" + key + ":", str(dict[key])
for base in cls.__bases__: for base in cls.__bases__:
if base not in done: if base not in done:
print_vars(base) print_vars(base)
args = sys.argv[1:] args = sys.argv[1:]

View File

@ -4,14 +4,14 @@
Generate .mo files from po files. Generate .mo files from po files.
""" """
import os.path
from distutils.core import Command from distutils.core import Command
from distutils.dep_util import newer from distutils.dep_util import newer
import os.path
import msgfmt import msgfmt
class build_mo(Command): class build_mo(Command):
description = 'Create .mo files from .po files' description = 'Create .mo files from .po files'
# List of option tuples: long name, short name (None if no short # List of option tuples: long name, short name (None if no short
@ -20,16 +20,16 @@ class build_mo(Command):
'Directory to build locale files'), 'Directory to build locale files'),
('force', 'f', 'Force creation of .mo files'), ('force', 'f', 'Force creation of .mo files'),
('all-linguas', None, ''), ('all-linguas', None, ''),
] ]
boolean_options = ['force'] boolean_options = ['force']
def initialize_options(self): def initialize_options (self):
self.build_dir = None self.build_dir = None
self.force = None self.force = None
self.all_linguas = None self.all_linguas = None
def finalize_options(self): def finalize_options (self):
self.set_undefined_options('build', self.set_undefined_options('build',
('force', 'force')) ('force', 'force'))
if self.build_dir is None: if self.build_dir is None:
@ -39,23 +39,24 @@ class build_mo(Command):
self.all_linguas = self.all_linguas.split(',') self.all_linguas = self.all_linguas.split(',')
def run(self): def run (self):
"""Run msgfmt.make() on all_linguas.""" """Run msgfmt.make() on all_linguas."""
if not self.all_linguas: if not self.all_linguas:
return return
for lingua in self.all_linguas: for lingua in self.all_linguas:
pofile = os.path.join('po', lingua + '.po') pofile = os.path.join('po', lingua + '.po')
outdir = os.path.join(self.build_dir, lingua, 'LC_MESSAGES') outdir = os.path.join(self.build_dir, lingua, 'LC_MESSAGES')
self.mkpath(outdir) self.mkpath(outdir)
outfile = os.path.join(outdir, 'gaphor.mo') outfile = os.path.join(outdir, 'gaphor.mo')
if self.force or newer(pofile, outfile): if self.force or newer(pofile, outfile):
print 'converting %s -> %s' % (pofile, outfile) print 'converting %s -> %s' % (pofile, outfile)
msgfmt.make(pofile, outfile) msgfmt.make(pofile, outfile)
else: else:
print 'not converting %s (output up-to-date)' % pofile print 'not converting %s (output up-to-date)' % pofile
from distutils.command.build import build from distutils.command.build import build
build.sub_commands.append(('build_mo', None)) build.sub_commands.append(('build_mo', None))

View File

@ -23,20 +23,18 @@ Build a PO template (for i18n) and update the .po files to reflect
the last changes. the last changes.
""" """
import os.path
import sys
from distutils.core import Command from distutils.core import Command
from commands import getstatus
import sys, os.path
import pygettext import pygettext
# from pygettext.main(): # from pygettext.main():
class Options: class Options:
# constants # constants
GNU = 1 GNU = 1
SOLARIS = 2 SOLARIS = 2
# defaults # defaults
extractall = 0 # FIXME: currently this option has no effect at all. extractall = 0 # FIXME: currently this option has no effect at all.
keywords = [] keywords = []
writelocations = 1 writelocations = 1
locationstyle = GNU locationstyle = GNU
@ -49,165 +47,166 @@ class Options:
class build_pot(Command): class build_pot(Command):
description = "Generate a .po template file (.pot) from python source files"
description="Generate a .po template file (.pot) from python source files"
user_options = [('msgmerge=', None, 'location of the msgmerge program'), user_options = [('msgmerge=', None, 'location of the msgmerge program'),
('extract-all', 'a', ''), ('extract-all', 'a', ''),
('default-domain=', 'd', ''), ('default-domain=', 'd', ''),
('escape', 'E', ''), ('escape', 'E', ''),
('docstrings', 'D', ''), ('docstrings', 'D', ''),
('keyword=', 'k', 'Comma separated list of keywords'), ('keyword=', 'k', 'Comma separated list of keywords'),
('no-default-keywords', 'K', ''), ('no-default-keywords', 'K', ''),
('add-location', 'n', ''), ('add-location', 'n', ''),
('no-location', None, ''), ('no-location', None, ''),
('style=', 'S', 'POT file style "gnu" or "solaris"'), ('style=', 'S', 'POT file style "gnu" or "solaris"'),
('output=', 'o', ''), ('output=', 'o', ''),
('output-dir=', 'p', ''), ('output-dir=', 'p', ''),
('width=', 'w', ''), ('width=', 'w', ''),
('exclude-file=', 'x', ''), ('exclude-file=', 'x', ''),
('all-linguas=', None, ''), ('all-linguas=', None, ''),
# ('no-docstrings=', 'X', ''), #('no-docstrings=', 'X', ''),
] ]
boolean_options = ['extract-all', 'escape', 'docstrings', boolean_options = [ 'extract-all', 'escape', 'docstrings',
'no-default-keywords', 'add-location', 'no-default-keywords', 'add-location',
'no-location', 'no-docstrings'] 'no-location', 'no-docstrings' ]
# constants # constants
GNU = 1 GNU = 1
SOLARIS = 2 SOLARIS = 2
def initialize_options(self): def initialize_options(self):
self.podir = 'po' self.podir = 'po'
self.msgmerge = 'msgmerge' self.msgmerge = 'msgmerge'
self.options = Options() self.options = Options()
# defaults for variable parsing: # defaults for variable parsing:
self.escape = 0 self.escape = 0
self.width = 78 self.width = 78
self.extract_all = 0 # doesn't do anything yet self.extract_all = 0 # doesn't do anything yet
self.default_domain = None self.default_domain = None
self.keyword = None self.keyword = None
self.no_default_keywords = 0 self.no_default_keywords = 0
self.no_location = 0 self.no_location = 0
self.style = None self.style = None
self.output = None self.output = None
self.output_dir = None self.output_dir = None
self.docstrings = 0 self.docstrings = 0
self.exclude_file = None self.exclude_file = None
# self.no_docstrings = None #self.no_docstrings = None
self.all_linguas = [] self.all_linguas = []
def finalize_options(self): def finalize_options(self):
options = self.options options = self.options
self.name = self.distribution.get_name() self.name = self.distribution.get_name()
# Build default options for the TokenEater # Build default options for the TokenEater
if self.default_domain: if self.default_domain:
self.output = self.default_domain + '.pot' self.output = self.default_domain + '.pot'
if self.keyword: if self.keyword:
options.keywords.extend(self.keyword.split(',')) options.keywords.extend(self.keyword.split(','))
if self.no_default_keywords: if self.no_default_keywords:
options.keywords = [] options.keywords = [ ]
if self.no_location: if self.no_location:
options.writelocations = 0 options.writelocations = 0
if self.style: if self.style:
if self.style == 'gnu': if self.style == 'gnu':
options.locationstyle = self.GNU options.locationstyle = self.GNU
elif self.style == 'solaris': elif self.style == 'solaris':
options.locationstyle = self.SOLARIS options.locationstyle = self.SOLARIS
else: else:
raise SystemExit, 'Invalid value for --style: %s' % self.style raise SystemExit, 'Invalid value for --style: %s' % self.style
if not self.output: if not self.output:
self.output = self.distribution.get_name() + '.pot' self.output = self.distribution.get_name() + '.pot'
if not self.output_dir: if not self.output_dir:
self.output_dir = self.podir self.output_dir = self.podir
if self.docstrings: if self.docstrings:
options.docstrings = 1 options.docstrings = 1
options.width = int(self.width) options.width = int(self.width)
if self.exclude_file: if self.exclude_file:
try: try:
fp = open(self.exclude_file) fp = open(self.exclude_file)
options.toexclude = fp.readlines() options.toexclude = fp.readlines()
fp.close() fp.close()
except IOError: except IOError:
raise SystemExit, "Can't read --exclude-file: %s" % self.exclude_file raise SystemExit, "Can't read --exclude-file: %s" % self.exclude_file
# skip: self.no_docstrings # skip: self.no_docstrings
if self.all_linguas: if self.all_linguas:
self.all_linguas = self.all_linguas.split(',') self.all_linguas = self.all_linguas.split(',')
# calculate escapes # calculate escapes
pygettext.make_escapes(self.escape) pygettext.make_escapes(self.escape)
# calculate all keywords # calculate all keywords
options.keywords.append('_') options.keywords.append('_')
if self.output_dir: if self.output_dir:
self.output = os.path.join(self.output_dir, self.output) self.output = os.path.join(self.output_dir, self.output)
self.packages = self.distribution.packages self.packages = self.distribution.packages
#self.all_linguas = self.distribution.get_all_linguas()
# self.all_linguas = self.distribution.get_all_linguas() #self.all_linguas = self.distribution.options['po']['all_linguas']
# self.all_linguas = self.distribution.options['po']['all_linguas']
def run(self): def run(self):
self.create_pot_file() self.create_pot_file()
self.merge_files() self.merge_files()
def create_pot_file(self): def create_pot_file(self):
"""
Create a new .pot file. This is basically a rework of the
main function of pygettext.
""" """
Create a new .pot file. This is basically a rework of the import glob
main function of pygettext. import tokenize
""" source_files = []
import glob for p in self.packages:
import tokenize pathlist = p.split('.')
source_files = [] path = apply(os.path.join, pathlist)
for p in self.packages: source_files.extend(glob.glob(os.path.join(path, '*.py')))
pathlist = p.split('.')
path = apply(os.path.join, pathlist)
source_files.extend(glob.glob(os.path.join(path, '*.py')))
# slurp through all the files # slurp through all the files
eater = pygettext.TokenEater(self.options) eater = pygettext.TokenEater(self.options)
for filename in source_files: for filename in source_files:
if self.verbose: if self.verbose:
print 'Working on %s' % filename print 'Working on %s' % filename
fp = open(filename) fp = open(filename)
try: try:
eater.set_filename(filename) eater.set_filename(filename)
try: try:
tokenize.tokenize(fp.readline, eater) tokenize.tokenize(fp.readline, eater)
except tokenize.TokenError, e: except tokenize.TokenError, e:
print '%s: %s, line %d, column %d' % ( print '%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1]) e[0], filename, e[1][0], e[1][1])
finally: finally:
fp.close() fp.close()
# write the output # write the output
if self.output == '-': if self.output == '-':
fp = sys.stdout fp = sys.stdout
else: else:
fp = open(self.output, 'w') fp = open(self.output, 'w')
try: try:
eater.write(fp) eater.write(fp)
finally: finally:
if fp is not sys.stdout: if fp is not sys.stdout:
fp.close() fp.close()
def merge_files(self): def merge_files(self):
if not self.all_linguas: if not self.all_linguas:
return return
for lingua in self.all_linguas: for lingua in self.all_linguas:
d = {'msgmerge': self.msgmerge, d = { 'msgmerge': self.msgmerge,
'po': os.path.join(self.output_dir, lingua + '.po'), 'po': os.path.join(self.output_dir, lingua + '.po'),
'pot': self.output 'pot': self.output
} }
if self.verbose: if self.verbose:
sys.stdout.write('Merging %(pot)s and %(po)s ' % d) sys.stdout.write('Merging %(pot)s and %(po)s ' % d)
sys.stdout.flush() sys.stdout.flush()
res = os.system('%(msgmerge)s %(po)s %(pot)s -o %(po)s' % d) res = os.system('%(msgmerge)s %(po)s %(pot)s -o %(po)s' % d)
if res: if res:
SystemExit, 'error while running msgmerge.' SystemExit, 'error while running msgmerge.'

View File

@ -26,32 +26,34 @@ Also a distutils tool, build_uml, is provided.
import os.path import os.path
from distutils.core import Command from distutils.core import Command
from distutils.dep_util import newer
from distutils.util import byte_compile from distutils.util import byte_compile
from distutils.dep_util import newer
class build_uml(Command): class build_uml(Command):
description = "Generate gaphor/UML/uml2.py." description = "Generate gaphor/UML/uml2.py."
user_options = [ user_options = [
('build-lib=', 'b', "build directory (where to install from)"), ('build-lib=','b', "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"), ('force', 'f', "force installation (overwrite existing files)"),
] ]
boolean_options = ['force'] boolean_options = [ 'force' ]
def initialize_options(self): def initialize_options(self):
# self.build_lib = None #self.build_lib = None
self.force = 0 self.force = 0
self.data_dir = None self.data_dir = None
def finalize_options(self): def finalize_options(self):
self.set_undefined_options('build', self.set_undefined_options('build',
# ('build_lib', 'build_lib'), #('build_lib', 'build_lib'),
('force', 'force')) ('force', 'force'))
def run(self): def run(self):
# sys.path.insert(0, self.build_lib) import sys
#sys.path.insert(0, self.build_lib)
self.generate_uml2() self.generate_uml2()
def generate_uml2(self): def generate_uml2(self):
@ -62,11 +64,11 @@ class build_uml(Command):
overrides = os.path.join('gaphor', 'UML', 'uml2.override') overrides = os.path.join('gaphor', 'UML', 'uml2.override')
model = os.path.join('gaphor', 'UML', 'uml2.gaphor') model = os.path.join('gaphor', 'UML', 'uml2.gaphor')
py_model = os.path.join('gaphor', 'UML', 'uml2.py') py_model = os.path.join('gaphor', 'UML', 'uml2.py')
outfile = py_model # os.path.join(self.build_lib, py_model) outfile = py_model #os.path.join(self.build_lib, py_model)
self.mkpath(os.path.dirname(outfile)) self.mkpath(os.path.dirname(outfile))
if self.force or newer(model, outfile) \ if self.force or newer(model, outfile) \
or newer(overrides, outfile) \ or newer(overrides, outfile) \
or newer(gen, outfile): or newer(gen, outfile):
print 'generating %s from %s...' % (py_model, model) print 'generating %s from %s...' % (py_model, model)
print ' (warnings can be ignored)' print ' (warnings can be ignored)'
import gen_uml import gen_uml
@ -75,4 +77,5 @@ class build_uml(Command):
print 'not generating %s (up-to-date)' % py_model print 'not generating %s (up-to-date)' % py_model
byte_compile([outfile]) byte_compile([outfile])
# vim:sw=4:et # vim:sw=4:et

View File

@ -25,6 +25,7 @@ into gaphor/UML/uml2.py.
Also a distutils tool, build_uml, is provided. Also a distutils tool, build_uml, is provided.
""" """
# #
# Create a UML 2.0 datamodel from the Gaphor 0.2.0 model file. # Create a UML 2.0 datamodel from the Gaphor 0.2.0 model file.
# #
@ -35,10 +36,9 @@ Also a distutils tool, build_uml, is provided.
# Recreate the model using some very dynamic class, so we can set all # Recreate the model using some very dynamic class, so we can set all
# attributes and traverse them to generate the data model. # attributes and traverse them to generate the data model.
import sys from gaphor.storage.parser import parse, base, element, canvas, canvasitem
import sys, string, operator
import override import override
from gaphor.storage.parser import parse, base, element
header = """# This file is generated by build_uml.py. DO NOT EDIT! header = """# This file is generated by build_uml.py. DO NOT EDIT!
@ -48,22 +48,20 @@ from properties import association, attribute, enumeration, derived, derivedunio
# Make getitem behave more politely # Make getitem behave more politely
base.__real_getitem__ = base.__getitem__ base.__real_getitem__ = base.__getitem__
def base__getitem__(self, key): def base__getitem__(self, key):
try: try:
return self.__real_getitem__(key) return self.__real_getitem__(key)
except KeyError: except KeyError:
return None return None
base.__getitem__ = base__getitem__ base.__getitem__ = base__getitem__
import re import re
pattern = r'([A-Z])' pattern = r'([A-Z])'
sub = r'_\1' sub = r'_\1'
def camelCase_to_underscore(str): def camelCase_to_underscore(str):
""" """
>>> camelCase_to_underscore('camelcase') >>> camelCase_to_underscore('camelcase')
@ -75,7 +73,6 @@ def camelCase_to_underscore(str):
""" """
return re.sub(pattern, sub, str).lower() return re.sub(pattern, sub, str).lower()
_ = camelCase_to_underscore _ = camelCase_to_underscore
@ -87,6 +84,7 @@ def msg(s):
class Writer: class Writer:
def __init__(self, filename, overrides=None): def __init__(self, filename, overrides=None):
self.overrides = overrides self.overrides = overrides
if filename: if filename:
@ -132,7 +130,7 @@ class Writer:
Write a definition for attribute a. Enumerations may be a dict Write a definition for attribute a. Enumerations may be a dict
of enumerations, indexed by ID. These are used to identify enums. of enumerations, indexed by ID. These are used to identify enums.
""" """
params = {} params = { }
type = a.typeValue type = a.typeValue
if type is None: if type is None:
raise ValueError('ERROR! type is not specified for property %s.%s' % (a.class_name, a.name)) raise ValueError('ERROR! type is not specified for property %s.%s' % (a.class_name, a.name))
@ -147,12 +145,12 @@ class Writer:
elif type.lower() == 'string': elif type.lower() == 'string':
# Change to basestr for Python 2.3 # Change to basestr for Python 2.3
type = 'str' type = 'str'
# type = '(str, unicode)' #type = '(str, unicode)'
default = a.defaultValue default = a.defaultValue
# Make sure types are represented the Python way: # Make sure types are represented the Python way:
if default and default.lower() in ('true', 'false'): if default and default.lower() in ('true', 'false'):
default = default.title() # True or False... default = default.title() # True or False...
if default is not None: if default is not None:
params['default'] = str(default) params['default'] = str(default)
@ -165,7 +163,7 @@ class Writer:
elif upper and upper != '1': elif upper and upper != '1':
params['upper'] = upper params['upper'] = upper
# kind, derived, a.name, type, default, lower, upper = parse_attribute(a) #kind, derived, a.name, type, default, lower, upper = parse_attribute(a)
full_name = "%s.%s" % (a.class_name, a.name) full_name = "%s.%s" % (a.class_name, a.name)
if self.overrides.has_override(full_name): if self.overrides.has_override(full_name):
@ -214,7 +212,7 @@ class Writer:
# Add the opposite property if the head itself is navigable: # Add the opposite property if the head itself is navigable:
if tail.navigable: if tail.navigable:
try: try:
# o_derived, o_name = parse_association_name(tail['name']) #o_derived, o_name = parse_association_name(tail['name'])
o_name = tail.name o_name = tail.name
o_derived = tail.derived o_derived = tail.derived
except KeyError: except KeyError:
@ -226,6 +224,7 @@ class Writer:
self.write_property("%s.%s" % (head.class_name, head.name), a + ')') self.write_property("%s.%s" % (head.class_name, head.name), a + ')')
def write_derivedunion(self, d): def write_derivedunion(self, d):
""" """
Write a derived union. If there are no subsets a warning Write a derived union. If there are no subsets a warning
@ -242,14 +241,12 @@ class Writer:
subs += '%s.%s' % (u.class_name, u.name) subs += '%s.%s' % (u.class_name, u.name)
if subs: if subs:
self.write_property("%s.%s" % (d.class_name, d.name), self.write_property("%s.%s" % (d.class_name, d.name),
"derivedunion('%s', %s, %s, %s, %s)" % ( "derivedunion('%s', %s, %s, %s, %s)" % (d.name, d.opposite_class_name, d.lower, d.upper == '*' and "'*'" or d.upper, subs))
d.name, d.opposite_class_name, d.lower, d.upper == '*' and "'*'" or d.upper, subs))
else: else:
if not self.overrides.has_override('%s.%s' % (d.class_name, d.name)): if not self.overrides.has_override('%s.%s' % (d.class_name, d.name)):
msg('no subsets for derived union: %s.%s[%s..%s]' % (d.class_name, d.name, d.lower, d.upper)) msg('no subsets for derived union: %s.%s[%s..%s]' % (d.class_name, d.name, d.lower, d.upper))
self.write_property("%s.%s" % (d.class_name, d.name), self.write_property("%s.%s" % (d.class_name, d.name),
"derivedunion('%s', %s, %s, %s)" % ( "derivedunion('%s', %s, %s, %s)" % (d.name, d.opposite_class_name, d.lower, d.upper == '*' and "'*'" or d.upper))
d.name, d.opposite_class_name, d.lower, d.upper == '*' and "'*'" or d.upper))
d.written = True d.written = True
def write_redefine(self, r): def write_redefine(self, r):
@ -263,7 +260,7 @@ class Writer:
def parse_association_name(name): def parse_association_name(name):
# First remove spaces # First remove spaces
name = name.replace(' ', '') name = name.replace(' ','')
derived = False derived = False
# Check if this is a derived union # Check if this is a derived union
while name and not name[0].isalpha(): while name and not name[0].isalpha():
@ -279,8 +276,9 @@ def parse_association_tags(appliedStereotypes):
for stereotype in appliedStereotypes or []: for stereotype in appliedStereotypes or []:
for slot in stereotype.slot or []: for slot in stereotype.slot or []:
# msg('scanning %s = %s' % (slot.definingFeature.name, slot.value.value)) #msg('scanning %s = %s' % (slot.definingFeature.name, slot.value.value))
if slot.definingFeature.name == 'subsets': if slot.definingFeature.name == 'subsets':
value = slot.value value = slot.value
@ -293,10 +291,9 @@ def parse_association_tags(appliedStereotypes):
# remove all whitespaces and stuff # remove all whitespaces and stuff
redefines = value.replace(' ', '').replace('\n', '').replace('\r', '') redefines = value.replace(' ', '').replace('\n', '').replace('\r', '')
# print 'found', subsets, redefines #print 'found', subsets, redefines
return subsets, redefines return subsets, redefines
def parse_association_end(head, tail): def parse_association_end(head, tail):
""" """
The head association end is enriched with the following attributes: The head association end is enriched with the following attributes:
@ -320,7 +317,7 @@ def parse_association_end(head, tail):
if name is None: if name is None:
raise ValueError('ERROR! no name, but navigable: %s (%s.%s)' % (head.id, head.class_name, head.name)) raise ValueError('ERROR! no name, but navigable: %s (%s.%s)' % (head.id, head.class_name, head.name))
# print head.id, head.lowerValue #print head.id, head.lowerValue
upper = head.upperValue or '*' upper = head.upperValue or '*'
lower = head.lowerValue or upper lower = head.lowerValue or upper
if lower == '*': if lower == '*':
@ -364,13 +361,13 @@ def generate(filename, outfile=None, overridesfile=None):
# extract usable elements from all_elements. Some elements are given # extract usable elements from all_elements. Some elements are given
# some extra attributes. # some extra attributes.
classes = {} classes = { }
enumerations = {} enumerations = { }
generalizations = {} generalizations = { }
associations = {} associations = { }
properties = {} properties = { }
operations = {} operations = { }
extensions = {} # for identifying metaclasses extensions = { } # for identifying metaclasses
for key, val in all_elements.items(): for key, val in all_elements.items():
# Find classes, *Kind (enumerations) are given special treatment # Find classes, *Kind (enumerations) are given special treatment
if isinstance(val, element): if isinstance(val, element):
@ -393,10 +390,10 @@ def generate(filename, outfile=None, overridesfile=None):
associations[key] = val associations[key] = val
elif val.type == 'Property': elif val.type == 'Property':
properties[key] = val properties[key] = val
# resolve(val, 'typeValue') #resolve(val, 'typeValue')
# resolve(val, 'defaultValue') #resolve(val, 'defaultValue')
# resolve(val, 'lowerValue') #resolve(val, 'lowerValue')
# resolve(val, 'upperValue') #resolve(val, 'upperValue')
resolve(val, 'appliedStereotype') resolve(val, 'appliedStereotype')
for st in val.appliedStereotype or []: for st in val.appliedStereotype or []:
resolve(st, 'slot') resolve(st, 'slot')
@ -411,7 +408,7 @@ def generate(filename, outfile=None, overridesfile=None):
# find inheritance relationships # find inheritance relationships
for g in generalizations.values(): for g in generalizations.values():
# assert g.specific and g.general #assert g.specific and g.general
specific = g['specific'] specific = g['specific']
general = g['general'] general = g['general']
classes[specific].generalization.append(classes[general]) classes[specific].generalization.append(classes[general])
@ -438,6 +435,7 @@ def generate(filename, outfile=None, overridesfile=None):
if ends: if ends:
del classes[e.memberEnd[0].type.id] del classes[e.memberEnd[0].type.id]
# create file header # create file header
writer.write(header) writer.write(header)
@ -451,16 +449,14 @@ def generate(filename, outfile=None, overridesfile=None):
c.stereotypeName = sType.name c.stereotypeName = sType.name
print " class '%s' has been stereotyped as '%s'" % (c.name, c.stereotypeName) print " class '%s' has been stereotyped as '%s'" % (c.name, c.stereotypeName)
writer.write("# class '%s' has been stereotyped as '%s'\n" % (c.name, c.stereotypeName)) writer.write("# class '%s' has been stereotyped as '%s'\n" % (c.name, c.stereotypeName))
#c.written = True
# c.written = True
def tag_children(me): def tag_children(me):
for child in me.specialization: for child in me.specialization:
child.stereotypeName = sType.name child.stereotypeName = sType.name
print " class '%s' has been stereotyped as '%s' too" % (child.name, child.stereotypeName) print " class '%s' has been stereotyped as '%s' too" % (child.name, child.stereotypeName)
writer.write("# class '%s' has been stereotyped as '%s' too\n" % (child.name, child.stereotypeName)) writer.write("# class '%s' has been stereotyped as '%s' too\n" % (child.name, child.stereotypeName))
# child.written = True #child.written = True
tag_children(child) tag_children(child)
tag_children(c) tag_children(c)
ignored_classes = set() ignored_classes = set()
@ -471,9 +467,9 @@ def generate(filename, outfile=None, overridesfile=None):
ignored_classes.add(c) ignored_classes.add(c)
else: else:
writer.write_classdef(c) writer.write_classdef(c)
# create attributes and enumerations # create attributes and enumerations
derivedattributes = {} derivedattributes = { }
for c in filter(lambda c: c not in ignored_classes, classes.values()): for c in filter(lambda c: c not in ignored_classes, classes.values()):
for p in c.get('ownedAttribute') or []: for p in c.get('ownedAttribute') or []:
a = properties.get(p) a = properties.get(p)
@ -486,8 +482,8 @@ def generate(filename, outfile=None, overridesfile=None):
writer.write_attribute(a, enumerations) writer.write_attribute(a, enumerations)
# create associations, derivedunions are held back # create associations, derivedunions are held back
derivedunions = {} # indexed by name in stead of id derivedunions = { } # indexed by name in stead of id
redefines = [] redefines = [ ]
for a in associations.values(): for a in associations.values():
ends = [] ends = []
# Resolve some properties: # Resolve some properties:
@ -507,24 +503,24 @@ def generate(filename, outfile=None, overridesfile=None):
for e1, e2 in ((ends[0], ends[1]), (ends[1], ends[0])): for e1, e2 in ((ends[0], ends[1]), (ends[1], ends[0])):
if a.asAttribute: if a.asAttribute:
if a.asAttribute is e1 and e1.navigable: if a.asAttribute is e1 and e1.navigable:
writer.write("# '%s.%s' is a simple attribute\n" % (e2.type.name, e1.name)) writer.write("# '%s.%s' is a simple attribute\n" % (e2.type.name, e1.name))
e1.class_name = e2.type.name e1.class_name = e2.type.name
e1.typeValue = 'str' e1.typeValue = 'str'
writer.write_attribute(e1, enumerations) writer.write_attribute(e1, enumerations)
e1.written = True e1.written = True
e2.written = True e2.written = True
elif e1.redefines: elif e1.redefines:
redefines.append(e1) redefines.append(e1)
elif e1.derived or overrides.derives('%s.%s' % (e1.class_name, e1.name)): elif e1.derived or overrides.derives('%s.%s' % (e1.class_name, e1.name)):
assert not derivedunions.get(e1.name), "%s.%s is already in derived union set in class %s" % ( assert not derivedunions.get(e1.name), "%s.%s is already in derived union set in class %s" % (e1.class_name, e1.name, derivedunions.get(e1.name).class_name)
e1.class_name, e1.name, derivedunions.get(e1.name).class_name)
derivedunions[e1.name] = e1 derivedunions[e1.name] = e1
e1.union = [] e1.union = [ ]
e1.written = False e1.written = False
elif e1.navigable: elif e1.navigable:
writer.write_association(e1, e2) writer.write_association(e1, e2)
# create derived unions, first link the association ends to the d # create derived unions, first link the association ends to the d
for a in (v for v in properties.values() if v.subsets): for a in (v for v in properties.values() if v.subsets):
for s in a.subsets or (): for s in a.subsets or ():
@ -534,6 +530,7 @@ def generate(filename, outfile=None, overridesfile=None):
except KeyError: except KeyError:
msg('not a derived union: %s.%s' % (a.class_name, s)) msg('not a derived union: %s.%s' % (a.class_name, s))
# TODO: We should do something smart here, since derived attributes (mostly) # TODO: We should do something smart here, since derived attributes (mostly)
# may depend on other derived attributes or associations. # may depend on other derived attributes or associations.
@ -559,7 +556,6 @@ def generate(filename, outfile=None, overridesfile=None):
if __name__ == '__main__': if __name__ == '__main__':
import doctest import doctest
doctest.testmod() doctest.testmod()
generate('uml2.gaphor') generate('uml2.gaphor')

View File

@ -1,10 +1,12 @@
from setuptools.command.install_lib import install_lib as _install_lib from setuptools.command.install_lib import install_lib as _install_lib
class install_lib(_install_lib): class install_lib(_install_lib):
def build(self): def build(self):
_install_lib.build(self) _install_lib.build(self)
self.run_command('build_uml') self.run_command('build_uml')
self.run_command('build_mo') self.run_command('build_mo')
# vim:sw=4:et:ai # vim:sw=4:et:ai

View File

@ -25,17 +25,18 @@ Options:
Display version information and exit. Display version information and exit.
""" """
import array
import getopt
import os
import struct
import sys import sys
import os
import getopt
import struct
import array
__version__ = "1.1" __version__ = "1.1"
MESSAGES = {} MESSAGES = {}
def usage(code, msg=''): def usage(code, msg=''):
print >> sys.stderr, __doc__ print >> sys.stderr, __doc__
if msg: if msg:
@ -43,6 +44,7 @@ def usage(code, msg=''):
sys.exit(code) sys.exit(code)
def add(id, str, fuzzy): def add(id, str, fuzzy):
"Add a non-fuzzy translation to the dictionary." "Add a non-fuzzy translation to the dictionary."
global MESSAGES global MESSAGES
@ -50,6 +52,7 @@ def add(id, str, fuzzy):
MESSAGES[id] = str MESSAGES[id] = str
def generate(): def generate():
"Return the generated output." "Return the generated output."
global MESSAGES global MESSAGES
@ -68,7 +71,7 @@ def generate():
# The header is 7 32-bit unsigned integers. We don't use hash tables, so # The header is 7 32-bit unsigned integers. We don't use hash tables, so
# the keys start right after the index tables. # the keys start right after the index tables.
# translated string. # translated string.
keystart = 7 * 4 + 16 * len(keys) keystart = 7*4+16*len(keys)
# and the values start after the keys # and the values start after the keys
valuestart = keystart + len(ids) valuestart = keystart + len(ids)
koffsets = [] koffsets = []
@ -76,22 +79,23 @@ def generate():
# The string table first has the list of keys, then the list of values. # The string table first has the list of keys, then the list of values.
# Each entry has first the size of the string, then the file offset. # Each entry has first the size of the string, then the file offset.
for o1, l1, o2, l2 in offsets: for o1, l1, o2, l2 in offsets:
koffsets += [l1, o1 + keystart] koffsets += [l1, o1+keystart]
voffsets += [l2, o2 + valuestart] voffsets += [l2, o2+valuestart]
offsets = koffsets + voffsets offsets = koffsets + voffsets
output = struct.pack("Iiiiiii", output = struct.pack("Iiiiiii",
0x950412deL, # Magic 0x950412deL, # Magic
0, # Version 0, # Version
len(keys), # # of entries len(keys), # # of entries
7 * 4, # start of key index 7*4, # start of key index
7 * 4 + len(keys) * 8, # start of value index 7*4+len(keys)*8, # start of value index
0, 0) # size and offset of hash table 0, 0) # size and offset of hash table
output += array.array("i", offsets).tostring() output += array.array("i", offsets).tostring()
output += ids output += ids
output += strs output += strs
return output return output
def make(filename, outfile): def make(filename, outfile):
ID = 1 ID = 1
STR = 2 STR = 2
@ -109,7 +113,7 @@ def make(filename, outfile):
except IOError, msg: except IOError, msg:
print >> sys.stderr, msg print >> sys.stderr, msg
sys.exit(1) sys.exit(1)
section = None section = None
fuzzy = 0 fuzzy = 0
@ -151,7 +155,7 @@ def make(filename, outfile):
msgstr += l msgstr += l
else: else:
print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \ print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
'before:' 'before:'
print >> sys.stderr, l print >> sys.stderr, l
sys.exit(1) sys.exit(1)
# Add last entry # Add last entry
@ -162,11 +166,12 @@ def make(filename, outfile):
output = generate() output = generate()
try: try:
open(outfile, "wb").write(output) open(outfile,"wb").write(output)
except IOError, msg: except IOError,msg:
print >> sys.stderr, msg print >> sys.stderr, msg
def main(): def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], 'hVo:', opts, args = getopt.getopt(sys.argv[1:], 'hVo:',

View File

@ -25,15 +25,17 @@ do its job correctly.
This is a simple rip-off of the override script used in PyGTK. This is a simple rip-off of the override script used in PyGTK.
""" """
import string
import sys, string
class Overrides: class Overrides:
def __init__(self, filename=None): def __init__(self, filename=None):
self.overrides = {} self.overrides = {}
if filename: if filename:
self.read_overrides(filename) self.read_overrides(filename)
def read_overrides(self, filename): def read_overrides(self, filename):
"""Read a file and return a dictionary of overriden properties """Read a file and return a dictionary of overriden properties
and their implementation. and their implementation.
@ -81,9 +83,9 @@ class Overrides:
deps = tuple(words[3:]) deps = tuple(words[3:])
self.overrides[func] = (deps, string.join(rest, ''), '%d: %s' % (startline, line)) self.overrides[func] = (deps, string.join(rest, ''), '%d: %s' % (startline, line))
elif words[0] == 'comment': elif words[0] == 'comment':
pass # ignore comments pass # ignore comments
else: else:
print "Unknown word: '%s', line %d"(words[0], startline) print "Unknown word: '%s', line %d" (words[0], startline)
raise SystemExit raise SystemExit
def has_override(self, key): def has_override(self, key):

View File

@ -16,7 +16,6 @@
# for selftesting # for selftesting
try: try:
import fintl import fintl
_ = fintl.gettext _ = fintl.gettext
except ImportError: except ImportError:
_ = lambda s: s _ = lambda s: s
@ -156,13 +155,13 @@ Options:
If `inputfile' is -, standard input is read. If `inputfile' is -, standard input is read.
""") """)
import getopt
import operator
import os import os
import sys import sys
import time import time
import getopt
import token import token
import tokenize import tokenize
import operator
__version__ = '1.5' __version__ = '1.5'
@ -171,6 +170,8 @@ DEFAULTKEYWORDS = ', '.join(default_keywords)
EMPTYSTRING = '' EMPTYSTRING = ''
# The normal pot-file header. msgmerge and Emacs's po-mode work better if it's # The normal pot-file header. msgmerge and Emacs's po-mode work better if it's
# there. # there.
pot_header = _('''\ pot_header = _('''\
@ -192,7 +193,7 @@ msgstr ""
''') ''')
def usage(code, msg=''): def usage(code, msg=''):
print >> sys.stderr, __doc__ % globals() print >> sys.stderr, __doc__ % globals()
if msg: if msg:
@ -200,9 +201,9 @@ def usage(code, msg=''):
sys.exit(code) sys.exit(code)
escapes = [] escapes = []
def make_escapes(pass_iso8859): def make_escapes(pass_iso8859):
global escapes global escapes
if pass_iso8859: if pass_iso8859:
@ -234,7 +235,7 @@ def escape(s):
def safe_eval(s): def safe_eval(s):
# unwrap quotes, safely # unwrap quotes, safely
return eval(s, {'__builtins__': {}}, {}) return eval(s, {'__builtins__':{}}, {})
def normalize(s): def normalize(s):
@ -253,7 +254,7 @@ def normalize(s):
s = '""\n"' + lineterm.join(lines) + '"' s = '""\n"' + lineterm.join(lines) + '"'
return s return s
def containsAny(str, set): def containsAny(str, set):
""" Check whether 'str' contains ANY of the chars in 'set' """ Check whether 'str' contains ANY of the chars in 'set'
""" """
@ -276,8 +277,8 @@ def _visit_pyfiles(list, dirname, names):
# add all *.py files to list # add all *.py files to list
list.extend( list.extend(
[os.path.join(dirname, file) [os.path.join(dirname, file)
for file in names for file in names
if os.path.splitext(file)[1] == _py_ext]) if os.path.splitext(file)[1] == _py_ext])
def _get_modpkg_path(dotted_name, pathlist=None): def _get_modpkg_path(dotted_name, pathlist=None):
@ -323,6 +324,7 @@ def getFilesForName(name):
""" Get a list of module files for a filename, a module or package name, """ Get a list of module files for a filename, a module or package name,
or a directory. or a directory.
""" """
import imp
if not os.path.exists(name): if not os.path.exists(name):
# check for glob chars # check for glob chars
@ -350,7 +352,7 @@ def getFilesForName(name):
return [] return []
class TokenEater: class TokenEater:
def __init__(self, options): def __init__(self, options):
self.__options = options self.__options = options
@ -363,9 +365,9 @@ class TokenEater:
def __call__(self, ttype, tstring, stup, etup, line): def __call__(self, ttype, tstring, stup, etup, line):
# dispatch # dispatch
## import token ## import token
## print >> sys.stderr, 'ttype:', token.tok_name[ttype], \ ## print >> sys.stderr, 'ttype:', token.tok_name[ttype], \
## 'tstring:', tstring ## 'tstring:', tstring
self.__state(ttype, tstring, stup[0]) self.__state(ttype, tstring, stup[0])
def __waiting(self, ttype, tstring, lineno): def __waiting(self, ttype, tstring, lineno):
@ -424,7 +426,7 @@ class TokenEater:
elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT, elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
token.NEWLINE, tokenize.NL]: token.NEWLINE, tokenize.NL]:
# warn if we see anything else than STRING or whitespace # warn if we see anything else than STRING or whitespace
print >> sys.stderr, _('*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"') % { print >>sys.stderr, _('*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"') % {
'token': tstring, 'file': self.__curfile, 'lineno': self.__lineno} 'token': tstring, 'file': self.__curfile, 'lineno': self.__lineno}
self.__state = self.__waiting self.__state = self.__waiting
@ -475,7 +477,7 @@ class TokenEater:
elif options.locationstyle == options.SOLARIS: elif options.locationstyle == options.SOLARIS:
for filename, lineno in v: for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno} d = {'filename': filename, 'lineno': lineno}
print >> fp, _( print >>fp, _(
'# File: %(filename)s, line: %(lineno)d') % d '# File: %(filename)s, line: %(lineno)d') % d
elif options.locationstyle == options.GNU: elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the # fit as many locations on one line, as long as the
@ -497,6 +499,7 @@ class TokenEater:
print >> fp, 'msgstr ""\n' print >> fp, 'msgstr ""\n'
def main(): def main():
global default_keywords global default_keywords
try: try:
@ -518,7 +521,7 @@ def main():
GNU = 1 GNU = 1
SOLARIS = 2 SOLARIS = 2
# defaults # defaults
extractall = 0 # FIXME: currently this option has no effect at all. extractall = 0 # FIXME: currently this option has no effect at all.
escape = 0 escape = 0
keywords = [] keywords = []
outpath = '' outpath = ''
@ -532,8 +535,8 @@ def main():
nodocstrings = {} nodocstrings = {}
options = Options() options = Options()
locations = {'gnu': options.GNU, locations = {'gnu' : options.GNU,
'solaris': options.SOLARIS, 'solaris' : options.SOLARIS,
} }
# parse options # parse options
@ -654,10 +657,11 @@ def main():
if closep: if closep:
fp.close() fp.close()
if __name__ == '__main__': if __name__ == '__main__':
main() main()
# some more test strings # some more test strings
_(u'a unicode string') _(u'a unicode string')
_('*** Seen unexpected token "%(token)s"' % {'token': 'test'}) # this one creates a warning _('*** Seen unexpected token "%(token)s"' % {'token': 'test'}) # this one creates a warning
_('more' 'than' 'one' 'string') _('more' 'than' 'one' 'string')

View File

@ -15,10 +15,9 @@ try:
except ImportError: except ImportError:
pass pass
import gaphor.UML
import gaphor.storage import gaphor.storage
import gaphor.storage.parser import gaphor.storage.parser
import gaphor.UML
class Compare(object): class Compare(object):
"""This class makes it possible to compare two files. """This class makes it possible to compare two files.
@ -38,7 +37,7 @@ class Compare(object):
"""Print a message generated by report(). """Print a message generated by report().
""" """
print msg print msg
def report(self, factory, element, name=None, value=None, isref=False): def report(self, factory, element, name=None, value=None, isref=False):
"""Report an element that has differences. """Report an element that has differences.
The attribute show_id can be set to False to suppress element ids. The attribute show_id can be set to False to suppress element ids.
@ -48,7 +47,7 @@ class Compare(object):
msg = '-' msg = '-'
else: else:
msg = '+' msg = '+'
if isinstance(element, gaphor.storage.parser.canvas): if isinstance(element, gaphor.storage.parser.canvas):
msg += ' <canvas>:' msg += ' <canvas>:'
else: else:
@ -169,6 +168,7 @@ class Compare(object):
self.report(self.factory1, element1, key, val1) self.report(self.factory1, element1, key, val1)
self.report(self.factory2, element2, key, val2) self.report(self.factory2, element2, key, val2)
def compare(self): def compare(self):
"""Start the comparison of the files provided to the constructor. """Start the comparison of the files provided to the constructor.
""" """
@ -180,7 +180,6 @@ class Compare(object):
self.check_missing_values(element1, element2) self.check_missing_values(element1, element2)
self.check_differences_values(element1, element2) self.check_differences_values(element1, element2)
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
@ -210,3 +209,4 @@ if __name__ == '__main__':
c = Compare(files[0], files[1]) c = Compare(files[0], files[1])
c.show_id = show_id c.show_id = show_id
c.compare() c.compare()

View File

@ -1,9 +1,9 @@
import re import re
pattern = r'([A-Z])' pattern = r'([A-Z])'
sub = r'_\1' sub = r'_\1'
def camelCase_to_underscore(str): def camelCase_to_underscore(str):
""" """
>>> camelCase_to_underscore('camelcase') >>> camelCase_to_underscore('camelcase')
@ -18,5 +18,4 @@ def camelCase_to_underscore(str):
if __name__ == '__main__': if __name__ == '__main__':
import doctest import doctest
doctest.testmod() doctest.testmod()