OLD | NEW |
(Empty) | |
| 1 library pub.preprocess; |
| 2 import 'package:string_scanner/string_scanner.dart'; |
| 3 import 'version.dart'; |
| 4 String preprocess(String input, Map<String, Version> versions, sourceUrl) { |
| 5 if (!input.contains(new RegExp(r"^//[>#]", multiLine: true))) return input; |
| 6 return new _Preprocessor(input, versions, sourceUrl).run(); |
| 7 } |
| 8 class _Preprocessor { |
| 9 final StringScanner _scanner; |
| 10 final Map<String, Version> _versions; |
| 11 final _buffer = new StringBuffer(); |
| 12 _Preprocessor(String input, this._versions, sourceUrl) |
| 13 : _scanner = new StringScanner(input, sourceUrl: sourceUrl); |
| 14 String run() { |
| 15 while (!_scanner.isDone) { |
| 16 if (_scanner.scan(new RegExp(r"//#[ \t]*"))) { |
| 17 _if(); |
| 18 } else { |
| 19 _emitText(); |
| 20 } |
| 21 } |
| 22 _scanner.expectDone(); |
| 23 return _buffer.toString(); |
| 24 } |
| 25 void _emitText() { |
| 26 while (!_scanner.isDone && !_scanner.matches("//#")) { |
| 27 if (_scanner.scan("//>")) { |
| 28 if (!_scanner.matches("\n")) _scanner.expect(" "); |
| 29 } |
| 30 _scanner.scan(new RegExp(r"[^\n]*\n?")); |
| 31 _buffer.write(_scanner.lastMatch[0]); |
| 32 } |
| 33 } |
| 34 void _ignoreText() { |
| 35 while (!_scanner.isDone && !_scanner.matches("//#")) { |
| 36 _scanner.scan(new RegExp(r"[^\n]*\n?")); |
| 37 } |
| 38 } |
| 39 void _if() { |
| 40 _scanner.expect(new RegExp(r"if[ \t]+"), name: "if statement"); |
| 41 _scanner.expect(new RegExp(r"[a-zA-Z0-9_]+"), name: "package name"); |
| 42 var package = _scanner.lastMatch[0]; |
| 43 _scanner.scan(new RegExp(r"[ \t]*")); |
| 44 var constraint = VersionConstraint.any; |
| 45 if (_scanner.scan(new RegExp(r"[^\n]+"))) { |
| 46 try { |
| 47 constraint = new VersionConstraint.parse(_scanner.lastMatch[0]); |
| 48 } on FormatException catch (error) { |
| 49 _scanner.error("Invalid version constraint: ${error.message}"); |
| 50 } |
| 51 } |
| 52 _scanner.expect("\n"); |
| 53 var allowed = |
| 54 _versions.containsKey(package) && |
| 55 constraint.allows(_versions[package]); |
| 56 if (allowed) { |
| 57 _emitText(); |
| 58 } else { |
| 59 _ignoreText(); |
| 60 } |
| 61 _scanner.expect("//#"); |
| 62 _scanner.scan(new RegExp(r"[ \t]*")); |
| 63 if (_scanner.scan("else")) { |
| 64 _scanner.expect("\n"); |
| 65 if (allowed) { |
| 66 _ignoreText(); |
| 67 } else { |
| 68 _emitText(); |
| 69 } |
| 70 _scanner.expect("//#"); |
| 71 _scanner.scan(new RegExp(r"[ \t]*")); |
| 72 } |
| 73 _scanner.expect("end"); |
| 74 if (!_scanner.isDone) _scanner.expect("\n"); |
| 75 } |
| 76 } |
OLD | NEW |