xref: /openbmc/phosphor-pid-control/sysfs/util.cpp (revision f8b6e55147148c3cfb42327ff267197a460b411c)
1 /**
2  * Copyright 2017 Google Inc.
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 "util.hpp"
18 
19 #include <filesystem>
20 #include <string>
21 
22 namespace pid_control
23 {
24 
25 /*
26  * Replace "**" in the provided path string with an appropriate concrete path
27  * component (the first directory entry found, on the assumption that there
28  * will only be a single candidate).
29  */
30 
31 namespace fs = std::filesystem;
32 
FixupPath(std::string original)33 std::string FixupPath(std::string original)
34 {
35     std::string::size_type n;
36 
37     /* TODO: Consider the merits of using regex for this. */
38     n = original.find("**");
39 
40     if (n != std::string::npos)
41     {
42         /* This path has some missing pieces and we support it. */
43         std::string base = original.substr(0, n);
44         std::string fldr;
45         std::string f = original.substr(n + 2, original.size() - (n + 2));
46 
47         /* Equivalent to glob and grab 0th entry. */
48         for (const auto& folder : fs::directory_iterator(base))
49         {
50             fldr = folder.path();
51             break;
52         }
53 
54         if (!fldr.length())
55         {
56             return original;
57         }
58 
59         return fldr + f;
60     }
61 
62     /* It'll throw an exception when we use it if it's still bad. */
63     return original;
64 }
65 
66 } // namespace pid_control
67