summaryrefslogtreecommitdiff
path: root/src/config.c
blob: 111a8b4544133d0fcdd75dcb9dd83c60c050ddb3 (plain)
    1 /**
    2  * A class to help with parsing standard config files
    3  *
    4  * Copyright (C) 2021 Aaron Ball <nullspoon@oper.io>
    5  *
    6  * Noteless is free software: you can redistribute it and/or modify
    7  * it under the terms of the GNU General Public License as published by
    8  * the Free Software Foundation, either version 3 of the License, or
    9  * (at your option) any later version.
   10  *
   11  * Noteless is distributed in the hope that it will be useful,
   12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   14  * GNU General Public License for more details.
   15  *
   16  * You should have received a copy of the GNU General Public License
   17  * along with noteless.  If not, see <http://www.gnu.org/licenses/>.
   18  */
   19 #include "config.h"
   20 
   21 void config_init(struct config *c) {
   22   c->extension[0] = 0;
   23   c->editor[0]    = 0;
   24   c->notepath[0]  = 0;
   25 }
   26 
   27 int config_read(struct config* c, char* path) {
   28   char linebuf[1024] = {0};
   29   char keybuf[1024] = {0};
   30   FILE* fd;
   31 
   32   fd = fopen(path, "r");
   33   if(!fd)
   34     return -2;
   35 
   36   while(fgets(linebuf, 1024, fd) != NULL) {
   37     if(linebuf[0] == '#')
   38       continue;
   39 
   40     if(config_linekey(linebuf, keybuf) == 1) {
   41       if(strcmp(keybuf, "extension") == 0) {
   42         strcpy(c->extension, config_lineval(linebuf));
   43       } else if(strcmp(keybuf, "path") == 0) {
   44         strcpy(c->notepath, config_lineval(linebuf));
   45       } else if(strcmp(keybuf, "editor") == 0) {
   46         strcpy(c->editor, config_lineval(linebuf));
   47       }
   48     }
   49   } 
   50   return 1;
   51 }
   52 
   53 int config_linekey(char* line, char* outbuf) {
   54   char* keyend = strchr(line, ' ');
   55   if(!keyend)
   56     return -1;
   57   strncpy(outbuf, line, keyend - line);
   58   outbuf[keyend - line] = '\0';
   59   return 1;
   60 }
   61 
   62 char* config_lineval(char* line) {
   63   char* start = strstr(line, " ");
   64 
   65   while(start[0] == ' ') {
   66     start++;
   67   }
   68   // If we hit the end of the line, no value was specified
   69   if(start[0] == '\0' || start[0] == '\n')
   70     return NULL;
   71   return trim(start);
   72 }

Generated by cgit