compileFile function

Future<bool> compileFile(
  1. String sourceName, {
  2. String? destinationName,
  3. bool verbose = false,
  4. bool newer = false,
  5. bool lineNumber = false,
  6. Encoding encoding = utf8,
  7. List<String>? imports,
  8. void onCompile(
    1. String source, {
    2. bool skipped,
    })?,
})

Compiles the RSP document of the given sourceName and write the result to the file of given destinationName.

It returns true if the file has been compiled.

  • newer - If true, it compiles only if the source file is newer or the destination file doesn't exist.
  • imports - additional imported packages, such as ["package:foo/foo.dart"].
  • onCompile - Optional. If specified, it is called when compiling a file, or when skipping the compilation because of not-modified

Implementation

Future<bool> compileFile(String sourceName, {String? destinationName,
    bool verbose = false, bool newer = false,
    bool lineNumber = false, Encoding encoding = utf8, List<String>? imports,
    void onCompile(String source, {bool skipped})?}) async {
  final source = File(sourceName);
  if (!await source.exists()) {
    print("File not found: ${sourceName}");
    return false;
  }

  File dest;
  if (destinationName == null) {
    final int i = sourceName.lastIndexOf('.');
    final int j = sourceName.lastIndexOf('/');
    destinationName = i >= 0 && j < i ? "${sourceName.substring(0, i + 1)}dart" : "${sourceName}.dart";
    dest = await _locate(destinationName);
  } else {
    dest = File(destinationName);
  }

  if (newer) {
    try {
      if ((await source.lastModified()).isBefore(await dest.lastModified())) {
        onCompile?.call(sourceName, skipped: true);
        return false;
      }
    } catch (_) {
      //ignore
    }
  }

  if (Path.normalize(source.path) == Path.normalize(dest.path)) {
    print("Source and destination are the same file, $source");
    return false;
  }

  if (verbose) {
    final int i = dest.path.lastIndexOf('/') + 1;
    print("Compile ${source.path} to ${i > 0 ? dest.path.substring(i) : dest.path}");
  }

  final text = await source.readAsString(encoding: encoding);
  final out = dest.openWrite(encoding: encoding);
  try {
    onCompile?.call(sourceName, skipped: false);
    compile(text, out, sourceName: sourceName,
        destinationName: _unipath(dest.path), //force to use '/' even in Windows
        encoding: encoding, verbose: verbose, lineNumber: lineNumber,
        imports: imports);
    return true;
  } on SyntaxError catch (e) {
    print("${e.message}\nCompilation aborted.");
    return false;
  } finally {
    out.close();
  }
}