mirror of
https://github.com/tomasriveral/NoteWrapper.git
synced 2026-08-12 10:20:46 +02:00
Merge (#19) from tomasriveral/clangd-test CI: add clang-format check
add documentation about this test add .clang-format file add build flag -Werror add clang-tools to shell.nix format whole project
This commit is contained in:
@@ -0,0 +1,3 @@
|
|||||||
|
BasedOnStyle: LLVM
|
||||||
|
IndentWidth: 4
|
||||||
|
ColumnLimit: 100
|
||||||
@@ -11,9 +11,17 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install clang
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y clang-format
|
||||||
|
- name: Check format
|
||||||
|
run: |
|
||||||
|
clang-format --version
|
||||||
|
find src -name "*.c" -o -name "*.h" | xargs clang-format --dry-run --Werror
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
sudo apt-get install -y \
|
sudo apt-get install -y \
|
||||||
gcc \
|
gcc \
|
||||||
make \
|
make \
|
||||||
|
|||||||
@@ -85,3 +85,12 @@ Before submitting a pull request, ensure that:
|
|||||||
* `make`, or
|
* `make`, or
|
||||||
* `nix-build` (on NixOS)
|
* `nix-build` (on NixOS)
|
||||||
* There are **no warnings or errors**
|
* There are **no warnings or errors**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Continuous integration
|
||||||
|
|
||||||
|
All PR will need to pass these checks:
|
||||||
|
1. `clang-format`. Running `find src -name "*.c" -o -name "*.h" | xargs clang-format -i` will automatically apply those rules.
|
||||||
|
2. The program must build without warning or error.
|
||||||
|
3. The program must run for five seconds without crashing.
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ CC := gcc
|
|||||||
|
|
||||||
VERSION := $(shell git describe --tags --always --dirty)
|
VERSION := $(shell git describe --tags --always --dirty)
|
||||||
|
|
||||||
CFLAGS := -Wall -Wextra -O2 \
|
CFLAGS := -Wall -Wextra -Werror -O2 \
|
||||||
-DVERSION=\"$(VERSION)\" \
|
-DVERSION=\"$(VERSION)\" \
|
||||||
$(shell pkg-config --cflags libcjson ncurses)
|
$(shell pkg-config --cflags libcjson ncurses)
|
||||||
|
|
||||||
|
|||||||
@@ -8,5 +8,6 @@ pkgs.mkShell {
|
|||||||
pkgs.gdb
|
pkgs.gdb
|
||||||
pkgs.valgrind
|
pkgs.valgrind
|
||||||
pkgs.kdePackages.kcachegrind
|
pkgs.kdePackages.kcachegrind
|
||||||
|
pkgs.clang-tools
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
+271
-133
@@ -1,6 +1,6 @@
|
|||||||
|
#include "notes.h"
|
||||||
#include "ui.h"
|
#include "ui.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
#include "notes.h"
|
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[]) {
|
||||||
int shouldDebug = 0;
|
int shouldDebug = 0;
|
||||||
@@ -14,10 +14,8 @@ int main(int argc, char *argv[]) {
|
|||||||
shouldDebug = 1;
|
shouldDebug = 1;
|
||||||
|
|
||||||
} else if (strcmp(arg, "--config") == 0) {
|
} else if (strcmp(arg, "--config") == 0) {
|
||||||
error(i + 1 == argc, "user",
|
error(i + 1 == argc, "user", "Missing argument. Use --config <path>");
|
||||||
"Missing argument. Use --config <path>");
|
|
||||||
overwriteConfigPath = ++i; // consume argument
|
overwriteConfigPath = ++i; // consume argument
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Short options (allow grouping like -V)
|
// Short options (allow grouping like -V)
|
||||||
@@ -32,10 +30,8 @@ int main(int argc, char *argv[]) {
|
|||||||
|
|
||||||
case 'c':
|
case 'c':
|
||||||
// must NOT be combined (needs argument)
|
// must NOT be combined (needs argument)
|
||||||
error(arg[j+1] != '\0', "user",
|
error(arg[j + 1] != '\0', "user", "-c cannot be combined (use -c <path>)");
|
||||||
"-c cannot be combined (use -c <path>)");
|
error(i + 1 == argc, "user", "Missing argument for -c");
|
||||||
error(i + 1 == argc, "user",
|
|
||||||
"Missing argument for -c");
|
|
||||||
|
|
||||||
overwriteConfigPath = ++i; // consume argument
|
overwriteConfigPath = ++i; // consume argument
|
||||||
goto arg_next;
|
goto arg_next;
|
||||||
@@ -47,9 +43,8 @@ int main(int argc, char *argv[]) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
arg_next:
|
arg_next:;
|
||||||
;
|
}
|
||||||
}
|
|
||||||
// gets the home directory
|
// gets the home directory
|
||||||
struct passwd *pw = getpwuid(getuid());
|
struct passwd *pw = getpwuid(getuid());
|
||||||
const char *homedir = pw->pw_dir;
|
const char *homedir = pw->pw_dir;
|
||||||
@@ -69,27 +64,33 @@ arg_next:
|
|||||||
}
|
}
|
||||||
// check if the config file exists
|
// check if the config file exists
|
||||||
struct stat st = {0};
|
struct stat st = {0};
|
||||||
error(stat(configPath, &st) == -1, "user", "The config file %s does not exist.\nMaybe try the default path to the config ~/.config/notewrapper/config.json\nOr if you used the flag -c or --config, verifiy that you point to the correct file.", configPath); // if the config directory does not exist
|
error(stat(configPath, &st) == -1, "user",
|
||||||
|
"The config file %s does not exist.\nMaybe try the default path to the config "
|
||||||
|
"~/.config/notewrapper/config.json\nOr if you used the flag -c or --config, verifiy that "
|
||||||
|
"you point to the correct file.",
|
||||||
|
configPath); // if the config directory does not exist
|
||||||
|
|
||||||
// opens config.json
|
// opens config.json
|
||||||
FILE *f = fopen(configPath, "r");
|
FILE *f = fopen(configPath, "r");
|
||||||
error(!f, "program", "The config file does exist, but can not be open.");
|
error(!f, "program", "The config file does exist, but can not be open.");
|
||||||
|
|
||||||
// loads and read the config file
|
// loads and read the config file
|
||||||
//gets the size
|
// gets the size
|
||||||
fseek(f, 0, SEEK_END);
|
fseek(f, 0, SEEK_END);
|
||||||
size_t size = ftell(f);
|
size_t size = ftell(f);
|
||||||
rewind(f);
|
rewind(f);
|
||||||
//gets the data
|
// gets the data
|
||||||
char *data = malloc(size+1);
|
char *data = malloc(size + 1);
|
||||||
error(!data, "program", "malloc failed allocating memory for the variable data.");
|
error(!data, "program", "malloc failed allocating memory for the variable data.");
|
||||||
size_t readBytes = fread(data, 1, size, f); // 1 --> size of each item
|
size_t readBytes = fread(data, 1, size, f); // 1 --> size of each item
|
||||||
|
|
||||||
if (readBytes!=size) {
|
if (readBytes != size) {
|
||||||
free(data);
|
free(data);
|
||||||
fclose(f);
|
fclose(f);
|
||||||
}
|
}
|
||||||
error(readBytes!=size, "program", "Failed to read config file (%s) (%zu bytes read, expected %ld)", configPath, readBytes, size);
|
error(readBytes != size, "program",
|
||||||
|
"Failed to read config file (%s) (%zu bytes read, expected %ld)", configPath, readBytes,
|
||||||
|
size);
|
||||||
data[size] = '\0';
|
data[size] = '\0';
|
||||||
fclose(f);
|
fclose(f);
|
||||||
|
|
||||||
@@ -97,21 +98,26 @@ arg_next:
|
|||||||
debug("Parsing the JSON config");
|
debug("Parsing the JSON config");
|
||||||
|
|
||||||
cJSON *json = cJSON_Parse(data);
|
cJSON *json = cJSON_Parse(data);
|
||||||
if (!json) {free(data);}
|
if (!json) {
|
||||||
|
free(data);
|
||||||
|
}
|
||||||
error(!json, "program", "JSON parse error");
|
error(!json, "program", "JSON parse error");
|
||||||
|
|
||||||
// Parse all of the directories which will( or do) contain the vaults
|
// Parse all of the directories which will( or do) contain the vaults
|
||||||
cJSON *dirJson = cJSON_GetObjectItem(json, "directory");
|
cJSON *dirJson = cJSON_GetObjectItem(json, "directory");
|
||||||
error(dirJson && !cJSON_IsArray(dirJson), "user", "In %s, \"directory\" is missing or isn't an array", configPath);
|
error(dirJson && !cJSON_IsArray(dirJson), "user",
|
||||||
|
"In %s, \"directory\" is missing or isn't an array", configPath);
|
||||||
int numDirectories = cJSON_GetArraySize(dirJson);
|
int numDirectories = cJSON_GetArraySize(dirJson);
|
||||||
debug("In %s, detected %d paths in \"directory\"", configPath, numDirectories);
|
debug("In %s, detected %d paths in \"directory\"", configPath, numDirectories);
|
||||||
error(numDirectories == 0, "user", "In %s, \"directory\" is an empty array.", configPath);
|
error(numDirectories == 0, "user", "In %s, \"directory\" is an empty array.", configPath);
|
||||||
|
|
||||||
char **directoriesArray = malloc(numDirectories * sizeof(char*));
|
char **directoriesArray = malloc(numDirectories * sizeof(char *));
|
||||||
debug("Directories:");
|
debug("Directories:");
|
||||||
cJSON *tempEntry = NULL;
|
cJSON *tempEntry = NULL;
|
||||||
int i = 0;
|
int i = 0;
|
||||||
cJSON_ArrayForEach(tempEntry, dirJson) { // iterate over all the elements of the array _i. e._ over all the dirs
|
cJSON_ArrayForEach(
|
||||||
|
tempEntry,
|
||||||
|
dirJson) { // iterate over all the elements of the array _i. e._ over all the dirs
|
||||||
if (tempEntry && cJSON_IsString(tempEntry)) {
|
if (tempEntry && cJSON_IsString(tempEntry)) {
|
||||||
if (cJSON_GetStringValue(tempEntry)[0] == '~') { // we must expand ~
|
if (cJSON_GetStringValue(tempEntry)[0] == '~') { // we must expand ~
|
||||||
char *tempUnFixedName = cJSON_GetStringValue(tempEntry);
|
char *tempUnFixedName = cJSON_GetStringValue(tempEntry);
|
||||||
@@ -121,10 +127,11 @@ arg_next:
|
|||||||
snprintf(directoriesArray[i], PATH_MAX, "%s%s", homedir, tempUnFixedName);
|
snprintf(directoriesArray[i], PATH_MAX, "%s%s", homedir, tempUnFixedName);
|
||||||
} else {
|
} else {
|
||||||
directoriesArray[i] = strdup(cJSON_GetStringValue(tempEntry));
|
directoriesArray[i] = strdup(cJSON_GetStringValue(tempEntry));
|
||||||
altDebug("%s\n",directoriesArray[i]);
|
altDebug("%s\n", directoriesArray[i]);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
error(1, "user", "In %s, in \"directory\", invalid type of one of the entries.", configPath);
|
error(1, "user", "In %s, in \"directory\", invalid type of one of the entries.",
|
||||||
|
configPath);
|
||||||
}
|
}
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
@@ -146,19 +153,28 @@ arg_next:
|
|||||||
debug("In %s, \"jumpToEndOfFileOnLaunch\" was set to %d.", configPath, shouldJumpToEnd);
|
debug("In %s, \"jumpToEndOfFileOnLaunch\" was set to %d.", configPath, shouldJumpToEnd);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
debug("In %s, \"jumpToEndOfFileOnLaunch\" wasn't set or we encountered a abnormal type. Defaulting to true.", configPath);
|
debug("In %s, \"jumpToEndOfFileOnLaunch\" wasn't set or we encountered a abnormal type. "
|
||||||
|
"Defaulting to true.",
|
||||||
|
configPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
char *editorToOpen = getenv("EDITOR"); // default to $EDITOR
|
char *editorToOpen = getenv("EDITOR"); // default to $EDITOR
|
||||||
int defaultEditor = 1; // this will be used in the warning if the editor does not exists or is unsupported.
|
int defaultEditor =
|
||||||
|
1; // this will be used in the warning if the editor does not exists or is unsupported.
|
||||||
cJSON *editorToOpenJSON = cJSON_GetObjectItem(json, "editor");
|
cJSON *editorToOpenJSON = cJSON_GetObjectItem(json, "editor");
|
||||||
if (editorToOpenJSON && cJSON_IsString(editorToOpenJSON)) {
|
if (editorToOpenJSON && cJSON_IsString(editorToOpenJSON)) {
|
||||||
editorToOpen = strdup(cJSON_GetStringValue(editorToOpenJSON)); // we must strdup and not just = as we will free all the json after (before parsing args)
|
editorToOpen = strdup(cJSON_GetStringValue(
|
||||||
|
editorToOpenJSON)); // we must strdup and not just = as we will free all the json after
|
||||||
|
// (before parsing args)
|
||||||
defaultEditor = 0;
|
defaultEditor = 0;
|
||||||
debug("In %s, \"editor\" was set to %s.", configPath, editorToOpen);
|
debug("In %s, \"editor\" was set to %s.", configPath, editorToOpen);
|
||||||
//error(!isStringInArray(editorToOpen, supportedEditor, numEditors), "user", "%s (fetched from config.json) is not a supported editor.", editorToOpen); // we check if editor is supported at the end
|
// error(!isStringInArray(editorToOpen, supportedEditor, numEditors), "user", "%s (fetched
|
||||||
|
// from config.json) is not a supported editor.", editorToOpen); // we check if editor is
|
||||||
|
// supported at the end
|
||||||
} else {
|
} else {
|
||||||
debug("In %s, \"editor\" wasn't set or we encountered a abnormal type. Defaulting to $EDITOR (%s).\n P.S. this might still be overwritten by -e or --editor.", configPath, editorToOpen);
|
debug("In %s, \"editor\" wasn't set or we encountered a abnormal type. Defaulting to "
|
||||||
|
"$EDITOR (%s).\n P.S. this might still be overwritten by -e or --editor.",
|
||||||
|
configPath, editorToOpen);
|
||||||
}
|
}
|
||||||
|
|
||||||
cJSON *journalRegexJSON = cJSON_GetObjectItem(json, "journalRegex");
|
cJSON *journalRegexJSON = cJSON_GetObjectItem(json, "journalRegex");
|
||||||
@@ -167,32 +183,42 @@ arg_next:
|
|||||||
journalRegex = strdup(cJSON_GetStringValue(journalRegexJSON));
|
journalRegex = strdup(cJSON_GetStringValue(journalRegexJSON));
|
||||||
debug("In %s, \"journalRegex\" was set to %s.", configPath, journalRegex);
|
debug("In %s, \"journalRegex\" was set to %s.", configPath, journalRegex);
|
||||||
} else {
|
} else {
|
||||||
debug("In %s, \"journalRegex\" wasn't set or we encountered a abnormal type. Defaulting to %s.", configPath, journalRegex);
|
debug("In %s, \"journalRegex\" wasn't set or we encountered a abnormal type. Defaulting to "
|
||||||
|
"%s.",
|
||||||
|
configPath, journalRegex);
|
||||||
}
|
}
|
||||||
|
|
||||||
char *timeFormat = "# \%Y \%m \%d \%a";// default
|
char *timeFormat = "# \%Y \%m \%d \%a"; // default
|
||||||
cJSON *timeFormatJSON = cJSON_GetObjectItem(json, "dateEntry");
|
cJSON *timeFormatJSON = cJSON_GetObjectItem(json, "dateEntry");
|
||||||
if (timeFormatJSON && cJSON_IsString(timeFormatJSON)) {
|
if (timeFormatJSON && cJSON_IsString(timeFormatJSON)) {
|
||||||
timeFormat = strdup(cJSON_GetStringValue(timeFormatJSON));
|
timeFormat = strdup(cJSON_GetStringValue(timeFormatJSON));
|
||||||
debug("In %s, \"dateEntry\" was set to %s.", configPath, timeFormat);
|
debug("In %s, \"dateEntry\" was set to %s.", configPath, timeFormat);
|
||||||
} else {
|
} else {
|
||||||
debug("In %s, \"dateEntry\" wasn't set or we encountered a abnormal type. Defaulting to %s.", configPath, timeFormat);
|
debug(
|
||||||
|
"In %s, \"dateEntry\" wasn't set or we encountered a abnormal type. Defaulting to %s.",
|
||||||
|
configPath, timeFormat);
|
||||||
}
|
}
|
||||||
int newLineOnOpening = 1;
|
int newLineOnOpening = 1;
|
||||||
cJSON *newLineOnOpeningJSON = cJSON_GetObjectItem(json, "newLineOnOpening");
|
cJSON *newLineOnOpeningJSON = cJSON_GetObjectItem(json, "newLineOnOpening");
|
||||||
if (newLineOnOpeningJSON && cJSON_IsBool(newLineOnOpeningJSON)) {
|
if (newLineOnOpeningJSON && cJSON_IsBool(newLineOnOpeningJSON)) {
|
||||||
debug("The value for newLineOnOpening in config.json is %d", cJSON_IsTrue(newLineOnOpeningJSON));
|
debug("The value for newLineOnOpening in config.json is %d",
|
||||||
|
cJSON_IsTrue(newLineOnOpeningJSON));
|
||||||
|
|
||||||
newLineOnOpening = cJSON_IsTrue(newLineOnOpeningJSON) ? 1 : 0;
|
newLineOnOpening = cJSON_IsTrue(newLineOnOpeningJSON) ? 1 : 0;
|
||||||
debug("In %s, \"newLineOnOpening\" was set to %d.", configPath, newLineOnOpening);
|
debug("In %s, \"newLineOnOpening\" was set to %d.", configPath, newLineOnOpening);
|
||||||
} else {
|
} else {
|
||||||
debug("In %s, \"newLineOnOpening\" wasn't set or we encountered a abnormal type. Defaulting to true.", configPath);
|
debug("In %s, \"newLineOnOpening\" wasn't set or we encountered a abnormal type. "
|
||||||
|
"Defaulting to true.",
|
||||||
|
configPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
int doesBackup = 0;
|
int doesBackup = 0;
|
||||||
int interval = 0; // this is an int. But some times it will be inputed a string. We must translate it.
|
int interval =
|
||||||
// to handle linking each directory to its backup path. We create an array of char*. If we want to backup the ith directory, the ith pointer will point to the path. Else, we set the ith pointer to NULL.
|
0; // this is an int. But some times it will be inputed a string. We must translate it.
|
||||||
char **backupDirectoriesArray = malloc(numDirectories*sizeof(char*));
|
// to handle linking each directory to its backup path. We create an array of char*. If we want
|
||||||
|
// to backup the ith directory, the ith pointer will point to the path. Else, we set the ith
|
||||||
|
// pointer to NULL.
|
||||||
|
char **backupDirectoriesArray = malloc(numDirectories * sizeof(char *));
|
||||||
char **rsyncArgs = NULL;
|
char **rsyncArgs = NULL;
|
||||||
int rsyncArgsNumber = 0;
|
int rsyncArgsNumber = 0;
|
||||||
cJSON *backupJSON = cJSON_GetObjectItem(json, "backup");
|
cJSON *backupJSON = cJSON_GetObjectItem(json, "backup");
|
||||||
@@ -209,27 +235,37 @@ arg_next:
|
|||||||
// handles the path to the backup for each directory
|
// handles the path to the backup for each directory
|
||||||
cJSON *pathToBackupJSON = cJSON_GetObjectItem(backupJSON, "directory");
|
cJSON *pathToBackupJSON = cJSON_GetObjectItem(backupJSON, "directory");
|
||||||
debug("%s", cJSON_Print(pathToBackupJSON));
|
debug("%s", cJSON_Print(pathToBackupJSON));
|
||||||
error(pathToBackupJSON == NULL && !(cJSON_IsObject(pathToBackupJSON) || cJSON_IsArray(pathToBackupJSON) || cJSON_IsString(pathToBackupJSON) || cJSON_IsNumber(pathToBackupJSON) || cJSON_IsBool(pathToBackupJSON)), "user", "In %s, incorrect type for \"directory\". It must be a JSON object.", configPath); // for some reason cJSON_IsObject does not work. So we must do it like this.
|
error(pathToBackupJSON == NULL &&
|
||||||
|
!(cJSON_IsObject(pathToBackupJSON) || cJSON_IsArray(pathToBackupJSON) ||
|
||||||
|
cJSON_IsString(pathToBackupJSON) || cJSON_IsNumber(pathToBackupJSON) ||
|
||||||
|
cJSON_IsBool(pathToBackupJSON)),
|
||||||
|
"user", "In %s, incorrect type for \"directory\". It must be a JSON object.",
|
||||||
|
configPath); // for some reason cJSON_IsObject does not work. So we must do it
|
||||||
|
// like this.
|
||||||
|
|
||||||
// we can't just iterate over directoriesArray as we replaced ~ to $HOME
|
// we can't just iterate over directoriesArray as we replaced ~ to $HOME
|
||||||
// we must iterate over the json entries
|
// we must iterate over the json entries
|
||||||
cJSON *directoryEntry = NULL;
|
cJSON *directoryEntry = NULL;
|
||||||
int i = 0;
|
int i = 0;
|
||||||
cJSON_ArrayForEach(directoryEntry, dirJson) { // iterate over all the elements of the array _i. e._ over all the dirs
|
cJSON_ArrayForEach(
|
||||||
|
directoryEntry,
|
||||||
|
dirJson) { // iterate over all the elements of the array _i. e._ over all the dirs
|
||||||
// we don't need to type error handle as we did it before
|
// we don't need to type error handle as we did it before
|
||||||
char *directoryEntryPath = cJSON_GetStringValue(directoryEntry);
|
char *directoryEntryPath = cJSON_GetStringValue(directoryEntry);
|
||||||
cJSON *pathToBackupForIthDirectoryJSON = cJSON_GetObjectItem(pathToBackupJSON, directoryEntryPath);
|
cJSON *pathToBackupForIthDirectoryJSON =
|
||||||
|
cJSON_GetObjectItem(pathToBackupJSON, directoryEntryPath);
|
||||||
if (pathToBackupForIthDirectoryJSON) { // if the entry exist
|
if (pathToBackupForIthDirectoryJSON) { // if the entry exist
|
||||||
char *textPath = cJSON_GetStringValue(pathToBackupForIthDirectoryJSON);
|
char *textPath = cJSON_GetStringValue(pathToBackupForIthDirectoryJSON);
|
||||||
if (textPath[0] == '~') {
|
if (textPath[0] == '~') {
|
||||||
textPath++; //cuts the ~
|
textPath++; // cuts the ~
|
||||||
backupDirectoriesArray[i] = malloc(PATH_MAX);
|
backupDirectoriesArray[i] = malloc(PATH_MAX);
|
||||||
error(backupDirectoriesArray[i] == NULL, "program", "malloc failed");
|
error(backupDirectoriesArray[i] == NULL, "program", "malloc failed");
|
||||||
snprintf(backupDirectoriesArray[i], PATH_MAX, "%s%s", homedir, textPath);
|
snprintf(backupDirectoriesArray[i], PATH_MAX, "%s%s", homedir, textPath);
|
||||||
} else {
|
} else {
|
||||||
backupDirectoriesArray[i] = strdup(textPath);
|
backupDirectoriesArray[i] = strdup(textPath);
|
||||||
}
|
}
|
||||||
debug("%s will be backed up to %s", directoriesArray[i], backupDirectoriesArray[i]);
|
debug("%s will be backed up to %s", directoriesArray[i],
|
||||||
|
backupDirectoriesArray[i]);
|
||||||
} else { // we set it to NULL to be sure we won't backup it
|
} else { // we set it to NULL to be sure we won't backup it
|
||||||
backupDirectoriesArray[i] = NULL;
|
backupDirectoriesArray[i] = NULL;
|
||||||
debug("%s won't be backed up", directoriesArray[i]);
|
debug("%s won't be backed up", directoriesArray[i]);
|
||||||
@@ -240,7 +276,8 @@ arg_next:
|
|||||||
// handles the interval of backup
|
// handles the interval of backup
|
||||||
cJSON *intervalJSON = cJSON_GetObjectItem(backupJSON, "interval");
|
cJSON *intervalJSON = cJSON_GetObjectItem(backupJSON, "interval");
|
||||||
if (intervalJSON && cJSON_IsString(intervalJSON)) {
|
if (intervalJSON && cJSON_IsString(intervalJSON)) {
|
||||||
char *temp = cJSON_GetStringValue(intervalJSON); // se comment higher. temp will be freed when calling free(json)
|
char *temp = cJSON_GetStringValue(
|
||||||
|
intervalJSON); // se comment higher. temp will be freed when calling free(json)
|
||||||
if (strcmp(temp, "daily") == 0) {
|
if (strcmp(temp, "daily") == 0) {
|
||||||
interval = DAILY;
|
interval = DAILY;
|
||||||
debug("interval in %s is set to \"daily\" which is %d", configPath, DAILY);
|
debug("interval in %s is set to \"daily\" which is %d", configPath, DAILY);
|
||||||
@@ -250,12 +287,27 @@ arg_next:
|
|||||||
} else if (strcmp(temp, "monthly") == 0) {
|
} else if (strcmp(temp, "monthly") == 0) {
|
||||||
interval = MONTHLY;
|
interval = MONTHLY;
|
||||||
debug("interval in %s is set to \"monthly\" which is %d", configPath, MONTHLY);
|
debug("interval in %s is set to \"monthly\" which is %d", configPath, MONTHLY);
|
||||||
} else {error(1, "user", "Unexpected string %s for entry \"interval\" in %s. You must put an int (number of seconds) or \"daily\" or \"weekly\" or \"monthly\".", intervalJSON->valuestring, configPath);}
|
} else {
|
||||||
|
error(1, "user",
|
||||||
|
"Unexpected string %s for entry \"interval\" in %s. You must put an int "
|
||||||
|
"(number of seconds) or \"daily\" or \"weekly\" or \"monthly\".",
|
||||||
|
intervalJSON->valuestring, configPath);
|
||||||
|
}
|
||||||
} else if (intervalJSON && cJSON_IsNumber(intervalJSON)) {
|
} else if (intervalJSON && cJSON_IsNumber(intervalJSON)) {
|
||||||
interval = (int)cJSON_GetNumberValue(intervalJSON);
|
interval = (int)cJSON_GetNumberValue(intervalJSON);
|
||||||
debug("interval in %s is set to %d", configPath, interval);
|
debug("interval in %s is set to %d", configPath, interval);
|
||||||
} else {error(1, "user", "%s did not contained an interval value inside the backup section or the value is from an unexpected type", configPath);}
|
} else {
|
||||||
} else{error(1, "user", "%s did not contained a enable value inside the backup section or the value is from an unexpected type", configPath);}
|
error(1, "user",
|
||||||
|
"%s did not contained an interval value inside the backup section or the "
|
||||||
|
"value is from an unexpected type",
|
||||||
|
configPath);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
error(1, "user",
|
||||||
|
"%s did not contained a enable value inside the backup section or the value is "
|
||||||
|
"from an unexpected type",
|
||||||
|
configPath);
|
||||||
|
}
|
||||||
// handle rsyncs array of arguments.
|
// handle rsyncs array of arguments.
|
||||||
cJSON *rsyncArgsJSON = cJSON_GetObjectItem(backupJSON, "rsyncArgs");
|
cJSON *rsyncArgsJSON = cJSON_GetObjectItem(backupJSON, "rsyncArgs");
|
||||||
if (rsyncArgsJSON && cJSON_IsArray(rsyncArgsJSON)) { // if it is what we expected
|
if (rsyncArgsJSON && cJSON_IsArray(rsyncArgsJSON)) { // if it is what we expected
|
||||||
@@ -268,16 +320,25 @@ arg_next:
|
|||||||
if (argJSON && cJSON_IsString(argJSON)) {
|
if (argJSON && cJSON_IsString(argJSON)) {
|
||||||
rsyncArgs[i] = strdup(cJSON_GetStringValue(argJSON));
|
rsyncArgs[i] = strdup(cJSON_GetStringValue(argJSON));
|
||||||
altDebug("%s\n", rsyncArgs[i]);
|
altDebug("%s\n", rsyncArgs[i]);
|
||||||
} else {error(1, "user", "One element in rsyncArgs array in %s is not a string", configPath);}
|
|
||||||
}
|
|
||||||
} else {error(1, "user", "%s did not contained a rsyncArgs array inside the backup section or the value is from an unexpected type", configPath);}
|
|
||||||
} else {
|
} else {
|
||||||
debug("In %s, \"backup\" wasn't set or we encountered a abnormal type. Defaulting to {\"enable\": false}.", configPath);
|
error(1, "user", "One element in rsyncArgs array in %s is not a string",
|
||||||
|
configPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
error(1, "user",
|
||||||
|
"%s did not contained a rsyncArgs array inside the backup section or the value "
|
||||||
|
"is from an unexpected type",
|
||||||
|
configPath);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
debug("In %s, \"backup\" wasn't set or we encountered a abnormal type. Defaulting to "
|
||||||
|
"{\"enable\": false}.",
|
||||||
|
configPath);
|
||||||
}
|
}
|
||||||
backup_config_end:
|
backup_config_end:
|
||||||
|
|
||||||
|
// cleans up
|
||||||
//cleans up
|
|
||||||
cJSON_Delete(json);
|
cJSON_Delete(json);
|
||||||
free(data);
|
free(data);
|
||||||
debug("Finished parsing the JSON config");
|
debug("Finished parsing the JSON config");
|
||||||
@@ -285,13 +346,15 @@ backup_config_end:
|
|||||||
//---------------------------------------------------------------------------------------------
|
//---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
// flags and arguments overwrite the config
|
// flags and arguments overwrite the config
|
||||||
debug("Parsing the attribute flags.\n This flags might overwrite the options in the config file.");
|
debug("Parsing the attribute flags.\n This flags might overwrite the options in the config "
|
||||||
// thoses bypasses are used if some specific flags are passed as args. This allows to bypass the TUI selectors
|
"file.");
|
||||||
|
// thoses bypasses are used if some specific flags are passed as args. This allows to bypass the
|
||||||
|
// TUI selectors
|
||||||
int bypassSelectionVault = 0;
|
int bypassSelectionVault = 0;
|
||||||
char *bypassSelectionVaultValue = NULL;
|
char *bypassSelectionVaultValue = NULL;
|
||||||
int bypassSelectionNote = 0;
|
int bypassSelectionNote = 0;
|
||||||
char *bypassSelectionNoteValue = NULL;
|
char *bypassSelectionNoteValue = NULL;
|
||||||
for (int i = 1; i < argc; i++) {
|
for (int i = 1; i < argc; i++) {
|
||||||
char *arg = argv[i];
|
char *arg = argv[i];
|
||||||
|
|
||||||
if (strncmp(arg, "--", 2) == 0) {
|
if (strncmp(arg, "--", 2) == 0) {
|
||||||
@@ -344,14 +407,20 @@ for (int i = 1; i < argc; i++) {
|
|||||||
printf("Options:\n");
|
printf("Options:\n");
|
||||||
printf(" -c, --config <path/to/config> Specify the config file.\n");
|
printf(" -c, --config <path/to/config> Specify the config file.\n");
|
||||||
printf(" -h, --help Display this message.\n");
|
printf(" -h, --help Display this message.\n");
|
||||||
printf(" -e, --editor Specify the editor to open.\n");
|
printf(
|
||||||
printf(" -j, --jump Jumps to the end of the file on opening.\n");
|
" -e, --editor Specify the editor to open.\n");
|
||||||
printf(" -J, --no-jump Do not jump to the end of the file\n");
|
printf(" -j, --jump Jumps to the end of the file "
|
||||||
printf(" -n, --note <note's name> Specify the note (or journal).\n");
|
"on opening.\n");
|
||||||
printf(" -r, --render Renders the note with Vivify.\n");
|
printf(" -J, --no-jump Do not jump to the end of "
|
||||||
|
"the file\n");
|
||||||
|
printf(" -n, --note <note's name> Specify the note (or "
|
||||||
|
"journal).\n");
|
||||||
|
printf(" -r, --render Renders the note with "
|
||||||
|
"Vivify.\n");
|
||||||
printf(" -R, --no-render Do not render.\n");
|
printf(" -R, --no-render Do not render.\n");
|
||||||
printf(" -v, --vault <vault's name> Specify the vault.\n");
|
printf(" -v, --vault <vault's name> Specify the vault.\n");
|
||||||
printf(" --version Display the program version and the GPL3 notice.\n");
|
printf(" --version Display the program version "
|
||||||
|
"and the GPL3 notice.\n");
|
||||||
printf(" -V, --verbose Show debug information.\n");
|
printf(" -V, --verbose Show debug information.\n");
|
||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
@@ -399,17 +468,25 @@ for (int i = 1; i < argc; i++) {
|
|||||||
case 'h':
|
case 'h':
|
||||||
printf("Usage: notewrapper [options]\n");
|
printf("Usage: notewrapper [options]\n");
|
||||||
printf("Options:\n");
|
printf("Options:\n");
|
||||||
printf(" -c, --config <path/to/config> Specify the config file.\n");
|
printf(
|
||||||
|
" -c, --config <path/to/config> Specify the config file.\n");
|
||||||
printf(" -h, --help Display this message.\n");
|
printf(" -h, --help Display this message.\n");
|
||||||
printf(" -e, --editor Specify the editor to open.\n");
|
printf(" -e, --editor Specify the editor to "
|
||||||
printf(" -j, --jump Jumps to the end of the file on opening.\n");
|
"open.\n");
|
||||||
printf(" -J, --no-jump Do not jump to the end of the file\n");
|
printf(" -j, --jump Jumps to the end of the "
|
||||||
printf(" -n, --note <note's name> Specify the note (or journal).\n");
|
"file on opening.\n");
|
||||||
printf(" -r, --render Renders the note with Vivify.\n");
|
printf(" -J, --no-jump Do not jump to the end "
|
||||||
|
"of the file\n");
|
||||||
|
printf(" -n, --note <note's name> Specify the note (or "
|
||||||
|
"journal).\n");
|
||||||
|
printf(" -r, --render Renders the note with "
|
||||||
|
"Vivify.\n");
|
||||||
printf(" -R, --no-render Do not render.\n");
|
printf(" -R, --no-render Do not render.\n");
|
||||||
printf(" -v, --vault <vault's name> Specify the vault.\n");
|
printf(" -v, --vault <vault's name> Specify the vault.\n");
|
||||||
printf(" --version Display the program version and the GPL3 notice.\n");
|
printf(" --version Display the program "
|
||||||
printf(" -V, --verbose Show debug information.\n");
|
"version and the GPL3 notice.\n");
|
||||||
|
printf(
|
||||||
|
" -V, --verbose Show debug information.\n");
|
||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
// -------- flags with arguments (MUST be last in group) --------
|
// -------- flags with arguments (MUST be last in group) --------
|
||||||
@@ -418,13 +495,10 @@ for (int i = 1; i < argc; i++) {
|
|||||||
case 'v':
|
case 'v':
|
||||||
case 'c': {
|
case 'c': {
|
||||||
|
|
||||||
error(arg[j + 1] != '\0',
|
error(arg[j + 1] != '\0', "user", "-%c must not be combined with other flags",
|
||||||
"user",
|
opt);
|
||||||
"-%c must not be combined with other flags", opt);
|
|
||||||
|
|
||||||
error(i + 1 == argc,
|
error(i + 1 == argc, "user", "Missing argument for -%c", opt);
|
||||||
"user",
|
|
||||||
"Missing argument for -%c", opt);
|
|
||||||
|
|
||||||
char *value = argv[++i];
|
char *value = argv[++i];
|
||||||
|
|
||||||
@@ -465,44 +539,54 @@ for (int i = 1; i < argc; i++) {
|
|||||||
error(1, "user", "Unexpected argument \"%s\"", arg);
|
error(1, "user", "Unexpected argument \"%s\"", arg);
|
||||||
}
|
}
|
||||||
|
|
||||||
next_arg:
|
next_arg:;
|
||||||
;
|
}
|
||||||
}
|
|
||||||
// if -n or --note is set but not -v or --vaults it gives an error
|
// if -n or --note is set but not -v or --vaults it gives an error
|
||||||
error(!bypassSelectionVault && bypassSelectionNote, "user", "If you want to specify the note, you must also specify the vault with -v <vault's name> or --vault <vault's name>.");
|
error(!bypassSelectionVault && bypassSelectionNote, "user",
|
||||||
|
"If you want to specify the note, you must also specify the vault with -v <vault's name> "
|
||||||
|
"or --vault <vault's name>.");
|
||||||
debug("Finished parsing the attribute flags");
|
debug("Finished parsing the attribute flags");
|
||||||
|
|
||||||
isEditorValid(editorToOpen, defaultEditor, shouldDebug); // check if editor is supported and if it is installed. If not, it will throw an error.
|
isEditorValid(editorToOpen, defaultEditor,
|
||||||
|
shouldDebug); // check if editor is supported and if it is installed. If not, it
|
||||||
|
// will throw an error.
|
||||||
|
|
||||||
if (doesBackup) {
|
if (doesBackup) {
|
||||||
debug("Handling backup");
|
debug("Handling backup");
|
||||||
handleBackups(directoriesArray, numDirectories, backupDirectoriesArray, homedir, interval, (const char**)rsyncArgs, rsyncArgsNumber, shouldDebug);
|
handleBackups(directoriesArray, numDirectories, backupDirectoriesArray, homedir, interval,
|
||||||
|
(const char **)rsyncArgs, rsyncArgsNumber, shouldDebug);
|
||||||
}
|
}
|
||||||
|
|
||||||
initscr(); //initialize ncurses
|
initscr(); // initialize ncurses
|
||||||
|
|
||||||
int shouldExit = 0;
|
int shouldExit = 0;
|
||||||
while(!shouldExit) {
|
while (!shouldExit) {
|
||||||
// this loop is the vault selector
|
// this loop is the vault selector
|
||||||
// select a vault
|
// select a vault
|
||||||
char *vaultSelected = NULL;
|
char *vaultSelected = NULL;
|
||||||
|
|
||||||
int vaultsCount = 0;
|
int vaultsCount = 0;
|
||||||
int *vaultsCountForEachDirectory = malloc(numDirectories*sizeof(int));
|
int *vaultsCountForEachDirectory = malloc(numDirectories * sizeof(int));
|
||||||
char **vaultsArray = getVaultsFromDirectories(directoriesArray, numDirectories, vaultsCountForEachDirectory, &vaultsCount, shouldDebug); // when selecting each vault won't show the directory from which they come. We will find this later.
|
char **vaultsArray = getVaultsFromDirectories(
|
||||||
|
directoriesArray, numDirectories, vaultsCountForEachDirectory, &vaultsCount,
|
||||||
|
shouldDebug); // when selecting each vault won't show the directory from which they
|
||||||
|
// come. We will find this later.
|
||||||
|
|
||||||
// bypass if -v or --vault is set
|
// bypass if -v or --vault is set
|
||||||
if (bypassSelectionVault) {
|
if (bypassSelectionVault) {
|
||||||
// bypasses the vault selection if the flag is -v. If the vault doesn't exist, just create a new one
|
// bypasses the vault selection if the flag is -v. If the vault doesn't exist, just
|
||||||
|
// create a new one
|
||||||
vaultSelected = bypassSelectionVaultValue;
|
vaultSelected = bypassSelectionVaultValue;
|
||||||
debug("bypassing vault selection");
|
debug("bypassing vault selection");
|
||||||
if (!isStringInArray(bypassSelectionVaultValue, (const char **)vaultsArray, vaultsCount)) { // we pass just vaultsCount and not vaultsCount + extraOptions to avoid matching with the extraOptions.
|
if (!isStringInArray(
|
||||||
|
bypassSelectionVaultValue, (const char **)vaultsArray,
|
||||||
|
vaultsCount)) { // we pass just vaultsCount and not vaultsCount + extraOptions
|
||||||
|
// to avoid matching with the extraOptions.
|
||||||
debug("[BYPASS] %s did not exist. Creating a new vault");
|
debug("[BYPASS] %s did not exist. Creating a new vault");
|
||||||
goto vault_creation;
|
goto vault_creation;
|
||||||
} else {
|
} else {
|
||||||
goto note_selection;
|
goto note_selection;
|
||||||
debug("[BYPASS] %s does exist. Going to note selection");
|
debug("[BYPASS] %s does exist. Going to note selection");
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -516,38 +600,52 @@ next_arg:
|
|||||||
|
|
||||||
// adds "create a new vault" into the vaultsArray
|
// adds "create a new vault" into the vaultsArray
|
||||||
const int extraOptions = 3;
|
const int extraOptions = 3;
|
||||||
vaultsArray = realloc(vaultsArray, (vaultsCount + extraOptions)*sizeof(char*)); // resize vaultsArray to fit the extra options
|
vaultsArray =
|
||||||
|
realloc(vaultsArray, (vaultsCount + extraOptions) *
|
||||||
|
sizeof(char *)); // resize vaultsArray to fit the extra options
|
||||||
vaultsArray[vaultsCount] = "Create a new vault"; // some more options that are not vaults
|
vaultsArray[vaultsCount] = "Create a new vault"; // some more options that are not vaults
|
||||||
vaultsArray[vaultsCount+1] = "Settings";
|
vaultsArray[vaultsCount + 1] = "Settings";
|
||||||
vaultsArray[vaultsCount+2] = "Quit (Ctrl+C)";
|
vaultsArray[vaultsCount + 2] = "Quit (Ctrl+C)";
|
||||||
|
|
||||||
|
vaultSelected = ncursesSelect(
|
||||||
|
vaultsArray, "Select vault to open (Use arrows or WASD, Enter to select):", vaultsCount,
|
||||||
|
extraOptions, " ", "Or select an option below", "", shouldDebug);
|
||||||
|
|
||||||
vaultSelected = ncursesSelect(vaultsArray, "Select vault to open (Use arrows or WASD, Enter to select):", vaultsCount, extraOptions, " ", "Or select an option below", "", shouldDebug);
|
// now that we won't use vaultsArray in this iteration of the loop, we should free it and
|
||||||
|
// all its elements. (As this is memory in the heap and not the stack and thus is our
|
||||||
// now that we won't use vaultsArray in this iteration of the loop, we should free it and all its elements. (As this is memory in the heap and not the stack and thus is our responsability to manage)
|
// responsability to manage)
|
||||||
for (int i = 0; i < vaultsCount; i++) {
|
for (int i = 0; i < vaultsCount; i++) {
|
||||||
if (vaultSelected != vaultsArray[i]) { // i forgot this condition before. and freed the pointer equal to vaultSelected... So don't remove this condition
|
if (vaultSelected !=
|
||||||
free(vaultsArray[i]); // we must only free the vaults options and not the extraOptions to avoid segfault
|
vaultsArray[i]) { // i forgot this condition before. and freed the pointer equal to
|
||||||
|
// vaultSelected... So don't remove this condition
|
||||||
|
free(vaultsArray[i]); // we must only free the vaults options and not the
|
||||||
|
// extraOptions to avoid segfault
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("Selected vault: %s", vaultSelected);
|
debug("Selected vault: %s", vaultSelected);
|
||||||
if (strcmp(vaultSelected,"Create a new vault") != 0 && strcmp(vaultSelected,"Settings") != 0 && strcmp(vaultSelected,"Quit (Ctrl+C)") != 0) {
|
if (strcmp(vaultSelected, "Create a new vault") != 0 &&
|
||||||
note_selection:
|
strcmp(vaultSelected, "Settings") != 0 && strcmp(vaultSelected, "Quit (Ctrl+C)") != 0) {
|
||||||
bypassSelectionVault = 0; // we must reset bypassSelectionVault to not get stuck in a infinite loop of bypassing
|
note_selection:
|
||||||
|
bypassSelectionVault = 0; // we must reset bypassSelectionVault to not get stuck in a
|
||||||
|
// infinite loop of bypassing
|
||||||
int shouldChangeVault = 0;
|
int shouldChangeVault = 0;
|
||||||
// we must find the directory from which the vault comes again.
|
// we must find the directory from which the vault comes again.
|
||||||
char *notesDirectoryString = getDirectoryFromVault(vaultSelected, vaultsArray, vaultsCount, vaultsCountForEachDirectory, directoriesArray, numDirectories, shouldDebug);
|
char *notesDirectoryString = getDirectoryFromVault(
|
||||||
|
vaultSelected, vaultsArray, vaultsCount, vaultsCountForEachDirectory,
|
||||||
|
directoriesArray, numDirectories, shouldDebug);
|
||||||
while (!shouldExit && !shouldChangeVault) {
|
while (!shouldExit && !shouldChangeVault) {
|
||||||
// this loop is the note selector
|
// this loop is the note selector
|
||||||
int filesCount = 0;
|
int filesCount = 0;
|
||||||
char **filesArray = getNotesFromVault(notesDirectoryString, vaultSelected, journalRegex, &filesCount, shouldDebug);
|
char **filesArray = getNotesFromVault(notesDirectoryString, vaultSelected,
|
||||||
|
journalRegex, &filesCount, shouldDebug);
|
||||||
|
|
||||||
int journalCount = 0;
|
int journalCount = 0;
|
||||||
char **journalArray = getJournalsFromVault(notesDirectoryString, vaultSelected, journalRegex, &journalCount, shouldDebug);
|
char **journalArray = getJournalsFromVault(
|
||||||
|
notesDirectoryString, vaultSelected, journalRegex, &journalCount, shouldDebug);
|
||||||
|
|
||||||
// appends the journal at the end of filesArray
|
// appends the journal at the end of filesArray
|
||||||
filesArray = realloc(filesArray, (filesCount + journalCount)*sizeof(char*));
|
filesArray = realloc(filesArray, (filesCount + journalCount) * sizeof(char *));
|
||||||
for (int i = 0; i < journalCount; i++) {
|
for (int i = 0; i < journalCount; i++) {
|
||||||
filesArray[i + filesCount] = journalArray[i];
|
filesArray[i + filesCount] = journalArray[i];
|
||||||
}
|
}
|
||||||
@@ -563,17 +661,22 @@ note_selection:
|
|||||||
}
|
}
|
||||||
// adds options
|
// adds options
|
||||||
int extraNotesOptions = 4;
|
int extraNotesOptions = 4;
|
||||||
filesArray = realloc(filesArray, (filesCount + extraNotesOptions)*sizeof(char*)); // resize filesArray to fit the extra options
|
filesArray = realloc(
|
||||||
|
filesArray, (filesCount + extraNotesOptions) *
|
||||||
|
sizeof(char *)); // resize filesArray to fit the extra options
|
||||||
filesArray[filesCount] = "Create new note";
|
filesArray[filesCount] = "Create new note";
|
||||||
filesArray[filesCount+1] = "Back to vault selection";
|
filesArray[filesCount + 1] = "Back to vault selection";
|
||||||
filesArray[filesCount+2] = "Delete vault";
|
filesArray[filesCount + 2] = "Delete vault";
|
||||||
filesArray[filesCount+3] = "Quit (Ctrl+C)";
|
filesArray[filesCount + 3] = "Quit (Ctrl+C)";
|
||||||
char *noteSelected;
|
char *noteSelected;
|
||||||
// if we set to bypass the note selector
|
// if we set to bypass the note selector
|
||||||
if (bypassSelectionNote) {
|
if (bypassSelectionNote) {
|
||||||
debug("We are bypassing note selection.");
|
debug("We are bypassing note selection.");
|
||||||
noteSelected = bypassSelectionNoteValue;
|
noteSelected = bypassSelectionNoteValue;
|
||||||
if (isStringInArray(noteSelected, (const char **)filesArray, filesCount)) {// we just give filesCount and not filesCount + extraOptions to avoid matching with an extra options.
|
if (isStringInArray(
|
||||||
|
noteSelected, (const char **)filesArray,
|
||||||
|
filesCount)) { // we just give filesCount and not filesCount +
|
||||||
|
// extraOptions to avoid matching with an extra options.
|
||||||
debug("The note specified with -n or --note does exist. Opening it.");
|
debug("The note specified with -n or --note does exist. Opening it.");
|
||||||
goto open_note;
|
goto open_note;
|
||||||
} else { // if the specified note doesn't exist. We creat it
|
} else { // if the specified note doesn't exist. We creat it
|
||||||
@@ -581,74 +684,109 @@ note_selection:
|
|||||||
goto note_creation;
|
goto note_creation;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
noteSelected = ncursesSelect(filesArray, "Select note or journal to open (Use arrows or WASD, Enter to select):", filesCount, extraNotesOptions, " ", "Or select an option below", "", shouldDebug);
|
noteSelected = ncursesSelect(
|
||||||
// now that we won't use filesArray in this iteration of the loop, we should free it and all its elements. (As this is memory in the heap and not the stack and thus is our responsability to manage)
|
filesArray,
|
||||||
|
"Select note or journal to open (Use arrows or WASD, Enter to select):",
|
||||||
|
filesCount, extraNotesOptions, " ", "Or select an option below", "",
|
||||||
|
shouldDebug);
|
||||||
|
// now that we won't use filesArray in this iteration of the loop, we should free it
|
||||||
|
// and all its elements. (As this is memory in the heap and not the stack and thus
|
||||||
|
// is our responsability to manage)
|
||||||
for (int i = 0; i < filesCount; i++) {
|
for (int i = 0; i < filesCount; i++) {
|
||||||
if (noteSelected != filesArray[i]) { // we must prevent noteSelected to be freed. It will cause a lot of problems
|
if (noteSelected != filesArray[i]) { // we must prevent noteSelected to be
|
||||||
free(filesArray[i]); // we must only free the files options and not the extraOptions to avoid segfault
|
// freed. It will cause a lot of problems
|
||||||
|
free(filesArray[i]); // we must only free the files options and not the
|
||||||
|
// extraOptions to avoid segfault
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
free(filesArray);
|
free(filesArray);
|
||||||
debug("Selected note: %s", noteSelected);
|
debug("Selected note: %s", noteSelected);
|
||||||
if (strcmp(noteSelected, "Create new note") != 0 && strcmp(noteSelected,"Back to vault selection") != 0 && strcmp(noteSelected, "Delete vault") != 0 && strcmp(noteSelected,"Quit (Ctrl+C)") != 0) {
|
if (strcmp(noteSelected, "Create new note") != 0 &&
|
||||||
open_note:
|
strcmp(noteSelected, "Back to vault selection") != 0 &&
|
||||||
bypassSelectionNote = 0; // we must reset bypassSelectionNote to avoid getting into an infinite loop of bypassing the note selection
|
strcmp(noteSelected, "Delete vault") != 0 &&
|
||||||
|
strcmp(noteSelected, "Quit (Ctrl+C)") != 0) {
|
||||||
|
open_note:
|
||||||
|
bypassSelectionNote =
|
||||||
|
0; // we must reset bypassSelectionNote to avoid getting into an infinite
|
||||||
|
// loop of bypassing the note selection
|
||||||
char *fullPath = malloc(PATH_MAX);
|
char *fullPath = malloc(PATH_MAX);
|
||||||
snprintf(fullPath, PATH_MAX, "%s/%s/%s", notesDirectoryString, vaultSelected, noteSelected);
|
snprintf(fullPath, PATH_MAX, "%s/%s/%s", notesDirectoryString, vaultSelected,
|
||||||
|
noteSelected);
|
||||||
// if it is a journal we must update it before
|
// if it is a journal we must update it before
|
||||||
regex_t regex;
|
regex_t regex;
|
||||||
int regexReturn = regcomp(®ex, journalRegex, 0);
|
int regexReturn = regcomp(®ex, journalRegex, 0);
|
||||||
error(regexReturn, "program", "Regex compilation failed.");
|
error(regexReturn, "program", "Regex compilation failed.");
|
||||||
regexReturn = regexec(®ex, noteSelected, 0, NULL, 0);
|
regexReturn = regexec(®ex, noteSelected, 0, NULL, 0);
|
||||||
|
|
||||||
|
|
||||||
int *journalWasUpdated = malloc(sizeof(int));
|
int *journalWasUpdated = malloc(sizeof(int));
|
||||||
*journalWasUpdated = 0;
|
*journalWasUpdated = 0;
|
||||||
if (!regexReturn) { // if the regex matches -> it's a journal
|
if (!regexReturn) { // if the regex matches -> it's a journal
|
||||||
debug("%s is a journal. Updating it...", noteSelected);
|
debug("%s is a journal. Updating it...", noteSelected);
|
||||||
fullPath = updateJournal(fullPath, noteSelected, timeFormat, journalWasUpdated, shouldDebug); // we return the path. As if it is a divided journal we must point to the correct entry
|
fullPath = updateJournal(
|
||||||
|
fullPath, noteSelected, timeFormat, journalWasUpdated,
|
||||||
|
shouldDebug); // we return the path. As if it is a divided journal we
|
||||||
|
// must point to the correct entry
|
||||||
}
|
}
|
||||||
if (newLineOnOpening) {
|
if (newLineOnOpening) {
|
||||||
if (*journalWasUpdated) {
|
if (*journalWasUpdated) {
|
||||||
appendToFile(fullPath, " \n", shouldDebug); // when updating the journal it adds a \n char at the end. So appendToFile(\n) does not work. We append a (special and rare) whitespace character + \n to bypass this issue.
|
appendToFile(
|
||||||
|
fullPath, " \n",
|
||||||
|
shouldDebug); // when updating the journal it adds a \n char at the
|
||||||
|
// end. So appendToFile(\n) does not work. We append a
|
||||||
|
// (special and rare) whitespace character + \n to
|
||||||
|
// bypass this issue.
|
||||||
}
|
}
|
||||||
appendToFile(fullPath, "\n", shouldDebug);
|
appendToFile(fullPath, "\n", shouldDebug);
|
||||||
}
|
}
|
||||||
openEditor(fullPath, editorToOpen, shouldRender, shouldJumpToEnd, shouldDebug);
|
openEditor(fullPath, editorToOpen, shouldRender, shouldJumpToEnd, shouldDebug);
|
||||||
free(fullPath);
|
free(fullPath);
|
||||||
} else if (strcmp(noteSelected,"Create new note") == 0) {
|
} else if (strcmp(noteSelected, "Create new note") == 0) {
|
||||||
note_creation:
|
note_creation:
|
||||||
noteSelected = createNewNote(notesDirectoryString, vaultSelected, bypassSelectionNote, bypassSelectionNoteValue, journalRegex, shouldDebug);
|
noteSelected =
|
||||||
|
createNewNote(notesDirectoryString, vaultSelected, bypassSelectionNote,
|
||||||
|
bypassSelectionNoteValue, journalRegex, shouldDebug);
|
||||||
// we can just go back to open_note
|
// we can just go back to open_note
|
||||||
goto open_note;
|
goto open_note;
|
||||||
} else if (strcmp(noteSelected,"Back to vault selection") == 0) {
|
} else if (strcmp(noteSelected, "Back to vault selection") == 0) {
|
||||||
shouldChangeVault = 1;
|
shouldChangeVault = 1;
|
||||||
} else if (strcmp(noteSelected, "Delete vault") == 0) {
|
} else if (strcmp(noteSelected, "Delete vault") == 0) {
|
||||||
// we must find where does the vault comes from.
|
// we must find where does the vault comes from.
|
||||||
char *notesDirectoryString = getDirectoryFromVault(vaultSelected, vaultsArray, vaultsCount, vaultsCountForEachDirectory, directoriesArray, numDirectories, shouldDebug);
|
char *notesDirectoryString = getDirectoryFromVault(
|
||||||
|
vaultSelected, vaultsArray, vaultsCount, vaultsCountForEachDirectory,
|
||||||
|
directoriesArray, numDirectories, shouldDebug);
|
||||||
const char *yesNo[] = {"No, go back to note selection.", "Yes."};
|
const char *yesNo[] = {"No, go back to note selection.", "Yes."};
|
||||||
char *answer = ncursesSelect((char **)yesNo, "Are you sure you want to delete the entire vault? This can not be undone (Use arrows or WASD, Enter to select):", 1, 1, " ", "", "", shouldDebug); debug("You answered: %s for deleting the vault %s", answer, vaultSelected);
|
char *answer =
|
||||||
|
ncursesSelect((char **)yesNo,
|
||||||
|
"Are you sure you want to delete the entire vault? This can "
|
||||||
|
"not be undone (Use arrows or WASD, Enter to select):",
|
||||||
|
1, 1, " ", "", "", shouldDebug);
|
||||||
|
debug("You answered: %s for deleting the vault %s", answer, vaultSelected);
|
||||||
if (strcmp(answer, "Yes.") == 0) {
|
if (strcmp(answer, "Yes.") == 0) {
|
||||||
// delete the vault after confirmation by the user
|
// delete the vault after confirmation by the user
|
||||||
char pathToRMRF[PATH_MAX];
|
char pathToRMRF[PATH_MAX];
|
||||||
snprintf(pathToRMRF, PATH_MAX, "%s/%s", notesDirectoryString, vaultSelected);
|
snprintf(pathToRMRF, PATH_MAX, "%s/%s", notesDirectoryString,
|
||||||
|
vaultSelected);
|
||||||
debug("Removed the directory: %s", pathToRMRF);
|
debug("Removed the directory: %s", pathToRMRF);
|
||||||
rmrf(pathToRMRF, shouldDebug);
|
rmrf(pathToRMRF, shouldDebug);
|
||||||
shouldChangeVault = 1;
|
shouldChangeVault = 1;
|
||||||
}
|
}
|
||||||
} else if (strcmp(noteSelected,"Quit (Ctrl+C)") == 0) {
|
} else if (strcmp(noteSelected, "Quit (Ctrl+C)") == 0) {
|
||||||
debug("The program was exited.");
|
debug("The program was exited.");
|
||||||
shouldExit = 1;
|
shouldExit = 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
free(vaultsArray);
|
free(vaultsArray);
|
||||||
} else if (strcmp(vaultSelected,"Create a new vault") == 0) {
|
} else if (strcmp(vaultSelected, "Create a new vault") == 0) {
|
||||||
vault_creation:
|
vault_creation:
|
||||||
createNewVault(directoriesArray, numDirectories, vaultsArray, vaultsCount, bypassSelectionVault, bypassSelectionVaultValue, shouldDebug);
|
createNewVault(directoriesArray, numDirectories, vaultsArray, vaultsCount,
|
||||||
bypassSelectionVault = 0; // we need to reset bypassSelectionVault to avoid getting into an infinite loop of bypassing
|
bypassSelectionVault, bypassSelectionVaultValue, shouldDebug);
|
||||||
} else if (strcmp(vaultSelected,"Settings") == 0) {
|
bypassSelectionVault = 0; // we need to reset bypassSelectionVault to avoid getting into
|
||||||
openEditor(configPath, editorToOpen, 0, 0, shouldDebug); // as this is not a md file we set render and jumptoEnfOfFile to 0
|
// an infinite loop of bypassing
|
||||||
} else if (strcmp(vaultSelected,"Quit (Ctrl+C)") == 0) {
|
} else if (strcmp(vaultSelected, "Settings") == 0) {
|
||||||
|
openEditor(
|
||||||
|
configPath, editorToOpen, 0, 0,
|
||||||
|
shouldDebug); // as this is not a md file we set render and jumptoEnfOfFile to 0
|
||||||
|
} else if (strcmp(vaultSelected, "Quit (Ctrl+C)") == 0) {
|
||||||
debug("The program was exited");
|
debug("The program was exited");
|
||||||
shouldExit = 1;
|
shouldExit = 1;
|
||||||
}
|
}
|
||||||
|
|||||||
+138
-61
@@ -1,7 +1,9 @@
|
|||||||
#include "notes.h"
|
#include "notes.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
|
||||||
char *getDirectoryFromVault(char *targetVault, char **vaultsArray, int vaultTotalNumber, int *vaultNumberPerDirectory, char **directoryArray, int directoryNumber, int shouldDebug) {
|
char *getDirectoryFromVault(char *targetVault, char **vaultsArray, int vaultTotalNumber,
|
||||||
|
int *vaultNumberPerDirectory, char **directoryArray,
|
||||||
|
int directoryNumber, int shouldDebug) {
|
||||||
debug("Searching the vault %s inside all the directories...", targetVault);
|
debug("Searching the vault %s inside all the directories...", targetVault);
|
||||||
debug("Here are how many vaults there is per directory:");
|
debug("Here are how many vaults there is per directory:");
|
||||||
for (int i = 0; i < directoryNumber; i++) {
|
for (int i = 0; i < directoryNumber; i++) {
|
||||||
@@ -23,38 +25,50 @@ char *getDirectoryFromVault(char *targetVault, char **vaultsArray, int vaultTota
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
error(1, "program", "the vault %s was not found", targetVault);
|
error(1, "program", "the vault %s was not found", targetVault);
|
||||||
return "this makes the compiler and clangd happy. Who doesn't want GCC and clangd to be happy? Such person would be a terrible monster... One must imagine GCC and clangd happy.";
|
return "this makes the compiler and clangd happy. Who doesn't want GCC and clangd to be happy? "
|
||||||
|
"Such person would be a terrible monster... One must imagine GCC and clangd happy.";
|
||||||
}
|
}
|
||||||
|
|
||||||
char **getJournalsFromVault(char *pathToVault, char *vault, char *journalRegex, int *count, int shouldDebug) {
|
char **getJournalsFromVault(char *pathToVault, char *vault, char *journalRegex, int *count,
|
||||||
|
int shouldDebug) {
|
||||||
debug("Searching %s for journals", vault);
|
debug("Searching %s for journals", vault);
|
||||||
// originally from https://www.geeksforgeeks.org/c/c-program-list-files-sub-directories-directory/
|
// originally from
|
||||||
|
// https://www.geeksforgeeks.org/c/c-program-list-files-sub-directories-directory/
|
||||||
struct dirent *vaultEntry;
|
struct dirent *vaultEntry;
|
||||||
char tempPath[PATH_MAX];
|
char tempPath[PATH_MAX];
|
||||||
snprintf(tempPath, sizeof(tempPath), "%s/%s", pathToVault, vault); // sets the full absolute path to fullPathEntry
|
snprintf(tempPath, sizeof(tempPath), "%s/%s", pathToVault,
|
||||||
|
vault); // sets the full absolute path to fullPathEntry
|
||||||
DIR *vaultDirectory = opendir(tempPath);
|
DIR *vaultDirectory = opendir(tempPath);
|
||||||
error(vaultDirectory==NULL, "program", "Could not open directory %s", tempPath);
|
error(vaultDirectory == NULL, "program", "Could not open directory %s", tempPath);
|
||||||
char **journalsArray = NULL; // will contain all the notes
|
char **journalsArray = NULL; // will contain all the notes
|
||||||
int journalsCount = 0; // we need to count how many notes there is to always readjust how many memory we alloc
|
int journalsCount =
|
||||||
|
0; // we need to count how many notes there is to always readjust how many memory we alloc
|
||||||
|
|
||||||
// https://stackoverflow.com/a/1085120 for regex code
|
// https://stackoverflow.com/a/1085120 for regex code
|
||||||
regex_t regex;
|
regex_t regex;
|
||||||
int regexReturn;
|
int regexReturn;
|
||||||
// compiles the regex
|
// compiles the regex
|
||||||
regexReturn = regcomp(®ex, journalRegex, 0);
|
regexReturn = regcomp(®ex, journalRegex, 0);
|
||||||
error(regexReturn, "program", "Regex could not compile. Perhaps there is an error with the regex string");
|
error(regexReturn, "program",
|
||||||
|
"Regex could not compile. Perhaps there is an error with the regex string");
|
||||||
debug("Regex compiled succesfully");
|
debug("Regex compiled succesfully");
|
||||||
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
||||||
// for readdir()
|
// for readdir()
|
||||||
debug("┌------------------------------------------\nDetected files and dirs from the vault");
|
debug("┌------------------------------------------\nDetected files and dirs from the vault");
|
||||||
while ((vaultEntry = readdir(vaultDirectory)) != NULL) { // we iterate over every entry from the dir. So files and dirs (. and .. included)
|
while (
|
||||||
|
(vaultEntry = readdir(vaultDirectory)) !=
|
||||||
|
NULL) { // we iterate over every entry from the dir. So files and dirs (. and .. included)
|
||||||
altDebug("%s ", vaultEntry->d_name);
|
altDebug("%s ", vaultEntry->d_name);
|
||||||
if (vaultEntry->d_name[0] != '.') { // if the entry don't start with a dot (so hidden dirs and hidden files)
|
if (vaultEntry->d_name[0] !=
|
||||||
|
'.') { // if the entry don't start with a dot (so hidden dirs and hidden files)
|
||||||
regexReturn = regexec(®ex, vaultEntry->d_name, 0, NULL, 0);
|
regexReturn = regexec(®ex, vaultEntry->d_name, 0, NULL, 0);
|
||||||
if (!regexReturn) { // if the regex matches
|
if (!regexReturn) { // if the regex matches
|
||||||
altDebug("matched with the regex. It is a journal.\n");
|
altDebug("matched with the regex. It is a journal.\n");
|
||||||
journalsArray = realloc(journalsArray, (journalsCount + 1)*sizeof(char*)); // resize notesArray so that
|
journalsArray =
|
||||||
journalsArray[journalsCount] = strdup(vaultEntry->d_name); // copy the dir name into notesArray
|
realloc(journalsArray,
|
||||||
|
(journalsCount + 1) * sizeof(char *)); // resize notesArray so that
|
||||||
|
journalsArray[journalsCount] =
|
||||||
|
strdup(vaultEntry->d_name); // copy the dir name into notesArray
|
||||||
journalsCount++;
|
journalsCount++;
|
||||||
} else {
|
} else {
|
||||||
altDebug("did not matched with the regex. It is a note.\n");
|
altDebug("did not matched with the regex. It is a note.\n");
|
||||||
@@ -70,17 +84,21 @@ char **getJournalsFromVault(char *pathToVault, char *vault, char *journalRegex,
|
|||||||
return journalsArray;
|
return journalsArray;
|
||||||
}
|
}
|
||||||
|
|
||||||
char** getNotesFromVault(char *pathToVault, char *vault, char *journalRegex, int *count, int shouldDebug) {
|
char **getNotesFromVault(char *pathToVault, char *vault, char *journalRegex, int *count,
|
||||||
// this function is inputed a path to a vault (which was selected before) and outpus all the suitable notes (so not the hidden ones)
|
int shouldDebug) {
|
||||||
// originally from https://www.geeksforgeeks.org/c/c-program-list-files-sub-directories-directory/
|
// this function is inputed a path to a vault (which was selected before) and outpus all the
|
||||||
|
// suitable notes (so not the hidden ones) originally from
|
||||||
|
// https://www.geeksforgeeks.org/c/c-program-list-files-sub-directories-directory/
|
||||||
debug("Searching %s for notes", vault);
|
debug("Searching %s for notes", vault);
|
||||||
struct dirent *vaultEntry;
|
struct dirent *vaultEntry;
|
||||||
char tempPath[PATH_MAX];
|
char tempPath[PATH_MAX];
|
||||||
snprintf(tempPath, sizeof(tempPath), "%s/%s", pathToVault, vault); // sets the full absolute path to fullPathEntry
|
snprintf(tempPath, sizeof(tempPath), "%s/%s", pathToVault,
|
||||||
|
vault); // sets the full absolute path to fullPathEntry
|
||||||
DIR *vaultDirectory = opendir(tempPath);
|
DIR *vaultDirectory = opendir(tempPath);
|
||||||
error(vaultDirectory==NULL, "program", "Could not open directory %s", tempPath);
|
error(vaultDirectory == NULL, "program", "Could not open directory %s", tempPath);
|
||||||
char **notesArray = NULL; // will contain all the notes
|
char **notesArray = NULL; // will contain all the notes
|
||||||
int notesCount = 0; // we need to count how many notes there is to always readjust how many memory we alloc
|
int notesCount =
|
||||||
|
0; // we need to count how many notes there is to always readjust how many memory we alloc
|
||||||
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
||||||
// for readdir()
|
// for readdir()
|
||||||
debug("┌------------------------------\nDetected Files and dirs from the vault:");
|
debug("┌------------------------------\nDetected Files and dirs from the vault:");
|
||||||
@@ -93,19 +111,30 @@ char** getNotesFromVault(char *pathToVault, char *vault, char *journalRegex, int
|
|||||||
int regexReturn;
|
int regexReturn;
|
||||||
// compiles the regex
|
// compiles the regex
|
||||||
regexReturn = regcomp(®ex, journalRegex, 0);
|
regexReturn = regcomp(®ex, journalRegex, 0);
|
||||||
if (entryName[0] != '.') { // if the entry don't start with a dot (so hidden dirs and hidden files)
|
if (entryName[0] !=
|
||||||
|
'.') { // if the entry don't start with a dot (so hidden dirs and hidden files)
|
||||||
char fullPathEntry[PATH_MAX]; // creates a string of size of the maximum path lenght
|
char fullPathEntry[PATH_MAX]; // creates a string of size of the maximum path lenght
|
||||||
snprintf(fullPathEntry, sizeof(fullPathEntry), "%s/%s/%s", pathToVault, vault, entryName); // sets the full absolute path to fullPathEntry
|
snprintf(fullPathEntry, sizeof(fullPathEntry), "%s/%s/%s", pathToVault, vault,
|
||||||
|
entryName); // sets the full absolute path to fullPathEntry
|
||||||
// check if it matches the regex. If it does not match regexReturn != 0.
|
// check if it matches the regex. If it does not match regexReturn != 0.
|
||||||
regexReturn = regexec(®ex, entryName, 0, NULL, 0);
|
regexReturn = regexec(®ex, entryName, 0, NULL, 0);
|
||||||
struct stat metadataPathEntry;
|
struct stat metadataPathEntry;
|
||||||
if (stat(fullPathEntry, &metadataPathEntry) == 0 && entryName[entryLenght - 3] == '.' && entryName[entryLenght - 2] == 'm' && entryName[entryLenght - 1] == 'd' && regexReturn && S_ISREG(metadataPathEntry.st_mode)) { // if this entry is a file ending in .md and that does no match the regex
|
if (stat(fullPathEntry, &metadataPathEntry) == 0 && entryName[entryLenght - 3] == '.' &&
|
||||||
notesArray = realloc(notesArray, (notesCount + 1)*sizeof(char*)); // resize notesArray so that
|
entryName[entryLenght - 2] == 'm' && entryName[entryLenght - 1] == 'd' &&
|
||||||
|
regexReturn &&
|
||||||
|
S_ISREG(metadataPathEntry.st_mode)) { // if this entry is a file ending in .md and
|
||||||
|
// that does no match the regex
|
||||||
|
notesArray = realloc(notesArray, (notesCount + 1) *
|
||||||
|
sizeof(char *)); // resize notesArray so that
|
||||||
notesArray[notesCount] = strdup(entryName); // copy the dir name into notesArray
|
notesArray[notesCount] = strdup(entryName); // copy the dir name into notesArray
|
||||||
notesCount++;
|
notesCount++;
|
||||||
altDebug("did not match with the regex. It is a note.\n");
|
altDebug("did not match with the regex. It is a note.\n");
|
||||||
} else if (!regexReturn) {altDebug("matched with the regex. It is a journal.\n");}
|
} else if (!regexReturn) {
|
||||||
} else {altDebug("was ignored\n");}
|
altDebug("matched with the regex. It is a journal.\n");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
altDebug("was ignored\n");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
altDebug("└ ------------------------------\n");
|
altDebug("└ ------------------------------\n");
|
||||||
|
|
||||||
@@ -115,36 +144,48 @@ char** getNotesFromVault(char *pathToVault, char *vault, char *journalRegex, int
|
|||||||
return notesArray;
|
return notesArray;
|
||||||
}
|
}
|
||||||
|
|
||||||
char **getVaultsFromDirectories(char **directoryStringArray, int directoryNumber, int *vaultsPerDirectoryNumber, int *count, int shouldDebug) {
|
char **getVaultsFromDirectories(char **directoryStringArray, int directoryNumber,
|
||||||
// to avoid having to work with a tree-dimensional array. We will use a 2d and vaultsPerDirectoryNumber will indicate the width of the directories.
|
int *vaultsPerDirectoryNumber, int *count, int shouldDebug) {
|
||||||
|
// to avoid having to work with a tree-dimensional array. We will use a 2d and
|
||||||
|
// vaultsPerDirectoryNumber will indicate the width of the directories.
|
||||||
char **vaultsArray = NULL;
|
char **vaultsArray = NULL;
|
||||||
int nthVault = 0; // this is only used internally to set the string into the right place in directoryStringArray.
|
int nthVault = 0; // this is only used internally to set the string into the right place in
|
||||||
|
// directoryStringArray.
|
||||||
int previousStartIndex = 0;
|
int previousStartIndex = 0;
|
||||||
for (int i = 0; i < directoryNumber; i++) {
|
for (int i = 0; i < directoryNumber; i++) {
|
||||||
debug("Opening %s", directoryStringArray[i]);
|
debug("Opening %s", directoryStringArray[i]);
|
||||||
// originally from https://www.geeksforgeeks.org/c/c-program-list-files-sub-directories-directory/
|
// originally from
|
||||||
|
// https://www.geeksforgeeks.org/c/c-program-list-files-sub-directories-directory/
|
||||||
struct dirent *vaultsDirectoryEntry;
|
struct dirent *vaultsDirectoryEntry;
|
||||||
DIR *vaultsDirectory = opendir(directoryStringArray[i]);
|
DIR *vaultsDirectory = opendir(directoryStringArray[i]);
|
||||||
error(!vaultsDirectory, "program", "Could not open directory %s", directoryStringArray[i]);
|
error(!vaultsDirectory, "program", "Could not open directory %s", directoryStringArray[i]);
|
||||||
vaultsPerDirectoryNumber[i] = 0;
|
vaultsPerDirectoryNumber[i] = 0;
|
||||||
debug("┌------------------------------\n Detected files and dirs %s:", directoryStringArray[i]);
|
debug("┌------------------------------\n Detected files and dirs %s:",
|
||||||
|
directoryStringArray[i]);
|
||||||
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
||||||
// for readdir()
|
// for readdir()
|
||||||
while((vaultsDirectoryEntry = readdir(vaultsDirectory)) != NULL) {
|
while ((vaultsDirectoryEntry = readdir(vaultsDirectory)) != NULL) {
|
||||||
char *entryName = vaultsDirectoryEntry->d_name; // gets the entry as a string value
|
char *entryName = vaultsDirectoryEntry->d_name; // gets the entry as a string value
|
||||||
altDebug("%s", entryName);
|
altDebug("%s", entryName);
|
||||||
if (entryName[0] != '.') { // if not hidden file/dir
|
if (entryName[0] != '.') { // if not hidden file/dir
|
||||||
char tempFullEntryPath[PATH_MAX]; // we recreate the full path to check it's proprieties
|
char tempFullEntryPath[PATH_MAX]; // we recreate the full path to check it's
|
||||||
|
// proprieties
|
||||||
snprintf(tempFullEntryPath, PATH_MAX, "%s%s", directoryStringArray[i], entryName);
|
snprintf(tempFullEntryPath, PATH_MAX, "%s%s", directoryStringArray[i], entryName);
|
||||||
altDebug(" (%s)", tempFullEntryPath);
|
altDebug(" (%s)", tempFullEntryPath);
|
||||||
//checking the metadata to see if it is a dir
|
// checking the metadata to see if it is a dir
|
||||||
struct stat metadataEntry;
|
struct stat metadataEntry;
|
||||||
if (stat(tempFullEntryPath, &metadataEntry) == 0 && S_ISDIR(metadataEntry.st_mode)) { // get's the metadata (stat should return 0 if fails) and sees if it is a dir.
|
if (stat(tempFullEntryPath, &metadataEntry) == 0 &&
|
||||||
|
S_ISDIR(metadataEntry.st_mode)) { // get's the metadata (stat should return 0 if
|
||||||
|
// fails) and sees if it is a dir.
|
||||||
altDebug(" is a vault");
|
altDebug(" is a vault");
|
||||||
vaultsArray = realloc(vaultsArray, sizeof(char *)*(nthVault + 1)); // resize vaultsArray
|
vaultsArray =
|
||||||
|
realloc(vaultsArray, sizeof(char *) * (nthVault + 1)); // resize vaultsArray
|
||||||
error(vaultsArray == NULL, "program", "realloc failed");
|
error(vaultsArray == NULL, "program", "realloc failed");
|
||||||
vaultsPerDirectoryNumber[i]++; // it will be used later to know which vaults goes into which directory
|
vaultsPerDirectoryNumber[i]++; // it will be used later to know which vaults
|
||||||
vaultsArray[nthVault] = strdup(entryName); // we use strdup and not strcpy, because memory used with opendir and readdir will be closed.
|
// goes into which directory
|
||||||
|
vaultsArray[nthVault] =
|
||||||
|
strdup(entryName); // we use strdup and not strcpy, because memory used with
|
||||||
|
// opendir and readdir will be closed.
|
||||||
error(vaultsArray[nthVault] == NULL, "program", "strdup failed");
|
error(vaultsArray[nthVault] == NULL, "program", "strdup failed");
|
||||||
nthVault++; // it is used immediatly to set the vault into directoryStringArray
|
nthVault++; // it is used immediatly to set the vault into directoryStringArray
|
||||||
} else {
|
} else {
|
||||||
@@ -155,7 +196,8 @@ char **getVaultsFromDirectories(char **directoryStringArray, int directoryNumber
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// we sort entries for the same vault. We can't sort them all. This would break the order.
|
// we sort entries for the same vault. We can't sort them all. This would break the order.
|
||||||
qsort(vaultsArray + previousStartIndex, nthVault - previousStartIndex, sizeof(const char *), compareString); // sorts the vaults alphabetically
|
qsort(vaultsArray + previousStartIndex, nthVault - previousStartIndex, sizeof(const char *),
|
||||||
|
compareString); // sorts the vaults alphabetically
|
||||||
closedir(vaultsDirectory);
|
closedir(vaultsDirectory);
|
||||||
previousStartIndex = nthVault;
|
previousStartIndex = nthVault;
|
||||||
}
|
}
|
||||||
@@ -167,8 +209,11 @@ char **getVaultsFromDirectories(char **directoryStringArray, int directoryNumber
|
|||||||
return vaultsArray;
|
return vaultsArray;
|
||||||
}
|
}
|
||||||
|
|
||||||
char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWasUpdated, int shouldDebug) {
|
char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWasUpdated,
|
||||||
path[PATH_MAX] = '\0'; // it assures it is a string (Most cases this does nothing). But rewriting at least one bytes make the compile happy. He doesn't want to return an unchanged input.
|
int shouldDebug) {
|
||||||
|
path[PATH_MAX] =
|
||||||
|
'\0'; // it assures it is a string (Most cases this does nothing). But rewriting at least
|
||||||
|
// one bytes make the compile happy. He doesn't want to return an unchanged input.
|
||||||
debug("Handling the journal %s", path);
|
debug("Handling the journal %s", path);
|
||||||
|
|
||||||
char *date = getFormatedTime(timeFormat, shouldDebug);
|
char *date = getFormatedTime(timeFormat, shouldDebug);
|
||||||
@@ -176,7 +221,8 @@ char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWas
|
|||||||
char dateWithExtension[PATH_MAX];
|
char dateWithExtension[PATH_MAX];
|
||||||
snprintf(dateWithExtension, PATH_MAX, "%s.md", date);
|
snprintf(dateWithExtension, PATH_MAX, "%s.md", date);
|
||||||
sanitize(dateWithExtension);
|
sanitize(dateWithExtension);
|
||||||
debug("Sanitized date: %s\n(it might be used later for a file name if the journal is divided)", dateWithExtension);
|
debug("Sanitized date: %s\n(it might be used later for a file name if the journal is divided)",
|
||||||
|
dateWithExtension);
|
||||||
struct stat metadata;
|
struct stat metadata;
|
||||||
stat(path, &metadata);
|
stat(path, &metadata);
|
||||||
if (S_ISREG(metadata.st_mode)) {
|
if (S_ISREG(metadata.st_mode)) {
|
||||||
@@ -193,33 +239,40 @@ char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWas
|
|||||||
snprintf(temp, PATH_MAX, "%s/", path); // appends a /. For safety
|
snprintf(temp, PATH_MAX, "%s/", path); // appends a /. For safety
|
||||||
strncpy(path, temp, PATH_MAX);
|
strncpy(path, temp, PATH_MAX);
|
||||||
DIR *dividedJournalDirectory = opendir(path);
|
DIR *dividedJournalDirectory = opendir(path);
|
||||||
error(dividedJournalDirectory==NULL, "program", "Could not open directory %s", path);
|
error(dividedJournalDirectory == NULL, "program", "Could not open directory %s", path);
|
||||||
/*char **entryArray = NULL; // will contain all the entries of the divided journal
|
/*char **entryArray = NULL; // will contain all the entries of the divided journal
|
||||||
// This time it will be different. We must add "invert" the extraOptions to the options so that the Create new entry in journal is on top
|
// This time it will be different. We must add "invert" the extraOptions to the options so
|
||||||
entryArray = realloc(entryArray, sizeof(char*));*/
|
that the Create new entry in journal is on top entryArray = realloc(entryArray,
|
||||||
|
sizeof(char*));*/
|
||||||
// simpler to just malloc 2 and later realloc
|
// simpler to just malloc 2 and later realloc
|
||||||
const int extraOptions = 3;
|
const int extraOptions = 3;
|
||||||
char **entryArray = malloc(extraOptions*sizeof(char*));
|
char **entryArray = malloc(extraOptions * sizeof(char *));
|
||||||
char *createEntryMessage = malloc(PATH_MAX);
|
char *createEntryMessage = malloc(PATH_MAX);
|
||||||
snprintf(createEntryMessage, PATH_MAX, "Create new entry for the journal %s", journal);
|
snprintf(createEntryMessage, PATH_MAX, "Create new entry for the journal %s", journal);
|
||||||
entryArray[0] = createEntryMessage;
|
entryArray[0] = createEntryMessage;
|
||||||
entryArray[1] = "Open random entry";
|
entryArray[1] = "Open random entry";
|
||||||
entryArray[2] = "Search inside entries";
|
entryArray[2] = "Search inside entries";
|
||||||
int entryCount = extraOptions; // we need to count how many dirs there is to always readjust how many memory we alloc
|
int entryCount = extraOptions; // we need to count how many dirs there is to always readjust
|
||||||
|
// how many memory we alloc
|
||||||
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
// Refer https://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
|
||||||
// for readdir()
|
// for readdir()
|
||||||
debug("┌------------------------------\n Detected files and dirs from %s:", path);
|
debug("┌------------------------------\n Detected files and dirs from %s:", path);
|
||||||
// iterates over all the entries from the dir
|
// iterates over all the entries from the dir
|
||||||
while ((dividedJournalEntry = readdir(dividedJournalDirectory)) != NULL) {
|
while ((dividedJournalEntry = readdir(dividedJournalDirectory)) != NULL) {
|
||||||
altDebug("%s\n", dividedJournalEntry->d_name);
|
altDebug("%s\n", dividedJournalEntry->d_name);
|
||||||
if (dividedJournalEntry->d_name[0] != '.') { // if the entry don't start with a dot (so hidden dirs and hidden files)
|
if (dividedJournalEntry->d_name[0] !=
|
||||||
|
'.') { // if the entry don't start with a dot (so hidden dirs and hidden files)
|
||||||
char fullPathEntry[PATH_MAX]; // creates a string of size of the maximum path lenght
|
char fullPathEntry[PATH_MAX]; // creates a string of size of the maximum path lenght
|
||||||
snprintf(fullPathEntry, sizeof(fullPathEntry), "%s/%s", path, dividedJournalEntry->d_name); // sets the full absolute path to fullPathEntry
|
snprintf(
|
||||||
|
fullPathEntry, sizeof(fullPathEntry), "%s/%s", path,
|
||||||
|
dividedJournalEntry->d_name); // sets the full absolute path to fullPathEntry
|
||||||
|
|
||||||
struct stat metadataPathEntry;
|
struct stat metadataPathEntry;
|
||||||
if (stat(fullPathEntry, &metadataPathEntry) == 0 && S_ISREG(metadataPathEntry.st_mode)) { // if this entry is a directory
|
if (stat(fullPathEntry, &metadataPathEntry) == 0 &&
|
||||||
entryArray = realloc(entryArray, (entryCount + 1)*sizeof(char*));
|
S_ISREG(metadataPathEntry.st_mode)) { // if this entry is a directory
|
||||||
entryArray[entryCount] = strdup(dividedJournalEntry->d_name); // copy the dir name into entryArray
|
entryArray = realloc(entryArray, (entryCount + 1) * sizeof(char *));
|
||||||
|
entryArray[entryCount] =
|
||||||
|
strdup(dividedJournalEntry->d_name); // copy the dir name into entryArray
|
||||||
entryCount++;
|
entryCount++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,17 +280,30 @@ char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWas
|
|||||||
altDebug("└------------------------------\n");
|
altDebug("└------------------------------\n");
|
||||||
// free's some used memory
|
// free's some used memory
|
||||||
closedir(dividedJournalDirectory);
|
closedir(dividedJournalDirectory);
|
||||||
qsort(entryArray + extraOptions, entryCount - extraOptions, sizeof(const char *), reverseCompareString); // sorts the journals entries alphabetically. // the + extraOptions - extraOptions is to not sort "Create new entry for the journal" or Open random entry which is the first element
|
qsort(entryArray + extraOptions, entryCount - extraOptions, sizeof(const char *),
|
||||||
|
reverseCompareString); // sorts the journals entries alphabetically. // the +
|
||||||
|
// extraOptions - extraOptions is to not sort "Create new entry
|
||||||
|
// for the journal" or Open random entry which is the first
|
||||||
|
// element
|
||||||
|
|
||||||
// we must now select to create new entry or to enter in old one
|
// we must now select to create new entry or to enter in old one
|
||||||
char *selectedOption = ncursesSelect(entryArray, "Create new entry or acces old entry (Use arrows or WASD, Enter to select):", extraOptions, entryCount - extraOptions, " ", " ", "", shouldDebug); // the "Create new entry for the journal %s" will be the only options. All other will be extraOptions. This is made so that "Create [...] %s" will always be on top
|
char *selectedOption = ncursesSelect(
|
||||||
|
entryArray,
|
||||||
|
"Create new entry or acces old entry (Use arrows or WASD, Enter to select):",
|
||||||
|
extraOptions, entryCount - extraOptions, " ", " ", "",
|
||||||
|
shouldDebug); // the "Create new entry for the journal %s" will be the only options. All
|
||||||
|
// other will be extraOptions. This is made so that "Create [...] %s" will
|
||||||
|
// always be on top
|
||||||
debug("Selected option from journal entry selection: %s", selectedOption);
|
debug("Selected option from journal entry selection: %s", selectedOption);
|
||||||
if (strcmp(selectedOption, createEntryMessage) == 0) { // create new entry
|
if (strcmp(selectedOption, createEntryMessage) == 0) { // create new entry
|
||||||
char temp[PATH_MAX];
|
char temp[PATH_MAX];
|
||||||
error(strlen(path)+1+strlen(dateWithExtension)+1>PATH_MAX, "Error file path too long. %s/%s must not exceed PATH_MAX", path, dateWithExtension);
|
error(strlen(path) + 1 + strlen(dateWithExtension) + 1 > PATH_MAX,
|
||||||
|
"Error file path too long. %s/%s must not exceed PATH_MAX", path,
|
||||||
|
dateWithExtension);
|
||||||
snprintf(temp, PATH_MAX, "%s/%s", path, dateWithExtension);
|
snprintf(temp, PATH_MAX, "%s/%s", path, dateWithExtension);
|
||||||
strncpy(path, temp, PATH_MAX);
|
strncpy(path, temp, PATH_MAX);
|
||||||
if (!isStringInArray(dateWithExtension, (const char **)entryArray, entryCount)) { // it only creates it if it doesn't already exist
|
if (!isStringInArray(dateWithExtension, (const char **)entryArray,
|
||||||
|
entryCount)) { // it only creates it if it doesn't already exist
|
||||||
// if it does exist it will just pass the full path
|
// if it does exist it will just pass the full path
|
||||||
debug("Creating entry %s inside %s", date, path);
|
debug("Creating entry %s inside %s", date, path);
|
||||||
FILE *file;
|
FILE *file;
|
||||||
@@ -249,24 +315,35 @@ char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWas
|
|||||||
free(createEntryMessage);
|
free(createEntryMessage);
|
||||||
*journalWasUpdated = 1;
|
*journalWasUpdated = 1;
|
||||||
} else {
|
} else {
|
||||||
debug("Today's entry (%s) already exist. We won't create a new one.", dateWithExtension);
|
debug("Today's entry (%s) already exist. We won't create a new one.",
|
||||||
|
dateWithExtension);
|
||||||
}
|
}
|
||||||
} else if (strcmp(selectedOption, entryArray[1]) == 0) { // if we choosed to open a random entry
|
} else if (strcmp(selectedOption, entryArray[1]) ==
|
||||||
|
0) { // if we choosed to open a random entry
|
||||||
// setting up the seed for rand()
|
// setting up the seed for rand()
|
||||||
srand(time(NULL)); // not totaly random, just pseudorandom
|
srand(time(NULL)); // not totaly random, just pseudorandom
|
||||||
int randomEntry = extraOptions + (rand() % (entryCount - extraOptions)); // we get a random number between extraOptions and entryCount (so all journal entries and not extraOptions)
|
int randomEntry =
|
||||||
|
extraOptions +
|
||||||
|
(rand() %
|
||||||
|
(entryCount -
|
||||||
|
extraOptions)); // we get a random number between extraOptions and entryCount (so
|
||||||
|
// all journal entries and not extraOptions)
|
||||||
char temp[PATH_MAX];
|
char temp[PATH_MAX];
|
||||||
snprintf(temp, PATH_MAX, "%s/%s", path, entryArray[randomEntry]); // reconstruct the path
|
snprintf(temp, PATH_MAX, "%s/%s", path,
|
||||||
|
entryArray[randomEntry]); // reconstruct the path
|
||||||
strncpy(path, temp, PATH_MAX);
|
strncpy(path, temp, PATH_MAX);
|
||||||
debug("Selected random entry %s. It's path is %s.", entryArray[randomEntry], path);
|
debug("Selected random entry %s. It's path is %s.", entryArray[randomEntry], path);
|
||||||
} else if (strcmp(selectedOption, entryArray[2]) == 0) { // if we choosed to search
|
} else if (strcmp(selectedOption, entryArray[2]) == 0) { // if we choosed to search
|
||||||
char *temp = fzfSelect(path, "Input text to be searched", shouldDebug); // uses ripgrep and fzf to search inside the files
|
char *temp = fzfSelect(path, "Input text to be searched",
|
||||||
char *selectedOption = malloc(PATH_MAX); // we can't just use path as both input and output of snprintf
|
shouldDebug); // uses ripgrep and fzf to search inside the files
|
||||||
|
char *selectedOption =
|
||||||
|
malloc(PATH_MAX); // we can't just use path as both input and output of snprintf
|
||||||
snprintf(selectedOption, PATH_MAX, "%s/%s", path, temp);
|
snprintf(selectedOption, PATH_MAX, "%s/%s", path, temp);
|
||||||
path = strdup(selectedOption);
|
path = strdup(selectedOption);
|
||||||
free(selectedOption);
|
free(selectedOption);
|
||||||
} else { // we just recreate the path to the selected entry
|
} else { // we just recreate the path to the selected entry
|
||||||
// snprintf does not like to have the same variable as input and output so we use a buffer
|
// snprintf does not like to have the same variable as input and output so we use a
|
||||||
|
// buffer
|
||||||
char temp[PATH_MAX];
|
char temp[PATH_MAX];
|
||||||
snprintf(temp, PATH_MAX, "%s/%s", path, selectedOption);
|
snprintf(temp, PATH_MAX, "%s/%s", path, selectedOption);
|
||||||
strncpy(path, temp, PATH_MAX);
|
strncpy(path, temp, PATH_MAX);
|
||||||
|
|||||||
+22
-15
@@ -1,23 +1,29 @@
|
|||||||
#ifndef NOTES_H
|
#ifndef NOTES_H
|
||||||
#define NOTES_H
|
#define NOTES_H
|
||||||
#include "utils.h"
|
|
||||||
#include "ui.h"
|
#include "ui.h"
|
||||||
|
#include "utils.h"
|
||||||
// find which directory contains targetVault
|
// find which directory contains targetVault
|
||||||
char *getDirectoryFromVault(char *targetVault, char **vaultsArray, int vaultTotalNumber, int *vaultNumberPerDirectory, char **directoryArray, int directoryNumber, int shouldDebug);
|
char *getDirectoryFromVault(char *targetVault, char **vaultsArray, int vaultTotalNumber,
|
||||||
|
int *vaultNumberPerDirectory, char **directoryArray,
|
||||||
|
int directoryNumber, int shouldDebug);
|
||||||
// gets the journals from the vault.
|
// gets the journals from the vault.
|
||||||
//to distinguish journals from note we use regex.
|
// to distinguish journals from note we use regex.
|
||||||
//Note: we must handle them separatly as journals can either be a single file (which will treat specially) or a directory.
|
// Note: we must handle them separatly as journals can either be a single file (which will treat
|
||||||
char **getJournalsFromVault(char *pathToVault, char *vault, char *journalRegex, int *count, int shouldDebug);
|
// specially) or a directory.
|
||||||
// this function is inputed a path to a vault (which was selected before) and outpus all the suitable notes (so not the hidden ones).
|
char **getJournalsFromVault(char *pathToVault, char *vault, char *journalRegex, int *count,
|
||||||
// journalRegex is the regex code for the journals. If a note matches this code, it is treated as a journal and it is not outputed from this function.
|
int shouldDebug);
|
||||||
char **getNotesFromVault(char *pathToVault, char *vault, char *journalRegex, int *count, int shouldDebug);
|
// this function is inputed a path to a vault (which was selected before) and outpus all the
|
||||||
// function gets as input an array of directoryNumber strings. Which are the directories the function will search for vaults.
|
// suitable notes (so not the hidden ones). journalRegex is the regex code for the journals. If a
|
||||||
// it returns an array of vaults.
|
// note matches this code, it is treated as a journal and it is not outputed from this function.
|
||||||
// the vaults are organized in order per directory.
|
char **getNotesFromVault(char *pathToVault, char *vault, char *journalRegex, int *count,
|
||||||
// vaultsPerDirectoryNumber and count should be initiallized before calling the function and the address be inputed.
|
int shouldDebug);
|
||||||
// count is the total number of vaults.
|
// function gets as input an array of directoryNumber strings. Which are the directories the
|
||||||
|
// function will search for vaults. it returns an array of vaults. the vaults are organized in order
|
||||||
|
// per directory. vaultsPerDirectoryNumber and count should be initiallized before calling the
|
||||||
|
// function and the address be inputed. count is the total number of vaults.
|
||||||
// vaultsPerDirectoryNumber gives how many vaults each directory has.
|
// vaultsPerDirectoryNumber gives how many vaults each directory has.
|
||||||
char **getVaultsFromDirectories(char **directoryStringArray, int directoryNumber, int *vaultsPerDirectoryNumber, int *count, int shouldDebug);
|
char **getVaultsFromDirectories(char **directoryStringArray, int directoryNumber,
|
||||||
|
int *vaultsPerDirectoryNumber, int *count, int shouldDebug);
|
||||||
// path is the path to the file.
|
// path is the path to the file.
|
||||||
// journal is the name of the file.
|
// journal is the name of the file.
|
||||||
// journalWasUpdated will be set to 1 if a new entry was created
|
// journalWasUpdated will be set to 1 if a new entry was created
|
||||||
@@ -25,5 +31,6 @@ char **getVaultsFromDirectories(char **directoryStringArray, int directoryNumber
|
|||||||
// creates new entry with date.
|
// creates new entry with date.
|
||||||
// for divided select if we want to acces to a new entry or a old one.
|
// for divided select if we want to acces to a new entry or a old one.
|
||||||
// returns the path to the file that needs to be opened.
|
// returns the path to the file that needs to be opened.
|
||||||
char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWasUpdated, int shouldDebug);
|
char *updateJournal(char *path, char *journal, char *timeFormat, int *journalWasUpdated,
|
||||||
|
int shouldDebug);
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
#include "ui.h"
|
#include "ui.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
|
||||||
void createNewVault(char **directoriesArray, int directoryCount, char **vaultsArray, int vaultCount, int bypass, char *bypassvalue, int shouldDebug) {
|
void createNewVault(char **directoriesArray, int directoryCount, char **vaultsArray, int vaultCount,
|
||||||
|
int bypass, char *bypassvalue, int shouldDebug) {
|
||||||
int duplicateWarning = 0; // set to 1 later if the vault you tried to create already existed
|
int duplicateWarning = 0; // set to 1 later if the vault you tried to create already existed
|
||||||
int emptyWarning = 0; // set to 1 later if inpted empty name
|
int emptyWarning = 0; // set to 1 later if inpted empty name
|
||||||
input_screen:
|
input_screen:
|
||||||
// choose in which directory the vault will be created
|
// choose in which directory the vault will be created
|
||||||
char *dirToVault = ncursesSelect(directoriesArray, "Select a directory, in which the vault will remain (Use arrows or WASD, Enter to select)", directoryCount, 0, "", "", " ", shouldDebug);
|
char *dirToVault = ncursesSelect(
|
||||||
|
directoriesArray,
|
||||||
|
"Select a directory, in which the vault will remain (Use arrows or WASD, Enter to select)",
|
||||||
|
directoryCount, 0, "", "", " ", shouldDebug);
|
||||||
char *vaultName = malloc(PATH_MAX);
|
char *vaultName = malloc(PATH_MAX);
|
||||||
if (!bypass) { // if won't bypass (if -v or --vault weren't set)
|
if (!bypass) { // if won't bypass (if -v or --vault weren't set)
|
||||||
echo();
|
echo();
|
||||||
@@ -32,15 +36,15 @@ input_screen:
|
|||||||
attroff(COLOR_PAIR(2));
|
attroff(COLOR_PAIR(2));
|
||||||
}
|
}
|
||||||
move(1, 1); // replace cursor
|
move(1, 1); // replace cursor
|
||||||
wgetnstr(stdscr, vaultName, PATH_MAX-1);
|
wgetnstr(stdscr, vaultName, PATH_MAX - 1);
|
||||||
refresh();
|
refresh();
|
||||||
endwin();
|
endwin();
|
||||||
reset_shell_mode();
|
reset_shell_mode();
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
fflush(stderr);
|
fflush(stderr);
|
||||||
} else {
|
} else {
|
||||||
strncpy(vaultName, bypassvalue, PATH_MAX -2); // -2 (and later -1) because indexing
|
strncpy(vaultName, bypassvalue, PATH_MAX - 2); // -2 (and later -1) because indexing
|
||||||
vaultName[PATH_MAX-1] = '\0';
|
vaultName[PATH_MAX - 1] = '\0';
|
||||||
}
|
}
|
||||||
// check if no empty string
|
// check if no empty string
|
||||||
if (strcmp(vaultName, "") == 0) {
|
if (strcmp(vaultName, "") == 0) {
|
||||||
@@ -51,8 +55,9 @@ input_screen:
|
|||||||
sanitize(vaultName);
|
sanitize(vaultName);
|
||||||
debug("Sanitized vaultName=%s", vaultName);
|
debug("Sanitized vaultName=%s", vaultName);
|
||||||
|
|
||||||
|
if (!isStringInArray(vaultName, (const char **)vaultsArray,
|
||||||
if (!isStringInArray(vaultName, (const char**)vaultsArray, vaultCount)) { // if vault doesnt already exists. We avoid vaults with the same name even if they are from different directories.
|
vaultCount)) { // if vault doesnt already exists. We avoid vaults with the
|
||||||
|
// same name even if they are from different directories.
|
||||||
char vaultFullPath[PATH_MAX]; // recreating the full path
|
char vaultFullPath[PATH_MAX]; // recreating the full path
|
||||||
sprintf(vaultFullPath, "%s/%s/", dirToVault, vaultName);
|
sprintf(vaultFullPath, "%s/%s/", dirToVault, vaultName);
|
||||||
|
|
||||||
@@ -64,7 +69,8 @@ input_screen:
|
|||||||
free(vaultName);
|
free(vaultName);
|
||||||
}
|
}
|
||||||
|
|
||||||
char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, char *bypassvalue, char *journalRegex, int shouldDebug) {
|
char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, char *bypassvalue,
|
||||||
|
char *journalRegex, int shouldDebug) {
|
||||||
// input from user for the name
|
// input from user for the name
|
||||||
char *fileName = malloc(BUFFER_SIZE);
|
char *fileName = malloc(BUFFER_SIZE);
|
||||||
if (!bypass) { // if we don't bypass. (if -n or --note weren't set.)
|
if (!bypass) { // if we don't bypass. (if -n or --note weren't set.)
|
||||||
@@ -73,9 +79,14 @@ char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, c
|
|||||||
clear();
|
clear();
|
||||||
printw("Enter the name of the new note: ");
|
printw("Enter the name of the new note: ");
|
||||||
mvprintw(3, 0, "Unsafe characters such as \\, and / will be replaced by _");
|
mvprintw(3, 0, "Unsafe characters such as \\, and / will be replaced by _");
|
||||||
mvprintw(4, 0, "If the name matches with the regex for a journal (%s), it will create a journal instead of a note.", journalRegex);
|
mvprintw(4, 0,
|
||||||
move(1,1);
|
"If the name matches with the regex for a journal (%s), it will create a journal "
|
||||||
wgetnstr(stdscr, fileName, BUFFER_SIZE-4); //limits the buffer to prevent overflow (-4 to account indexing and from ".md" in case we need to add it later)
|
"instead of a note.",
|
||||||
|
journalRegex);
|
||||||
|
move(1, 1);
|
||||||
|
wgetnstr(stdscr, fileName,
|
||||||
|
BUFFER_SIZE - 4); // limits the buffer to prevent overflow (-4 to account indexing
|
||||||
|
// and from ".md" in case we need to add it later)
|
||||||
refresh();
|
refresh();
|
||||||
endwin();
|
endwin();
|
||||||
reset_shell_mode();
|
reset_shell_mode();
|
||||||
@@ -83,9 +94,12 @@ char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, c
|
|||||||
fflush(stderr);
|
fflush(stderr);
|
||||||
} else { // bypasses user input if we bypass is set to 1
|
} else { // bypasses user input if we bypass is set to 1
|
||||||
strncpy(fileName, bypassvalue, BUFFER_SIZE);
|
strncpy(fileName, bypassvalue, BUFFER_SIZE);
|
||||||
fileName[BUFFER_SIZE-1] = '\0';
|
fileName[BUFFER_SIZE - 1] = '\0';
|
||||||
}
|
}
|
||||||
error(strcmp(fileName, "") == 0, "user", "fileName is empty"); // replace this with a warning and add a warning if duplicate file and handle case where multiple warnings (if such case is possible)
|
error(
|
||||||
|
strcmp(fileName, "") == 0, "user",
|
||||||
|
"fileName is empty"); // replace this with a warning and add a warning if duplicate file and
|
||||||
|
// handle case where multiple warnings (if such case is possible)
|
||||||
// check/sanitize the input
|
// check/sanitize the input
|
||||||
debug("Inputed fileName=%s", fileName);
|
debug("Inputed fileName=%s", fileName);
|
||||||
sanitize(fileName);
|
sanitize(fileName);
|
||||||
@@ -105,7 +119,10 @@ char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, c
|
|||||||
char **options = malloc(32); // the number of bytes is exactly what in the two strings
|
char **options = malloc(32); // the number of bytes is exactly what in the two strings
|
||||||
options[0] = "Divided journal";
|
options[0] = "Divided journal";
|
||||||
options[1] = "Unified journal";
|
options[1] = "Unified journal";
|
||||||
char *optionSelected = ncursesSelect(options, "Select which type of journal you want to create (Use arrows or WASD, Enter to select):", 2, 0, "", "", " ", shouldDebug);
|
char *optionSelected = ncursesSelect(options,
|
||||||
|
"Select which type of journal you want to create "
|
||||||
|
"(Use arrows or WASD, Enter to select):",
|
||||||
|
2, 0, "", "", " ", shouldDebug);
|
||||||
debug("%s was selected to be a %s", fileName, optionSelected);
|
debug("%s was selected to be a %s", fileName, optionSelected);
|
||||||
if (strcmp(optionSelected, options[0]) == 0) { // if it is a divided journal
|
if (strcmp(optionSelected, options[0]) == 0) { // if it is a divided journal
|
||||||
char *fileFullPath = malloc(PATH_MAX);
|
char *fileFullPath = malloc(PATH_MAX);
|
||||||
@@ -121,8 +138,11 @@ char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, c
|
|||||||
char *fileFullPath = malloc(PATH_MAX);
|
char *fileFullPath = malloc(PATH_MAX);
|
||||||
snprintf(fileFullPath, PATH_MAX, "%s/%s/%s", dirToVault, vaultFromDir, fileName);
|
snprintf(fileFullPath, PATH_MAX, "%s/%s/%s", dirToVault, vaultFromDir, fileName);
|
||||||
int len = strlen(fileFullPath);
|
int len = strlen(fileFullPath);
|
||||||
if (fileFullPath[len-3] != '.' || fileFullPath[len-2] != 'm' || fileFullPath[len-1] != 'd') { // there might be a cleaner way to do this
|
if (fileFullPath[len - 3] != '.' || fileFullPath[len - 2] != 'm' ||
|
||||||
error(len > PATH_MAX - 3, "user", "%s is too big (greater than PATH_MAX-3) and we can't append .md", fileFullPath);
|
fileFullPath[len - 1] != 'd') { // there might be a cleaner way to do this
|
||||||
|
error(len > PATH_MAX - 3, "user",
|
||||||
|
"%s is too big (greater than PATH_MAX-3) and we can't append .md",
|
||||||
|
fileFullPath);
|
||||||
strncat(fileFullPath, ".md", PATH_MAX);
|
strncat(fileFullPath, ".md", PATH_MAX);
|
||||||
// we checked before if fileName didn't already exist.
|
// we checked before if fileName didn't already exist.
|
||||||
// we must redo it as we add a .mode
|
// we must redo it as we add a .mode
|
||||||
@@ -141,10 +161,13 @@ char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, c
|
|||||||
debug("%s does not match with %s treating it as a note", fileName, journalRegex);
|
debug("%s does not match with %s treating it as a note", fileName, journalRegex);
|
||||||
// if there is no .md add an .md
|
// if there is no .md add an .md
|
||||||
int len = strlen(fileName);
|
int len = strlen(fileName);
|
||||||
if (fileName[len-3] != '.' || fileName[len-2] != 'm' || fileName[len-1] != 'd') { // there might be a cleaner way to do this
|
if (fileName[len - 3] != '.' || fileName[len - 2] != 'm' ||
|
||||||
strcat(fileName, ".md"); // this should not cause an overflow issue as we get at most 252 chars (+'.'+'m'+'d'+'\0' makes it to 256) with wgetnstr
|
fileName[len - 1] != 'd') { // there might be a cleaner way to do this
|
||||||
|
strcat(fileName, ".md"); // this should not cause an overflow issue as we get at most
|
||||||
|
// 252 chars (+'.'+'m'+'d'+'\0' makes it to 256) with wgetnstr
|
||||||
}
|
}
|
||||||
char *fileFullPath = malloc(PATH_MAX); // this dinamically allocated because we use it in the main function to call openEditor
|
char *fileFullPath = malloc(PATH_MAX); // this dinamically allocated because we use it in
|
||||||
|
// the main function to call openEditor
|
||||||
sprintf(fileFullPath, "%s/%s/%s", dirToVault, vaultFromDir, fileName);
|
sprintf(fileFullPath, "%s/%s/%s", dirToVault, vaultFromDir, fileName);
|
||||||
FILE *filePointer;
|
FILE *filePointer;
|
||||||
filePointer = fopen(fileFullPath, "w"); // creates and opens the file
|
filePointer = fopen(fileFullPath, "w"); // creates and opens the file
|
||||||
@@ -156,8 +179,9 @@ char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, c
|
|||||||
return fileName;
|
return fileName;
|
||||||
}
|
}
|
||||||
|
|
||||||
char* fzfSelect(char *pathToFiles, char *selectText, int shouldDebug) {
|
char *fzfSelect(char *pathToFiles, char *selectText, int shouldDebug) {
|
||||||
// we are gonna write each line of each files (with the filename and the line number to an index)
|
// we are gonna write each line of each files (with the filename and the line number to an
|
||||||
|
// index)
|
||||||
char command[CMD_BUFFER];
|
char command[CMD_BUFFER];
|
||||||
char indexFile[] = "/tmp/notewrapper_index_XXXXXX";
|
char indexFile[] = "/tmp/notewrapper_index_XXXXXX";
|
||||||
|
|
||||||
@@ -170,11 +194,8 @@ char* fzfSelect(char *pathToFiles, char *selectText, int shouldDebug) {
|
|||||||
* Build index once into temp file
|
* Build index once into temp file
|
||||||
* format: file:line:content
|
* format: file:line:content
|
||||||
*/
|
*/
|
||||||
snprintf(command, sizeof(command),
|
snprintf(command, sizeof(command), "rg --line-number --no-heading --color=never . \"%s\" > %s",
|
||||||
"rg --line-number --no-heading --color=never . \"%s\" > %s",
|
pathToFiles, indexFile);
|
||||||
pathToFiles,
|
|
||||||
indexFile
|
|
||||||
);
|
|
||||||
|
|
||||||
debug("INDEX CMD: %s", command);
|
debug("INDEX CMD: %s", command);
|
||||||
|
|
||||||
@@ -222,14 +243,14 @@ char* fzfSelect(char *pathToFiles, char *selectText, int shouldDebug) {
|
|||||||
--bind 'change:show-preview'
|
--bind 'change:show-preview'
|
||||||
→ preview only appears after first selection change (not at startup)
|
→ preview only appears after first selection change (not at startup)
|
||||||
*/
|
*/
|
||||||
snprintf(command, sizeof(command),
|
snprintf(
|
||||||
|
command, sizeof(command),
|
||||||
"cat %s | fzf --delimiter ':' --prompt='%s' "
|
"cat %s | fzf --delimiter ':' --prompt='%s' "
|
||||||
"--preview 'file={1}; line={2}; nl -ba \"$file\" | sed -n \"$((line-5)),$((line+5))p\" | sed \"$((line-$(($((line-5))))+1))s/^/\\x1b[31m-> \\x1b[0m/\"' "
|
"--preview 'file={1}; line={2}; nl -ba \"$file\" | sed -n \"$((line-5)),$((line+5))p\" | "
|
||||||
|
"sed \"$((line-$(($((line-5))))+1))s/^/\\x1b[31m-> \\x1b[0m/\"' "
|
||||||
"--preview-window=right:60%%:hidden "
|
"--preview-window=right:60%%:hidden "
|
||||||
"--bind 'change:show-preview'",
|
"--bind 'change:show-preview'",
|
||||||
indexFile,
|
indexFile, selectText ? selectText : "> ");
|
||||||
selectText ? selectText : "> "
|
|
||||||
);
|
|
||||||
debug("FZF CMD: %s", command);
|
debug("FZF CMD: %s", command);
|
||||||
|
|
||||||
FILE *fzfPipe = popen(command, "r");
|
FILE *fzfPipe = popen(command, "r");
|
||||||
@@ -253,7 +274,7 @@ char* fzfSelect(char *pathToFiles, char *selectText, int shouldDebug) {
|
|||||||
result = NULL;
|
result = NULL;
|
||||||
while (token != NULL) {
|
while (token != NULL) {
|
||||||
result = token;
|
result = token;
|
||||||
token = strtok(NULL, "/"); //Passing NULL means “don’t start a new string, resume
|
token = strtok(NULL, "/"); // Passing NULL means “don’t start a new string, resume
|
||||||
}
|
}
|
||||||
|
|
||||||
// clean up
|
// clean up
|
||||||
@@ -263,22 +284,27 @@ char* fzfSelect(char *pathToFiles, char *selectText, int shouldDebug) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
char* ncursesSelect(char **options, char *optionsText, int optionsNumber, int extraOptionsNumber, char *bottomText, char *middleText, char *topText, int shouldDebug) { // TODO we should see how it handles larges strings (like large directories)
|
char *ncursesSelect(
|
||||||
int highlight = 0; //curently highlighted option
|
char **options, char *optionsText, int optionsNumber, int extraOptionsNumber, char *bottomText,
|
||||||
|
char *middleText, char *topText,
|
||||||
|
int shouldDebug) { // TODO we should see how it handles larges strings (like large directories)
|
||||||
|
int highlight = 0; // curently highlighted option
|
||||||
int key;
|
int key;
|
||||||
|
|
||||||
cbreak(); // disable line buffering
|
cbreak(); // disable line buffering
|
||||||
noecho(); // don't echo key presses
|
noecho(); // don't echo key presses
|
||||||
keypad(stdscr, TRUE); // enable arrow keys
|
keypad(stdscr, TRUE); // enable arrow keys
|
||||||
start_color();
|
start_color();
|
||||||
curs_set(0); // sets the cursor to invisible. (We will emulate the cursor with a hightlight that go up and down).
|
curs_set(0); // sets the cursor to invisible. (We will emulate the cursor with a hightlight that
|
||||||
|
// go up and down).
|
||||||
use_default_colors();
|
use_default_colors();
|
||||||
init_pair(1, COLOR_WHITE, -1); // color for optionsNumber (so notes, vaults, etc.)
|
init_pair(1, COLOR_WHITE, -1); // color for optionsNumber (so notes, vaults, etc.)
|
||||||
init_pair(2, COLOR_BLUE, -1); // color for extraOptionsNumber (so settings, delete notes, create vault, etc.)
|
init_pair(2, COLOR_BLUE,
|
||||||
|
-1); // color for extraOptionsNumber (so settings, delete notes, create vault, etc.)
|
||||||
while (1) {
|
while (1) {
|
||||||
clear();
|
clear();
|
||||||
attron(COLOR_PAIR(1));
|
attron(COLOR_PAIR(1));
|
||||||
mvprintw(0,0, "%s", optionsText);
|
mvprintw(0, 0, "%s", optionsText);
|
||||||
int offset = 1;
|
int offset = 1;
|
||||||
if (strcmp(bottomText, "") != 0) {
|
if (strcmp(bottomText, "") != 0) {
|
||||||
mvprintw(offset, 1, "%s", bottomText);
|
mvprintw(offset, 1, "%s", bottomText);
|
||||||
@@ -289,14 +315,14 @@ char* ncursesSelect(char **options, char *optionsText, int optionsNumber, int ex
|
|||||||
if (i == highlight) {
|
if (i == highlight) {
|
||||||
attron(A_REVERSE);
|
attron(A_REVERSE);
|
||||||
} // highlight selected
|
} // highlight selected
|
||||||
mvprintw(i+offset, 2, "%s", options[i]);
|
mvprintw(i + offset, 2, "%s", options[i]);
|
||||||
if (i == highlight) {
|
if (i == highlight) {
|
||||||
attroff(A_REVERSE);
|
attroff(A_REVERSE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
attroff(COLOR_PAIR(1));
|
attroff(COLOR_PAIR(1));
|
||||||
if (strcmp(middleText, "") != 0) {
|
if (strcmp(middleText, "") != 0) {
|
||||||
mvprintw(offset+optionsNumber, 1, "%s", middleText);
|
mvprintw(offset + optionsNumber, 1, "%s", middleText);
|
||||||
offset++;
|
offset++;
|
||||||
}
|
}
|
||||||
// Printf extraOptions with highlighting
|
// Printf extraOptions with highlighting
|
||||||
@@ -305,24 +331,24 @@ char* ncursesSelect(char **options, char *optionsText, int optionsNumber, int ex
|
|||||||
if (k == highlight) {
|
if (k == highlight) {
|
||||||
attron(A_REVERSE);
|
attron(A_REVERSE);
|
||||||
}
|
}
|
||||||
mvprintw(k+offset, 2, "%s", options[k]);
|
mvprintw(k + offset, 2, "%s", options[k]);
|
||||||
if (k == highlight) {
|
if (k == highlight) {
|
||||||
attroff(A_REVERSE);
|
attroff(A_REVERSE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
attroff(COLOR_PAIR(2));
|
attroff(COLOR_PAIR(2));
|
||||||
attron(COLOR_PAIR(1));
|
attron(COLOR_PAIR(1));
|
||||||
mvprintw(offset+optionsNumber+extraOptionsNumber, 1, "%s", topText);
|
mvprintw(offset + optionsNumber + extraOptionsNumber, 1, "%s", topText);
|
||||||
attroff(COLOR_PAIR(1));
|
attroff(COLOR_PAIR(1));
|
||||||
key = getch(); //get some int which value correspond to some key being pressed
|
key = getch(); // get some int which value correspond to some key being pressed
|
||||||
|
|
||||||
switch(key) {
|
switch (key) {
|
||||||
case KEY_UP:
|
case KEY_UP:
|
||||||
case 'w':
|
case 'w':
|
||||||
case 'W':
|
case 'W':
|
||||||
highlight--;
|
highlight--;
|
||||||
if (highlight < 0) {
|
if (highlight < 0) {
|
||||||
highlight = optionsNumber + extraOptionsNumber - 1;// can't select the -1nth option
|
highlight = optionsNumber + extraOptionsNumber - 1; // can't select the -1nth option
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 's':
|
case 's':
|
||||||
@@ -337,7 +363,7 @@ char* ncursesSelect(char **options, char *optionsText, int optionsNumber, int ex
|
|||||||
goto end_loop;
|
goto end_loop;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
end_loop:
|
end_loop:
|
||||||
endwin(); // end ncurses mode
|
endwin(); // end ncurses mode
|
||||||
fflush(stderr);
|
fflush(stderr);
|
||||||
debug("Selected option: %s", options[highlight]);
|
debug("Selected option: %s", options[highlight]);
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
#ifndef UI_H
|
#ifndef UI_H
|
||||||
#define UI_H
|
#define UI_H
|
||||||
|
|
||||||
|
#include "utils.h"
|
||||||
|
#include <ctype.h>
|
||||||
|
#include <limits.h>
|
||||||
|
#include <ncurses.h>
|
||||||
|
#include <pwd.h>
|
||||||
|
#include <regex.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <ncurses.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
#include <sys/stat.h>
|
#include <sys/stat.h>
|
||||||
#include <pwd.h>
|
#include <unistd.h>
|
||||||
#include <ctype.h>
|
|
||||||
#include <limits.h>
|
|
||||||
#include <regex.h>
|
|
||||||
#include "utils.h"
|
|
||||||
#define CMD_BUFFER 4096 // for fzfSelect
|
#define CMD_BUFFER 4096 // for fzfSelect
|
||||||
#define RESULT_BUFFER 1024 // for fzfSelect
|
#define RESULT_BUFFER 1024 // for fzfSelect
|
||||||
|
|
||||||
@@ -21,27 +21,27 @@ also can create a journal if the name matches with journalRegex.
|
|||||||
returns the path to the note.
|
returns the path to the note.
|
||||||
If you want to bypass the input TUI set bypass to 1 and bypassvalue to the note name
|
If you want to bypass the input TUI set bypass to 1 and bypassvalue to the note name
|
||||||
*/
|
*/
|
||||||
char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, char *bypassvalue, char *journalRegex, int debug);
|
char *createNewNote(char dirToVault[PATH_MAX], char *vaultFromDir, int bypass, char *bypassvalue,
|
||||||
|
char *journalRegex, int debug);
|
||||||
/*
|
/*
|
||||||
Chooses in which directory it want to create the vault.
|
Chooses in which directory it want to create the vault.
|
||||||
Uses ncurses to get an input from the user.
|
Uses ncurses to get an input from the user.
|
||||||
Creates a new vault with this input.
|
Creates a new vault with this input.
|
||||||
If vault already exists, prints a warning.
|
If vault already exists, prints a warning.
|
||||||
returns nothing. */
|
returns nothing. */
|
||||||
void createNewVault(char **directoriesArray, int directoryCount, char **vaultsArray, int vaultCount, int bypass, char *bypassvalue, int debug);
|
void createNewVault(char **directoriesArray, int directoryCount, char **vaultsArray, int vaultCount,
|
||||||
|
int bypass, char *bypassvalue, int debug);
|
||||||
// uses fzf and ripgrep to search inside the files to choose between all the options.
|
// uses fzf and ripgrep to search inside the files to choose between all the options.
|
||||||
char* fzfSelect(char *pathToFiles, char *selectText, int shouldDebug);
|
char *fzfSelect(char *pathToFiles, char *selectText, int shouldDebug);
|
||||||
/*this function is used multiple times let the user select one options from many with ncurses in a TUI.
|
/*this function is used multiple times let the user select one options from many with ncurses in a
|
||||||
options is the array of strings with all the options.
|
TUI. options is the array of strings with all the options. optionsText is the text that will be
|
||||||
optionsText is the text that will be printed at the top (For example: "Please select ...").
|
printed at the top (For example: "Please select ..."). we distinguish options from extraOptions.
|
||||||
we distinguish options from extraOptions.
|
|
||||||
options could be the list of all notes or all vaults.
|
options could be the list of all notes or all vaults.
|
||||||
extraOptions are options that are special and have a special color (for ex: "Delete vault", "Settings", etc.).
|
extraOptions are options that are special and have a special color (for ex: "Delete vault",
|
||||||
note: extraOptions should be at the end of options.
|
"Settings", etc.). note: extraOptions should be at the end of options. topText is printed between
|
||||||
topText is printed between options text and the start of options.
|
options text and the start of options. middleText (usally \n) is printed between options and
|
||||||
middleText (usally \n) is printed between options and extraOptions.
|
extraOptions. bottomText is printed bellow. topText and middle must be exactly one line. If you want
|
||||||
bottomText is printed bellow.
|
empty lines use " " and not "". returns the selected option. */
|
||||||
topText and middle must be exactly one line. If you want empty lines use " " and not "".
|
char *ncursesSelect(char **options, char *optionsText, int optionsNumber, int extraOptionsNumber,
|
||||||
returns the selected option. */
|
char *bottomText, char *middleText, char *topText, int debug);
|
||||||
char* ncursesSelect(char **options, char *optionsText, int optionsNumber, int extraOptionsNumber, char *bottomText, char *middleText, char *topText, int debug);
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
+102
-76
@@ -11,7 +11,7 @@ int compareString(const void *a, const void *b) {
|
|||||||
int reverseCompareString(const void *a, const void *b) {
|
int reverseCompareString(const void *a, const void *b) {
|
||||||
const char *str1 = *(const char **)a;
|
const char *str1 = *(const char **)a;
|
||||||
const char *str2 = *(const char **)b;
|
const char *str2 = *(const char **)b;
|
||||||
return -1*strcmp(str1, str2);
|
return -1 * strcmp(str1, str2);
|
||||||
}
|
}
|
||||||
|
|
||||||
void getCurrentTime(int *hour, int *minute, int *second) {
|
void getCurrentTime(int *hour, int *minute, int *second) {
|
||||||
@@ -23,21 +23,24 @@ void getCurrentTime(int *hour, int *minute, int *second) {
|
|||||||
*second = local->tm_sec; // Extract seconds
|
*second = local->tm_sec; // Extract seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
void _debug(const int d, const char *file, const int line, const char *function, const char *message, ...) { // use for formatted debug
|
void _debug(const int d, const char *file, const int line, const char *function,
|
||||||
|
const char *message, ...) { // use for formatted debug
|
||||||
if (d) {
|
if (d) {
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
fflush(stderr);
|
fflush(stderr);
|
||||||
va_list args; //variadic function stuff
|
va_list args; // variadic function stuff
|
||||||
va_start(args, message);
|
va_start(args, message);
|
||||||
int h, m, s;
|
int h, m, s;
|
||||||
getCurrentTime(&h, &m, &s);
|
getCurrentTime(&h, &m, &s);
|
||||||
fprintf(stderr, "\e[0;32m[DEBUG -- %d:%d:%d] From file %s line %d function %s:\e[0m\n", h, m, s, file, line, function);
|
fprintf(stderr, "\e[0;32m[DEBUG -- %d:%d:%d] From file %s line %d function %s:\e[0m\n", h,
|
||||||
|
m, s, file, line, function);
|
||||||
vfprintf(stderr, message, args);
|
vfprintf(stderr, message, args);
|
||||||
fprintf(stderr, "\e[0m\n");
|
fprintf(stderr, "\e[0m\n");
|
||||||
va_end(args);
|
va_end(args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
void _altDebug(const int d, const char *message, ...) { // use for less formal debuggin. (usefull if enumerating or making a list
|
void _altDebug(const int d, const char *message,
|
||||||
|
...) { // use for less formal debuggin. (usefull if enumerating or making a list
|
||||||
if (d) {
|
if (d) {
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
fflush(stderr);
|
fflush(stderr);
|
||||||
@@ -48,11 +51,14 @@ void _altDebug(const int d, const char *message, ...) { // use for less formal d
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _error(const int shouldDebug, const int condition, const char *type, const char *file, const int line, const char *function, const char *message, ...) { // used for formatted errors
|
void _error(const int shouldDebug, const int condition, const char *type, const char *file,
|
||||||
|
const int line, const char *function, const char *message,
|
||||||
|
...) { // used for formatted errors
|
||||||
if (condition) {
|
if (condition) {
|
||||||
int h, m, s;
|
int h, m, s;
|
||||||
getCurrentTime(&h, &m, &s);
|
getCurrentTime(&h, &m, &s);
|
||||||
fprintf(stderr, "\e[0;31m[%s ERROR -- %d:%d:%d] From file %s line %d function %s:\n", type, h, m, s, file, line, function);
|
fprintf(stderr, "\e[0;31m[%s ERROR -- %d:%d:%d] From file %s line %d function %s:\n", type,
|
||||||
|
h, m, s, file, line, function);
|
||||||
if (errno != 0) {
|
if (errno != 0) {
|
||||||
fprintf(stderr, " (System-level error message: %s)\n", strerror(errno));
|
fprintf(stderr, " (System-level error message: %s)\n", strerror(errno));
|
||||||
} else {
|
} else {
|
||||||
@@ -70,7 +76,8 @@ void _error(const int shouldDebug, const int condition, const char *type, const
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void copyDir(const char *source, const char *destination, const char **rsyncArgs, const int rsyncArgsNumber, const int shouldDebug) {
|
static void copyDir(const char *source, const char *destination, const char **rsyncArgs,
|
||||||
|
const int rsyncArgsNumber, const int shouldDebug) {
|
||||||
debug("Backuping... source: %s and destination: %s", source, destination);
|
debug("Backuping... source: %s and destination: %s", source, destination);
|
||||||
debug("Rsync has %d extra arguments", rsyncArgsNumber);
|
debug("Rsync has %d extra arguments", rsyncArgsNumber);
|
||||||
pid_t pid = fork();
|
pid_t pid = fork();
|
||||||
@@ -79,16 +86,16 @@ static void copyDir(const char *source, const char *destination, const char **rs
|
|||||||
|
|
||||||
if (pid == 0) {
|
if (pid == 0) {
|
||||||
// Child process: execute rsync
|
// Child process: execute rsync
|
||||||
char **args = malloc((4 + rsyncArgsNumber)*sizeof(char*));
|
char **args = malloc((4 + rsyncArgsNumber) * sizeof(char *));
|
||||||
args[0] = "rsync";
|
args[0] = "rsync";
|
||||||
for (int i = 0; i < rsyncArgsNumber; i++) {
|
for (int i = 0; i < rsyncArgsNumber; i++) {
|
||||||
args[i+1] = (char *)rsyncArgs[i];
|
args[i + 1] = (char *)rsyncArgs[i];
|
||||||
if (i == rsyncArgsNumber-1) { // last loop
|
if (i == rsyncArgsNumber - 1) { // last loop
|
||||||
args[i+2] = (char*)source;
|
args[i + 2] = (char *)source;
|
||||||
args[i+3] = (char*)destination;
|
args[i + 3] = (char *)destination;
|
||||||
args[i+4] = NULL; // execvp expect last arg to be NULL
|
args[i + 4] = NULL; // execvp expect last arg to be NULL
|
||||||
debug("rsync command:");
|
debug("rsync command:");
|
||||||
for (int k = 0; k <= i+4; k++) {
|
for (int k = 0; k <= i + 4; k++) {
|
||||||
altDebug("%s ", args[k]);
|
altDebug("%s ", args[k]);
|
||||||
}
|
}
|
||||||
altDebug("\n");
|
altDebug("\n");
|
||||||
@@ -116,11 +123,9 @@ void initAppFilesAndDirs(const char *home, const int shouldDebug) {
|
|||||||
char config_dir[PATH_MAX];
|
char config_dir[PATH_MAX];
|
||||||
char cache_dir[PATH_MAX];
|
char cache_dir[PATH_MAX];
|
||||||
|
|
||||||
snprintf(config_dir, sizeof(config_dir),
|
snprintf(config_dir, sizeof(config_dir), "%s/.config/", home);
|
||||||
"%s/.config/", home);
|
|
||||||
|
|
||||||
snprintf(cache_dir, sizeof(cache_dir),
|
snprintf(cache_dir, sizeof(cache_dir), "%s/.cache/", home);
|
||||||
"%s/.cache/", home);
|
|
||||||
|
|
||||||
ensureDir(config_dir, shouldDebug);
|
ensureDir(config_dir, shouldDebug);
|
||||||
ensureDir(cache_dir, shouldDebug);
|
ensureDir(cache_dir, shouldDebug);
|
||||||
@@ -131,8 +136,7 @@ void initAppFilesAndDirs(const char *home, const int shouldDebug) {
|
|||||||
ensureDir(config_dir, shouldDebug);
|
ensureDir(config_dir, shouldDebug);
|
||||||
ensureDir(cache_dir, shouldDebug);
|
ensureDir(cache_dir, shouldDebug);
|
||||||
|
|
||||||
|
char config_file[PATH_MAX + 12];
|
||||||
char config_file[PATH_MAX+12];
|
|
||||||
snprintf(config_file, sizeof(config_file), "%s/config.json", config_dir);
|
snprintf(config_file, sizeof(config_file), "%s/config.json", config_dir);
|
||||||
|
|
||||||
FILE *f = fopen(config_file, "r");
|
FILE *f = fopen(config_file, "r");
|
||||||
@@ -143,29 +147,34 @@ void initAppFilesAndDirs(const char *home, const int shouldDebug) {
|
|||||||
debug("Creating default config file.");
|
debug("Creating default config file.");
|
||||||
FILE *w = fopen(config_file, "w");
|
FILE *w = fopen(config_file, "w");
|
||||||
error(!w, "program", "fopen failed opening %s");
|
error(!w, "program", "fopen failed opening %s");
|
||||||
fprintf(w, //TODO CHANGE default json
|
fprintf(w, // TODO CHANGE default json
|
||||||
"{\n"
|
"{\n"
|
||||||
" \"directory\": [\"~/Documents/\"],\n"// I personally use ~/Documents/Notes. But the dir doesn't exist most times. So for the default user it is better to put ~/Documents
|
" \"directory\": [\"~/Documents/\"],\n" // I personally use ~/Documents/Notes. But the
|
||||||
" \"render\": true,\n"
|
// dir doesn't exist most times. So for the
|
||||||
" \"jumpToEndOfFileOnLaunch\": true,\n"
|
// default user it is better to put ~/Documents
|
||||||
" \"editor\": \"neovim\",\n"
|
" \"render\": true,\n"
|
||||||
" \"journalRegex\": \".*journal.*\",\n"
|
" \"jumpToEndOfFileOnLaunch\": true,\n"
|
||||||
" \"dateEntry\": \"# %%Y %%m %%d %%a\",\n"
|
" \"editor\": \"neovim\",\n"
|
||||||
" \"newLineOnOpening\": true,\n"
|
" \"journalRegex\": \".*journal.*\",\n"
|
||||||
" \"backup\": {\n"
|
" \"dateEntry\": \"# %%Y %%m %%d %%a\",\n"
|
||||||
" \"enable\": false,\n"
|
" \"newLineOnOpening\": true,\n"
|
||||||
" \"directory\": {\n"
|
" \"backup\": {\n"
|
||||||
" \"~/Documents/\": \"path/to/backup/\"\n"
|
" \"enable\": false,\n"
|
||||||
" },\n"
|
" \"directory\": {\n"
|
||||||
" \"interval\": \"weekly\",\n"
|
" \"~/Documents/\": \"path/to/backup/\"\n"
|
||||||
" \"rsyncArgs\": [\"-Lqah\", \"--update\"]\n"
|
" },\n"
|
||||||
" }\n"
|
" \"interval\": \"weekly\",\n"
|
||||||
"}\n");
|
" \"rsyncArgs\": [\"-Lqah\", \"--update\"]\n"
|
||||||
|
" }\n"
|
||||||
|
"}\n");
|
||||||
|
|
||||||
fclose(w);
|
fclose(w);
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleBackups(char **sourceDirectoryArray, const int sourceNumber, char **destinationDirectoryArray, const char *homeDir, const int interval, const char **rsyncArguments, const int rsyncArgumentsNumber, const int shouldDebug) {
|
void handleBackups(char **sourceDirectoryArray, const int sourceNumber,
|
||||||
|
char **destinationDirectoryArray, const char *homeDir, const int interval,
|
||||||
|
const char **rsyncArguments, const int rsyncArgumentsNumber,
|
||||||
|
const int shouldDebug) {
|
||||||
int shouldBackup = 0;
|
int shouldBackup = 0;
|
||||||
time_t now = time(NULL);
|
time_t now = time(NULL);
|
||||||
debug("Time since epoch is %ld", (long)now);
|
debug("Time since epoch is %ld", (long)now);
|
||||||
@@ -202,7 +211,8 @@ void handleBackups(char **sourceDirectoryArray, const int sourceNumber, char **d
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (difftime(now, lastBackupTime) > interval) {
|
if (difftime(now, lastBackupTime) > interval) {
|
||||||
debug("(difftime) %d is greater than (interval) %d -> backuping...", difftime(now, lastBackupTime), interval);
|
debug("(difftime) %d is greater than (interval) %d -> backuping...",
|
||||||
|
difftime(now, lastBackupTime), interval);
|
||||||
shouldBackup = 1;
|
shouldBackup = 1;
|
||||||
cacheFile = fopen(cacheFilePATH, "w");
|
cacheFile = fopen(cacheFilePATH, "w");
|
||||||
if (!cacheFile) {
|
if (!cacheFile) {
|
||||||
@@ -211,7 +221,8 @@ void handleBackups(char **sourceDirectoryArray, const int sourceNumber, char **d
|
|||||||
fprintf(cacheFile, "%ld\n", (long)now);
|
fprintf(cacheFile, "%ld\n", (long)now);
|
||||||
fclose(cacheFile);
|
fclose(cacheFile);
|
||||||
} else {
|
} else {
|
||||||
debug("(difftime) %d is smaller than (interval) %d -> no need to backup.", difftime(now, lastBackupTime), interval);
|
debug("(difftime) %d is smaller than (interval) %d -> no need to backup.",
|
||||||
|
difftime(now, lastBackupTime), interval);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,23 +231,36 @@ void handleBackups(char **sourceDirectoryArray, const int sourceNumber, char **d
|
|||||||
for (int i = 0; i < sourceNumber; i++) {
|
for (int i = 0; i < sourceNumber; i++) {
|
||||||
debug("%s", destinationDirectoryArray[i]);
|
debug("%s", destinationDirectoryArray[i]);
|
||||||
if (destinationDirectoryArray[i]) { // if we don't want to backup it, it was set to NULL
|
if (destinationDirectoryArray[i]) { // if we don't want to backup it, it was set to NULL
|
||||||
copyDir(sourceDirectoryArray[i], destinationDirectoryArray[i], rsyncArguments, rsyncArgumentsNumber, shouldDebug);
|
copyDir(sourceDirectoryArray[i], destinationDirectoryArray[i], rsyncArguments,
|
||||||
|
rsyncArgumentsNumber, shouldDebug);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int isEditorValid (char *editorToCheck, int useDefaultEditor, int shouldDebug) { // check if editor is supported and if it is installed
|
int isEditorValid(char *editorToCheck, int useDefaultEditor,
|
||||||
|
int shouldDebug) { // check if editor is supported and if it is installed
|
||||||
// check if supported
|
// check if supported
|
||||||
if (useDefaultEditor) { // we use a different error message if it defaulted to $EDITOR
|
if (useDefaultEditor) { // we use a different error message if it defaulted to $EDITOR
|
||||||
error(!isStringInArray(editorToCheck, supportedEditor, numEditors), "user", "%s is not a supported editor.\n(defaulted to $EDITOR as neither \"editor\" was set in the configuration file nor -e/--editor <editor> was set.)\n See https://github.com/tomasriveral/NoteWrapper#editor-support for a list of supported editors.", editorToCheck);
|
error(!isStringInArray(editorToCheck, supportedEditor, numEditors), "user",
|
||||||
|
"%s is not a supported editor.\n(defaulted to $EDITOR as neither \"editor\" was set "
|
||||||
|
"in the configuration file nor -e/--editor <editor> was set.)\n See "
|
||||||
|
"https://github.com/tomasriveral/NoteWrapper#editor-support for a list of supported "
|
||||||
|
"editors.",
|
||||||
|
editorToCheck);
|
||||||
} else {
|
} else {
|
||||||
error(!isStringInArray(editorToCheck, supportedEditor, numEditors), "user", "%s is not a supported editor.\n See https://github.com/tomasriveral/NoteWrapper#editor-support for a list of supported editors.", editorToCheck);
|
error(!isStringInArray(editorToCheck, supportedEditor, numEditors), "user",
|
||||||
|
"%s is not a supported editor.\n See "
|
||||||
|
"https://github.com/tomasriveral/NoteWrapper#editor-support for a list of supported "
|
||||||
|
"editors.",
|
||||||
|
editorToCheck);
|
||||||
}
|
}
|
||||||
// check if installed
|
// check if installed
|
||||||
char *editor;
|
char *editor;
|
||||||
if (strcmp(editorToCheck, "neovim") == 0) { // some executables are not name the same as the project
|
if (strcmp(editorToCheck, "neovim") ==
|
||||||
editor = strdup("nvim"); // we must use strdup and not just copy as we would have modified editorToOpen in main
|
0) { // some executables are not name the same as the project
|
||||||
|
editor = strdup("nvim"); // we must use strdup and not just copy as we would have modified
|
||||||
|
// editorToOpen in main
|
||||||
} else if (strcmp(editorToCheck, "helix") == 0) {
|
} else if (strcmp(editorToCheck, "helix") == 0) {
|
||||||
editor = strdup("hx");
|
editor = strdup("hx");
|
||||||
} else if (strcmp(editorToCheck, "kakoune") == 0) {
|
} else if (strcmp(editorToCheck, "kakoune") == 0) {
|
||||||
@@ -245,7 +269,9 @@ int isEditorValid (char *editorToCheck, int useDefaultEditor, int shouldDebug) {
|
|||||||
editor = strdup(editorToCheck);
|
editor = strdup(editorToCheck);
|
||||||
}
|
}
|
||||||
char *path_env = getenv("PATH");
|
char *path_env = getenv("PATH");
|
||||||
error(!path_env, "program", "getenv(\"PATH\") failed to get your path. NoteWrapper is unable to check if your desired editor is installed\n");
|
error(!path_env, "program",
|
||||||
|
"getenv(\"PATH\") failed to get your path. NoteWrapper is unable to check if your "
|
||||||
|
"desired editor is installed\n");
|
||||||
debug("Your PATH is %s", path_env);
|
debug("Your PATH is %s", path_env);
|
||||||
char *paths = strdup(path_env); // duplicate because strtok modifies the string
|
char *paths = strdup(path_env); // duplicate because strtok modifies the string
|
||||||
char *dir = strtok(paths, ":");
|
char *dir = strtok(paths, ":");
|
||||||
@@ -286,7 +312,8 @@ int isStringInArray(const char *string, const char **array, const int len) {
|
|||||||
|
|
||||||
int isStringInFile(const char *path, const char *string, const int shouldDebug) {
|
int isStringInFile(const char *path, const char *string, const int shouldDebug) {
|
||||||
FILE *file = fopen(path, "r");
|
FILE *file = fopen(path, "r");
|
||||||
error(file == NULL, "program", "While searching for \"%s\", we could not open file %s", string, path);
|
error(file == NULL, "program", "While searching for \"%s\", we could not open file %s", string,
|
||||||
|
path);
|
||||||
char buf[BUFFER_SIZE];
|
char buf[BUFFER_SIZE];
|
||||||
|
|
||||||
while (fgets(buf, BUFFER_SIZE, file) != NULL) {
|
while (fgets(buf, BUFFER_SIZE, file) != NULL) {
|
||||||
@@ -302,7 +329,10 @@ void appendToFile(const char *path, const char *string, const int shouldDebug) {
|
|||||||
FILE *file = fopen(path, "r");
|
FILE *file = fopen(path, "r");
|
||||||
char lastLine[1024] = {0};
|
char lastLine[1024] = {0};
|
||||||
error(file == NULL, "program", "could not open %s", path);
|
error(file == NULL, "program", "could not open %s", path);
|
||||||
char buffer[BUFFER_SIZE]; // it does not matter if we have a small buffer. string is relatively small (most time \n or the name of the file). So it is under BUFFER_SIZE. If the last line is more than BUFFER_SIZE. It can't be equal to string
|
char buffer[BUFFER_SIZE]; // it does not matter if we have a small buffer. string is relatively
|
||||||
|
// small (most time \n or the name of the file). So it is under
|
||||||
|
// BUFFER_SIZE. If the last line is more than BUFFER_SIZE. It can't be
|
||||||
|
// equal to string
|
||||||
|
|
||||||
// Read file line by line to get the last one
|
// Read file line by line to get the last one
|
||||||
while (fgets(buffer, sizeof(buffer), file) != NULL) {
|
while (fgets(buffer, sizeof(buffer), file) != NULL) {
|
||||||
@@ -331,7 +361,8 @@ void appendToFile(const char *path, const char *string, const int shouldDebug) {
|
|||||||
void sanitize(char *string) {
|
void sanitize(char *string) {
|
||||||
size_t stringLenght = strlen(string);
|
size_t stringLenght = strlen(string);
|
||||||
for (size_t i = 0; i < stringLenght; i++) {
|
for (size_t i = 0; i < stringLenght; i++) {
|
||||||
if ((!isalnum((unsigned char)string[i]) && strchr("~/\\:*?\"\'|!$[]{}<>\n\r\t", string[i]))) { // replace unwanted chars by '_'
|
if ((!isalnum((unsigned char)string[i]) &&
|
||||||
|
strchr("~/\\:*?\"\'|!$[]{}<>\n\r\t", string[i]))) { // replace unwanted chars by '_'
|
||||||
string[i] = '_';
|
string[i] = '_';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -351,11 +382,14 @@ int unlink_cb(const char *filePath, const struct stat *sb, int typeflag, struct
|
|||||||
(void)typeflag;
|
(void)typeflag;
|
||||||
(void)ftwbuf;
|
(void)ftwbuf;
|
||||||
|
|
||||||
int shouldDebug = 1; //normally shouldDebug should be passed to the function. However, it's to difficult here and the best it to set it to 1.
|
int shouldDebug = 1; // normally shouldDebug should be passed to the function. However, it's to
|
||||||
|
// difficult here and the best it to set it to 1.
|
||||||
|
|
||||||
// some sanity checks to be sure that we don't delete something we shouldn't
|
// some sanity checks to be sure that we don't delete something we shouldn't
|
||||||
error(strcmp(filePath, "") == 0, "program", "filePath is empty. Refusing to delete directory");
|
error(strcmp(filePath, "") == 0, "program", "filePath is empty. Refusing to delete directory");
|
||||||
error(filePath[0] == '.', "program", "%s starts with \".\". For security reasons, use absolute path and not relative path.", filePath);
|
error(filePath[0] == '.', "program",
|
||||||
|
"%s starts with \".\". For security reasons, use absolute path and not relative path.",
|
||||||
|
filePath);
|
||||||
|
|
||||||
int rv = remove(filePath);
|
int rv = remove(filePath);
|
||||||
error(rv, "program", "remove() failed to delete %s", filePath);
|
error(rv, "program", "remove() failed to delete %s", filePath);
|
||||||
@@ -367,16 +401,16 @@ int rmrf(char *path, int shouldDebug) {
|
|||||||
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
|
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
int openEditor(char *path, char *editor, int render, int shouldJumpToEndOfFile, int shouldDebug) {
|
int openEditor(char *path, char *editor, int render, int shouldJumpToEndOfFile, int shouldDebug) {
|
||||||
|
|
||||||
// this ensures that ncurses won't affect the editor behaviour
|
// this ensures that ncurses won't affect the editor behaviour
|
||||||
pid_t editor_pid = fork();
|
pid_t editor_pid = fork();
|
||||||
error(editor_pid < 0, "program", "fork() failed.");
|
error(editor_pid < 0, "program", "fork() failed.");
|
||||||
|
|
||||||
// instead of reusing part of the codes, for any new editor copy an example and adapt it. This is in case we need a custom fix for an editor.
|
// instead of reusing part of the codes, for any new editor copy an example and adapt it. This
|
||||||
|
// is in case we need a custom fix for an editor.
|
||||||
|
|
||||||
if (editor_pid == 0) {
|
if (editor_pid == 0) {
|
||||||
// =========================
|
// =========================
|
||||||
// CHILD: launch editor
|
// CHILD: launch editor
|
||||||
// =========================
|
// =========================
|
||||||
@@ -442,14 +476,12 @@ if (editor_pid == 0) {
|
|||||||
if (viv_pid == 0) {
|
if (viv_pid == 0) {
|
||||||
// GRANDCHILD → viv
|
// GRANDCHILD → viv
|
||||||
|
|
||||||
|
|
||||||
char viv_path[PATH_MAX];
|
char viv_path[PATH_MAX];
|
||||||
strncpy(viv_path, path, PATH_MAX - 1);
|
strncpy(viv_path, path, PATH_MAX - 1);
|
||||||
viv_path[PATH_MAX - 1] = '\0';
|
viv_path[PATH_MAX - 1] = '\0';
|
||||||
|
|
||||||
if (shouldJumpToEndOfFile) {
|
if (shouldJumpToEndOfFile) {
|
||||||
strncat(viv_path, ":99999",
|
strncat(viv_path, ":99999", PATH_MAX - strlen(viv_path) - 1);
|
||||||
PATH_MAX - strlen(viv_path) - 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("Running viv %s", viv_path);
|
debug("Running viv %s", viv_path);
|
||||||
@@ -481,14 +513,12 @@ if (editor_pid == 0) {
|
|||||||
if (viv_pid == 0) {
|
if (viv_pid == 0) {
|
||||||
// GRANDCHILD → viv
|
// GRANDCHILD → viv
|
||||||
|
|
||||||
|
|
||||||
char viv_path[PATH_MAX];
|
char viv_path[PATH_MAX];
|
||||||
strncpy(viv_path, path, PATH_MAX - 1);
|
strncpy(viv_path, path, PATH_MAX - 1);
|
||||||
viv_path[PATH_MAX - 1] = '\0';
|
viv_path[PATH_MAX - 1] = '\0';
|
||||||
|
|
||||||
if (shouldJumpToEndOfFile) {
|
if (shouldJumpToEndOfFile) {
|
||||||
strncat(viv_path, ":99999",
|
strncat(viv_path, ":99999", PATH_MAX - strlen(viv_path) - 1);
|
||||||
PATH_MAX - strlen(viv_path) - 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("Running viv %s", viv_path);
|
debug("Running viv %s", viv_path);
|
||||||
@@ -522,14 +552,12 @@ if (editor_pid == 0) {
|
|||||||
if (viv_pid == 0) {
|
if (viv_pid == 0) {
|
||||||
// GRANDCHILD → viv
|
// GRANDCHILD → viv
|
||||||
|
|
||||||
|
|
||||||
char viv_path[PATH_MAX];
|
char viv_path[PATH_MAX];
|
||||||
strncpy(viv_path, path, PATH_MAX - 1);
|
strncpy(viv_path, path, PATH_MAX - 1);
|
||||||
viv_path[PATH_MAX - 1] = '\0';
|
viv_path[PATH_MAX - 1] = '\0';
|
||||||
|
|
||||||
if (shouldJumpToEndOfFile) {
|
if (shouldJumpToEndOfFile) {
|
||||||
strncat(viv_path, ":99999",
|
strncat(viv_path, ":99999", PATH_MAX - strlen(viv_path) - 1);
|
||||||
PATH_MAX - strlen(viv_path) - 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("Running viv %s", viv_path);
|
debug("Running viv %s", viv_path);
|
||||||
@@ -561,14 +589,12 @@ if (editor_pid == 0) {
|
|||||||
if (viv_pid == 0) {
|
if (viv_pid == 0) {
|
||||||
// GRANDCHILD → viv
|
// GRANDCHILD → viv
|
||||||
|
|
||||||
|
|
||||||
char viv_path[PATH_MAX];
|
char viv_path[PATH_MAX];
|
||||||
strncpy(viv_path, path, PATH_MAX - 1);
|
strncpy(viv_path, path, PATH_MAX - 1);
|
||||||
viv_path[PATH_MAX - 1] = '\0';
|
viv_path[PATH_MAX - 1] = '\0';
|
||||||
|
|
||||||
if (shouldJumpToEndOfFile) {
|
if (shouldJumpToEndOfFile) {
|
||||||
strncat(viv_path, ":99999",
|
strncat(viv_path, ":99999", PATH_MAX - strlen(viv_path) - 1);
|
||||||
PATH_MAX - strlen(viv_path) - 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("Running viv %s", viv_path);
|
debug("Running viv %s", viv_path);
|
||||||
@@ -600,14 +626,12 @@ if (editor_pid == 0) {
|
|||||||
if (viv_pid == 0) {
|
if (viv_pid == 0) {
|
||||||
// GRANDCHILD → viv
|
// GRANDCHILD → viv
|
||||||
|
|
||||||
|
|
||||||
char viv_path[PATH_MAX];
|
char viv_path[PATH_MAX];
|
||||||
strncpy(viv_path, path, PATH_MAX - 1);
|
strncpy(viv_path, path, PATH_MAX - 1);
|
||||||
viv_path[PATH_MAX - 1] = '\0';
|
viv_path[PATH_MAX - 1] = '\0';
|
||||||
|
|
||||||
if (shouldJumpToEndOfFile) {
|
if (shouldJumpToEndOfFile) {
|
||||||
strncat(viv_path, ":99999",
|
strncat(viv_path, ":99999", PATH_MAX - strlen(viv_path) - 1);
|
||||||
PATH_MAX - strlen(viv_path) - 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("Running viv %s", viv_path);
|
debug("Running viv %s", viv_path);
|
||||||
@@ -637,7 +661,9 @@ if (editor_pid == 0) {
|
|||||||
// PARENT: wait ONLY editor
|
// PARENT: wait ONLY editor
|
||||||
// =========================
|
// =========================
|
||||||
int status;
|
int status;
|
||||||
while (waitpid(editor_pid, &status, 0) == -1) { // we can't just use waitpid(). Because when resizing the terminal, waitpid() is returned so we loop to see if there is not a problem
|
while (waitpid(editor_pid, &status, 0) ==
|
||||||
|
-1) { // we can't just use waitpid(). Because when resizing the terminal, waitpid() is
|
||||||
|
// returned so we loop to see if there is not a problem
|
||||||
if (errno != EINTR) {
|
if (errno != EINTR) {
|
||||||
perror("waitpid");
|
perror("waitpid");
|
||||||
break;
|
break;
|
||||||
|
|||||||
+31
-28
@@ -1,60 +1,60 @@
|
|||||||
#ifndef UTILS_H
|
#ifndef UTILS_H
|
||||||
#define UTILS_H
|
#define UTILS_H
|
||||||
|
|
||||||
|
#include <cjson/cJSON.h>
|
||||||
|
#include <ctype.h>
|
||||||
|
#include <dirent.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <ftw.h>
|
||||||
|
#include <limits.h>
|
||||||
|
#include <ncurses.h>
|
||||||
|
#include <pwd.h>
|
||||||
|
#include <regex.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <dirent.h>
|
|
||||||
#include <sys/stat.h>
|
#include <sys/stat.h>
|
||||||
#include <unistd.h>
|
|
||||||
#include <ftw.h>
|
|
||||||
#include <pwd.h>
|
|
||||||
#include <ncurses.h>
|
|
||||||
#include <ctype.h>
|
|
||||||
#include <sys/wait.h>
|
#include <sys/wait.h>
|
||||||
#include <limits.h>
|
|
||||||
#include <cjson/cJSON.h>
|
|
||||||
#include <regex.h>
|
|
||||||
#include <errno.h>
|
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include <ftw.h>
|
#include <unistd.h>
|
||||||
#ifndef VERSION
|
#ifndef VERSION
|
||||||
#define VERSION "dev"
|
#define VERSION "dev"
|
||||||
#endif
|
#endif
|
||||||
#define BUFFER_SIZE 256 //standard buffer size.
|
#define BUFFER_SIZE 256 // standard buffer size.
|
||||||
// the three supported values are "daily" "weekly" and "monthly" (for months we use the avarage lenght of a month in a non leap year). All values were calculated on my loyal TI-30 ECO RS
|
// the three supported values are "daily" "weekly" and "monthly" (for months we use the avarage
|
||||||
|
// lenght of a month in a non leap year). All values were calculated on my loyal TI-30 ECO RS
|
||||||
#define DAILY 86400
|
#define DAILY 86400
|
||||||
#define WEEKLY 604800
|
#define WEEKLY 604800
|
||||||
#define MONTHLY 2628000 // calculated from the average lenght of a non leap year
|
#define MONTHLY 2628000 // calculated from the average lenght of a non leap year
|
||||||
#define debug(message, ...) \
|
#define debug(message, ...) \
|
||||||
_debug(shouldDebug, __FILE__, __LINE__, __func__, message, ##__VA_ARGS__)
|
_debug(shouldDebug, __FILE__, __LINE__, __func__, message, ##__VA_ARGS__)
|
||||||
#define altDebug(message, ...) \
|
#define altDebug(message, ...) _altDebug(shouldDebug, message, ##__VA_ARGS__)
|
||||||
_altDebug(shouldDebug, message, ##__VA_ARGS__)
|
|
||||||
#define error(condition, type, message, ...) \
|
#define error(condition, type, message, ...) \
|
||||||
_error(shouldDebug, condition, type, __FILE__, __LINE__, __func__, message, ##__VA_ARGS__)
|
_error(shouldDebug, condition, type, __FILE__, __LINE__, __func__, message, ##__VA_ARGS__)
|
||||||
// you must edit this two values if you want to add suport for an editor
|
// you must edit this two values if you want to add suport for an editor
|
||||||
extern const char *supportedEditor[]; // array of supported editors
|
extern const char *supportedEditor[]; // array of supported editors
|
||||||
extern const int numEditors; // number of supported editors
|
extern const int numEditors; // number of supported editors
|
||||||
|
|
||||||
|
// compares two strings alphabetically.
|
||||||
//compares two strings alphabetically.
|
// this function is used for qsort
|
||||||
//this function is used for qsort
|
|
||||||
int compareString(const void *a, const void *b);
|
int compareString(const void *a, const void *b);
|
||||||
// compares two strings in reversed alphabetical order
|
// compares two strings in reversed alphabetical order
|
||||||
// this function is used for qsort
|
// this function is used for qsort
|
||||||
int reverseCompareString(const void *a, const void *b);
|
int reverseCompareString(const void *a, const void *b);
|
||||||
// checks if editor is supported and if it installed.
|
// checks if editor is supported and if it installed.
|
||||||
// this basically checks all the dirs from your path for the editor. This is a safety check.
|
// this basically checks all the dirs from your path for the editor. This is a safety check.
|
||||||
// If the executable from an editor is not the editor name (for example neovim and nvim), you must handle at the start of the function.
|
// If the executable from an editor is not the editor name (for example neovim and nvim), you must
|
||||||
// This can return an error and stop the program.
|
// handle at the start of the function. This can return an error and stop the program.
|
||||||
int isEditorValid(char *editorToCheck, int useDefaultEditor, int debug);
|
int isEditorValid(char *editorToCheck, int useDefaultEditor, int debug);
|
||||||
// please use the macro debug instead of _debug.
|
// please use the macro debug instead of _debug.
|
||||||
//formated debugging.
|
// formated debugging.
|
||||||
void _debug(const int d, const char *file, const int line, const char *function, const char *message, ...);
|
void _debug(const int d, const char *file, const int line, const char *function,
|
||||||
//use for less formal debuggin. (usefull if enumerating or making a list).
|
const char *message, ...);
|
||||||
|
// use for less formal debuggin. (usefull if enumerating or making a list).
|
||||||
void _altDebug(const int d, const char *message, ...);
|
void _altDebug(const int d, const char *message, ...);
|
||||||
// formated error.
|
// formated error.
|
||||||
void _error(const int shouldDebug, const int condition, const char *type, const char *file, const int line, const char *function, const char *message, ...);
|
void _error(const int shouldDebug, const int condition, const char *type, const char *file,
|
||||||
|
const int line, const char *function, const char *message, ...);
|
||||||
// Returns 1 if the string is in the array.
|
// Returns 1 if the string is in the array.
|
||||||
// Returns 0 if the string is not in the array.
|
// Returns 0 if the string is not in the array.
|
||||||
// If you want to only check the first n elements of the array, pass n as len.
|
// If you want to only check the first n elements of the array, pass n as len.
|
||||||
@@ -68,8 +68,8 @@ void appendToFile(const char *path, const char *string, const int shouldDebug);
|
|||||||
// replace unwanted chars by '_'.
|
// replace unwanted chars by '_'.
|
||||||
// '.' is replaced if it is only the first two chars
|
// '.' is replaced if it is only the first two chars
|
||||||
void sanitize(char *string);
|
void sanitize(char *string);
|
||||||
//from https://stackoverflow.com/a/5467788.
|
// from https://stackoverflow.com/a/5467788.
|
||||||
//deletes an entire directory. Use with parsimony and carefullness.
|
// deletes an entire directory. Use with parsimony and carefullness.
|
||||||
int rmrf(char *path, int shouldDebug);
|
int rmrf(char *path, int shouldDebug);
|
||||||
// Inputs are the path to the file, the editor to open and some rendering option.
|
// Inputs are the path to the file, the editor to open and some rendering option.
|
||||||
// render: if we render the .md file with Vivify.
|
// render: if we render the .md file with Vivify.
|
||||||
@@ -84,6 +84,9 @@ char *getFormatedTime(char *format, int shouldDebug);
|
|||||||
If need launches in the background rsync to do the backuping.
|
If need launches in the background rsync to do the backuping.
|
||||||
Each pair of source/destination will launch one rsync process.
|
Each pair of source/destination will launch one rsync process.
|
||||||
If a pair don't need to be backed up, the destination should be set to NULL.
|
If a pair don't need to be backed up, the destination should be set to NULL.
|
||||||
rsyncArgs is the array of arguments to be passed to rsync. Do not inclue destination or source. It will be added in the function.*/
|
rsyncArgs is the array of arguments to be passed to rsync. Do not inclue destination or source. It
|
||||||
void handleBackups(char **sourceDirectoryArray, const int sourceDirectoryNumber, char **destinationDirectoryArray, const char *homeDir, const int interval, const char **rsyncArgs, const int rsyncArgsNumber, const int shouldDebug);
|
will be added in the function.*/
|
||||||
|
void handleBackups(char **sourceDirectoryArray, const int sourceDirectoryNumber,
|
||||||
|
char **destinationDirectoryArray, const char *homeDir, const int interval,
|
||||||
|
const char **rsyncArgs, const int rsyncArgsNumber, const int shouldDebug);
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
Reference in New Issue
Block a user