aboutsummaryrefslogtreecommitdiffstats
path: root/bots/todo-js/tools.js
blob: ed3ed39103b1a3da6005a9e9e6c9dcc9d7d63fe6 (plain) (blame)
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
const fs = require('fs');
const path = require('path');

/**
 * Add a new todo item
 * @typedef {Object} AddTodoArgs
 * @property {string} desc - The task description
 * @param {AddTodoArgs} args
 */
exports.add_todo = function addTodo(args) {
  const todosFile = _getTodosFile();
  if (fs.existsSync(todosFile)) {
    const num = JSON.parse(fs.readFileSync(todosFile)).reduce((max, item) => Math.max(max, item.id), 0) + 1;
    const data = fs.readFileSync(todosFile);
    fs.writeFileSync(todosFile, JSON.stringify([...JSON.parse(data), { id: num, desc: args.desc }]));
    console.log(`Successfully added todo id=${num}`);
  } else {
    fs.writeFileSync(todosFile, JSON.stringify([{ id: 1, desc: args.desc }]));
    console.log('Successfully added todo id=1');
  }
}

/**
 * Delete an existing todo item
 * @typedef {Object} DelTodoArgs
 * @property {number} id - The task id
 * @param {DelTodoArgs} args
 */
exports.del_todo = function delTodo(args) {
  const todosFile = _getTodosFile();
  if (fs.existsSync(todosFile)) {
    const data = fs.readFileSync(todosFile);
    const newData = JSON.parse(data).filter(item => item.id !== args.id);
    fs.writeFileSync(todosFile, JSON.stringify(newData));
    console.log(`Successfully deleted todo id=${args.id}`);
  } else {
    _die('Empty todo list');
  }
}

/**
 * Display the current todo list in json format.
 */
exports.list_todos = function listTodos() {
  const todosFile = _getTodosFile();
  if (fs.existsSync(todosFile)) {
    console.log(fs.readFileSync(todosFile, "utf8"));
  } else {
    _die('Empty todo list');
  }
}

/**
 * Delete the entire todo list.
 */
exports.clear_todos = function clearTodos() {
  const todosFile = _getTodosFile();
  fs.unlinkSync(todosFile)
  console.log("Successfully deleted entry todo list");
}

function _getTodosFile() {
  const cacheDir = process.env.LLM_BOT_CACHE_DIR || '/tmp';
  if (!fs.existsSync(cacheDir)) {
    fs.mkdirSync(cacheDir, { recursive: true });
  }
  return path.join(cacheDir, 'todos.json');
}

function _die(message) {
  console.error(message);
  process.exit(1);
}