Skip to content

Commit

Permalink
LICENSE, README, clean up public API, etc.
Browse files Browse the repository at this point in the history
  • Loading branch information
munificent committed Nov 7, 2014
1 parent 0757d74 commit 46a5419
Show file tree
Hide file tree
Showing 12 changed files with 332 additions and 149 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*No changes yet!*
26 changes: 26 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
72 changes: 72 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.
84 changes: 0 additions & 84 deletions bin/fmt.dart

This file was deleted.

108 changes: 108 additions & 0 deletions bin/format.dart
Original file line number Diff line number Diff line change
@@ -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");
}
}
29 changes: 29 additions & 0 deletions example/format.dart
Original file line number Diff line number Diff line change
@@ -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|");
}
1 change: 1 addition & 0 deletions lib/dart_style.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
library dart_style;

export 'src/dart_formatter.dart';
export 'src/formatter_exception.dart';
Loading

0 comments on commit 46a5419

Please sign in to comment.