template.dart 6.96 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:mustache/mustache.dart' as mustache;
6

7
import 'base/file_system.dart';
8
import 'cache.dart';
9 10 11 12 13 14 15 16 17 18 19
import 'globals.dart';

/// Expands templates in a directory to a destination. All files that must
/// undergo template expansion should end with the '.tmpl' extension. All other
/// files are ignored. In case the contents of entire directories must be copied
/// as is, the directory itself can end with '.tmpl' extension. Files within
/// such a directory may also contain the '.tmpl' extension and will be
/// considered for expansion. In case certain files need to be copied but
/// without template expansion (images, data files, etc.), the '.copy.tmpl'
/// extension may be used.
///
20 21 22 23 24
/// Folders with platform/language-specific content must be named
/// '<platform>-<language>.tmpl'.
///
/// Files in the destination will contain none of the '.tmpl', '.copy.tmpl'
/// or '-<language>.tmpl' extensions.
25 26
class Template {
  Template(Directory templateSource, Directory baseDir) {
27
    _templateFilePaths = <String, String>{};
28 29 30 31 32

    if (!templateSource.existsSync()) {
      return;
    }

33
    final List<FileSystemEntity> templateFiles = templateSource.listSync(recursive: true);
34 35 36 37 38 39 40

    for (FileSystemEntity entity in templateFiles) {
      if (entity is! File) {
        // We are only interesting in template *file* URIs.
        continue;
      }

41
      final String relativePath = fs.path.relative(entity.path,
42 43
          from: baseDir.absolute.path);

44
      if (relativePath.contains(templateExtension)) {
45 46 47
        // If '.tmpl' appears anywhere within the path of this entity, it is
        // is a candidate for rendering. This catches cases where the folder
        // itself is a template.
48
        _templateFilePaths[relativePath] = fs.path.absolute(entity.path);
49 50 51 52
      }
    }
  }

Ian Hickson's avatar
Ian Hickson committed
53 54
  factory Template.fromName(String name) {
    // All named templates are placed in the 'templates' directory
55
    final Directory templateDir = templateDirectoryInPackage(name);
56
    return Template(templateDir, templateDir);
Ian Hickson's avatar
Ian Hickson committed
57 58
  }

59 60
  static const String templateExtension = '.tmpl';
  static const String copyTemplateExtension = '.copy.tmpl';
61
  final Pattern _kTemplateLanguageVariant = RegExp(r'(\w+)-(\w+)\.tmpl.*');
62

63 64
  Map<String /* relative */, String /* absolute source */> _templateFilePaths;

65 66 67
  int render(
    Directory destination,
    Map<String, dynamic> context, {
68
    bool overwriteExisting = true,
69
    bool printStatusWhenWriting = true,
70
  }) {
71
    destination.createSync(recursive: true);
Devon Carew's avatar
Devon Carew committed
72
    int fileCount = 0;
73

74 75 76 77 78 79 80 81 82 83 84 85 86 87
    /// Returns the resolved destination path corresponding to the specified
    /// raw destination path, after performing language filtering and template
    /// expansion on the path itself.
    ///
    /// Returns null if the given raw destination path has been filtered.
    String renderPath(String relativeDestinationPath) {
      final Match match = _kTemplateLanguageVariant.matchAsPrefix(relativeDestinationPath);
      if (match != null) {
        final String platform = match.group(1);
        final String language = context['${platform}Language'];
        if (language != match.group(2))
          return null;
        relativeDestinationPath = relativeDestinationPath.replaceAll('$platform-$language.tmpl', platform);
      }
88 89 90 91 92
      // Only build a web project if explicitly asked.
      final bool web = context['web'];
      if (relativeDestinationPath.contains('web') && !web) {
        return null;
      }
93
      final String projectName = context['projectName'];
94
      final String androidIdentifier = context['androidIdentifier'];
95 96
      final String pluginClass = context['pluginClass'];
      final String destinationDirPath = destination.absolute.path;
97
      final String pathSeparator = fs.path.separator;
98
      String finalDestinationPath = fs.path
99
        .join(destinationDirPath, relativeDestinationPath)
100 101
        .replaceAll(copyTemplateExtension, '')
        .replaceAll(templateExtension, '');
102 103 104 105 106

      if (androidIdentifier != null) {
        finalDestinationPath = finalDestinationPath
            .replaceAll('androidIdentifier', androidIdentifier.replaceAll('.', pathSeparator));
      }
107 108
      if (projectName != null)
        finalDestinationPath = finalDestinationPath.replaceAll('projectName', projectName);
109 110
      if (pluginClass != null)
        finalDestinationPath = finalDestinationPath.replaceAll('pluginClass', pluginClass);
111 112 113 114
      return finalDestinationPath;
    }

    _templateFilePaths.forEach((String relativeDestinationPath, String absoluteSourcePath) {
115 116 117 118
      final bool withRootModule = context['withRootModule'] ?? false;
      if (!withRootModule && absoluteSourcePath.contains('flutter_root'))
        return;

119 120 121
      final String finalDestinationPath = renderPath(relativeDestinationPath);
      if (finalDestinationPath == null)
        return;
122 123
      final File finalDestinationFile = fs.file(finalDestinationPath);
      final String relativePathForLogging = fs.path.relative(finalDestinationFile.path);
124 125 126 127 128

      // Step 1: Check if the file needs to be overwritten.

      if (finalDestinationFile.existsSync()) {
        if (overwriteExisting) {
129
          finalDestinationFile.deleteSync(recursive: true);
130 131
          if (printStatusWhenWriting)
            printStatus('  $relativePathForLogging (overwritten)');
132 133
        } else {
          // The file exists but we cannot overwrite it, move on.
134 135
          if (printStatusWhenWriting)
            printTrace('  $relativePathForLogging (existing - skipped)');
136 137 138
          return;
        }
      } else {
139 140
        if (printStatusWhenWriting)
          printStatus('  $relativePathForLogging (created)');
141 142
      }

Devon Carew's avatar
Devon Carew committed
143 144
      fileCount++;

145
      finalDestinationFile.createSync(recursive: true);
146
      final File sourceFile = fs.file(absoluteSourcePath);
147

148
      // Step 2: If the absolute paths ends with a '.copy.tmpl', this file does
149 150
      //         not need mustache rendering but needs to be directly copied.

151 152
      if (sourceFile.path.endsWith(copyTemplateExtension)) {
        sourceFile.copySync(finalDestinationFile.path);
153 154 155 156 157 158 159

        return;
      }

      // Step 3: If the absolute path ends with a '.tmpl', this file needs
      //         rendering via mustache.

160
      if (sourceFile.path.endsWith(templateExtension)) {
161
        final String templateContents = sourceFile.readAsStringSync();
162
        final String renderedContents = mustache.Template(templateContents).renderString(context);
163 164 165 166 167 168 169 170 171

        finalDestinationFile.writeAsStringSync(renderedContents);

        return;
      }

      // Step 4: This file does not end in .tmpl but is in a directory that
      //         does. Directly copy the file to the destination.

172
      sourceFile.copySync(finalDestinationFile.path);
173
    });
Devon Carew's avatar
Devon Carew committed
174 175

    return fileCount;
176 177 178
  }
}

179
Directory templateDirectoryInPackage(String name) {
180
  final String templatesDir = fs.path.join(Cache.flutterRoot,
181
      'packages', 'flutter_tools', 'templates');
182
  return fs.directory(fs.path.join(templatesDir, name));
183
}