claugeas/AugFuncs.h

106 lines
3.0 KiB
C++

#include "AugSettings.h"
#include "augeas.h"
#include "map"
#ifndef BLUEWEST_AUGEAS_BLUEAUG_H
#define BLUEWEST_AUGEAS_BLUEAUG_H
class AugFuncs {
static void testSource(const AugSettings& settings) {
int r;
struct augeas *aug;
char *s;
aug = aug_init(settings.root, settings.loadPath, AUG_NO_STDINC | AUG_NO_LOAD);
r = aug_load_file(aug, "/etc/hosts");
r = aug_source(aug, "/files/etc/hosts/1/ipaddr", nullptr);
std::cout << "The value read from node: " << s << std::endl;
aug_close(aug);
}
/// Get the tree of the /etc/hosts file printed in the console
/// Implementation based on https://github.com/Nexenta/node-augeas/blob/756276c432cc9e506836800ac9d217bedbbef55c/libaugeas.cc#L784
public:
// This prints the actual file
void printPreview(const AugSettings& settings, const std::string& matchPath, const std::string& filePath) {
struct augeas *aug;
int r;
char *s;
char *etc_hosts_fn = nullptr;
FILE *hosts_fp = nullptr;
char *hosts_txt = nullptr;
aug = aug_init(settings.root, settings.loadPath, AUG_NO_STDINC | AUG_NO_LOAD);
r = aug_load_file(aug, filePath.c_str());
r = aug_preview(aug, matchPath.c_str(), &s);
std::cout << s << std::endl;
free(hosts_txt);
free(s);
aug_close(aug);
}
void printAugTree(
const AugSettings& settings,
const std::string& matchPath,
const std::string& filePath
) {
struct augeas *aug;
int r;
FILE *out = tmpfile();
aug = aug_init(settings.root, settings.loadPath, AUG_NO_STDINC | AUG_NO_LOAD);
r = aug_load_file(aug, filePath.c_str());
r = aug_print(aug, out,matchPath.c_str());
std::map <std::string, std::string> stdBindList;
std::map <std::string , std::string>::iterator pos;
char line[256];
rewind(out);
while (fgets(line, 256, out) != nullptr) {
// remove end of line
line[strlen(line) - 1] = '\0';
std::string s = line;
// skip comments
if (s.find("#comment") != std::string::npos)
continue;
s = s.substr(matchPath.length() - 1);
// split by '=' sign
size_t eqpos = s.find(" = ");
if (eqpos == std::string::npos)
continue;
// extract key and value
std::string key = s.substr(0, eqpos);
std::string value = s.substr(eqpos + 3);
// remove '"' sign from around value
value.erase(value.begin());
value.erase(value.end() - 1);
stdBindList.insert(std::pair<std::string,std::string>(key,value)); // 2
}
fclose(out);
for (pos = stdBindList.begin();pos!=stdBindList.end();pos++)
{
std::cout << "Key: " << pos->first << ";" << " Value: " << pos->second << std::endl;
}
aug_close(aug);
}
};
#endif //BLUEWEST_AUGEAS_BLUEAUG_H