blob: 7d230f298fbeaa9601979093bcec8fa666de71f2 [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;
Matthias Sohnc156c962023-09-30 22:15:23 +020022import javax.annotation.Nullable;
Dave Borowitzbcd753d2013-02-08 11:10:19 -080023
24/** Static utilities for dealing with pathnames. */
Dave Borowitzcfc1c532015-02-18 13:41:19 -080025class PathUtil {
Dave Borowitz6d9bc5a2013-06-19 09:12:52 -070026 private static final CharMatcher MATCHER = CharMatcher.is('/');
27 static final Splitter SPLITTER = Splitter.on(MATCHER);
Dave Borowitzbcd753d2013-02-08 11:10:19 -080028
Matthias Sohnc156c962023-09-30 22:15:23 +020029 static @Nullable String simplifyPathUpToRoot(String path, String root) {
Dave Borowitzbcd753d2013-02-08 11:10:19 -080030 if (path.startsWith("/")) {
31 return null;
32 }
33
34 root = Strings.nullToEmpty(root);
35 // simplifyPath() normalizes "a/../../" to "a", so manually check whether
36 // the path leads above the root.
37 int depth = new StringTokenizer(root, "/").countTokens();
38 for (String part : SPLITTER.split(path)) {
39 if (part.equals("..")) {
40 depth--;
41 if (depth < 0) {
42 return null;
43 }
44 } else if (!part.isEmpty() && !part.equals(".")) {
45 depth++;
46 }
47 }
48
49 String result = Files.simplifyPath(!root.isEmpty() ? root + "/" + path : path);
50 return !result.equals(".") ? result : "";
51 }
52
Dave Borowitz6d9bc5a2013-06-19 09:12:52 -070053 static String basename(String path) {
54 path = MATCHER.trimTrailingFrom(path);
55 int slash = path.lastIndexOf('/');
56 if (slash < 0) {
57 return path;
58 }
59 return path.substring(slash + 1);
60 }
61
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020062 private PathUtil() {}
Dave Borowitzbcd753d2013-02-08 11:10:19 -080063}