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

Side by Side Diff: args/lib/src/usage.dart

Issue 1400473008: Roll Observatory packages and add a roll script (Closed) Base URL: git@github.com:dart-lang/observatory_pub_packages.git@master
Patch Set: Created 5 years, 2 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 unified diff | Download patch
« no previous file with comments | « args/lib/src/parser.dart ('k') | args/lib/src/usage_exception.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 library args.src.usage;
6
7 import 'dart:math';
8
9 import '../args.dart';
10
11 /// Takes an [ArgParser] and generates a string of usage (i.e. help) text for
12 /// its defined options.
13 ///
14 /// Internally, it works like a tabular printer. The output is divided into
15 /// three horizontal columns, like so:
16 ///
17 /// -h, --help Prints the usage information
18 /// | | | |
19 ///
20 /// It builds the usage text up one column at a time and handles padding with
21 /// spaces and wrapping to the next line to keep the cells correctly lined up.
22 class Usage {
23 static const NUM_COLUMNS = 3; // Abbreviation, long name, help.
24
25 /// A list of the [Option]s intermingled with [String] separators.
26 final List optionsAndSeparators;
27
28 /// The working buffer for the generated usage text.
29 StringBuffer buffer;
30
31 /// The column that the "cursor" is currently on.
32 ///
33 /// If the next call to [write()] is not for this column, it will correctly
34 /// handle advancing to the next column (and possibly the next row).
35 int currentColumn = 0;
36
37 /// The width in characters of each column.
38 List<int> columnWidths;
39
40 /// The number of sequential lines of text that have been written to the last
41 /// column (which shows help info).
42 ///
43 /// We track this so that help text that spans multiple lines can be padded
44 /// with a blank line after it for separation. Meanwhile, sequential options
45 /// with single-line help will be compacted next to each other.
46 int numHelpLines = 0;
47
48 /// How many newlines need to be rendered before the next bit of text can be
49 /// written.
50 ///
51 /// We do this lazily so that the last bit of usage doesn't have dangling
52 /// newlines. We only write newlines right *before* we write some real
53 /// content.
54 int newlinesNeeded = 0;
55
56 Usage(this.optionsAndSeparators);
57
58 /// Generates a string displaying usage information for the defined options.
59 /// This is basically the help text shown on the command line.
60 String generate() {
61 buffer = new StringBuffer();
62
63 calculateColumnWidths();
64
65 for (var optionOrSeparator in optionsAndSeparators) {
66 if (optionOrSeparator is String) {
67 // Ensure that there's always a blank line before a separator.
68 if (buffer.isNotEmpty) buffer.write("\n\n");
69 buffer.write(optionOrSeparator);
70 newlinesNeeded = 1;
71 continue;
72 }
73
74 var option = optionOrSeparator as Option;
75 if (option.hide) continue;
76
77 write(0, getAbbreviation(option));
78 write(1, getLongOption(option));
79
80 if (option.help != null) write(2, option.help);
81
82 if (option.allowedHelp != null) {
83 var allowedNames = option.allowedHelp.keys.toList(growable: false);
84 allowedNames.sort();
85 newline();
86 for (var name in allowedNames) {
87 write(1, getAllowedTitle(name));
88 write(2, option.allowedHelp[name]);
89 }
90 newline();
91 } else if (option.allowed != null) {
92 write(2, buildAllowedList(option));
93 } else if (option.defaultValue != null) {
94 if (option.isFlag && option.defaultValue == true) {
95 write(2, '(defaults to on)');
96 } else if (!option.isFlag) {
97 write(2, '(defaults to "${option.defaultValue}")');
98 }
99 }
100
101 // If any given option displays more than one line of text on the right
102 // column (i.e. help, default value, allowed options, etc.) then put a
103 // blank line after it. This gives space where it's useful while still
104 // keeping simple one-line options clumped together.
105 if (numHelpLines > 1) newline();
106 }
107
108 return buffer.toString();
109 }
110
111 String getAbbreviation(Option option) {
112 if (option.abbreviation != null) {
113 return '-${option.abbreviation}, ';
114 } else {
115 return '';
116 }
117 }
118
119 String getLongOption(Option option) {
120 var result;
121 if (option.negatable) {
122 result = '--[no-]${option.name}';
123 } else {
124 result = '--${option.name}';
125 }
126
127 if (option.valueHelp != null) result += "=<${option.valueHelp}>";
128
129 return result;
130 }
131
132 String getAllowedTitle(String allowed) {
133 return ' [$allowed]';
134 }
135
136 void calculateColumnWidths() {
137 int abbr = 0;
138 int title = 0;
139 for (var option in optionsAndSeparators) {
140 if (option is! Option) continue;
141 if (option.hide) continue;
142
143 // Make room in the first column if there are abbreviations.
144 abbr = max(abbr, getAbbreviation(option).length);
145
146 // Make room for the option.
147 title = max(title, getLongOption(option).length);
148
149 // Make room for the allowed help.
150 if (option.allowedHelp != null) {
151 for (var allowed in option.allowedHelp.keys) {
152 title = max(title, getAllowedTitle(allowed).length);
153 }
154 }
155 }
156
157 // Leave a gutter between the columns.
158 title += 4;
159 columnWidths = [abbr, title];
160 }
161
162 void newline() {
163 newlinesNeeded++;
164 currentColumn = 0;
165 numHelpLines = 0;
166 }
167
168 void write(int column, String text) {
169 var lines = text.split('\n');
170
171 // Strip leading and trailing empty lines.
172 while (lines.length > 0 && lines[0].trim() == '') {
173 lines.removeRange(0, 1);
174 }
175
176 while (lines.length > 0 && lines[lines.length - 1].trim() == '') {
177 lines.removeLast();
178 }
179
180 for (var line in lines) {
181 writeLine(column, line);
182 }
183 }
184
185 void writeLine(int column, String text) {
186 // Write any pending newlines.
187 while (newlinesNeeded > 0) {
188 buffer.write('\n');
189 newlinesNeeded--;
190 }
191
192 // Advance until we are at the right column (which may mean wrapping around
193 // to the next line.
194 while (currentColumn != column) {
195 if (currentColumn < NUM_COLUMNS - 1) {
196 buffer.write(padRight('', columnWidths[currentColumn]));
197 } else {
198 buffer.write('\n');
199 }
200 currentColumn = (currentColumn + 1) % NUM_COLUMNS;
201 }
202
203 if (column < columnWidths.length) {
204 // Fixed-size column, so pad it.
205 buffer.write(padRight(text, columnWidths[column]));
206 } else {
207 // The last column, so just write it.
208 buffer.write(text);
209 }
210
211 // Advance to the next column.
212 currentColumn = (currentColumn + 1) % NUM_COLUMNS;
213
214 // If we reached the last column, we need to wrap to the next line.
215 if (column == NUM_COLUMNS - 1) newlinesNeeded++;
216
217 // Keep track of how many consecutive lines we've written in the last
218 // column.
219 if (column == NUM_COLUMNS - 1) {
220 numHelpLines++;
221 } else {
222 numHelpLines = 0;
223 }
224 }
225
226 String buildAllowedList(Option option) {
227 var allowedBuffer = new StringBuffer();
228 allowedBuffer.write('[');
229 bool first = true;
230 for (var allowed in option.allowed) {
231 if (!first) allowedBuffer.write(', ');
232 allowedBuffer.write(allowed);
233 if (allowed == option.defaultValue) {
234 allowedBuffer.write(' (default)');
235 }
236 first = false;
237 }
238 allowedBuffer.write(']');
239 return allowedBuffer.toString();
240 }
241 }
242
243 /// Pads [source] to [length] by adding spaces at the end.
244 String padRight(String source, int length) {
245 final result = new StringBuffer();
246 result.write(source);
247
248 while (result.length < length) {
249 result.write(' ');
250 }
251
252 return result.toString();
253 }
OLDNEW
« no previous file with comments | « args/lib/src/parser.dart ('k') | args/lib/src/usage_exception.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698