Permalink
Browse files

LICENSE, README, clean up public API, etc.

  • Loading branch information...
munificent committed Nov 7, 2014
1 parent 0757d74 commit 46a5419acbbb412a9aad4db27bfd85c1d954ac7b
Showing with 332 additions and 149 deletions.
  1. +1 −0 CHANGELOG.md
  2. +26 −0 LICENSE
  3. +72 −0 README.md
  4. +0 −84 bin/fmt.dart
  5. +108 −0 bin/format.dart
  6. +29 −0 example/format.dart
  7. +1 −0 lib/dart_style.dart
  8. +12 −62 lib/src/dart_formatter.dart
  9. +28 −0 lib/src/error_listener.dart
  10. +44 −0 lib/src/formatter_exception.dart
  11. +1 −1 pubspec.lock
  12. +10 −2 pubspec.yaml
View
@@ -0,0 +1 @@
*No changes yet!*
View
26 LICENSE
@@ -0,0 +1,26 @@
Copyright 2014, the Dart project authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
View
@@ -0,0 +1,72 @@
The dart_style package defines an automatic, opinionated formatter for Dart
code. It replaces the whitespace in your program with what it deems to be the
best formatting for it. Resulting code should following the [Dart style guide][]
but, moreso, should look nice to most human readers, most of the time.
It handles indentation, inline whitespace and (by far the most difficult),
intelligent line wrapping. It has no problems with nested collections, function
expressions, long argument lists, or otherwise tricky code.
## Running it
The package exposes a simple command-line wrapper around the core formatting
library. The easiest way to invoke it is to [globally activate][] the package
and let pub put its executable on your path:
$ pub global activate dart_style
$ dartfmt ...
If you don't want `dartfmt` on your path, you can run it explicitly:
$ pub global activate dart_style --no-executables
$ pub global run dart_style:format ...
The formatter takes a list of paths, which can point to directories or files.
If the path is a directory, it processes every `.dart` file in that directory
or any of its subdirectories.
By default, it formats each file and just prints the resulting code to stdout.
If you pass `-w`, it will instead overwrite your existing files with the
formatted results.
You may pass an `--line-length` option to control the width of the page that it
wraps lines to fit within, but you're strongly encouraged to keep the default
line length of 80 columns.
## Using it programmatically
The package also exposes a single dart_style library containing a programmatic
API for formatting code. Simple usage looks like this:
import 'package:dart_style/dart_style.dart';
main() {
var formatter = new DartFormatter();
try {
formatter.format("""
library an_entire_compilation_unit;
class SomeClass {}
""");
formatter.formatStatement("aSingle(statement);");
} on FormatterException catch (ex) {
print(ex);
}
}
[dart style guide]: https://www.dartlang.org/articles/style-guide/
[globally activate]: https://www.dartlang.org/tools/pub/cmd/pub-global.html
## Stability
You can rely on the formatter to not break your code or change its semantics.
If it does do so, this is a critical bug and we'll fix it quickly.
The heuristics the formatter uses to determine the "best" way to split a line
are still being developed and may change over time. The ones today cover most
common uses, but there's room for more refinement. We don't promise that code
produced by the formatter today will be identical to the same code run through
a later version of the formatter. We do hope that you'll like the output of the
later version more.
View
@@ -1,84 +0,0 @@
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:dart_style/dart_style.dart';
main(List<String> args) {
if (args.length == 1) {
if (new Directory(args[0]).existsSync()) {
reformatDirectory(args[0]);
} else if (new File(args[0]).existsSync()) {
reformatFile(args[0]);
} else {
// TODO(rnystrom): Report error.
}
return;
}
// This code is just for testing right now.
/*
1234567890123456789012345678901234567890
*/
formatStmt("sendPort.send({'type': 'error', 'error': 'oops'});");
}
void formatStmt(String source, [int pageWidth = 40]) {
var result = new DartFormatter(pageWidth: pageWidth).formatStatement(source);
drawRuler("before", pageWidth);
print(source);
drawRuler("after", pageWidth);
print(result);
}
void formatUnit(String source, [int pageWidth = 40]) {
var result = new DartFormatter(pageWidth: pageWidth).format(source);
drawRuler("before", pageWidth);
print(source);
drawRuler("after", pageWidth);
print(result);
}
void drawRuler(String label, int width) {
var padding = " " * (width - label.length - 1);
print("$label:$padding|");
}
/// Runs the formatter on every .dart file in [path] (and its subdirectories),
/// and replaces them with their formatted output.
void reformatDirectory(String path) {
for (var entry in new Directory(path).listSync(recursive: true)) {
if (!entry.path.endsWith(".dart")) continue;
var relative = p.relative(entry.path, from: path);
print(relative);
var formatter = new DartFormatter();
try {
var file = entry as File;
var source = file.readAsStringSync();
var formatted = formatter.format(source);
file.writeAsStringSync(formatted);
print("$relative: done");
} on FormatterException catch(err) {
print("$relative: failed with\n$err");
}
}
}
void reformatFile(String path) {
var formatter = new DartFormatter();
try {
var file = new File(path);
var source = file.readAsStringSync();
var formatted = formatter.format(source);
file.writeAsStringSync(formatted);
print("$path: done");
} on FormatterException catch(err) {
print("$path: failed with\n$err");
}
}
View
@@ -0,0 +1,108 @@
import 'dart:io';
import 'package:args/args.dart';
import 'package:path/path.dart' as p;
import 'package:dart_style/dart_style.dart';
bool overwrite = false;
int lineLength = 80;
void main(List<String> args) {
var parser = new ArgParser();
parser.addFlag("help", abbr: "h", negatable: false,
help: "Shows usage information.");
parser.addOption("line-length", abbr: "l",
help: "Wrap lines longer than this.",
defaultsTo: "80");
parser.addFlag("overwrite", abbr: "w", negatable: false,
help: "Overwrite input files with formatted output.\n"
"If unset, prints results to standard output.");
var options = parser.parse(args);
if (options["help"]) {
printUsage(parser);
return;
}
overwrite = options["overwrite"];
try {
lineLength = int.parse(options["line-length"]);
} on FormatException catch (_) {
printUsage(parser, '--line-length must be an integer, was '
'"${options['line-length']}".');
exitCode = 64;
return;
}
if (options.rest.isEmpty) {
printUsage(parser,
"Please provide at least one directory or file to format.");
exitCode = 64;
return;
}
for (var path in options.rest) {
var directory = new Directory(path);
if (directory.existsSync()) {
processDirectory(directory);
continue;
}
var file = new File(path);
if (file.existsSync()) {
processFile(file);
} else {
stderr.writeln('No file or directory found at "$path".');
}
}
}
void printUsage(ArgParser parser, [String error]) {
var output = stdout;
var message = "Reformats whitespace in Dart source files.";
if (error != null) {
message = error;
output = stdout;
}
output.write("""$message
Usage: dartfmt [-l <line length>] <files or directories...>
${parser.usage}
""");
}
/// Runs the formatter on every .dart file in [path] (and its subdirectories),
/// and replaces them with their formatted output.
void processDirectory(Directory directory) {
print("Formatting directory ${directory.path}:");
for (var entry in directory.listSync(recursive: true)) {
if (!entry.path.endsWith(".dart")) continue;
var relative = p.relative(entry.path, from: directory.path);
processFile(entry, relative);
}
}
/// Runs the formatter on [file].
void processFile(File file, [String label]) {
if (label == null) label = file.path;
var formatter = new DartFormatter(pageWidth: lineLength);
try {
var output = formatter.format(file.readAsStringSync());
if (overwrite) {
file.writeAsStringSync(output);
print("Formatted $label");
} else {
print(output);
}
} on FormatterException catch (err) {
stderr.writeln("Failed $label:\n$err");
}
}
View
@@ -0,0 +1,29 @@
import 'package:dart_style/dart_style.dart';
void main(List<String> args) {
formatStmt("sendPort.send({'type': 'error', 'error': 'oops'});");
formatUnit("class Foo{}");
}
void formatStmt(String source, [int pageWidth = 40]) {
var result = new DartFormatter(pageWidth: pageWidth).formatStatement(source);
drawRuler("before", pageWidth);
print(source);
drawRuler("after", pageWidth);
print(result);
}
void formatUnit(String source, [int pageWidth = 40]) {
var result = new DartFormatter(pageWidth: pageWidth).format(source);
drawRuler("before", pageWidth);
print(source);
drawRuler("after", pageWidth);
print(result);
}
void drawRuler(String label, int width) {
var padding = " " * (width - label.length - 1);
print("$label:$padding|");
}
View
@@ -5,3 +5,4 @@
library dart_style;
export 'src/dart_formatter.dart';
export 'src/formatter_exception.dart';
Oops, something went wrong.

0 comments on commit 46a5419

Please sign in to comment.