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