summaryrefslogtreecommitdiff
path: root/src/edit.c
blob: 93ad44fc760d0c92641d0a45a715f2f001a6f273 (plain)
    1  /**
    2   * Journal-tools provides simple tools for keeping journal entries
    3   * Copyright (C) 2023  Aaron Ball, nullspoon@oper.io
    4   *
    5   * This program is free software: you can redistribute it and/or modify
    6   * it under the terms of the GNU General Public License as published by
    7   * the Free Software Foundation, either version 3 of the License, or
    8   * (at your option) any later version.
    9   *
   10   * This program is distributed in the hope that it will be useful,
   11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   13   * GNU General Public License for more details.
   14   *
   15   * You should have received a copy of the GNU General Public License
   16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
   17   */
   18 #include "edit.h"
   19 
   20 // A sloppy copy function
   21 int _cp(char* src, char* dest) {
   22   FILE* fdsrc = NULL;
   23   FILE* fddest = NULL;
   24   unsigned int buf = 0;
   25 
   26   fdsrc = fopen(src, "r");
   27   if(!fdsrc) {
   28     fprintf(stderr, "Could not open %s for reading\n", src);
   29     return -1;
   30   }
   31 
   32   fddest = fopen(dest, "w");
   33   if(!fddest) {
   34     fprintf(stderr, "Could not open %s for writing\n", dest);
   35     return -1;
   36   }
   37 
   38   while((buf = fgetc(fdsrc)) != EOF)
   39     fputc(buf, fddest);
   40 
   41   fclose(fdsrc);
   42   fclose(fddest);
   43   return 0;
   44 }
   45 
   46 int edit_exec(char* dir, char* file, char* ext) {
   47   char* editor = "vim";
   48   char templatebuf[512] = {0};
   49   char filebuf[512] = {0};
   50   char cmdbuf[1024] = {0};
   51 
   52   if(getenv("EDITOR") != NULL)
   53     editor = getenv("EDITOR");
   54 
   55   // Populate path and template buffers
   56   snprintf(filebuf, 512, "%s/%s.%s", dir, file, ext);
   57   snprintf(templatebuf, 512, "%s/.template.%s", dir, ext);
   58 
   59   // If a template file is found, copy it to the new path before editing
   60   // Only do this is the target file doesn't yet exist. No overwrite.
   61   if(access(templatebuf, R_OK) == 0 && access(filebuf, R_OK) != 0)
   62     if(_cp(templatebuf, filebuf) != 0)
   63       exit(1);
   64 
   65   // Construct the command and execute
   66   sprintf(cmdbuf, "%s %s", editor, filebuf);
   67   return system(cmdbuf);
   68 }

Generated by cgit