qments/examples/main.c

110 lines
2.8 KiB
C

/* Reads text from stdio and creates comment using unix fs driver in current directory */
/* TODO: add path, displayname as arguments */
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include "comment.h"
#include "driver.h"
#include "drivers/unix_fs/unix_fs_driver.h"
char *
get_username()
{
uid_t uid = geteuid();
struct passwd *pw = getpwuid(uid);
if (pw) {
return pw->pw_name;
}
return "";
}
void usage() {
fprintf(stderr, "Simple utility to leave comment using unix_fs_driver\n");
fprintf(stderr, "usage: <tool-name> [-p path] [-r reply_id] [-d displayname] [-i input_file]");
fprintf(stderr, "-p path:\t path to comment storage \n");
fprintf(stderr, "-r reply_id:\t ID of comment you are replying to, 0 if yours is top-level\n");
fprintf(stderr, "-d displayname:\t Displayname to attach to comment\n");
fprintf(stderr, "-i input_file:\t File containing comment text(defaults to stdin)\n");
}
int
main(int argc, char *argv[])
{
const Driver *driver = &unix_fs_driver;
char *path = ".";
char *user_sid = get_username();
char *user_displayname = user_sid;
char *text_filename = NULL;
int reply_id = 0;
int opt;
while ((opt = getopt(argc, argv, "p:d:r:i:")) != -1) {
switch (opt) {
case 'p':
path = optarg;
break;
case 'd':
user_displayname = optarg;
break;
case 'r':
reply_id = strtol(optarg, NULL, 10);
if (reply_id < 0) {
fprintf(stderr, "error: reply id can't be less than 0\n");
usage();
exit(EXIT_FAILURE);
}
break;
case 'i':
text_filename = optarg;
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
size_t cur_buf_size = 256;
size_t idx = 0;
char *text = malloc(cur_buf_size);
FILE *input_stream = (text_filename ? fopen(text_filename, "r") : stdin);
if (input_stream == NULL) {
fprintf(stderr, "error: cannot open input file\n");
perror("fopen");
exit(EXIT_FAILURE);
}
int ch;
while ((ch = getchar()) != EOF) {
if (idx + 1 == cur_buf_size) {
cur_buf_size *= 2;
text = realloc(text, cur_buf_size);
}
text[idx++] = ch;
}
text[idx] = '\0';
time_t current_time;
time(&current_time);
UnixFsDriverData driver_data = { path };
CommentHeader *header = mk_comment_header(reply_id, current_time, strlen(text), user_sid, user_displayname);
int retval = driver->leave_comment(&driver_data, header, text);
free(text);
if (retval < 0) {
return retval;
} else {
return 0;
}
}