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
# serve to show the default.
import sys, os
# 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
# 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 -----------------------------------------------------
# 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
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
@ -29,7 +31,7 @@ templates_path = ['_templates']
source_suffix = '.txt'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'contents'
@ -49,37 +51,37 @@ release = '0.17.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
#today = ''
# 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
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# 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.
# add_function_parentheses = True
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
#modindex_common_prefix = []
# -- 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
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
#html_theme_options = {}
# 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
# "<project> v<release> documentation".
# html_title = None
#html_title = None
# 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
# 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
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
#html_favicon = None
# 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,
@ -119,85 +121,86 @@ html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# 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
# typographically correct entities.
# html_use_smartypants = True
#html_use_smartypants = True
# 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
# template names.
# html_additional_pages = {}
#html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
#html_domain_indices = True
# 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.
# html_split_index = False
#html_split_index = False
# 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.
# html_show_sphinx = True
#html_show_sphinx = 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
# contain a <link> tag referring to it. The value of this option must be the
# 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").
# html_file_suffix = None
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Gaphordoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
# latex_paper_size = 'letter'
#latex_paper_size = 'letter'
# 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
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('contents', 'Gaphor.tex', u'Gaphor Documentation',
u'Gaphor development team', 'manual'),
('contents', 'Gaphor.tex', u'Gaphor Documentation',
u'Gaphor development team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
#latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
# latex_preamble = ''
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
# latex_appendices = []
#latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------

View File

@ -3,21 +3,21 @@
"""This script list classes and optionally attributes from UML model
created with Gaphor."""
import optparse
import sys
import optparse
import gaphor.UML as UML
from gaphor import Application
import gaphor.UML as UML
# Setup command line options.
#Setup command line options.
usage = 'usage: %prog [options] file.gaphor'
parser = optparse.OptionParser(usage=usage)
parser.add_option('-a', \
'--attributes', \
dest='attrs', \
action='store_true', \
parser.add_option('-a',\
'--attributes',\
dest='attrs',\
action='store_true',\
help='Print class attributes')
(options, args) = parser.parse_args()
@ -26,25 +26,26 @@ if len(args) != 1:
parser.print_help()
sys.exit(1)
# The model file to load.
#The model file to load.
model = args[0]
# Create the Gaphor application object.
#Create the Gaphor application object.
Application.init()
# Get services we need.
#Get services we need.
element_factory = Application.get_service('element_factory')
file_manager = Application.get_service('file_manager')
# Load model from file.
#Load model from file.
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)):
print 'Found class %s' % cls.name
if options.attrs:
for attr in cls.ownedAttribute:
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.
"""
import sys
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 = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
@ -64,28 +63,23 @@ md5_data = {
}
import sys, os
try:
from hashlib import md5
except ImportError:
from md5 import md5
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >> sys.stderr, (
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""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.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools;
setuptools.bootstrap_install_from = egg
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
return do_download()
try:
pkg_resources.require("setuptools>=" + version);
return
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >> sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay=15
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""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.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2
egg_name = "setuptools-%s-py%s.egg" % (version, sys.version[:3])
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
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.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
);
from time import sleep;
sleep(delay)
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto, "wb");
dst.write(data)
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
@ -188,21 +208,21 @@ def main(argv, version=DEFAULT_VERSION):
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0, egg)
sys.path.insert(0,egg)
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:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >> sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>=" + version
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
@ -211,17 +231,16 @@ def main(argv, version=DEFAULT_VERSION):
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv) + [download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
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.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
@ -229,7 +248,7 @@ def update_md5(filenames):
for name in filenames:
base = os.path.basename(name)
f = open(name, 'rb')
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
@ -239,23 +258,27 @@ def update_md5(filenames):
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb');
src = f.read();
f.close()
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >> sys.stderr, "Internal error!"
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile, 'w')
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__ == '__main__':
if len(sys.argv) > 2 and sys.argv[1] == '--md5update':
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])

View File

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

View File

@ -21,7 +21,6 @@
Recursive attribute access functions.
"""
def rgetattr(obj, attr):
"""
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)
setattr(obj, attrs[-1], val)
# 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.
"""

View File

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

View File

@ -7,8 +7,8 @@ dependencies.
VERSION = '0.17.1'
import os
import sys
sys.path.insert(0, '.')
from ez_setup import use_setuptools
@ -16,9 +16,10 @@ from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# try:
# from sphinx.setup_command import BuildDoc
# except ImportError, e:
from distutils.cmd import Command
#try:
#from sphinx.setup_command import BuildDoc
#except ImportError, e:
# print 'No Sphynx found'
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.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
# before the build_py code.
from setuptools.command.build_py import build_py
class build_py_with_sub_commands(build_py):
def run(self):
for cmd_name in self.get_sub_commands():
self.run_command(cmd_name)
build_py.run(self)
build_py_with_sub_commands.sub_commands.append(('build_uml', None))
setup(
name='gaphor',
version=VERSION,
@ -58,7 +60,7 @@ Gaphor is a UML modeling tool written in Python.
It uses the GTK+ environment for user interaction.
""",
classifiers=[
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: X11 Applications :: GTK',
'Intended Audience :: Developers',
@ -74,37 +76,37 @@ It uses the GTK+ environment for user interaction.
'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
'gaphas >= 0.7.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': [
'gaphor = gaphor:main',
'gaphorconvert = gaphor.tools.gaphorconvert:main',
],
'gaphor.services': [
'component_registry = gaphor.services.componentregistry:ZopeComponentRegistry',
# 'event_dispatcher = gaphor.services.eventdispatcher:EventDispatcher',
#'event_dispatcher = gaphor.services.eventdispatcher:EventDispatcher',
'adapter_loader = gaphor.services.adapterloader:AdapterLoader',
'properties = gaphor.services.properties:Properties',
'undo_manager = gaphor.services.undomanager:UndoManager',
'element_factory = gaphor.UML.elementfactory:ElementFactoryService',
'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',
'action_manager = gaphor.services.actionmanager:ActionManager',
'ui_manager = gaphor.services.actionmanager:UIManager',
@ -112,17 +114,17 @@ It uses the GTK+ environment for user interaction.
'copy = gaphor.services.copyservice:CopyService',
'sanitizer = gaphor.services.sanitizerservice:SanitizerService',
'element_dispatcher = gaphor.services.elementdispatcher:ElementDispatcher',
# 'property_dispatcher = gaphor.services.propertydispatcher:PropertyDispatcher',
#'property_dispatcher = gaphor.services.propertydispatcher:PropertyDispatcher',
'xmi_export = gaphor.plugins.xmiexport:XMIExport',
'diagram_layout = gaphor.plugins.diagramlayout:DiagramLayout',
'pynsource = gaphor.plugins.pynsource:PyNSource',
# 'check_metamodel = gaphor.plugins.checkmetamodel:CheckModelWindow',
# 'live_object_browser = gaphor.plugins.liveobjectbrowser:LiveObjectBrowser',
#'check_metamodel = gaphor.plugins.checkmetamodel:CheckModelWindow',
#'live_object_browser = gaphor.plugins.liveobjectbrowser:LiveObjectBrowser',
'alignment = gaphor.plugins.alignment:Alignment',
'help = gaphor.services.helpservice:HelpService',
],
'gaphor.uicomponents': [
# 'mainwindow = gaphor.ui.mainwindow:MainWindow',
#'mainwindow = gaphor.ui.mainwindow:MainWindow',
'namespace = gaphor.ui.mainwindow:Namespace',
'toolbox = gaphor.ui.mainwindow:Toolbox',
'consolewindow = gaphor.ui.consolewindow:ConsoleWindow',
@ -130,32 +132,32 @@ It uses the GTK+ environment for user interaction.
],
},
cmdclass={
'build_py': build_py_with_sub_commands,
'build_uml': build_uml,
# 'build_doc': BuildDoc,
'build_mo': build_mo,
'build_pot': build_pot,
'install_lib': install_lib,
'run': run,
cmdclass = {
'build_py': build_py_with_sub_commands,
'build_uml': build_uml,
#'build_doc': BuildDoc,
'build_mo': build_mo,
'build_pot': build_pot,
'install_lib': install_lib,
'run': run,
},
setup_requires=[
# 'Sphinx >= 1.0.6',
setup_requires = [
#'Sphinx >= 1.0.6',
'nose >= 0.10.4',
'setuptools-git >= 0.3.4'
],
test_suite='nose.collector',
test_suite = 'nose.collector',
options=dict(
build_pot=dict(
all_linguas=','.join(LINGUAS),
options = dict(
build_pot = dict(
all_linguas = ','.join(LINGUAS),
),
build_mo=dict(
all_linguas=','.join(LINGUAS),
build_mo = dict(
all_linguas = ','.join(LINGUAS),
),
),
)
# vim:sw=4:et:ai

View File

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

View File

@ -4,14 +4,14 @@
Generate .mo files from po files.
"""
import os.path
from distutils.core import Command
from distutils.dep_util import newer
import os.path
import msgfmt
class build_mo(Command):
description = 'Create .mo files from .po files'
# 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'),
('force', 'f', 'Force creation of .mo files'),
('all-linguas', None, ''),
]
]
boolean_options = ['force']
def initialize_options(self):
def initialize_options (self):
self.build_dir = None
self.force = None
self.all_linguas = None
def finalize_options(self):
def finalize_options (self):
self.set_undefined_options('build',
('force', 'force'))
if self.build_dir is None:
@ -39,23 +39,24 @@ class build_mo(Command):
self.all_linguas = self.all_linguas.split(',')
def run(self):
"""Run msgfmt.make() on all_linguas."""
if not self.all_linguas:
return
def run (self):
"""Run msgfmt.make() on all_linguas."""
if not self.all_linguas:
return
for lingua in self.all_linguas:
pofile = os.path.join('po', lingua + '.po')
outdir = os.path.join(self.build_dir, lingua, 'LC_MESSAGES')
for lingua in self.all_linguas:
pofile = os.path.join('po', lingua + '.po')
outdir = os.path.join(self.build_dir, lingua, 'LC_MESSAGES')
self.mkpath(outdir)
outfile = os.path.join(outdir, 'gaphor.mo')
if self.force or newer(pofile, outfile):
outfile = os.path.join(outdir, 'gaphor.mo')
if self.force or newer(pofile, outfile):
print 'converting %s -> %s' % (pofile, outfile)
msgfmt.make(pofile, outfile)
msgfmt.make(pofile, outfile)
else:
print 'not converting %s (output up-to-date)' % pofile
from distutils.command.build import build
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.
"""
import os.path
import sys
from distutils.core import Command
from commands import getstatus
import sys, os.path
import pygettext
# from pygettext.main():
class Options:
# constants
GNU = 1
SOLARIS = 2
# defaults
extractall = 0 # FIXME: currently this option has no effect at all.
extractall = 0 # FIXME: currently this option has no effect at all.
keywords = []
writelocations = 1
locationstyle = GNU
@ -49,165 +47,166 @@ class Options:
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'),
('extract-all', 'a', ''),
('default-domain=', 'd', ''),
('escape', 'E', ''),
('docstrings', 'D', ''),
('keyword=', 'k', 'Comma separated list of keywords'),
('no-default-keywords', 'K', ''),
('add-location', 'n', ''),
('no-location', None, ''),
('style=', 'S', 'POT file style "gnu" or "solaris"'),
('output=', 'o', ''),
('output-dir=', 'p', ''),
('width=', 'w', ''),
('exclude-file=', 'x', ''),
('all-linguas=', None, ''),
# ('no-docstrings=', 'X', ''),
]
('default-domain=', 'd', ''),
('escape', 'E', ''),
('docstrings', 'D', ''),
('keyword=', 'k', 'Comma separated list of keywords'),
('no-default-keywords', 'K', ''),
('add-location', 'n', ''),
('no-location', None, ''),
('style=', 'S', 'POT file style "gnu" or "solaris"'),
('output=', 'o', ''),
('output-dir=', 'p', ''),
('width=', 'w', ''),
('exclude-file=', 'x', ''),
('all-linguas=', None, ''),
#('no-docstrings=', 'X', ''),
]
boolean_options = ['extract-all', 'escape', 'docstrings',
'no-default-keywords', 'add-location',
'no-location', 'no-docstrings']
boolean_options = [ 'extract-all', 'escape', 'docstrings',
'no-default-keywords', 'add-location',
'no-location', 'no-docstrings' ]
# constants
GNU = 1
SOLARIS = 2
def initialize_options(self):
self.podir = 'po'
self.msgmerge = 'msgmerge'
self.podir = 'po'
self.msgmerge = 'msgmerge'
self.options = Options()
self.options = Options()
# defaults for variable parsing:
# defaults for variable parsing:
self.escape = 0
self.width = 78
self.extract_all = 0 # doesn't do anything yet
self.default_domain = None
self.keyword = None
self.no_default_keywords = 0
self.no_location = 0
self.style = None
self.output = None
self.output_dir = None
self.extract_all = 0 # doesn't do anything yet
self.default_domain = None
self.keyword = None
self.no_default_keywords = 0
self.no_location = 0
self.style = None
self.output = None
self.output_dir = None
self.docstrings = 0
self.exclude_file = None
# self.no_docstrings = None
self.exclude_file = None
#self.no_docstrings = None
self.all_linguas = []
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
if self.default_domain:
self.output = self.default_domain + '.pot'
if self.keyword:
options.keywords.extend(self.keyword.split(','))
if self.no_default_keywords:
options.keywords = []
if self.no_location:
options.writelocations = 0
if self.style:
if self.style == 'gnu':
options.locationstyle = self.GNU
elif self.style == 'solaris':
options.locationstyle = self.SOLARIS
else:
raise SystemExit, 'Invalid value for --style: %s' % self.style
if not self.output:
self.output = self.distribution.get_name() + '.pot'
if not self.output_dir:
self.output_dir = self.podir
if self.docstrings:
options.docstrings = 1
options.width = int(self.width)
if self.exclude_file:
try:
fp = open(self.exclude_file)
options.toexclude = fp.readlines()
fp.close()
except IOError:
raise SystemExit, "Can't read --exclude-file: %s" % self.exclude_file
# skip: self.no_docstrings
# Build default options for the TokenEater
if self.default_domain:
self.output = self.default_domain + '.pot'
if self.keyword:
options.keywords.extend(self.keyword.split(','))
if self.no_default_keywords:
options.keywords = [ ]
if self.no_location:
options.writelocations = 0
if self.style:
if self.style == 'gnu':
options.locationstyle = self.GNU
elif self.style == 'solaris':
options.locationstyle = self.SOLARIS
else:
raise SystemExit, 'Invalid value for --style: %s' % self.style
if not self.output:
self.output = self.distribution.get_name() + '.pot'
if not self.output_dir:
self.output_dir = self.podir
if self.docstrings:
options.docstrings = 1
options.width = int(self.width)
if self.exclude_file:
try:
fp = open(self.exclude_file)
options.toexclude = fp.readlines()
fp.close()
except IOError:
raise SystemExit, "Can't read --exclude-file: %s" % self.exclude_file
# skip: self.no_docstrings
if self.all_linguas:
self.all_linguas = self.all_linguas.split(',')
# calculate escapes
pygettext.make_escapes(self.escape)
# calculate escapes
pygettext.make_escapes(self.escape)
# calculate all keywords
options.keywords.append('_')
# calculate all keywords
options.keywords.append('_')
if self.output_dir:
self.output = os.path.join(self.output_dir, self.output)
if self.output_dir:
self.output = os.path.join(self.output_dir, self.output)
self.packages = self.distribution.packages
# self.all_linguas = self.distribution.get_all_linguas()
# self.all_linguas = self.distribution.options['po']['all_linguas']
self.packages = self.distribution.packages
#self.all_linguas = self.distribution.get_all_linguas()
#self.all_linguas = self.distribution.options['po']['all_linguas']
def run(self):
self.create_pot_file()
self.merge_files()
self.create_pot_file()
self.merge_files()
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
main function of pygettext.
"""
import glob
import tokenize
source_files = []
for p in self.packages:
pathlist = p.split('.')
path = apply(os.path.join, pathlist)
source_files.extend(glob.glob(os.path.join(path, '*.py')))
import glob
import tokenize
source_files = []
for p in self.packages:
pathlist = p.split('.')
path = apply(os.path.join, pathlist)
source_files.extend(glob.glob(os.path.join(path, '*.py')))
# slurp through all the files
eater = pygettext.TokenEater(self.options)
for filename in source_files:
if self.verbose:
print 'Working on %s' % filename
fp = open(filename)
try:
eater.set_filename(filename)
try:
tokenize.tokenize(fp.readline, eater)
except tokenize.TokenError, e:
print '%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1])
finally:
fp.close()
# slurp through all the files
eater = pygettext.TokenEater(self.options)
for filename in source_files:
if self.verbose:
print 'Working on %s' % filename
fp = open(filename)
try:
eater.set_filename(filename)
try:
tokenize.tokenize(fp.readline, eater)
except tokenize.TokenError, e:
print '%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1])
finally:
fp.close()
# write the output
if self.output == '-':
fp = sys.stdout
else:
fp = open(self.output, 'w')
try:
eater.write(fp)
finally:
if fp is not sys.stdout:
fp.close()
# write the output
if self.output == '-':
fp = sys.stdout
else:
fp = open(self.output, 'w')
try:
eater.write(fp)
finally:
if fp is not sys.stdout:
fp.close()
def merge_files(self):
if not self.all_linguas:
return
if not self.all_linguas:
return
for lingua in self.all_linguas:
d = {'msgmerge': self.msgmerge,
'po': os.path.join(self.output_dir, lingua + '.po'),
'pot': self.output
}
if self.verbose:
sys.stdout.write('Merging %(pot)s and %(po)s ' % d)
for lingua in self.all_linguas:
d = { 'msgmerge': self.msgmerge,
'po': os.path.join(self.output_dir, lingua + '.po'),
'pot': self.output
}
if self.verbose:
sys.stdout.write('Merging %(pot)s and %(po)s ' % d)
sys.stdout.flush()
res = os.system('%(msgmerge)s %(po)s %(pot)s -o %(po)s' % d)
if res:
SystemExit, 'error while running msgmerge.'
res = os.system('%(msgmerge)s %(po)s %(pot)s -o %(po)s' % d)
if res:
SystemExit, 'error while running msgmerge.'

View File

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

View File

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

View File

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

View File

@ -25,17 +25,18 @@ Options:
Display version information and exit.
"""
import array
import getopt
import os
import struct
import sys
import os
import getopt
import struct
import array
__version__ = "1.1"
MESSAGES = {}
def usage(code, msg=''):
print >> sys.stderr, __doc__
if msg:
@ -43,6 +44,7 @@ def usage(code, msg=''):
sys.exit(code)
def add(id, str, fuzzy):
"Add a non-fuzzy translation to the dictionary."
global MESSAGES
@ -50,6 +52,7 @@ def add(id, str, fuzzy):
MESSAGES[id] = str
def generate():
"Return the generated output."
global MESSAGES
@ -68,7 +71,7 @@ def generate():
# The header is 7 32-bit unsigned integers. We don't use hash tables, so
# the keys start right after the index tables.
# translated string.
keystart = 7 * 4 + 16 * len(keys)
keystart = 7*4+16*len(keys)
# and the values start after the keys
valuestart = keystart + len(ids)
koffsets = []
@ -76,22 +79,23 @@ def generate():
# 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.
for o1, l1, o2, l2 in offsets:
koffsets += [l1, o1 + keystart]
voffsets += [l2, o2 + valuestart]
koffsets += [l1, o1+keystart]
voffsets += [l2, o2+valuestart]
offsets = koffsets + voffsets
output = struct.pack("Iiiiiii",
0x950412deL, # Magic
0, # Version
len(keys), # # of entries
7 * 4, # start of key index
7 * 4 + len(keys) * 8, # start of value index
0, 0) # size and offset of hash table
0x950412deL, # Magic
0, # Version
len(keys), # # of entries
7*4, # start of key index
7*4+len(keys)*8, # start of value index
0, 0) # size and offset of hash table
output += array.array("i", offsets).tostring()
output += ids
output += strs
return output
def make(filename, outfile):
ID = 1
STR = 2
@ -109,7 +113,7 @@ def make(filename, outfile):
except IOError, msg:
print >> sys.stderr, msg
sys.exit(1)
section = None
fuzzy = 0
@ -151,7 +155,7 @@ def make(filename, outfile):
msgstr += l
else:
print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
'before:'
'before:'
print >> sys.stderr, l
sys.exit(1)
# Add last entry
@ -162,11 +166,12 @@ def make(filename, outfile):
output = generate()
try:
open(outfile, "wb").write(output)
except IOError, msg:
open(outfile,"wb").write(output)
except IOError,msg:
print >> sys.stderr, msg
def main():
try:
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.
"""
import string
import sys, string
class Overrides:
def __init__(self, filename=None):
self.overrides = {}
if filename:
self.read_overrides(filename)
def read_overrides(self, filename):
"""Read a file and return a dictionary of overriden properties
and their implementation.
@ -81,9 +83,9 @@ class Overrides:
deps = tuple(words[3:])
self.overrides[func] = (deps, string.join(rest, ''), '%d: %s' % (startline, line))
elif words[0] == 'comment':
pass # ignore comments
pass # ignore comments
else:
print "Unknown word: '%s', line %d"(words[0], startline)
print "Unknown word: '%s', line %d" (words[0], startline)
raise SystemExit
def has_override(self, key):

View File

@ -16,7 +16,6 @@
# for selftesting
try:
import fintl
_ = fintl.gettext
except ImportError:
_ = lambda s: s
@ -156,13 +155,13 @@ Options:
If `inputfile' is -, standard input is read.
""")
import getopt
import operator
import os
import sys
import time
import getopt
import token
import tokenize
import operator
__version__ = '1.5'
@ -171,6 +170,8 @@ DEFAULTKEYWORDS = ', '.join(default_keywords)
EMPTYSTRING = ''
# The normal pot-file header. msgmerge and Emacs's po-mode work better if it's
# there.
pot_header = _('''\
@ -192,7 +193,7 @@ msgstr ""
''')
def usage(code, msg=''):
print >> sys.stderr, __doc__ % globals()
if msg:
@ -200,9 +201,9 @@ def usage(code, msg=''):
sys.exit(code)
escapes = []
def make_escapes(pass_iso8859):
global escapes
if pass_iso8859:
@ -234,7 +235,7 @@ def escape(s):
def safe_eval(s):
# unwrap quotes, safely
return eval(s, {'__builtins__': {}}, {})
return eval(s, {'__builtins__':{}}, {})
def normalize(s):
@ -253,7 +254,7 @@ def normalize(s):
s = '""\n"' + lineterm.join(lines) + '"'
return s
def containsAny(str, 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
list.extend(
[os.path.join(dirname, file)
for file in names
if os.path.splitext(file)[1] == _py_ext])
for file in names
if os.path.splitext(file)[1] == _py_ext])
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,
or a directory.
"""
import imp
if not os.path.exists(name):
# check for glob chars
@ -350,7 +352,7 @@ def getFilesForName(name):
return []
class TokenEater:
def __init__(self, options):
self.__options = options
@ -363,9 +365,9 @@ class TokenEater:
def __call__(self, ttype, tstring, stup, etup, line):
# dispatch
## import token
## print >> sys.stderr, 'ttype:', token.tok_name[ttype], \
## 'tstring:', tstring
## import token
## print >> sys.stderr, 'ttype:', token.tok_name[ttype], \
## 'tstring:', tstring
self.__state(ttype, tstring, stup[0])
def __waiting(self, ttype, tstring, lineno):
@ -424,7 +426,7 @@ class TokenEater:
elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
token.NEWLINE, tokenize.NL]:
# 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}
self.__state = self.__waiting
@ -475,7 +477,7 @@ class TokenEater:
elif options.locationstyle == options.SOLARIS:
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
print >> fp, _(
print >>fp, _(
'# File: %(filename)s, line: %(lineno)d') % d
elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the
@ -497,6 +499,7 @@ class TokenEater:
print >> fp, 'msgstr ""\n'
def main():
global default_keywords
try:
@ -518,7 +521,7 @@ def main():
GNU = 1
SOLARIS = 2
# 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
keywords = []
outpath = ''
@ -532,8 +535,8 @@ def main():
nodocstrings = {}
options = Options()
locations = {'gnu': options.GNU,
'solaris': options.SOLARIS,
locations = {'gnu' : options.GNU,
'solaris' : options.SOLARIS,
}
# parse options
@ -654,10 +657,11 @@ def main():
if closep:
fp.close()
if __name__ == '__main__':
main()
# some more test strings
_(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')

View File

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

View File

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