View Javadoc
1   /*
2    * Copyright (C) 2009, Mykola Nikishov <mn@mn.com.ua>
3    * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
4    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
5    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
6    * Copyright (C) 2013, Robin Stocker <robin@nibor.org>
7    * Copyright (C) 2015, Patrick Steinhardt <ps@pks.im>
8    * and other copyright owners as documented in the project's IP log.
9    *
10   * This program and the accompanying materials are made available
11   * under the terms of the Eclipse Distribution License v1.0 which
12   * accompanies this distribution, is reproduced below, and is
13   * available at http://www.eclipse.org/org/documents/edl-v10.php
14   *
15   * All rights reserved.
16   *
17   * Redistribution and use in source and binary forms, with or
18   * without modification, are permitted provided that the following
19   * conditions are met:
20   *
21   * - Redistributions of source code must retain the above copyright
22   *   notice, this list of conditions and the following disclaimer.
23   *
24   * - Redistributions in binary form must reproduce the above
25   *   copyright notice, this list of conditions and the following
26   *   disclaimer in the documentation and/or other materials provided
27   *   with the distribution.
28   *
29   * - Neither the name of the Eclipse Foundation, Inc. nor the
30   *   names of its contributors may be used to endorse or promote
31   *   products derived from this software without specific prior
32   *   written permission.
33   *
34   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
35   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
36   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
39   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
43   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
46   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47   */
48  
49  package org.eclipse.jgit.transport;
50  
51  import java.io.ByteArrayOutputStream;
52  import java.io.File;
53  import java.io.Serializable;
54  import java.io.UnsupportedEncodingException;
55  import java.net.URISyntaxException;
56  import java.net.URL;
57  import java.util.BitSet;
58  import java.util.regex.Matcher;
59  import java.util.regex.Pattern;
60  
61  import org.eclipse.jgit.internal.JGitText;
62  import org.eclipse.jgit.lib.Constants;
63  import org.eclipse.jgit.util.RawParseUtils;
64  import org.eclipse.jgit.util.StringUtils;
65  
66  /**
67   * This URI like construct used for referencing Git archives over the net, as
68   * well as locally stored archives. It is similar to RFC 2396 URI's, but also
69   * support SCP and the malformed file://&lt;path&gt; syntax (as opposed to the correct
70   * file:&lt;path&gt; syntax.
71   */
72  public class URIish implements Serializable {
73  	/**
74  	 * Part of a pattern which matches the scheme part (git, http, ...) of an
75  	 * URI. Defines one capturing group containing the scheme without the
76  	 * trailing colon and slashes
77  	 */
78  	private static final String SCHEME_P = "([a-z][a-z0-9+-]+)://"; //$NON-NLS-1$
79  
80  	/**
81  	 * Part of a pattern which matches the optional user/password part (e.g.
82  	 * root:pwd@ in git://root:pwd@host.xyz/a.git) of URIs. Defines two
83  	 * capturing groups: the first containing the user and the second containing
84  	 * the password
85  	 */
86  	private static final String OPT_USER_PWD_P = "(?:([^/:]+)(?::([^\\\\/]+))?@)?"; //$NON-NLS-1$
87  
88  	/**
89  	 * Part of a pattern which matches the host part of URIs. Defines one
90  	 * capturing group containing the host name.
91  	 */
92  	private static final String HOST_P = "((?:[^\\\\/:]+)|(?:\\[[0-9a-f:]+\\]))"; //$NON-NLS-1$
93  
94  	/**
95  	 * Part of a pattern which matches the optional port part of URIs. Defines
96  	 * one capturing group containing the port without the preceding colon.
97  	 */
98  	private static final String OPT_PORT_P = "(?::(\\d+))?"; //$NON-NLS-1$
99  
100 	/**
101 	 * Part of a pattern which matches the ~username part (e.g. /~root in
102 	 * git://host.xyz/~root/a.git) of URIs. Defines no capturing group.
103 	 */
104 	private static final String USER_HOME_P = "(?:/~(?:[^\\\\/]+))"; //$NON-NLS-1$
105 
106 	/**
107 	 * Part of a pattern which matches the optional drive letter in paths (e.g.
108 	 * D: in file:///D:/a.txt). Defines no capturing group.
109 	 */
110 	private static final String OPT_DRIVE_LETTER_P = "(?:[A-Za-z]:)?"; //$NON-NLS-1$
111 
112 	/**
113 	 * Part of a pattern which matches a relative path. Relative paths don't
114 	 * start with slash or drive letters. Defines no capturing group.
115 	 */
116 	private static final String RELATIVE_PATH_P = "(?:(?:[^\\\\/]+[\\\\/]+)*[^\\\\/]+[\\\\/]*)"; //$NON-NLS-1$
117 
118 	/**
119 	 * Part of a pattern which matches a relative or absolute path. Defines no
120 	 * capturing group.
121 	 */
122 	private static final String PATH_P = "(" + OPT_DRIVE_LETTER_P + "[\\\\/]?" //$NON-NLS-1$ //$NON-NLS-2$
123 			+ RELATIVE_PATH_P + ")"; //$NON-NLS-1$
124 
125 	private static final long serialVersionUID = 1L;
126 
127 	/**
128 	 * A pattern matching standard URI: </br>
129 	 * <code>scheme "://" user_password? hostname? portnumber? path</code>
130 	 */
131 	private static final Pattern FULL_URI = Pattern.compile("^" // //$NON-NLS-1$
132 			+ SCHEME_P //
133 			+ "(?:" // start a group containing hostname and all options only //$NON-NLS-1$
134 					// availabe when a hostname is there
135 			+ OPT_USER_PWD_P //
136 			+ HOST_P //
137 			+ OPT_PORT_P //
138 			+ "(" // open a group capturing the user-home-dir-part //$NON-NLS-1$
139 			+ (USER_HOME_P + "?") //$NON-NLS-1$
140 			+ "(?:" // start non capturing group for host //$NON-NLS-1$
141 					// separator or end of line
142 			+ "[\\\\/])|$" //$NON-NLS-1$
143 			+ ")" // close non capturing group for the host//$NON-NLS-1$
144 					// separator or end of line
145 			+ ")?" // close the optional group containing hostname //$NON-NLS-1$
146 			+ "(.+)?" //$NON-NLS-1$
147 			+ "$"); //$NON-NLS-1$
148 
149 	/**
150 	 * A pattern matching the reference to a local file. This may be an absolute
151 	 * path (maybe even containing windows drive-letters) or a relative path.
152 	 */
153 	private static final Pattern LOCAL_FILE = Pattern.compile("^" // //$NON-NLS-1$
154 			+ "([\\\\/]?" + PATH_P + ")" // //$NON-NLS-1$ //$NON-NLS-2$
155 			+ "$"); //$NON-NLS-1$
156 
157 	/**
158 	 * A pattern matching a URI for the scheme 'file' which has only ':/' as
159 	 * separator between scheme and path. Standard file URIs have '://' as
160 	 * separator, but java.io.File.toURI() constructs those URIs.
161 	 */
162 	private static final Pattern SINGLE_SLASH_FILE_URI = Pattern.compile("^" // //$NON-NLS-1$
163 			+ "(file):([\\\\/](?![\\\\/])" // //$NON-NLS-1$
164 			+ PATH_P //
165 			+ ")$"); //$NON-NLS-1$
166 
167 	/**
168 	 * A pattern matching a SCP URI's of the form user@host:path/to/repo.git
169 	 */
170 	private static final Pattern RELATIVE_SCP_URI = Pattern.compile("^" // //$NON-NLS-1$
171 			+ OPT_USER_PWD_P //
172 			+ HOST_P //
173 			+ ":(" // //$NON-NLS-1$
174 			+ ("(?:" + USER_HOME_P + "[\\\\/])?") // //$NON-NLS-1$ //$NON-NLS-2$
175 			+ RELATIVE_PATH_P //
176 			+ ")$"); //$NON-NLS-1$
177 
178 	/**
179 	 * A pattern matching a SCP URI's of the form user@host:/path/to/repo.git
180 	 */
181 	private static final Pattern ABSOLUTE_SCP_URI = Pattern.compile("^" // //$NON-NLS-1$
182 			+ OPT_USER_PWD_P //
183 			+ "([^\\\\/:]{2,})" // //$NON-NLS-1$
184 			+ ":(" // //$NON-NLS-1$
185 			+ "[\\\\/]" + RELATIVE_PATH_P // //$NON-NLS-1$
186 			+ ")$"); //$NON-NLS-1$
187 
188 	private String scheme;
189 
190 	private String path;
191 
192 	private String rawPath;
193 
194 	private String user;
195 
196 	private String pass;
197 
198 	private int port = -1;
199 
200 	private String host;
201 
202 	/**
203 	 * Parse and construct an {@link URIish} from a string
204 	 *
205 	 * @param s
206 	 * @throws URISyntaxException
207 	 */
208 	public URIish(String s) throws URISyntaxException {
209 		if (StringUtils.isEmptyOrNull(s)) {
210 			throw new URISyntaxException("The uri was empty or null", //$NON-NLS-1$
211 					JGitText.get().cannotParseGitURIish);
212 		}
213 		Matcher matcher = SINGLE_SLASH_FILE_URI.matcher(s);
214 		if (matcher.matches()) {
215 			scheme = matcher.group(1);
216 			rawPath = cleanLeadingSlashes(matcher.group(2), scheme);
217 			path = unescape(rawPath);
218 			return;
219 		}
220 		matcher = FULL_URI.matcher(s);
221 		if (matcher.matches()) {
222 			scheme = matcher.group(1);
223 			user = unescape(matcher.group(2));
224 			pass = unescape(matcher.group(3));
225 			host = unescape(matcher.group(4));
226 			if (matcher.group(5) != null)
227 				port = Integer.parseInt(matcher.group(5));
228 			rawPath = cleanLeadingSlashes(
229 					n2e(matcher.group(6)) + n2e(matcher.group(7)), scheme);
230 			path = unescape(rawPath);
231 			return;
232 		}
233 		matcher = RELATIVE_SCP_URI.matcher(s);
234 		if (matcher.matches()) {
235 			user = matcher.group(1);
236 			pass = matcher.group(2);
237 			host = matcher.group(3);
238 			rawPath = matcher.group(4);
239 			path = rawPath;
240 			return;
241 		}
242 		matcher = ABSOLUTE_SCP_URI.matcher(s);
243 		if (matcher.matches()) {
244 			user = matcher.group(1);
245 			pass = matcher.group(2);
246 			host = matcher.group(3);
247 			rawPath = matcher.group(4);
248 			path = rawPath;
249 			return;
250 		}
251 		matcher = LOCAL_FILE.matcher(s);
252 		if (matcher.matches()) {
253 			rawPath = matcher.group(1);
254 			path = rawPath;
255 			return;
256 		}
257 		throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish);
258 	}
259 
260 	private static int parseHexByte(byte c1, byte c2) {
261 			return ((RawParseUtils.parseHexInt4(c1) << 4)
262 					| RawParseUtils.parseHexInt4(c2));
263 	}
264 
265 	private static String unescape(String s) throws URISyntaxException {
266 		if (s == null)
267 			return null;
268 		if (s.indexOf('%') < 0)
269 			return s;
270 
271 		byte[] bytes;
272 		try {
273 			bytes = s.getBytes(Constants.CHARACTER_ENCODING);
274 		} catch (UnsupportedEncodingException e) {
275 			throw new RuntimeException(e); // can't happen
276 		}
277 
278 		byte[] os = new byte[bytes.length];
279 		int j = 0;
280 		for (int i = 0; i < bytes.length; ++i) {
281 			byte c = bytes[i];
282 			if (c == '%') {
283 				if (i + 2 >= bytes.length)
284 					throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish);
285 				byte c1 = bytes[i + 1];
286 				byte c2 = bytes[i + 2];
287 				int val;
288 				try {
289 					val = parseHexByte(c1, c2);
290 				} catch (ArrayIndexOutOfBoundsException e) {
291 					throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish);
292 				}
293 				os[j++] = (byte) val;
294 				i += 2;
295 			} else
296 				os[j++] = c;
297 		}
298 		return RawParseUtils.decode(os, 0, j);
299 	}
300 
301 	private static final BitSet reservedChars = new BitSet(127);
302 
303 	static {
304 		for (byte b : Constants.encodeASCII("!*'();:@&=+$,/?#[]")) //$NON-NLS-1$
305 			reservedChars.set(b);
306 	}
307 
308 	/**
309 	 * Escape unprintable characters optionally URI-reserved characters
310 	 *
311 	 * @param s
312 	 *            The Java String to encode (may contain any character)
313 	 * @param escapeReservedChars
314 	 *            true to escape URI reserved characters
315 	 * @param encodeNonAscii
316 	 *            encode any non-ASCII characters
317 	 * @return a URI-encoded string
318 	 */
319 	private static String escape(String s, boolean escapeReservedChars,
320 			boolean encodeNonAscii) {
321 		if (s == null)
322 			return null;
323 		ByteArrayOutputStream os = new ByteArrayOutputStream(s.length());
324 		byte[] bytes;
325 		try {
326 			bytes = s.getBytes(Constants.CHARACTER_ENCODING);
327 		} catch (UnsupportedEncodingException e) {
328 			throw new RuntimeException(e); // cannot happen
329 		}
330 		for (int i = 0; i < bytes.length; ++i) {
331 			int b = bytes[i] & 0xFF;
332 			if (b <= 32 || (encodeNonAscii && b > 127) || b == '%'
333 					|| (escapeReservedChars && reservedChars.get(b))) {
334 				os.write('%');
335 				byte[] tmp = Constants.encodeASCII(String.format("%02x", //$NON-NLS-1$
336 						Integer.valueOf(b)));
337 				os.write(tmp[0]);
338 				os.write(tmp[1]);
339 			} else {
340 				os.write(b);
341 			}
342 		}
343 		byte[] buf = os.toByteArray();
344 		return RawParseUtils.decode(buf, 0, buf.length);
345 	}
346 
347 	private String n2e(String s) {
348 		if (s == null)
349 			return ""; //$NON-NLS-1$
350 		else
351 			return s;
352 	}
353 
354 	// takes care to cut of a leading slash if a windows drive letter or a
355 	// user-home-dir specifications are
356 	private String cleanLeadingSlashes(String p, String s) {
357 		if (p.length() >= 3
358 				&& p.charAt(0) == '/'
359 				&& p.charAt(2) == ':'
360 				&& (p.charAt(1) >= 'A' && p.charAt(1) <= 'Z' || p.charAt(1) >= 'a'
361 						&& p.charAt(1) <= 'z'))
362 			return p.substring(1);
363 		else if (s != null && p.length() >= 2 && p.charAt(0) == '/'
364 				&& p.charAt(1) == '~')
365 			return p.substring(1);
366 		else
367 			return p;
368 	}
369 
370 	/**
371 	 * Construct a URIish from a standard URL.
372 	 *
373 	 * @param u
374 	 *            the source URL to convert from.
375 	 */
376 	public URIish(final URL u) {
377 		scheme = u.getProtocol();
378 		path = u.getPath();
379 		path = cleanLeadingSlashes(path, scheme);
380 		try {
381 			rawPath = u.toURI().getRawPath();
382 			rawPath = cleanLeadingSlashes(rawPath, scheme);
383 		} catch (URISyntaxException e) {
384 			throw new RuntimeException(e); // Impossible
385 		}
386 
387 		final String ui = u.getUserInfo();
388 		if (ui != null) {
389 			final int d = ui.indexOf(':');
390 			user = d < 0 ? ui : ui.substring(0, d);
391 			pass = d < 0 ? null : ui.substring(d + 1);
392 		}
393 
394 		port = u.getPort();
395 		host = u.getHost();
396 	}
397 
398 	/** Create an empty, non-configured URI. */
399 	public URIish() {
400 		// Configure nothing.
401 	}
402 
403 	private URIish(final URIish u) {
404 		this.scheme = u.scheme;
405 		this.rawPath = u.rawPath;
406 		this.path = u.path;
407 		this.user = u.user;
408 		this.pass = u.pass;
409 		this.port = u.port;
410 		this.host = u.host;
411 	}
412 
413 	/**
414 	 * @return true if this URI references a repository on another system.
415 	 */
416 	public boolean isRemote() {
417 		return getHost() != null;
418 	}
419 
420 	/**
421 	 * @return host name part or null
422 	 */
423 	public String getHost() {
424 		return host;
425 	}
426 
427 	/**
428 	 * Return a new URI matching this one, but with a different host.
429 	 *
430 	 * @param n
431 	 *            the new value for host.
432 	 * @return a new URI with the updated value.
433 	 */
434 	public URIish setHost(final String n) {
435 		final URIish r = new URIish(this);
436 		r.host = n;
437 		return r;
438 	}
439 
440 	/**
441 	 * @return protocol name or null for local references
442 	 */
443 	public String getScheme() {
444 		return scheme;
445 	}
446 
447 	/**
448 	 * Return a new URI matching this one, but with a different scheme.
449 	 *
450 	 * @param n
451 	 *            the new value for scheme.
452 	 * @return a new URI with the updated value.
453 	 */
454 	public URIish setScheme(final String n) {
455 		final URIish r = new URIish(this);
456 		r.scheme = n;
457 		return r;
458 	}
459 
460 	/**
461 	 * @return path name component
462 	 */
463 	public String getPath() {
464 		return path;
465 	}
466 
467 	/**
468 	 * @return path name component
469 	 */
470 	public String getRawPath() {
471 		return rawPath;
472 	}
473 
474 	/**
475 	 * Return a new URI matching this one, but with a different path.
476 	 *
477 	 * @param n
478 	 *            the new value for path.
479 	 * @return a new URI with the updated value.
480 	 */
481 	public URIish setPath(final String n) {
482 		final URIish r = new URIish(this);
483 		r.path = n;
484 		r.rawPath = n;
485 		return r;
486 	}
487 
488 	/**
489 	 * Return a new URI matching this one, but with a different (raw) path.
490 	 *
491 	 * @param n
492 	 *            the new value for path.
493 	 * @return a new URI with the updated value.
494 	 * @throws URISyntaxException
495 	 */
496 	public URIish setRawPath(final String n) throws URISyntaxException {
497 		final URIish r = new URIish(this);
498 		r.path = unescape(n);
499 		r.rawPath = n;
500 		return r;
501 	}
502 
503 	/**
504 	 * @return user name requested for transfer or null
505 	 */
506 	public String getUser() {
507 		return user;
508 	}
509 
510 	/**
511 	 * Return a new URI matching this one, but with a different user.
512 	 *
513 	 * @param n
514 	 *            the new value for user.
515 	 * @return a new URI with the updated value.
516 	 */
517 	public URIish setUser(final String n) {
518 		final URIish r = new URIish(this);
519 		r.user = n;
520 		return r;
521 	}
522 
523 	/**
524 	 * @return password requested for transfer or null
525 	 */
526 	public String getPass() {
527 		return pass;
528 	}
529 
530 	/**
531 	 * Return a new URI matching this one, but with a different password.
532 	 *
533 	 * @param n
534 	 *            the new value for password.
535 	 * @return a new URI with the updated value.
536 	 */
537 	public URIish setPass(final String n) {
538 		final URIish r = new URIish(this);
539 		r.pass = n;
540 		return r;
541 	}
542 
543 	/**
544 	 * @return port number requested for transfer or -1 if not explicit
545 	 */
546 	public int getPort() {
547 		return port;
548 	}
549 
550 	/**
551 	 * Return a new URI matching this one, but with a different port.
552 	 *
553 	 * @param n
554 	 *            the new value for port.
555 	 * @return a new URI with the updated value.
556 	 */
557 	public URIish setPort(final int n) {
558 		final URIish r = new URIish(this);
559 		r.port = n > 0 ? n : -1;
560 		return r;
561 	}
562 
563 	@Override
564 	public int hashCode() {
565 		int hc = 0;
566 		if (getScheme() != null)
567 			hc = hc * 31 + getScheme().hashCode();
568 		if (getUser() != null)
569 			hc = hc * 31 + getUser().hashCode();
570 		if (getPass() != null)
571 			hc = hc * 31 + getPass().hashCode();
572 		if (getHost() != null)
573 			hc = hc * 31 + getHost().hashCode();
574 		if (getPort() > 0)
575 			hc = hc * 31 + getPort();
576 		if (getPath() != null)
577 			hc = hc * 31 + getPath().hashCode();
578 		return hc;
579 	}
580 
581 	@Override
582 	public boolean equals(final Object obj) {
583 		if (!(obj instanceof URIish))
584 			return false;
585 		final URIish b = (URIish) obj;
586 		if (!eq(getScheme(), b.getScheme()))
587 			return false;
588 		if (!eq(getUser(), b.getUser()))
589 			return false;
590 		if (!eq(getPass(), b.getPass()))
591 			return false;
592 		if (!eq(getHost(), b.getHost()))
593 			return false;
594 		if (getPort() != b.getPort())
595 			return false;
596 		if (!eq(getPath(), b.getPath()))
597 			return false;
598 		return true;
599 	}
600 
601 	private static boolean eq(final String a, final String b) {
602 		if (a == b)
603 			return true;
604 		if (StringUtils.isEmptyOrNull(a) && StringUtils.isEmptyOrNull(b))
605 			return true;
606 		if (a == null || b == null)
607 			return false;
608 		return a.equals(b);
609 	}
610 
611 	/**
612 	 * Obtain the string form of the URI, with the password included.
613 	 *
614 	 * @return the URI, including its password field, if any.
615 	 */
616 	public String toPrivateString() {
617 		return format(true, false);
618 	}
619 
620 	@Override
621 	public String toString() {
622 		return format(false, false);
623 	}
624 
625 	private String format(final boolean includePassword, boolean escapeNonAscii) {
626 		final StringBuilder r = new StringBuilder();
627 		if (getScheme() != null) {
628 			r.append(getScheme());
629 			r.append("://"); //$NON-NLS-1$
630 		}
631 
632 		if (getUser() != null) {
633 			r.append(escape(getUser(), true, escapeNonAscii));
634 			if (includePassword && getPass() != null) {
635 				r.append(':');
636 				r.append(escape(getPass(), true, escapeNonAscii));
637 			}
638 		}
639 
640 		if (getHost() != null) {
641 			if (getUser() != null && getUser().length() > 0)
642 				r.append('@');
643 			r.append(escape(getHost(), false, escapeNonAscii));
644 			if (getScheme() != null && getPort() > 0) {
645 				r.append(':');
646 				r.append(getPort());
647 			}
648 		}
649 
650 		if (getPath() != null) {
651 			if (getScheme() != null) {
652 				if (!getPath().startsWith("/") && !getPath().isEmpty()) //$NON-NLS-1$
653 					r.append('/');
654 			} else if (getHost() != null)
655 				r.append(':');
656 			if (getScheme() != null)
657 				if (escapeNonAscii)
658 					r.append(escape(getPath(), false, escapeNonAscii));
659 				else
660 					r.append(getRawPath());
661 			else
662 				r.append(getPath());
663 		}
664 
665 		return r.toString();
666 	}
667 
668 	/**
669 	 * @return the URI as an ASCII string. Password is not included.
670 	 */
671 	public String toASCIIString() {
672 		return format(false, true);
673 	}
674 
675 	/**
676 	 * @return the URI including password, formatted with only ASCII characters
677 	 *         such that it will be valid for use over the network.
678 	 */
679 	public String toPrivateASCIIString() {
680 		return format(true, true);
681 	}
682 
683 	/**
684 	 * Get the "humanish" part of the path. Some examples of a 'humanish' part
685 	 * for a full path:
686 	 * <table summary="path vs humanish path" border="1">
687 	 * <tr>
688 	 * <th>Path</th>
689 	 * <th>Humanish part</th>
690 	 * </tr>
691 	 * <tr>
692 	 * <td><code>/path/to/repo.git</code></td>
693 	 * <td rowspan="4"><code>repo</code></td>
694 	 * </tr>
695 	 * <tr>
696 	 * <td><code>/path/to/repo.git/</code></td>
697 	 * </tr>
698 	 * <tr>
699 	 * <td><code>/path/to/repo/.git</code></td>
700 	 * </tr>
701 	 * <tr>
702 	 * <td><code>/path/to/repo/</code></td>
703 	 * </tr>
704 	 * <tr>
705 	 * <td><code>localhost</code></td>
706 	 * <td><code>ssh://localhost/</code></td>
707 	 * </tr>
708 	 * <tr>
709 	 * <td><code>/path//to</code></td>
710 	 * <td>an empty string</td>
711 	 * </tr>
712 	 * </table>
713 	 *
714 	 * @return the "humanish" part of the path. May be an empty string. Never
715 	 *         {@code null}.
716 	 * @throws IllegalArgumentException
717 	 *             if it's impossible to determine a humanish part, or path is
718 	 *             {@code null} or empty
719 	 * @see #getPath
720 	 */
721 	public String getHumanishName() throws IllegalArgumentException {
722 		String s = getPath();
723 		if ("/".equals(s) || "".equals(s)) //$NON-NLS-1$ //$NON-NLS-2$
724 			s = getHost();
725 		if (s == null) // $NON-NLS-1$
726 			throw new IllegalArgumentException();
727 
728 		String[] elements;
729 		if ("file".equals(scheme) || LOCAL_FILE.matcher(s).matches()) //$NON-NLS-1$
730 			elements = s.split("[\\" + File.separatorChar + "/]"); //$NON-NLS-1$ //$NON-NLS-2$
731 		else
732 			elements = s.split("/+"); //$NON-NLS-1$
733 		if (elements.length == 0)
734 			throw new IllegalArgumentException();
735 		String result = elements[elements.length - 1];
736 		if (Constants.DOT_GIT.equals(result))
737 			result = elements[elements.length - 2];
738 		else if (result.endsWith(Constants.DOT_GIT_EXT))
739 			result = result.substring(0, result.length()
740 					- Constants.DOT_GIT_EXT.length());
741 		return result;
742 	}
743 
744 }