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

Unified Diff: sdk/lib/_internal/pub/lib/src/command/serve.dart

Issue 20204003: First stab at a dev server in pub using barback. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Revise. Created 7 years, 5 months 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 side-by-side diff with in-line comments
Download patch
Index: sdk/lib/_internal/pub/lib/src/command/serve.dart
diff --git a/sdk/lib/_internal/pub/lib/src/command/serve.dart b/sdk/lib/_internal/pub/lib/src/command/serve.dart
new file mode 100644
index 0000000000000000000000000000000000000000..6ee964fc71b744015645eef1e3d2e53943d0fe06
--- /dev/null
+++ b/sdk/lib/_internal/pub/lib/src/command/serve.dart
@@ -0,0 +1,142 @@
+// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library pub.command.serve;
+
+import 'dart:async';
+import 'dart:io';
+
+import 'package:barback/barback.dart';
+import 'package:path/path.dart' as path;
+
+import '../command.dart';
+import '../entrypoint.dart';
+import '../exit_codes.dart' as exit_codes;
+import '../log.dart' as log;
+import '../pub_package_provider.dart';
+import '../utils.dart';
+
+final _green = getPlatformString('\u001b[32m');
+final _red = getPlatformString('\u001b[31m');
+final _none = getPlatformString('\u001b[0m');
+
+/// Handles the `serve` pub command.
+class ServeCommand extends PubCommand {
+ String get description => "Run a local web development server.";
+ String get usage => 'pub serve';
+
+ ServeCommand() {
+ commandParser.addOption('port', defaultsTo: '8080',
+ help: 'The port to listen on.');
+ }
+
+ Future onRun() {
+ return PubPackageProvider.create(entrypoint).then((provider) {
+ var port;
+ try {
+ port = int.parse(commandOptions['port']);
+ } on FormatException catch(_) {
+ log.error('Could not parse port "${commandOptions['port']}"');
+ this.printUsage();
+ exit(exit_codes.USAGE);
+ }
+
+ var barback = new Barback(provider);
+
+ barback.results.listen((result) {
+ if (result.succeeded) {
+ log.message("Build completed ${_green}successfully$_none");
+ } else {
+ log.message("Build completed with "
+ "${_red}${result.errors.length}$_none errors.");
+ }
+ });
+
+ barback.errors.listen((error) {
+ log.error("${_red}Build error:\n$error$_none");
+ });
+
+ // Add all of the visible files.
+ for (var package in provider.packages) {
+ barback.updateSources(provider.listAssets(package));
+ }
+ // TODO(rnystrom): Watch file system and update sources again when they
+ // are added or modified.
+
+ HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, port).then((server) {
+ log.message("Serving ${entrypoint.root.name} "
+ "on http://localhost:${server.port}");
+
+ server.listen((request) {
+ var id = getIdFromUri(request.uri);
+ barback.getAssetById(id).then((asset) {
+ log.message(
+ "$_green${request.method}$_none ${request.uri} -> $asset");
+ // TODO(rnystrom): Set content-type based on asset type.
+ return request.response.addStream(asset.read()).then((_) {
+ request.response.close();
+ });
+ }).catchError((error) {
+ log.error("$_red${request.method}$_none ${request.uri} -> $error");
+ if (error is AssetNotFoundException) {
+ request.response.statusCode = 404;
+ request.response.reasonPhrase = "Not Found";
+ request.response.write(error);
+ } else {
+ request.response.statusCode = 500;
+ request.response.reasonPhrase = "Internal Server Error";
+ request.response.writeln(error);
+ request.response.writeln(getAttachedStackTrace(error));
+ }
nweiz 2013/07/29 20:23:15 Error responses should have the content-type set t
+ request.response.close();
+ });
+ });
+ });
+
+ // TODO(rnystrom): Hack! Return a future that never completes to leave
+ // pub running.
+ return new Completer().future;
+ });
+ }
+
+ AssetId getIdFromUri(Uri uri) {
+ var uriBuilder = new path.Builder(style: path.Style.url);
nweiz 2013/07/29 20:23:15 I think the pattern we usually use for this is a t
Bob Nystrom 2013/07/29 21:45:43 Added default builders for each style to path and
+ var parts = uriBuilder.split(uri.path);
+
+ // Strip the leading "/" from the URL.
+ parts.removeAt(0);
+
+ // Special case: if the URL is "/", map it to "web/index.html".
+ // TODO(rnystrom): What about directory URLs? Should "foo" or "foo/" map
+ // to "foo/index.html"?
+ if (parts.isEmpty) parts = ["index.html"];
+
+ // Checks to see if [uri]'s path contains a special directory [name] that
+ // identifies an asset within some package. If so, maps the package name
+ // and path following that to be within [dir] inside that package.
+ AssetId _trySpecialUrl(String name, String dir) {
+ // Find the package name and the relative path in the package.
+ var index = parts.indexOf(name);
+ if (index == -1) return null;
+ if (index + 1 >= parts.length) return null;
+
+ var package = parts[index + 1];
+ var assetPath = uriBuilder.join(dir,
+ uriBuilder.joinAll(parts.skip(index + 2)));
+ return new AssetId(package, assetPath);
+ }
nweiz 2013/07/29 20:23:15 Currently this won't 404 for "/packages" if there'
Bob Nystrom 2013/07/29 21:45:43 Made it do the right thing.
+
+ // See if it's "packages" URL.
+ var id = _trySpecialUrl("packages", "lib");
+ if (id != null) return id;
+
+ // See if it's an "assets" URL.
+ id = _trySpecialUrl("assets", "asset");
+ if (id != null) return id;
+
+ // Otherwise, it's a path in current package's web directory.
+ return new AssetId(entrypoint.root.name,
+ uriBuilder.join("web", uriBuilder.joinAll(parts)));
+ }
+}

Powered by Google App Engine
This is Rietveld 408576698