Skip to content
Browse files

Docs and file organization.

  • Loading branch information...
1 parent 2493ab6 commit 138f3e01fb7742078faff8acfe9f2851d9b5e117 @anutron committed May 1, 2011
View
36 test_runner/mootools_request_php.py
@@ -0,0 +1,36 @@
+import time
+import simplejson
+from django.http import HttpResponse, HttpResponseRedirect
+
+def mootools_request_php(req):
+ """ Recreates Request.php from the MooTools specs runner environment. """
+ content_types = {
+ 'text': 'text/plain',
+ 'html': 'text/html',
+ 'xml': 'application/xml',
+ 'json': 'application/json',
+ 'script': 'application/javascript',
+ 'javascript': 'application/javascript'
+ }
+ sleep = req.REQUEST.get('__sleep')
+ response = req.REQUEST.get('__response')
+ reqtype = req.REQUEST.get('__type', 'html')
+ retrieve = req.REQUEST.get('__retrieve')
+ if sleep is not None:
+ time.sleep(float(sleep))
+
+ if response is not None:
+ return HttpResponse(response, mimetype=content_types[reqtype])
+ elif retrieve is not None:
+ response = simplejson.dumps(simplejson.loads(retrieve))
+ return HttpResponse(response, mimetype=content_types[reqtype])
+ else:
+ obj = {
+ 'method': req.META['REQUEST_METHOD'].lower()
+ }
+ if obj['method'] == 'get':
+ obj['get'] = simplejson.loads(simplejson.dumps(req.GET))
+ elif obj['method'] == 'post':
+ obj['post'] = simplejson.loads(simplejson.dumps(req.POST))
+ response = simplejson.dumps(obj)
+ return HttpResponse(response, mimetype=content_types[reqtype])
View
2 test_runner/templates/blank.mako
@@ -1,5 +1,5 @@
${test}
<link rel="stylesheet" href="/static/css/minibuttons.css" type="text/css" media="screen" title="no title" charset="utf-8">
-<%namespace name="components" file="test_components.mako" />
+<%namespace name="components" file="demo_components.mako" />
${components.nav(current=current)}
View
2 test_runner/templates/test.mako → test_runner/templates/demo.mako
@@ -1,4 +1,4 @@
-<%namespace name="components" file="test_components.mako" />
+<%namespace name="components" file="demo_components.mako" />
${components.header(title=title, projects=projects, current=current, next=next, previous=previous, excluded_tests=excluded_tests)}
${test}
${components.nav(current=current)}
View
0 test_runner/templates/test_components.mako → test_runner/templates/demo_components.mako
File renamed without changes.
View
2 test_runner/templates/markdown.mako
@@ -1,4 +1,4 @@
-<%namespace name="components" file="test_components.mako" />
+<%namespace name="components" file="demo_components.mako" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
View
2 test_runner/templates/view_source.mako
@@ -1,4 +1,4 @@
-<%namespace name="components" file="test_components.mako" />
+<%namespace name="components" file="demo_components.mako" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
View
67 test_runner/urls.py
@@ -1,39 +1,46 @@
from django.conf.urls.defaults import *
import os
-urlpatterns = patterns('test_runner.views',
- (r'^$', 'index'),
- (r'^test/', 'test'),
- (r'^bottom_frame/', 'bottom_frame'),
- (r'^welcome/', 'welcome'),
- (r'^top_nav/', 'top_nav'),
- (r'^test_menu/', 'test_menu'),
- (r'^docs_menu/', 'docs_menu'),
- (r'^specs/', 'specs'),
- (r'^benchmarks/', 'specs', {'template':'benchmarks.mako'}),
- (r'^moorunner/(?P<path>.*)$', 'moorunner'),
- (r'^Helpers/request.php$', 'mootools_request_php'),
- (r'^assets/(?P<path>.*)$', 'generic_asset'),
- (r'^source/', 'view_source'),
- (r'^docs/(?P<path>.*)$', 'docs'),
- (r'^get_source_file/(?P<project>(\w|-|_)+)/(?P<path>.*)$', 'get_source_file'),
- (r'^asset/(?P<project>(\w|-|_)+)/(?P<path>.*)$', 'asset'),
+urlpatterns = patterns('test_runner',
+ (r'^$', 'views.index'),
+ (r'^bottom_frame/', 'views.bottom_frame'),
+ (r'^top_nav/', 'views.top_nav'),
+
+ (r'^welcome/', 'views.welcome'),
+ (r'^test_menu/', 'views.test_menu'),
+ (r'^docs_menu/', 'views.docs_menu'),
+
+ (r'^docs/(?P<path>.*)$', 'views.docs'),
+ (r'^source/', 'views.view_source'),
+ (r'^demo/', 'views.demo'),
+ (r'^specs/', 'views.specs'),
+ (r'^moorunner/(?P<path>.*)$', 'views.moorunner'),
+ (r'^benchmarks/', 'views.specs', {'template':'benchmarks.mako'}),
+
+ (r'^assets/(?P<path>.*)$', 'views.generic_asset'),
+ (r'^get_source_file/(?P<project>(\w|-|_)+)/(?P<path>.*)$', 'views.get_source_file'),
+ (r'^asset/(?P<project>(\w|-|_)+)/(?P<path>.*)$', 'views.asset'),
(r'^depender/', include('depender.urls')),
+
# Echo
- url(r'^echo/js/$','echo_js', name='echo_js'),
- url(r'^echo/json/$','echo_json', name='echo_json'),
- url(r'^echo/jsonp/$','echo_jsonp', name='echo_jsonp'),
- url(r'^echo/html/$','echo_html', name='echo_html'),
- url(r'^echo/xml/$','echo_xml', name='echo_xml'),
+ url(r'^echo/js/$','views.echo_js', name='echo_js'),
+ url(r'^echo/json/$','views.echo_json', name='echo_json'),
+ url(r'^echo/jsonp/$','views.echo_jsonp', name='echo_jsonp'),
+ url(r'^echo/html/$','views.echo_html', name='echo_html'),
+ url(r'^echo/xml/$','views.echo_xml', name='echo_xml'),
# OLD ECHO
- url(r'^ajax_json_response/$','ajax_json_response', name='ajax_json_response'),
- url(r'^ajax_html_javascript_response/$','ajax_html_javascript_response', name='ajax_html_javascript_response'),
- url(r'^ajax_json_echo/$','ajax_json_echo', name='ajax_json_echo'),
- url(r'^ajax_json_echo/nodelay/$','ajax_json_echo', {'delay': False}, name='ajax_json_echo_nodelay'),
- url(r'^ajax_html_echo/$','ajax_html_echo', name='ajax_html_echo'),
- url(r'^ajax_html_echo/nodelay/$','ajax_html_echo', {'delay': False}, name='ajax_html_echo_nodelay'),
- url(r'^ajax_xml_echo/$','ajax_xml_echo', name='ajax_xml_echo'),
- url(r'^ajax_xml_echo/nodelay/$','ajax_xml_echo', {'delay': False}, name='ajax_xml_echo_nodelay'),
+ url(r'^ajax_json_response/$','views.ajax_json_response', name='ajax_json_response'),
+ url(r'^ajax_html_javascript_response/$','views.ajax_html_javascript_response', name='ajax_html_javascript_response'),
+ url(r'^ajax_json_echo/$','views.ajax_json_echo', name='ajax_json_echo'),
+ url(r'^ajax_json_echo/nodelay/$','views.ajax_json_echo', {'delay': False}, name='ajax_json_echo_nodelay'),
+ url(r'^ajax_html_echo/$','views.ajax_html_echo', name='ajax_html_echo'),
+ url(r'^ajax_html_echo/nodelay/$','views.ajax_html_echo', {'delay': False}, name='ajax_html_echo_nodelay'),
+ url(r'^ajax_xml_echo/$','views.ajax_xml_echo', name='ajax_xml_echo'),
+ url(r'^ajax_xml_echo/nodelay/$','views.ajax_xml_echo', {'delay': False}, name='ajax_xml_echo_nodelay'),
+
+ # MooTools request.php implementation
+ (r'^Helpers/request.php$', 'mootools_request_php.mootools_request_php'),
+
)
View
607 test_runner/views.py
@@ -26,33 +26,21 @@
MARKDOWN_MATCHER = re.compile("\.(markdown|md)$")
JS_MATCHER = re.compile("\.(js)$")
+excluded_tests = []
+if hasattr(settings,'EXCLUDED_TESTS'):
+ excluded_tests = settings.EXCLUDED_TESTS
+
def index(request):
+ """ The main frameset. """
return render_to_response('index.mako',
{
'title': settings.TITLE_PREFIX
}
)
-def top_nav(request):
- return render_to_response('top_nav.mako', {
- 'title': settings.TITLE_PREFIX,
- 'show_docs': True,
- 'show_demos': True,
- 'show_specs': True,
- 'show_benchmarks': True,
- })
-
-def bottom_frame(request):
- menu = request.REQUEST.get('menu_path')
- content = request.REQUEST.get('content_path')
- return render_to_response('bottom_frame.mako', {
- 'title': settings.TITLE_PREFIX,
- 'menu': menu,
- 'content': content
- })
-
def welcome(request):
+ """ The default 'home' page for the main content frame; pulls in WELCOME.md from the test_runner. """
welcome_file = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "WELCOME.md"))
welcome = open(welcome_file, 'rb').read()
return render_to_response('markdown.mako',
@@ -63,26 +51,101 @@ def welcome(request):
}
)
-def test_menu(request):
- projects, dir_map = get_files(settings.MOOTOOLS_TEST_LOCATIONS, HTML_MATCHER, url_maker=make_url)
- return render_to_response('left_menu.mako',
- {
- 'projects': projects,
- 'title': 'Demos',
- 'excluded_tests': get_excluded_tests()
- }
- )
-def docs_menu(request):
- projects, dir_map = get_docs_files()
- return render_to_response('left_menu.mako',
+
+# DEMOS
+def demo(request):
+ """ Given a project and path, renders the configured demo to the browser. """
+ project = request.REQUEST.get('project')
+ path = request.REQUEST.get('path')
+ sleeper(request)
+ if project is None or path is None:
+ raise Exception("You must specify a project and a path.")
+
+ projects, dir_map = get_test_files()
+
+ project_dir = settings.MOOTOOLS_TEST_LOCATIONS[project]
+ full_path = os.path.normpath(project_dir+path)
+
+ dir_keys = dir_map.keys()
+ try:
+ current_index = dir_keys.index(full_path)
+ except:
+ raise Exception("The path %s was not found." % path)
+
+ prev = None
+ next = None
+ found = False
+ for proj, directories in sorted(projects.items()):
+ if next is not None:
+ break
+ for directory in sorted(directories):
+ if next is not None:
+ break
+ for file_path, file_title in sorted(directory['file_dict'].items()):
+ if next is not None:
+ break
+ if found:
+ next = file_path
+ if str(file_path.split('path=')[-1]) == str(path):
+ found = True
+ if not found:
+ prev = file_path
+
+ if prev:
+ prev_name = make_title(prev.split('/')[-1])
+ else:
+ prev_name = None
+ if next:
+ next_name = make_title(next.split('/')[-1])
+ else:
+ next_name = None
+
+ test_source = open(full_path).read()
+ template = 'demo.mako'
+
+ post_vars = None
+ if request.POST: post_vars = request.POST.iteritems()
+ if request.REQUEST.get('sleep'):
+ sleep = int(request.REQUEST.get('sleep'))
+ time.sleep(sleep)
+ if re.search("mako$", full_path):
+ request.path = request.META.get('PATH_INFO')
+ if request.META.get('QUERY_STRING') and len(request.META.get('QUERY_STRING')) > 0:
+ request.path += "?" + request.META.get('QUERY_STRING')
+ def get_asset_url(project, path):
+ return "/asset/" + project + "/" + path
+ source = Template(test_source).render(
+ post_vars = post_vars,
+ get_var = request.REQUEST.get,
+ get_list = request.REQUEST.getlist,
+ request_path = request.path,
+ get_request = lambda: request,
+ get_asset_url = get_asset_url
+ )
+ else:
+ source = test_source
+ if 'test_runner_no_wrapper' in source or request.REQUEST.get('no_wrapper') == 'true':
+ template = 'blank.mako'
+
+ return render_to_response(template,
{
+ 'test': source,
+ 'title': make_title(path.split('/')[-1]),
+ 'current': make_demo_url(project, path),
'projects': projects,
- 'title': 'Docs',
+ 'title_prefix': settings.TITLE_PREFIX,
+ 'previous': prev,
+ 'prev_name':prev_name,
+ 'next': next,
+ 'next_name':next_name,
+ 'excluded_tests': excluded_tests,
}
)
+# SPECS
def specs(request, template="specs.mako"):
+ """ Renders either a menu to choose tests or the runner with the selected tests. """
specs = settings.MOOTOOLS_SPECS_AND_BENCHMARKS
if request.GET.get('preset') is None:
return render_to_response(template, {
@@ -99,32 +162,186 @@ def specs(request, template="specs.mako"):
})
def moorunner(request, path):
+ """ Returns an asset from the MooTools Jasmine test runner. """
return read_asset(os.path.normpath(settings.MOOTOOLS_RUNNER_PATH + '/' + path))
+
+# VIEW SOURCE
+def view_source(request):
+ """ Returns the contents of a given project/path combination in the view-source viewer. Reads
+ yaml files that configure addtional sources to include in the view. """
+ def format_code(extension, code_str):
+ """Fix indent and highlight code"""
+ try:
+ lexer = get_lexer_by_name('html', tabsize=2)
+ return highlight(code_str, lexer, HtmlFormatter())
+ except KeyError:
+ LOG.warn('Cannot find lexer for extension %s' % (extension,))
+ return "<div><pre>%s</pre></div>" % (code_str,)
+
+ project = request.REQUEST.get('project')
+ path = request.REQUEST.get('path')
+ if project is None or path is None:
+ raise Exception("You must specify a project and a path.")
+
+ projects, dir_map = get_test_files()
+ project_dir = settings.MOOTOOLS_TEST_LOCATIONS[project]
+ full_path = os.path.normpath(project_dir+path)
+
+ file_path, extension = os.path.splitext(path)
+ try:
+ data = format_code(extension[1:], file(full_path).read())
+ except OSError, ex:
+ raise Exception("Cannot read requested gallery template: %s" % (path,))
+
+ # Load the js references
+ js_data = { } # map of { name: js content }
+ yml_file = os.path.splitext(full_path)[0] + '.yml'
+ if os.path.exists(yml_file):
+ yml = yaml.load(file(yml_file))
+ try:
+ for ref in yml['js-references']:
+ try:
+ js_pkg, js_comp = ref.split('/')
+ except ValueError:
+ raise Exception('Invalid line "%s" in file %s' % (ref, yml_file))
+ try:
+ file_data = dep.get((js_pkg, js_comp))
+ js_data[ref] = format_code('js', file_data.content)
+ except:
+ raise Exception(
+ 'Cannot locate "%s" package "%s" component' % (js_pkg, js_comp))
+ except KeyError, ex:
+ LOG.warn('%s does not have a "js-references" section' % (yml_file,))
+
+ return render_to_response('view_source.mako',
+ {
+ 'data': data,
+ 'js_data': js_data,
+ 'title': make_title(path.split('/')[-1]),
+ 'current': make_demo_url(project, path),
+ 'projects': projects,
+ 'title_prefix': settings.TITLE_PREFIX,
+ }
+ )
+
+
+# DOCS
+def docs(request, path):
+ if path == '':
+ path = "test-runner/WELCOME"
+ if not re.search("md$(?i)", path):
+ path = path + '.md'
+ text = None
+ if '..' in path:
+ raise Exception('invalid path: %s' % path)
+ else:
+ md = os.path.abspath(os.path.join(settings.DOC_ROOT, path))
+ if os.path.isfile(md):
+ text = open(md, 'rb').read()
+ if text is None:
+ raise Exception("The path %s was not found." % path)
+ else:
+ parsed = markdown(text)
+ dirs, files = get_docs_files()
+
+ toc = []
+
+ def replacer(matchobj):
+ match = matchobj.group(0)
+ match = re.sub('\{#|}', '', match)
+ toc.append(match)
+ return '<a class="toc_anchor" name="' + match + '"></a><a href="#top" class="to_top">back to top</a>'
+
+ parsed = re.sub("\{#.*?}", replacer, parsed)
+
+ return render_to_response('markdown.mako',
+ {
+ 'body': parsed,
+ 'docs': files,
+ 'title': make_title(path.split('/')[-1]),
+ 'title_prefix': settings.TITLE_PREFIX,
+ 'current': 'docs/' + path,
+ 'dirs': dirs,
+ 'toc': toc
+ }
+ )
+
+
+# NAVIGATION
+def top_nav(request):
+ """ Renders the top navigation frame. """
+ return render_to_response('top_nav.mako', {
+ 'title': settings.TITLE_PREFIX,
+ 'show_docs': True,
+ 'show_demos': True,
+ 'show_specs': True,
+ 'show_benchmarks': True,
+ })
+
+def bottom_frame(request):
+ """ Given a url for the menu_path and content_path renders the bottom frames. """
+ menu = request.REQUEST.get('menu_path')
+ content = request.REQUEST.get('content_path')
+ return render_to_response('bottom_frame.mako', {
+ 'title': settings.TITLE_PREFIX,
+ 'menu': menu,
+ 'content': content
+ })
+
+def test_menu(request):
+ """ Renders a menu with a list of all available tests. """
+ projects, dir_map = get_files(settings.MOOTOOLS_TEST_LOCATIONS, HTML_MATCHER, url_maker=make_demo_url)
+ return render_to_response('left_menu.mako',
+ {
+ 'projects': projects,
+ 'title': 'Demos',
+ 'excluded_tests': excluded_tests
+ }
+ )
+def docs_menu(request):
+ """ Renders a menu with a list of all available docs. """
+ projects, dir_map = get_docs_files()
+ return render_to_response('left_menu.mako',
+ {
+ 'projects': projects,
+ 'title': 'Docs',
+ }
+ )
+
+
+
+# ASSETS
def get_source_file(request, project, path):
+ """ Given a project returns the contents of a file in its /Source directory. """
if '..' in path:
raise Exception("The path %s is invalid." % path)
full_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", project, "Source", path))
return read_asset(full_path)
-
def asset(request, project, path):
+ """ Given a project returns a file located in the test configuration path inside a subdirecotry called _assets. """
project_dir = settings.MOOTOOLS_TEST_LOCATIONS[project]
if '..' in path:
raise Exception("The path %s is invalid." % path)
full_path = os.path.normpath(project_dir + "/_assets/" + path)
return read_asset(full_path)
def assets(request, project, path):
+ """ Deprecated """
return asset(request, project, path)
def generic_asset(request, path):
+ """ A wrapper for generic paths. Reads configuration values from settings for any path and
+ returns the configured path's contents instead. This is useful when you are running specs
+ from a 3rd party (MooTools Core, for example) that expects certain files to be in a specific place. """
if hasattr(settings,'GENERIC_ASSETS') and settings.GENERIC_ASSETS[path] is not None:
return read_asset(os.path.normpath(settings.GENERIC_ASSETS[path]))
else:
raise Exception("The asset for %s was not found." % path)
def read_asset(path):
+ """ Given a path, reads the contents of that file and returns it with the proper mime type. """
if not os.path.isfile(path):
raise Exception("The file %s was not found." % path)
data = open(path, "rb").read()
@@ -147,85 +364,50 @@ def read_asset(path):
raise Exception("Unknown asset type (currently only html/png/gif/jpg/css/js are supported).")
-def mootools_request_php(req):
- content_types = {
- 'text': 'text/plain',
- 'html': 'text/html',
- 'xml': 'application/xml',
- 'json': 'application/json',
- 'script': 'application/javascript',
- 'javascript': 'application/javascript'
- }
- sleep = req.REQUEST.get('__sleep')
- response = req.REQUEST.get('__response')
- reqtype = req.REQUEST.get('__type', 'html')
- retrieve = req.REQUEST.get('__retrieve')
- if sleep is not None:
- time.sleep(float(sleep))
-
- if response is not None:
- return HttpResponse(response, mimetype=content_types[reqtype])
- elif retrieve is not None:
- response = simplejson.dumps(simplejson.loads(retrieve))
- return HttpResponse(response, mimetype=content_types[reqtype])
- else:
- obj = {
- 'method': req.META['REQUEST_METHOD'].lower()
- }
- if obj['method'] == 'get':
- obj['get'] = simplejson.loads(simplejson.dumps(req.GET))
- elif obj['method'] == 'post':
- obj['post'] = simplejson.loads(simplejson.dumps(req.POST))
- response = simplejson.dumps(obj)
- return HttpResponse(response, mimetype=content_types[reqtype])
-
+# ECHOS
# the following ajax responses borrowed from MooShell - thx Piotr!
def echo_js(req):
" respond JS from GET/POST['js']"
sleeper(req)
return HttpResponse(req.REQUEST.get('js', ''),
mimetype='application/javascript')
-
def echo_json(req):
- " respond with GET/POST['json'] "
- sleeper(req)
- try:
- response = simplejson.dumps(
- simplejson.loads(req.REQUEST.get('json', '{}')))
- except Exception, e:
- response = simplejson.dumps({'error': str(e)})
-
- return HttpResponse(
- response,
- mimetype='application/javascript'
- )
-
+ " respond with GET/POST['json'] "
+ sleeper(req)
+ try:
+ response = simplejson.dumps(
+ simplejson.loads(req.REQUEST.get('json', '{}')))
+ except Exception, e:
+ response = simplejson.dumps({'error': str(e)})
+
+ return HttpResponse(
+ response,
+ mimetype='application/javascript'
+ )
def echo_html(req):
" respond with GET/POST['html'] "
sleeper(req)
return HttpResponse(req.REQUEST.get('html', ''))
-
def echo_jsonp(req):
- " respond what provided via GET/POST "
- sleeper(req)
- response = {}
- callback = req.REQUEST.get('callback', False)
- noresponse_keys = ['callback', 'delay']
-
- for key, value in req.REQUEST.items():
- if key not in noresponse_keys:
- response.update({key: value})
-
- response = simplejson.dumps(response)
-
- if callback:
- response = '%s(%s);' % (callback, response)
-
- return HttpResponse(response, mimetype='application/javascript')
-
+ " respond what provided via GET/POST "
+ sleeper(req)
+ response = {}
+ callback = req.REQUEST.get('callback', False)
+ noresponse_keys = ['callback', 'delay']
+
+ for key, value in req.REQUEST.items():
+ if key not in noresponse_keys:
+ response.update({key: value})
+
+ response = simplejson.dumps(response)
+
+ if callback:
+ response = '%s(%s);' % (callback, response)
+
+ return HttpResponse(response, mimetype='application/javascript')
def echo_xml(req):
" respond with GET/POST['xml'] "
@@ -249,23 +431,20 @@ def ajax_json_echo(req, delay=True):
c['post_response'].update({key: value})
return HttpResponse(simplejson.dumps(c),mimetype='application/javascript')
-
def ajax_html_echo(req, delay=True):
" OLD: echo POST['html'] "
if delay:
time.sleep(random.uniform(1,3))
t = req.POST.get('html','')
return HttpResponse(t)
-
def ajax_xml_echo(req, delay=True):
" OLD: echo POST['xml'] "
if delay:
time.sleep(random.uniform(1,3))
t = req.POST.get('xml','')
return HttpResponse(t, mimetype='application/xml')
-
def ajax_json_response(req):
" OLD: standard JSON response "
response_string = req.POST.get('response_string','This is a sample string')
@@ -278,179 +457,21 @@ def ajax_json_response(req):
mimetype='application/javascript'
)
-
def ajax_html_javascript_response(req):
return HttpResponse("""<p>A sample paragraph</p>
<script type='text/javascript'>alert('sample alert');</script>""")
-def view_source(request):
- project = request.REQUEST.get('project')
- path = request.REQUEST.get('path')
- if project is None or path is None:
- raise Exception("You must specify a project and a path.")
-
- projects, dir_map = get_test_files()
- project_dir = settings.MOOTOOLS_TEST_LOCATIONS[project]
- full_path = os.path.normpath(project_dir+path)
-
- file_path, extension = os.path.splitext(path)
- try:
- data = format_code(extension[1:], file(full_path).read())
- except OSError, ex:
- raise Exception("Cannot read requested gallery template: %s" % (path,))
-
- # Load the js references
- js_data = { } # map of { name: js content }
- yml_file = os.path.splitext(full_path)[0] + '.yml'
- if os.path.exists(yml_file):
- yml = yaml.load(file(yml_file))
- try:
- for ref in yml['js-references']:
- try:
- js_pkg, js_comp = ref.split('/')
- except ValueError:
- raise Exception('Invalid line "%s" in file %s' % (ref, yml_file))
- try:
- file_data = dep.get((js_pkg, js_comp))
- js_data[ref] = format_code('js', file_data.content)
- except:
- raise Exception(
- 'Cannot locate "%s" package "%s" component' % (js_pkg, js_comp))
- except KeyError, ex:
- LOG.warn('%s does not have a "js-references" section' % (yml_file,))
-
- return render_to_response('view_source.mako',
- {
- 'data': data,
- 'js_data': js_data,
- 'title': make_title(path.split('/')[-1]),
- 'current': make_url(path, project),
- 'projects': projects,
- 'title_prefix': settings.TITLE_PREFIX,
- }
- )
-
-
-def format_code(extension, code_str):
- """Fix indent and highlight code"""
- try:
- lexer = get_lexer_by_name('html', tabsize=2)
- return highlight(code_str, lexer, HtmlFormatter())
- except KeyError:
- LOG.warn('Cannot find lexer for extension %s' % (extension,))
- return "<div><pre>%s</pre></div>" % (code_str,)
-
-
-def test(request):
- project = request.REQUEST.get('project')
- path = request.REQUEST.get('path')
- sleeper(request)
- if project is None or path is None:
- raise Exception("You must specify a project and a path.")
-
- projects, dir_map = get_test_files()
-
- project_dir = settings.MOOTOOLS_TEST_LOCATIONS[project]
- full_path = os.path.normpath(project_dir+path)
-
- dir_keys = dir_map.keys()
- try:
- current_index = dir_keys.index(full_path)
- except:
- raise Exception("The path %s was not found." % path)
-
- prev = None
- next = None
- found = False
- for proj, directories in sorted(projects.items()):
- if next is not None:
- break
- for directory in sorted(directories):
- if next is not None:
- break
- for file_path, file_title in sorted(directory['file_dict'].items()):
- if next is not None:
- break
- if found:
- next = file_path
- if str(file_path.split('path=')[-1]) == str(path):
- found = True
- if not found:
- prev = file_path
-
- if prev:
- prev_name = make_title(prev.split('/')[-1])
- else:
- prev_name = None
- if next:
- next_name = make_title(next.split('/')[-1])
- else:
- next_name = None
-
-
- test_source = open(full_path).read()
- template = 'test.mako'
-
- post_vars = None
- if request.POST: post_vars = request.POST.iteritems()
- if request.REQUEST.get('sleep'):
- sleep = int(request.REQUEST.get('sleep'))
- time.sleep(sleep)
- if re.search("mako$", full_path):
- request.path = request.META.get('PATH_INFO')
- if request.META.get('QUERY_STRING') and len(request.META.get('QUERY_STRING')) > 0:
- request.path += "?" + request.META.get('QUERY_STRING')
- source = Template(test_source).render(
- post_vars = post_vars,
- get_var = request.REQUEST.get,
- get_list = request.REQUEST.getlist,
- request_path = request.path,
- get_request = lambda: request,
- get_asset_url = get_asset_url
- )
- else:
- source = test_source
- if 'test_runner_no_wrapper' in source or request.REQUEST.get('no_wrapper') == 'true':
- template = 'blank.mako'
-
- return render_to_response(template,
- {
- 'test': source,
- 'title': make_title(path.split('/')[-1]),
- 'current': make_url(path, project),
- 'projects': projects,
- 'title_prefix': settings.TITLE_PREFIX,
- 'previous': prev,
- 'prev_name':prev_name,
- 'next': next,
- 'next_name':next_name,
- 'excluded_tests': get_excluded_tests(),
- }
- )
-
-def get_asset_url(project, path):
- return "/asset/" + project + "/" + path
-
-
-def get_excluded_tests():
- excluded_tests = []
- if hasattr(settings,'EXCLUDED_TESTS'):
- excluded_tests = settings.EXCLUDED_TESTS
- return excluded_tests
-
-def get_url(test):
- project_dir = settings.MOOTOOLS_TEST_LOCATIONS[test['project']]
- path = test['filename'].replace(project_dir, '')
- return make_url(path, test['project'])
+# FILE CRAWLERS
def get_files_by_project(project, directory, matcher, url_maker, dirs = None, file_map = None, include_root = None):
+ """ Given a project and a direcotry, returns all files in that directory that match the specified 'matcher' regular expression. """
if dirs is None:
dirs = {}
if file_map is None:
file_map = {}
def get_file_dict(files, directory):
- return dict([(url_maker(file.replace(directory, ''), project), make_title(file.split('/')[-1])) for file in files])
-
+ return dict([(url_maker(project, file.replace(directory, '')), make_title(file.split('/')[-1])) for file in files])
+
def match_files(current_dir, recurse=True):
matching_files = []
for entry in os.listdir(current_dir):
@@ -485,6 +506,7 @@ def match_files(current_dir, recurse=True):
def get_files(locations, matcher, url_maker):
+ """ Given a dict of locations, finds all files in those locations that match the specified 'matcher' regular expression. """
dirs = {}
file_map = {}
@@ -494,74 +516,47 @@ def get_files(locations, matcher, url_maker):
return dirs, file_map
def get_test_files(project = None):
+ """ Given a specified project, return all the HTML files in that configured path from the settings.
+ If no project is specified, returns all HTML files in all the configured test directories."""
if project:
return get_files_by_project(project, settings.MOOTOOLS_TEST_LOCATIONS[project],
- matcher=HTML_MATCHER, url_maker=make_url)
- return get_files(locations=settings.MOOTOOLS_TEST_LOCATIONS, matcher=HTML_MATCHER, url_maker=make_url)
+ matcher=HTML_MATCHER, url_maker=make_demo_url)
+ return get_files(locations=settings.MOOTOOLS_TEST_LOCATIONS, matcher=HTML_MATCHER, url_maker=make_demo_url)
def get_docs_files(project=None):
+ """ Gets all markdown documents in a specified project or, if none is specified, all the markdown
+ files in all the specified docs directories from the settings. """
if project:
return get_files_by_project(project, settings.DOCS[project],
matcher=MARKDOWN_MATCHER, url_maker=docs_url)
return get_files(locations=settings.DOCS, matcher=MARKDOWN_MATCHER, url_maker=docs_url)
def get_js_in_dir_tree(directory):
+ """ Given a path to a directory, finds all JavaScript files.
+ Does not appear to be used? """
js = []
for root, subdirs, files in os.walk(directory):
js.extend([os.path.join(directory, name) for name in os.listdir(os.path.join(directory)) if JS_MATCHER.search(name)])
for subdir in subdirs:
js.extend(get_js_in_dir_tree(os.path.join(directory, subdir)))
return js
-def make_url(path, project):
- return '/test/?project='+quote(project)+'&path='+path
+
+# URL & TITLE MAKERS
+def make_demo_url(project, path):
+ """ Given a path and a project, returns a url for the demo."""
+ return '/demo/?project='+quote(project)+'&path='+path
def make_title(path):
+ """ Given a path, return a suiteable title for the file name."""
return re.sub('[\._]', ' ', re.sub('(\.(html|mako|md|markdown))', '', path))
-def docs_url(path, project):
+def docs_url(project, path):
+ """ Given a project and a path, return the url for the docs. """
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
project_path = settings.DOCS[project]
docs_path = project_path.replace(root, '')
return os.path.normpath('/docs/' + docs_path + path);
-def docs(request, path):
- if path == '':
- path = "test-runner/WELCOME"
- if not re.search("md$(?i)", path):
- path = path + '.md'
- text = None
- if '..' in path:
- raise Exception('invalid path: %s' % path)
- else:
- md = os.path.abspath(os.path.join(settings.DOC_ROOT, path))
- if os.path.isfile(md):
- text = open(md, 'rb').read()
- if text is None:
- raise Exception("The path %s was not found." % path)
- else:
- parsed = markdown(text)
- dirs, files = get_docs_files()
-
- toc = []
-
- def replacer(matchobj):
- match = matchobj.group(0)
- match = re.sub('\{#|}', '', match)
- toc.append(match)
- return '<a class="toc_anchor" name="' + match + '"></a><a href="#top" class="to_top">back to top</a>'
-
- parsed = re.sub("\{#.*?}", replacer, parsed)
-
- return render_to_response('markdown.mako',
- {
- 'body': parsed,
- 'docs': files,
- 'title': make_title(path.split('/')[-1]),
- 'title_prefix': settings.TITLE_PREFIX,
- 'current': 'docs/' + path,
- 'dirs': dirs,
- 'toc': toc
- }
- )
-
+
+

0 comments on commit 138f3e0

Please sign in to comment.
Something went wrong with that request. Please try again.