diff options
Diffstat (limited to 'src/edit.c')
-rw-r--r-- | src/edit.c | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/edit.c b/src/edit.c new file mode 100644 index 0000000..93ad44f --- /dev/null +++ b/src/edit.c @@ -0,0 +1,68 @@ + /** + * Journal-tools provides simple tools for keeping journal entries + * Copyright (C) 2023 Aaron Ball, nullspoon@oper.io + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +#include "edit.h" + +// A sloppy copy function +int _cp(char* src, char* dest) { + FILE* fdsrc = NULL; + FILE* fddest = NULL; + unsigned int buf = 0; + + fdsrc = fopen(src, "r"); + if(!fdsrc) { + fprintf(stderr, "Could not open %s for reading\n", src); + return -1; + } + + fddest = fopen(dest, "w"); + if(!fddest) { + fprintf(stderr, "Could not open %s for writing\n", dest); + return -1; + } + + while((buf = fgetc(fdsrc)) != EOF) + fputc(buf, fddest); + + fclose(fdsrc); + fclose(fddest); + return 0; +} + +int edit_exec(char* dir, char* file, char* ext) { + char* editor = "vim"; + char templatebuf[512] = {0}; + char filebuf[512] = {0}; + char cmdbuf[1024] = {0}; + + if(getenv("EDITOR") != NULL) + editor = getenv("EDITOR"); + + // Populate path and template buffers + snprintf(filebuf, 512, "%s/%s.%s", dir, file, ext); + snprintf(templatebuf, 512, "%s/.template.%s", dir, ext); + + // If a template file is found, copy it to the new path before editing + // Only do this is the target file doesn't yet exist. No overwrite. + if(access(templatebuf, R_OK) == 0 && access(filebuf, R_OK) != 0) + if(_cp(templatebuf, filebuf) != 0) + exit(1); + + // Construct the command and execute + sprintf(cmdbuf, "%s %s", editor, filebuf); + return system(cmdbuf); +} |