Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generalizes to support multiple migrators #16

Merged
merged 7 commits into from Apr 18, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Expand Up @@ -23,7 +23,7 @@ All submissions, including submissions by project members, require review.
### File headers
All files in the project must start with the following header.

// Copyright 2018 Google LLC
// Copyright 2019 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
Expand Down
9 changes: 9 additions & 0 deletions bin/sass_migrator.dart
@@ -0,0 +1,9 @@
// Copyright 2019 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'package:sass_migrator/runner.dart';

main(List<String> args) => MigratorRunner().execute(args);
58 changes: 0 additions & 58 deletions bin/sass_module_migrator.dart

This file was deleted.

59 changes: 59 additions & 0 deletions lib/runner.dart
@@ -0,0 +1,59 @@
// Copyright 2019 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'dart:io';

import 'package:args/command_runner.dart';
import 'package:path/path.dart' as p;

import 'src/migrators/module.dart';

/// A command runner that runs a migrator based on provided arguments.
class MigratorRunner extends CommandRunner<p.PathMap<String>> {
final invocation = "sass_migrator <migrator> [options] <entrypoint.scss...>";

MigratorRunner()
: super("sass_migrator", "Migrates stylesheets to new Sass versions.") {
argParser.addFlag('migrate-deps',
abbr: 'd', help: 'Migrate dependencies in addition to entrypoints.');
argParser.addFlag('dry-run',
abbr: 'n',
help: 'Show which files would be migrated but make no changes.');
argParser.addFlag('verbose',
abbr: 'v',
help: 'Print text of migrated files when running with --dry-run.');
jathak marked this conversation as resolved.
Show resolved Hide resolved
addCommand(ModuleMigrator());
}

/// Runs a migrator and then writes the migrated files to disk unless
/// --dry-run is passed.
jathak marked this conversation as resolved.
Show resolved Hide resolved
Future execute(Iterable<String> args) async {
var argResults = parse(args);
var migrated = await runCommand(argResults);
if (migrated == null) return;

if (migrated.isEmpty) {
print('Nothing to migrate!');
return;
}

if (argResults['dry-run']) {
print('Dry run. Logging migrated files instead of overwriting...\n');
for (var path in migrated.keys) {
print('$path');
if (argResults['verbose']) {
print('=' * 80);
print(migrated[path]);
jathak marked this conversation as resolved.
Show resolved Hide resolved
}
}
} else {
for (var path in migrated.keys) {
if (argResults['verbose']) print("Overwriting $path...");
File(path).writeAsStringSync(migrated[path]);
}
}
}
}
101 changes: 101 additions & 0 deletions lib/src/migration_visitor.dart
@@ -0,0 +1,101 @@
// Copyright 2019 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'dart:io';

// The sass package's API is not necessarily stable. It is being imported with
// the Sass team's explicit knowledge and approval. See
// https://github.com/sass/dart-sass/issues/236.
import 'package:sass/src/ast/sass.dart';
import 'package:sass/src/syntax.dart';
import 'package:sass/src/visitor/recursive_ast.dart';

import 'package:path/path.dart' as p;

import 'migrator.dart';
import 'patch.dart';
import 'utils.dart';

/// A visitor that migrates a stylesheet.
///
/// When [run] is called, this visitor traverses a stylesheet's AST, allowing
/// subclasses to override one or more methods and add to [patches]. Once the
/// stylesheet has been visited, the migrated contents (based on [patches]) will
/// be stored in [migrator]'s [migrated] map.
///
/// If [migrateDependencies] is enabled, this visitor will construct and run a
/// new instance of itself (using [newInstance]) each time it encounters an
/// @import or @use rule.
jathak marked this conversation as resolved.
Show resolved Hide resolved
abstract class MigrationVisitor extends RecursiveAstVisitor {
/// The migrator running on this stylesheet.
Migrator get migrator;

/// The canonical path of the stylesheet being migrated.
jathak marked this conversation as resolved.
Show resolved Hide resolved
String get path;

/// The stylesheet being migrated.
Stylesheet stylesheet;
jathak marked this conversation as resolved.
Show resolved Hide resolved

/// The syntax this stylesheet uses.
Syntax syntax;
jathak marked this conversation as resolved.
Show resolved Hide resolved

/// The patches to be applied to the stylesheet being migrated.
final List<Patch> patches = [];
jathak marked this conversation as resolved.
Show resolved Hide resolved

/// Returns a new instance of this MigrationVisitor with the same migrator
/// and [newPath].
MigrationVisitor newInstance(String newPath);
jathak marked this conversation as resolved.
Show resolved Hide resolved

/// Runs the migrator and stores the migrated contents in `migrator.migrated`.
void run() {
var contents = File(path).readAsStringSync();
syntax = Syntax.forPath(path);
stylesheet = Stylesheet.parse(contents, syntax, url: path);
jathak marked this conversation as resolved.
Show resolved Hide resolved
visitStylesheet(stylesheet);
var results = getMigratedContents();
if (results != null) {
migrator.migrated[path] = results;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I mentioned above, it's a code smell when you're directly modifying another class's collection. It's also a code smell when you're making calls to the class that "owns" your class, rather than letting it make calls to you.

I'd probably make this method return the result of getMigratedContents(). Then the Migrator can choose what to do with that information.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed this to have migrated as a field of MigrationVisitor, with any dependency visitors created with newInstance getting a reference to the same map so that they can all add to it and the entrypoint's visitor can pass the complete map back to Migrator when run returns.

Do you think this is fine, or would it be better to have each visitor maintain its own map and then copy the results from each of its dependencies?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good question. I'd say make the migrated field private to MigrationVisitor and give it total responsibility for handling the output, but you need to pass it through newInstance() somehow...

What if we restructure this so that you don't need to construct multiple visitors at all? Rather than passing a URL to the constructor, pass it to run(). That also means that when we get around to de-duplicating repeated imports/uses (which will probably be necessary for large-scale performance), there's a natural place for that as well.

This does mean that per-file state can't just be stored as final fields on the subclass. But you can override visitStylesheet() to set it temporarily:

@override
void visitStylesheet(StylesheetNode node) {
  var oldNamespaces = _namespaces;
  var oldAdditionalUseRules = _additionalUseRules;
  var oldConfigurableVariables = _configurableVariables;
  _namespaces = {};
  _additionalUseRules = Set();
  _configurableVariables = normalizedSet();
  super.visitStylesheet(node);
  _namespaces = oldNamespaces;
  _additionalUseRules = oldAdditionalUseRules;
  _configurableVariables = oldConfigurableVariables;
}

This is basically how Dart Sass's EvaluateVisitor works. WDYT?

}
}

/// Returns the migrated contents of this file, or null if the file does not
/// change.
///
/// This will be called by [run] and the results will be stored in
/// `migrator.migrated`.
String getMigratedContents() => patches.isNotEmpty
jathak marked this conversation as resolved.
Show resolved Hide resolved
? Patch.applyAll(patches.first.selection.file, patches)
: null;

/// Returns the canonical path of [url] when resolved relative to the current
/// path.
String resolveImportUrl(String url) =>
jathak marked this conversation as resolved.
Show resolved Hide resolved
canonicalizePath(p.join(p.dirname(path), url));

/// If [migrator.migrateDependencies] is enabled, any dynamic imports within
/// this [node] will be migrated before continuing.
@override
visitImportRule(ImportRule node) {
super.visitImportRule(node);
for (var import in node.imports) {
if (import is DynamicImport) {
if (migrator.migrateDependencies) {
jathak marked this conversation as resolved.
Show resolved Hide resolved
newInstance(resolveImportUrl(import.url)).run();
}
}
}
}

/// If [migrator.migrateDependencies] is enabled, this dependency will be
/// migrated before continuing.
@override
visitUseRule(UseRule node) {
super.visitUseRule(node);
if (migrator.migrateDependencies) {
newInstance(resolveImportUrl(node.url.toString())).run();
}
}
}