• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 The Bazel Authors. 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 package com.google.devtools.build.android;
15 
16 import com.google.devtools.common.options.Converter;
17 import com.google.devtools.common.options.OptionsParsingException;
18 import java.io.File;
19 import java.nio.file.FileSystems;
20 import java.nio.file.Files;
21 import java.nio.file.InvalidPathException;
22 import java.nio.file.Path;
23 
24 /**
25  * Some convenient converters used by android actions. Note: These are specific to android actions.
26  */
27 public final class Converters {
28   private static final Converter<String> IDENTITY_CONVERTER = new Converter<String>() {
29     @Override public String convert(String input) {
30       return input;
31     }
32 
33     @Override public String getTypeDescription() {
34       return "a string";
35     }
36   };
37 
38   /** Validating converter for Paths. A Path is considered valid if it resolves to a file. */
39   public static class PathConverter implements Converter<Path> {
40 
41     private final boolean mustExist;
42 
PathConverter()43     public PathConverter() {
44       this.mustExist = false;
45     }
46 
PathConverter(boolean mustExist)47     protected PathConverter(boolean mustExist) {
48       this.mustExist = mustExist;
49     }
50 
51     @Override
convert(String input)52     public Path convert(String input) throws OptionsParsingException {
53       try {
54         Path path = FileSystems.getDefault().getPath(input);
55         if (mustExist && !Files.exists(path)) {
56           throw new OptionsParsingException(
57               String.format("%s is not a valid path: it does not exist.", input));
58         }
59         return path;
60       } catch (InvalidPathException e) {
61         throw new OptionsParsingException(
62             String.format("%s is not a valid path: %s.", input, e.getMessage()), e);
63       }
64     }
65 
66     @Override
getTypeDescription()67     public String getTypeDescription() {
68       return "a valid filesystem path";
69     }
70   }
71 
72   /**
73    * Validating converter for Paths. A Path is considered valid if it resolves to a file and exists.
74    */
75   public static class ExistingPathConverter extends PathConverter {
ExistingPathConverter()76     public ExistingPathConverter() {
77       super(true);
78     }
79   }
80 }
81