• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <cstdlib>  // EXIT_{FAILURE,SUCCESS}
18 #include <functional>
19 #include <iostream>
20 #include <map>
21 #include <memory>
22 #include <ostream>
23 #include <string>
24 #include <vector>
25 
26 #include "Commands.h"
27 #include "idmap2/CommandLineOptions.h"
28 #include "idmap2/Result.h"
29 #include "idmap2/SysTrace.h"
30 
31 using android::idmap2::CommandLineOptions;
32 using android::idmap2::Result;
33 using android::idmap2::Unit;
34 
35 using NameToFunctionMap =
36     std::map<std::string, std::function<Result<Unit>(const std::vector<std::string>&)>>;
37 
38 namespace {
39 
PrintUsage(const NameToFunctionMap & commands,std::ostream & out)40 void PrintUsage(const NameToFunctionMap& commands, std::ostream& out) {
41   out << "usage: idmap2 [";
42   for (auto iter = commands.cbegin(); iter != commands.cend(); iter++) {
43     if (iter != commands.cbegin()) {
44       out << "|";
45     }
46     out << iter->first;
47   }
48   out << "]" << std::endl;
49 }
50 
51 }  // namespace
52 
main(int argc,char ** argv)53 int main(int argc, char** argv) {
54   SYSTRACE << "main";
55   const NameToFunctionMap commands = {
56       {"create", Create}, {"dump", Dump}, {"lookup", Lookup}, {"scan", Scan}, {"verify", Verify},
57   };
58   if (argc <= 1) {
59     PrintUsage(commands, std::cerr);
60     return EXIT_FAILURE;
61   }
62   const std::unique_ptr<std::vector<std::string>> args =
63       CommandLineOptions::ConvertArgvToVector(argc - 1, const_cast<const char**>(argv + 1));
64   if (!args) {
65     std::cerr << "error: failed to parse command line options" << std::endl;
66     return EXIT_FAILURE;
67   }
68   const auto iter = commands.find(argv[1]);
69   if (iter == commands.end()) {
70     std::cerr << argv[1] << ": command not found" << std::endl;
71     PrintUsage(commands, std::cerr);
72     return EXIT_FAILURE;
73   }
74   const auto result = iter->second(*args);
75   if (!result) {
76     std::cerr << "error: " << result.GetErrorMessage() << std::endl;
77     return EXIT_FAILURE;
78   }
79   return EXIT_SUCCESS;
80 }
81