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

Side by Side Diff: observatory_pub_packages/path/src/context.dart

Issue 816693004: Add observatory_pub_packages snapshot to third_party (Closed) Base URL: http://dart.googlecode.com/svn/third_party/
Patch Set: Created 6 years 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 | Annotate | Revision Log
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 path.context;
6
7 import 'internal_style.dart';
8 import 'style.dart';
9 import 'parsed_path.dart';
10 import 'path_exception.dart';
11 import '../path.dart' as p;
12
13 Context createInternal() => new Context._internal();
14
15 /// An instantiable class for manipulating paths. Unlike the top-level
16 /// functions, this lets you explicitly select what platform the paths will use.
17 class Context {
18 /// Creates a new path context for the given style and current directory.
19 ///
20 /// If [style] is omitted, it uses the host operating system's path style. If
21 /// only [current] is omitted, it defaults ".". If *both* [style] and
22 /// [current] are omitted, [current] defaults to the real current working
23 /// directory.
24 ///
25 /// On the browser, [style] defaults to [Style.url] and [current] defaults to
26 /// the current URL.
27 factory Context({Style style, String current}) {
28 if (current == null) {
29 if (style == null) {
30 current = p.current;
31 } else {
32 current = ".";
33 }
34 }
35
36 if (style == null) {
37 style = Style.platform;
38 } else if (style is! InternalStyle) {
39 throw new ArgumentError("Only styles defined by the path package are "
40 "allowed.");
41 }
42
43 return new Context._(style, current);
44 }
45
46 /// Create a [Context] to be used internally within path.
47 Context._internal() : style = Style.platform, _current = null;
48
49 Context._(this.style, this._current);
50
51 /// The style of path that this context works with.
52 final InternalStyle style;
53
54 /// The current directory given when Context was created. If null, current
55 /// directory is evaluated from 'p.current'.
56 final String _current;
57
58 /// The current directory that relative paths are relative to.
59 String get current => _current != null ? _current : p.current;
60
61 /// Gets the path separator for the context's [style]. On Mac and Linux,
62 /// this is `/`. On Windows, it's `\`.
63 String get separator => style.separator;
64
65 /// Creates a new path by appending the given path parts to [current].
66 /// Equivalent to [join()] with [current] as the first argument. Example:
67 ///
68 /// var context = new Context(current: '/root');
69 /// context.absolute('path', 'to', 'foo'); // -> '/root/path/to/foo'
70 ///
71 /// If [current] isn't absolute, this won't return an absolute path.
72 String absolute(String part1, [String part2, String part3, String part4,
73 String part5, String part6, String part7]) {
74 return join(current, part1, part2, part3, part4, part5, part6, part7);
75 }
76
77 /// Gets the part of [path] after the last separator on the context's
78 /// platform.
79 ///
80 /// context.basename('path/to/foo.dart'); // -> 'foo.dart'
81 /// context.basename('path/to'); // -> 'to'
82 ///
83 /// Trailing separators are ignored.
84 ///
85 /// context.basename('path/to/'); // -> 'to'
86 String basename(String path) => _parse(path).basename;
87
88 /// Gets the part of [path] after the last separator on the context's
89 /// platform, and without any trailing file extension.
90 ///
91 /// context.basenameWithoutExtension('path/to/foo.dart'); // -> 'foo'
92 ///
93 /// Trailing separators are ignored.
94 ///
95 /// context.basenameWithoutExtension('path/to/foo.dart/'); // -> 'foo'
96 String basenameWithoutExtension(String path) =>
97 _parse(path).basenameWithoutExtension;
98
99 /// Gets the part of [path] before the last separator.
100 ///
101 /// context.dirname('path/to/foo.dart'); // -> 'path/to'
102 /// context.dirname('path/to'); // -> 'path'
103 ///
104 /// Trailing separators are ignored.
105 ///
106 /// context.dirname('path/to/'); // -> 'path'
107 String dirname(String path) {
108 var parsed = _parse(path);
109 parsed.removeTrailingSeparators();
110 if (parsed.parts.isEmpty) return parsed.root == null ? '.' : parsed.root;
111 if (parsed.parts.length == 1) {
112 return parsed.root == null ? '.' : parsed.root;
113 }
114 parsed.parts.removeLast();
115 parsed.separators.removeLast();
116 parsed.removeTrailingSeparators();
117 return parsed.toString();
118 }
119
120 /// Gets the file extension of [path]: the portion of [basename] from the last
121 /// `.` to the end (including the `.` itself).
122 ///
123 /// context.extension('path/to/foo.dart'); // -> '.dart'
124 /// context.extension('path/to/foo'); // -> ''
125 /// context.extension('path.to/foo'); // -> ''
126 /// context.extension('path/to/foo.dart.js'); // -> '.js'
127 ///
128 /// If the file name starts with a `.`, then it is not considered an
129 /// extension:
130 ///
131 /// context.extension('~/.bashrc'); // -> ''
132 /// context.extension('~/.notes.txt'); // -> '.txt'
133 String extension(String path) => _parse(path).extension;
134
135 // TODO(nweiz): add a UNC example for Windows once issue 7323 is fixed.
136 /// Returns the root of [path] if it's absolute, or an empty string if it's
137 /// relative.
138 ///
139 /// // Unix
140 /// context.rootPrefix('path/to/foo'); // -> ''
141 /// context.rootPrefix('/path/to/foo'); // -> '/'
142 ///
143 /// // Windows
144 /// context.rootPrefix(r'path\to\foo'); // -> ''
145 /// context.rootPrefix(r'C:\path\to\foo'); // -> r'C:\'
146 ///
147 /// // URL
148 /// context.rootPrefix('path/to/foo'); // -> ''
149 /// context.rootPrefix('http://dartlang.org/path/to/foo');
150 /// // -> 'http://dartlang.org'
151 String rootPrefix(String path) {
152 var root = _parse(path).root;
153 return root == null ? '' : root;
154 }
155
156 /// Returns `true` if [path] is an absolute path and `false` if it is a
157 /// relative path.
158 ///
159 /// On POSIX systems, absolute paths start with a `/` (forward slash). On
160 /// Windows, an absolute path starts with `\\`, or a drive letter followed by
161 /// `:/` or `:\`. For URLs, absolute paths either start with a protocol and
162 /// optional hostname (e.g. `http://dartlang.org`, `file://`) or with a `/`.
163 ///
164 /// URLs that start with `/` are known as "root-relative", since they're
165 /// relative to the root of the current URL. Since root-relative paths are
166 /// still absolute in every other sense, [isAbsolute] will return true for
167 /// them. They can be detected using [isRootRelative].
168 bool isAbsolute(String path) => _parse(path).isAbsolute;
169
170 /// Returns `true` if [path] is a relative path and `false` if it is absolute.
171 /// On POSIX systems, absolute paths start with a `/` (forward slash). On
172 /// Windows, an absolute path starts with `\\`, or a drive letter followed by
173 /// `:/` or `:\`.
174 bool isRelative(String path) => !this.isAbsolute(path);
175
176 /// Returns `true` if [path] is a root-relative path and `false` if it's not.
177 ///
178 /// URLs that start with `/` are known as "root-relative", since they're
179 /// relative to the root of the current URL. Since root-relative paths are
180 /// still absolute in every other sense, [isAbsolute] will return true for
181 /// them. They can be detected using [isRootRelative].
182 ///
183 /// No POSIX and Windows paths are root-relative.
184 bool isRootRelative(String path) => _parse(path).isRootRelative;
185
186 /// Joins the given path parts into a single path. Example:
187 ///
188 /// context.join('path', 'to', 'foo'); // -> 'path/to/foo'
189 ///
190 /// If any part ends in a path separator, then a redundant separator will not
191 /// be added:
192 ///
193 /// context.join('path/', 'to', 'foo'); // -> 'path/to/foo
194 ///
195 /// If a part is an absolute path, then anything before that will be ignored:
196 ///
197 /// context.join('path', '/to', 'foo'); // -> '/to/foo'
198 ///
199 String join(String part1, [String part2, String part3, String part4,
200 String part5, String part6, String part7, String part8]) {
201 var parts = [part1, part2, part3, part4, part5, part6, part7, part8];
202 _validateArgList("join", parts);
203 return joinAll(parts.where((part) => part != null));
204 }
205
206 /// Joins the given path parts into a single path. Example:
207 ///
208 /// context.joinAll(['path', 'to', 'foo']); // -> 'path/to/foo'
209 ///
210 /// If any part ends in a path separator, then a redundant separator will not
211 /// be added:
212 ///
213 /// context.joinAll(['path/', 'to', 'foo']); // -> 'path/to/foo
214 ///
215 /// If a part is an absolute path, then anything before that will be ignored:
216 ///
217 /// context.joinAll(['path', '/to', 'foo']); // -> '/to/foo'
218 ///
219 /// For a fixed number of parts, [join] is usually terser.
220 String joinAll(Iterable<String> parts) {
221 var buffer = new StringBuffer();
222 var needsSeparator = false;
223 var isAbsoluteAndNotRootRelative = false;
224
225 for (var part in parts.where((part) => part != '')) {
226 if (this.isRootRelative(part) && isAbsoluteAndNotRootRelative) {
227 // If the new part is root-relative, it preserves the previous root but
228 // replaces the path after it.
229 var parsed = _parse(part);
230 parsed.root = this.rootPrefix(buffer.toString());
231 if (style.needsSeparator(parsed.root)) {
232 parsed.separators[0] = style.separator;
233 }
234 buffer.clear();
235 buffer.write(parsed.toString());
236 } else if (this.isAbsolute(part)) {
237 isAbsoluteAndNotRootRelative = !this.isRootRelative(part);
238 // An absolute path discards everything before it.
239 buffer.clear();
240 buffer.write(part);
241 } else {
242 if (part.length > 0 && style.containsSeparator(part[0])) {
243 // The part starts with a separator, so we don't need to add one.
244 } else if (needsSeparator) {
245 buffer.write(separator);
246 }
247
248 buffer.write(part);
249 }
250
251 // Unless this part ends with a separator, we'll need to add one before
252 // the next part.
253 needsSeparator = style.needsSeparator(part);
254 }
255
256 return buffer.toString();
257 }
258
259 // TODO(nweiz): add a UNC example for Windows once issue 7323 is fixed.
260 /// Splits [path] into its components using the current platform's
261 /// [separator]. Example:
262 ///
263 /// context.split('path/to/foo'); // -> ['path', 'to', 'foo']
264 ///
265 /// The path will *not* be normalized before splitting.
266 ///
267 /// context.split('path/../foo'); // -> ['path', '..', 'foo']
268 ///
269 /// If [path] is absolute, the root directory will be the first element in the
270 /// array. Example:
271 ///
272 /// // Unix
273 /// context.split('/path/to/foo'); // -> ['/', 'path', 'to', 'foo']
274 ///
275 /// // Windows
276 /// context.split(r'C:\path\to\foo'); // -> [r'C:\', 'path', 'to', 'foo']
277 List<String> split(String path) {
278 var parsed = _parse(path);
279 // Filter out empty parts that exist due to multiple separators in a row.
280 parsed.parts = parsed.parts.where((part) => !part.isEmpty)
281 .toList();
282 if (parsed.root != null) parsed.parts.insert(0, parsed.root);
283 return parsed.parts;
284 }
285
286 /// Normalizes [path], simplifying it by handling `..`, and `.`, and
287 /// removing redundant path separators whenever possible.
288 ///
289 /// context.normalize('path/./to/..//file.text'); // -> 'path/file.txt'
290 String normalize(String path) {
291 var parsed = _parse(path);
292 parsed.normalize();
293 return parsed.toString();
294 }
295
296 /// Attempts to convert [path] to an equivalent relative path relative to
297 /// [root].
298 ///
299 /// var context = new Context(current: '/root/path');
300 /// context.relative('/root/path/a/b.dart'); // -> 'a/b.dart'
301 /// context.relative('/root/other.dart'); // -> '../other.dart'
302 ///
303 /// If the [from] argument is passed, [path] is made relative to that instead.
304 ///
305 /// context.relative('/root/path/a/b.dart',
306 /// from: '/root/path'); // -> 'a/b.dart'
307 /// context.relative('/root/other.dart',
308 /// from: '/root/path'); // -> '../other.dart'
309 ///
310 /// If [path] and/or [from] are relative paths, they are assumed to be
311 /// relative to [current].
312 ///
313 /// Since there is no relative path from one drive letter to another on
314 /// Windows, this will return an absolute path in that case.
315 ///
316 /// context.relative(r'D:\other', from: r'C:\other'); // -> 'D:\other'
317 ///
318 /// This will also return an absolute path if an absolute [path] is passed to
319 /// a context with a relative path for [current].
320 ///
321 /// var context = new Context(r'some/relative/path');
322 /// context.relative(r'/absolute/path'); // -> '/absolute/path'
323 ///
324 /// If [root] is relative, it may be impossible to determine a path from
325 /// [from] to [path]. For example, if [root] and [path] are "." and [from] is
326 /// "/", no path can be determined. In this case, a [PathException] will be
327 /// thrown.
328 String relative(String path, {String from}) {
329 from = from == null ? current : this.join(current, from);
330
331 // We can't determine the path from a relative path to an absolute path.
332 if (this.isRelative(from) && this.isAbsolute(path)) {
333 return this.normalize(path);
334 }
335
336 // If the given path is relative, resolve it relative to the context's
337 // current directory.
338 if (this.isRelative(path) || this.isRootRelative(path)) {
339 path = this.absolute(path);
340 }
341
342 // If the path is still relative and `from` is absolute, we're unable to
343 // find a path from `from` to `path`.
344 if (this.isRelative(path) && this.isAbsolute(from)) {
345 throw new PathException('Unable to find a path to "$path" from "$from".');
346 }
347
348 var fromParsed = _parse(from)..normalize();
349 var pathParsed = _parse(path)..normalize();
350
351 if (fromParsed.parts.length > 0 && fromParsed.parts[0] == '.') {
352 return pathParsed.toString();
353 }
354
355 // If the root prefixes don't match (for example, different drive letters
356 // on Windows), then there is no relative path, so just return the absolute
357 // one. In Windows, drive letters are case-insenstive and we allow
358 // calculation of relative paths, even if a path has not been normalized.
359 if (fromParsed.root != pathParsed.root &&
360 ((fromParsed.root == null || pathParsed.root == null) ||
361 fromParsed.root.toLowerCase().replaceAll('/', '\\') !=
362 pathParsed.root.toLowerCase().replaceAll('/', '\\'))) {
363 return pathParsed.toString();
364 }
365
366 // Strip off their common prefix.
367 while (fromParsed.parts.length > 0 && pathParsed.parts.length > 0 &&
368 fromParsed.parts[0] == pathParsed.parts[0]) {
369 fromParsed.parts.removeAt(0);
370 fromParsed.separators.removeAt(1);
371 pathParsed.parts.removeAt(0);
372 pathParsed.separators.removeAt(1);
373 }
374
375 // If there are any directories left in the from path, we need to walk up
376 // out of them. If a directory left in the from path is '..', it cannot
377 // be cancelled by adding a '..'.
378 if (fromParsed.parts.length > 0 && fromParsed.parts[0] == '..') {
379 throw new PathException('Unable to find a path to "$path" from "$from".');
380 }
381 pathParsed.parts.insertAll(0,
382 new List.filled(fromParsed.parts.length, '..'));
383 pathParsed.separators[0] = '';
384 pathParsed.separators.insertAll(1,
385 new List.filled(fromParsed.parts.length, style.separator));
386
387 // Corner case: the paths completely collapsed.
388 if (pathParsed.parts.length == 0) return '.';
389
390 // Corner case: path was '.' and some '..' directories were added in front.
391 // Don't add a final '/.' in that case.
392 if (pathParsed.parts.length > 1 && pathParsed.parts.last == '.') {
393 pathParsed.parts.removeLast();
394 pathParsed.separators..removeLast()..removeLast()..add('');
395 }
396
397 // Make it relative.
398 pathParsed.root = '';
399 pathParsed.removeTrailingSeparators();
400
401 return pathParsed.toString();
402 }
403
404 /// Returns `true` if [child] is a path beneath `parent`, and `false`
405 /// otherwise.
406 ///
407 /// path.isWithin('/root/path', '/root/path/a'); // -> true
408 /// path.isWithin('/root/path', '/root/other'); // -> false
409 /// path.isWithin('/root/path', '/root/path'); // -> false
410 bool isWithin(String parent, String child) {
411 var relative;
412 try {
413 relative = this.relative(child, from: parent);
414 } on PathException catch (_) {
415 // If no relative path from [parent] to [child] is found, [child]
416 // definitely isn't a child of [parent].
417 return false;
418 }
419
420 var parts = this.split(relative);
421 return this.isRelative(relative) && parts.first != '..' &&
422 parts.first != '.';
423 }
424
425 /// Removes a trailing extension from the last part of [path].
426 ///
427 /// context.withoutExtension('path/to/foo.dart'); // -> 'path/to/foo'
428 String withoutExtension(String path) {
429 var parsed = _parse(path);
430
431 for (var i = parsed.parts.length - 1; i >= 0; i--) {
432 if (!parsed.parts[i].isEmpty) {
433 parsed.parts[i] = parsed.basenameWithoutExtension;
434 break;
435 }
436 }
437
438 return parsed.toString();
439 }
440
441 /// Returns the path represented by [uri], which may be a [String] or a [Uri].
442 ///
443 /// For POSIX and Windows styles, [uri] must be a `file:` URI. For the URL
444 /// style, this will just convert [uri] to a string.
445 ///
446 /// // POSIX
447 /// context.fromUri('file:///path/to/foo')
448 /// // -> '/path/to/foo'
449 ///
450 /// // Windows
451 /// context.fromUri('file:///C:/path/to/foo')
452 /// // -> r'C:\path\to\foo'
453 ///
454 /// // URL
455 /// context.fromUri('http://dartlang.org/path/to/foo')
456 /// // -> 'http://dartlang.org/path/to/foo'
457 ///
458 /// If [uri] is relative, a relative path will be returned.
459 ///
460 /// path.fromUri('path/to/foo'); // -> 'path/to/foo'
461 String fromUri(uri) {
462 if (uri is String) uri = Uri.parse(uri);
463 return style.pathFromUri(uri);
464 }
465
466 /// Returns the URI that represents [path].
467 ///
468 /// For POSIX and Windows styles, this will return a `file:` URI. For the URL
469 /// style, this will just convert [path] to a [Uri].
470 ///
471 /// // POSIX
472 /// context.toUri('/path/to/foo')
473 /// // -> Uri.parse('file:///path/to/foo')
474 ///
475 /// // Windows
476 /// context.toUri(r'C:\path\to\foo')
477 /// // -> Uri.parse('file:///C:/path/to/foo')
478 ///
479 /// // URL
480 /// context.toUri('http://dartlang.org/path/to/foo')
481 /// // -> Uri.parse('http://dartlang.org/path/to/foo')
482 Uri toUri(String path) {
483 if (isRelative(path)) {
484 return style.relativePathToUri(path);
485 } else {
486 return style.absolutePathToUri(join(current, path));
487 }
488 }
489
490 /// Returns a terse, human-readable representation of [uri].
491 ///
492 /// [uri] can be a [String] or a [Uri]. If it can be made relative to the
493 /// current working directory, that's done. Otherwise, it's returned as-is.
494 /// This gracefully handles non-`file:` URIs for [Style.posix] and
495 /// [Style.windows].
496 ///
497 /// The returned value is meant for human consumption, and may be either URI-
498 /// or path-formatted.
499 ///
500 /// // POSIX
501 /// var context = new Context(current: '/root/path');
502 /// context.prettyUri('file:///root/path/a/b.dart'); // -> 'a/b.dart'
503 /// context.prettyUri('http://dartlang.org/'); // -> 'http://dartlang.org'
504 ///
505 /// // Windows
506 /// var context = new Context(current: r'C:\root\path');
507 /// context.prettyUri('file:///C:/root/path/a/b.dart'); // -> r'a\b.dart'
508 /// context.prettyUri('http://dartlang.org/'); // -> 'http://dartlang.org'
509 ///
510 /// // URL
511 /// var context = new Context(current: 'http://dartlang.org/root/path');
512 /// context.prettyUri('http://dartlang.org/root/path/a/b.dart');
513 /// // -> r'a/b.dart'
514 /// context.prettyUri('file:///root/path'); // -> 'file:///root/path'
515 String prettyUri(uri) {
516 if (uri is String) uri = Uri.parse(uri);
517 if (uri.scheme == 'file' && style == Style.url) return uri.toString();
518 if (uri.scheme != 'file' && uri.scheme != '' && style != Style.url) {
519 return uri.toString();
520 }
521
522 var path = normalize(fromUri(uri));
523 var rel = relative(path);
524 var components = split(rel);
525
526 // Only return a relative path if it's actually shorter than the absolute
527 // path. This avoids ugly things like long "../" chains to get to the root
528 // and then go back down.
529 return split(rel).length > split(path).length ? path : rel;
530 }
531
532 ParsedPath _parse(String path) => new ParsedPath.parse(path, style);
533 }
534
535 /// Validates that there are no non-null arguments following a null one and
536 /// throws an appropriate [ArgumentError] on failure.
537 _validateArgList(String method, List<String> args) {
538 for (var i = 1; i < args.length; i++) {
539 // Ignore nulls hanging off the end.
540 if (args[i] == null || args[i - 1] != null) continue;
541
542 var numArgs;
543 for (numArgs = args.length; numArgs >= 1; numArgs--) {
544 if (args[numArgs - 1] != null) break;
545 }
546
547 // Show the arguments.
548 var message = new StringBuffer();
549 message.write("$method(");
550 message.write(args.take(numArgs)
551 .map((arg) => arg == null ? "null" : '"$arg"')
552 .join(", "));
553 message.write("): part ${i - 1} was null, but part $i was not.");
554 throw new ArgumentError(message.toString());
555 }
556 }
OLDNEW
« no previous file with comments | « observatory_pub_packages/path/src/characters.dart ('k') | observatory_pub_packages/path/src/internal_style.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698