aboutsummaryrefslogtreecommitdiff
path: root/src/history.cc
blob: 4b3eba10eef83c3ff8f680bbe4c97ef9fad35db8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

#include "history.h"

#include <sys/stat.h>
#include <fcntl.h>
#include <print>
#include <cstdio>
#include <unistd.h>
#include <fstream>
#include <iostream>

#include "util/io.h"

using namespace std;

namespace ov4
{

void add_history(const std::string &s)
{
    history_vec.push_back(s);
}

void clear_history()
{
    history_vec.clear();
}

size_t get_last_index()
{
    return history_vec.size() - 1;
}

string get_default_history_path()
{
    return get_home_dir() + '/' + ".ccshell_history";
}

void load_history(const string &path)
{
    history_vec.clear();
    ifstream ifs(path);
    if (!ifs.is_open())
    {
        loggerln("load_history: fail to open history");
        return;
    }
    string tmp;
    while (getline(ifs, tmp))
    {
        history_vec.push_back(tmp);
    }
    return;
}

void save_history(const string &path)
{
    int fd = open(path.c_str(), O_WRONLY | O_CREAT);
    if (fd == -1) 
    {
        loggerln("save_history: fail to open() history");
        return;
    }
    char f_mode = 'w';
    FILE *f = fdopen(fd, &f_mode);
    if (f == nullptr)
    {
        loggerln("save_history: fail to fdopen() history");
        close(fd);
        return;
    }

    for (auto &c : history_vec)
    {
        println(f, "{}", c);
    }

    fflush(f);
    fsync(fd);
    fclose(f);
}
    
}