blob: 2df8cdce3e71f00c6b5ce5b6bde2ad6b73730f3c [file] [log] [blame]
Dave Borowitzbcd753d2013-02-08 11:10:19 -08001// Copyright 2012 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package com.google.gitiles;
16
Dave Borowitz6d9bc5a2013-06-19 09:12:52 -070017import com.google.common.base.CharMatcher;
Dave Borowitzbcd753d2013-02-08 11:10:19 -080018import com.google.common.base.Splitter;
19import com.google.common.base.Strings;
20import com.google.common.io.Files;
Dave Borowitzbcd753d2013-02-08 11:10:19 -080021import java.util.StringTokenizer;
22
23/** Static utilities for dealing with pathnames. */
Dave Borowitzcfc1c532015-02-18 13:41:19 -080024class PathUtil {
Dave Borowitz6d9bc5a2013-06-19 09:12:52 -070025 private static final CharMatcher MATCHER = CharMatcher.is('/');
26 static final Splitter SPLITTER = Splitter.on(MATCHER);
Dave Borowitzbcd753d2013-02-08 11:10:19 -080027
28 static String simplifyPathUpToRoot(String path, String root) {
29 if (path.startsWith("/")) {
30 return null;
31 }
32
33 root = Strings.nullToEmpty(root);
34 // simplifyPath() normalizes "a/../../" to "a", so manually check whether
35 // the path leads above the root.
36 int depth = new StringTokenizer(root, "/").countTokens();
37 for (String part : SPLITTER.split(path)) {
38 if (part.equals("..")) {
39 depth--;
40 if (depth < 0) {
41 return null;
42 }
43 } else if (!part.isEmpty() && !part.equals(".")) {
44 depth++;
45 }
46 }
47
48 String result = Files.simplifyPath(!root.isEmpty() ? root + "/" + path : path);
49 return !result.equals(".") ? result : "";
50 }
51
Dave Borowitz6d9bc5a2013-06-19 09:12:52 -070052 static String basename(String path) {
53 path = MATCHER.trimTrailingFrom(path);
54 int slash = path.lastIndexOf('/');
55 if (slash < 0) {
56 return path;
57 }
58 return path.substring(slash + 1);
59 }
60
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020061 private PathUtil() {}
Dave Borowitzbcd753d2013-02-08 11:10:19 -080062}