Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(464)

Side by Side Diff: client/tools/htmlconverter.py

Issue 8495002: Support --frog flag in htmlconverter.py (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 9 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file 1 # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
2 # for details. All rights reserved. Use of this source code is governed by a 2 # for details. All rights reserved. Use of this source code is governed by a
3 # BSD-style license that can be found in the LICENSE file. 3 # BSD-style license that can be found in the LICENSE file.
4 4
5 #!/usr/bin/env python 5 #!/usr/bin/env python
6 # 6 #
7 7
8 """Rewrites HTML files, converting Dart script sections into JavaScript. 8 """Rewrites HTML files, converting Dart script sections into JavaScript.
9 9
10 Process HTML files, and internally changes script sections that use Dart code 10 Process HTML files, and internally changes script sections that use Dart code
(...skipping 17 matching lines...) Expand all
28 LIBRARY_PATTERN = "^#library\(.*\);" 28 LIBRARY_PATTERN = "^#library\(.*\);"
29 IMPORT_SOURCE_MATCHER = re.compile( 29 IMPORT_SOURCE_MATCHER = re.compile(
30 r"^ *(#import|#source)(\(['\"])([^'\"]*)(.*\);)", re.MULTILINE) 30 r"^ *(#import|#source)(\(['\"])([^'\"]*)(.*\);)", re.MULTILINE)
31 DOM_IMPORT_MATCHER = re.compile( 31 DOM_IMPORT_MATCHER = re.compile(
32 r"^#import\(['\"]dart\:dom['\"].*\);", re.MULTILINE) 32 r"^#import\(['\"]dart\:dom['\"].*\);", re.MULTILINE)
33 HTML_NO_PREFIX_IMPORT_MATCHER = re.compile( 33 HTML_NO_PREFIX_IMPORT_MATCHER = re.compile(
34 r"^#import.*(dart:html|html.dart)['\"]\);", re.MULTILINE) 34 r"^#import.*(dart:html|html.dart)['\"]\);", re.MULTILINE)
35 JSON_IMPORT_MATCHER = re.compile( 35 JSON_IMPORT_MATCHER = re.compile(
36 r"^#import\(['\"]dart:json['\"].*\);", re.MULTILINE) 36 r"^#import\(['\"]dart:json['\"].*\);", re.MULTILINE)
37 37
38 COMPILER_NOT_FOUND_ERROR = ( 38 DARTC_NOT_FOUND_ERROR = (
39 """Couldn't find compiler: please run the following commands: 39 """Couldn't find compiler: please run the following commands:
40 $ cd %s 40 $ cd %s
41 $ ./tools/build.py --arch=ia32""") 41 $ ./tools/build.py --arch=ia32""")
42 42
43 FROG_NOT_FOUND_ERROR = (
44 """Couldn't find compiler: please run the following commands:
45 $ cd %s/frog
46 $ ./tools/build.py -m release""")
47
43 ENTRY_POINT = """ 48 ENTRY_POINT = """
44 #library('entry'); 49 #library('entry');
45 #import('dart:dom'); 50 #import('dart:dom');
46 #import('%s', prefix: 'original'); 51 #import('%s', prefix: 'original');
47 main() { 52 main() {
48 window.addEventListener('DOMContentLoaded', (e) => original.main(), false); 53 window.addEventListener('DOMContentLoaded', (e) => original.main(), false);
49 } 54 }
50 """ 55 """
51 56
52 CSS_TEMPLATE = '<style type="text/css">%s</style>' 57 CSS_TEMPLATE = '<style type="text/css">%s</style>'
(...skipping 20 matching lines...) Expand all
73 def repl(matchobj): 78 def repl(matchobj):
74 path = matchobj.group(3) 79 path = matchobj.group(3)
75 if not path.startswith('dart:'): 80 if not path.startswith('dart:'):
76 path = abspath(path) 81 path = abspath(path)
77 return (matchobj.group(1) + matchobj.group(2) + path + matchobj.group(4)) 82 return (matchobj.group(1) + matchobj.group(2) + path + matchobj.group(4))
78 return IMPORT_SOURCE_MATCHER.sub(repl, contents) 83 return IMPORT_SOURCE_MATCHER.sub(repl, contents)
79 84
80 class DartCompiler(object): 85 class DartCompiler(object):
81 """ Common code for compiling Dart script tags in an HTML file. """ 86 """ Common code for compiling Dart script tags in an HTML file. """
82 87
83 def __init__(self, optimize=False, verbose=False, extra_flags=""): 88 def __init__(self, optimize=False, use_frog=False, verbose=False,
89 extra_flags=""):
84 self.optimize = optimize 90 self.optimize = optimize
85 self.verbose = verbose 91 self.verbose = verbose
86 self.extra_flags = extra_flags 92 self.extra_flags = extra_flags
93 self.use_frog = use_frog
87 94
88 def compileCode(self, src=None, body=None): 95 def compileCode(self, src=None, body=None):
89 """ Compile the given source code. 96 """ Compile the given source code.
90 97
91 Either the script tag has a src attribute or a non-empty body (one of the 98 Either the script tag has a src attribute or a non-empty body (one of the
92 arguments will be none, the other is not). 99 arguments will be none, the other is not).
93 100
94 Args: 101 Args:
95 src: a string pointing to a Dart script file. 102 src: a string pointing to a Dart script file.
96 body: a string containing Dart code. 103 body: a string containing Dart code.
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
157 with open(self.outputFileName(wrappedfile, outdir), 'r') as f: 164 with open(self.outputFileName(wrappedfile, outdir), 'r') as f:
158 res = f.read() 165 res = f.read()
159 166
160 # Cleanup 167 # Cleanup
161 if indir is not None: 168 if indir is not None:
162 shutil.rmtree(indir) 169 shutil.rmtree(indir)
163 shutil.rmtree(outdir) 170 shutil.rmtree(outdir)
164 return CHROMIUM_SCRIPT_TEMPLATE % res 171 return CHROMIUM_SCRIPT_TEMPLATE % res
165 172
166 def compileCommand(self, inputfile, outdir): 173 def compileCommand(self, inputfile, outdir):
167 binary = abspath(join(DART_PATH, 174 if not self.use_frog:
168 # TODO(sigmund): support also mode = release 175 binary = abspath(join(DART_PATH,
169 utils.GetBuildRoot(utils.GuessOS(), 'debug', 'ia32'), 176 # TODO(sigmund): support also mode = release
170 'dartc')) 177 utils.GetBuildRoot(utils.GuessOS(), 'debug', 'ia32'),
171 if not exists(binary): 178 'dartc'))
172 raise ConverterException(COMPILER_NOT_FOUND_ERROR % DART_PATH) 179 if not exists(binary):
173 cmd = [binary, 180 raise ConverterException(DARTC_NOT_FOUND_ERROR % DART_PATH)
174 '-noincremental', 181 cmd = [binary,
175 '--work', outdir, 182 '-noincremental',
176 '--out', self.outputFileName(inputfile, outdir)] 183 '--work', outdir,
177 if self.optimize: 184 '--out', self.outputFileName(inputfile, outdir)]
178 cmd.append('--optimize') 185 if self.optimize:
179 cmd.append(self.extra_flags); 186 cmd.append('--optimize')
187 else:
188 binary = abspath(join(DART_PATH, 'frog',
189 utils.GetBuildRoot(utils.GuessOS(), 'release', 'ia32'),
190 'frog', 'bin', 'frogsh'))
191 if not exists(binary):
192 raise ConverterException(FROG_NOT_FOUND_ERROR % DART_PATH)
193 cmd = [binary, '--compile-only',
194 '--out=' + self.outputFileName(inputfile, outdir)]
195 if self.extra_flags != "":
196 cmd.append(self.extra_flags);
180 cmd.append(inputfile) 197 cmd.append(inputfile)
181 return cmd 198 return cmd
182 199
183 def outputFileName(self, inputfile, outdir): 200 def outputFileName(self, inputfile, outdir):
184 return join(outdir, basename(inputfile) + '.js') 201 return join(outdir, basename(inputfile) + '.js')
185 202
186 def execute(cmd, verbose=False): 203 def execute(cmd, verbose=False):
187 """Execute a command in a subprocess. """ 204 """Execute a command in a subprocess. """
188 if verbose: print 'Executing: ' + ' '.join(cmd) 205 if verbose: print 'Executing: ' + ' '.join(cmd)
189 try: 206 try:
(...skipping 271 matching lines...) Expand 10 before | Expand all | Expand 10 after
461 """ An exception encountered during the convertion process """ 478 """ An exception encountered during the convertion process """
462 pass 479 pass
463 480
464 def Flags(): 481 def Flags():
465 """ Constructs a parser for extracting flags from the command line. """ 482 """ Constructs a parser for extracting flags from the command line. """
466 result = optparse.OptionParser() 483 result = optparse.OptionParser()
467 result.add_option("--optimize", 484 result.add_option("--optimize",
468 help="Use optimizer in dartc", 485 help="Use optimizer in dartc",
469 default=False, 486 default=False,
470 action="store_true") 487 action="store_true")
488 result.add_option("--frog",
489 help="Use the frog compiler",
490 default=False,
491 action="store_true")
471 result.add_option("--verbose", 492 result.add_option("--verbose",
472 help="Print verbose output", 493 help="Print verbose output",
473 default=False, 494 default=False,
474 action="store_true") 495 action="store_true")
475 result.add_option("-o", "--out", 496 result.add_option("-o", "--out",
476 help="Output directory", 497 help="Output directory",
477 type="string", 498 type="string",
478 default=None, 499 default=None,
479 action="store") 500 action="store")
480 result.add_option("-t", "--target", 501 result.add_option("-t", "--target",
(...skipping 20 matching lines...) Expand all
501 contents = f.read() 522 contents = f.read()
502 prefix_path = dirname(filename) 523 prefix_path = dirname(filename)
503 524
504 # outdirBase is the directory to place all subdirectories for other dart files 525 # outdirBase is the directory to place all subdirectories for other dart files
505 # and resources. 526 # and resources.
506 converter = DartToDartHTMLConverter(prefix_path, outdirBase, verbose) 527 converter = DartToDartHTMLConverter(prefix_path, outdirBase, verbose)
507 converter.feed(contents) 528 converter.feed(contents)
508 converter.close() 529 converter.close()
509 writeOut(converter.getResult(), outfile) 530 writeOut(converter.getResult(), outfile)
510 531
511 def convertForChromium(filename, optimize, extra_flags, outfile, verbose): 532 def convertForChromium(
533 filename, optimize, use_frog, extra_flags, outfile, verbose):
512 """ Converts a file for a chromium target. """ 534 """ Converts a file for a chromium target. """
513 with open(filename, 'r') as f: 535 with open(filename, 'r') as f:
514 contents = f.read() 536 contents = f.read()
515 prefix_path = dirname(filename) 537 prefix_path = dirname(filename)
516 converter = DartHTMLConverter(DartCompiler(optimize, verbose, extra_flags), 538 converter = DartHTMLConverter(
517 prefix_path) 539 DartCompiler(optimize, use_frog, verbose, extra_flags), prefix_path)
518 converter.feed(contents) 540 converter.feed(contents)
519 converter.close() 541 converter.close()
520 writeOut(converter.getResult(), outfile) 542 writeOut(converter.getResult(), outfile)
521 543
522 def convertForOffline(filename, outfile, verbose, encode_images): 544 def convertForOffline(filename, outfile, verbose, encode_images):
523 """ Converts a file for offline use. """ 545 """ Converts a file for offline use. """
524 with codecs.open(filename, 'r', 'utf-8') as f: 546 with codecs.open(filename, 'r', 'utf-8') as f:
525 contents = f.read() 547 contents = f.read()
526 converter = OfflineHTMLConverter(dirname(filename), 548 converter = OfflineHTMLConverter(dirname(filename),
527 dirname(outfile), 549 dirname(outfile),
(...skipping 19 matching lines...) Expand all
547 return 1 569 return 1
548 570
549 try: 571 try:
550 filename = args[0] 572 filename = args[0]
551 extension = filename[filename.rfind('.'):] 573 extension = filename[filename.rfind('.'):]
552 if extension != '.html' and extension != '.htm': 574 if extension != '.html' and extension != '.htm':
553 print "Invalid input file extension: %s" % extension 575 print "Invalid input file extension: %s" % extension
554 return 1 576 return 1
555 outfile = join(options.out, filename) 577 outfile = join(options.out, filename)
556 if 'chromium' in options.target or 'js' in options.target: 578 if 'chromium' in options.target or 'js' in options.target:
557 convertForChromium(filename, options.optimize, options.extra_flags, 579 convertForChromium(filename, options.optimize,
580 options.frog, options.extra_flags,
558 outfile.replace(extension, '-js' + extension), options.verbose) 581 outfile.replace(extension, '-js' + extension), options.verbose)
559 if 'dartium' in options.target: 582 if 'dartium' in options.target:
560 convertForDartium(filename, options.out, 583 convertForDartium(filename, options.out,
561 outfile.replace(extension, '-dart' + extension), options.verbose) 584 outfile.replace(extension, '-dart' + extension), options.verbose)
562 except Exception as e: 585 except Exception as e:
563 print "%sERROR%s: %s" % (RED_COLOR, NO_COLOR, str(e)) 586 print "%sERROR%s: %s" % (RED_COLOR, NO_COLOR, str(e))
564 return 1 587 return 1
565 return 0 588 return 0
566 589
567 if __name__ == '__main__': 590 if __name__ == '__main__':
568 sys.exit(main()) 591 sys.exit(main())
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698