Auto-delete output file on error

This commit is contained in:
Wilson Lin 2018-07-06 13:47:54 +12:00
parent cabf7c4e02
commit 9037789510
2 changed files with 24 additions and 3 deletions

View File

@ -1,9 +1,11 @@
#ifndef _HDR_HYPERBUILD_ERROR
#define _HDR_HYPERBUILD_ERROR
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
typedef enum hbe_errcode {
HBE_INTERR_PEEK_OFFSET_GEQ_ZERO = 1,
@ -25,6 +27,12 @@ typedef enum hbe_errcode {
HBE_PARSE_EXPECTED_NOT_FOUND,
} hbe_errcode_t;
static char *hbe_fatal_autodelete_file = NULL;
void hbe_fatal_set_autodelete(char *path) {
hbe_fatal_autodelete_file = path;
}
void hbe_debug(char *fmt, ...) {
va_list args;
va_start(args, fmt);
@ -51,6 +59,14 @@ void hbe_fatal(hbe_errcode_t errcode, char *fmt, ...) {
fprintf(stderr, "\n");
va_end(args);
if (hbe_fatal_autodelete_file != NULL) {
if (unlink(hbe_fatal_autodelete_file)) {
hbe_warn("Failed to delete file %s with error %d", hbe_fatal_autodelete_file, errno);
} else {
hbe_debug("%s has been deleted", hbe_fatal_autodelete_file);
}
}
// NOTE: $errcode must be less than 256 (see man exit(3))
exit(errcode);
}

View File

@ -17,11 +17,11 @@ int main(int argc, char **argv) {
// Set up rules
hb_r_init();
// Prepare config
char *input_path = NULL;
char *output_path = NULL;
int c;
// Parse arguments
while (1) {
static struct option long_options[] = {
{"input", required_argument, NULL, 'i'},
@ -30,7 +30,7 @@ int main(int argc, char **argv) {
};
int option_index = 0;
c = getopt_long(argc, argv, "i:o:", long_options, &option_index);
int c = getopt_long(argc, argv, "i:o:", long_options, &option_index);
if (c == -1) {
break;
@ -53,6 +53,11 @@ int main(int argc, char **argv) {
hbu_fstreamin_t input = hbu_fstreamin_create(input_path);
hbu_fstreamout_t output = hbu_fstreamout_create(output_path);
if (output != NULL) {
// Set after opening output stream (file is created then)
hbe_fatal_set_autodelete(output_path);
}
hbu_pipe_t pipe = hbu_pipe_create_blank();
hbu_pipe_blank_set_input(pipe, input);
hbu_pipe_blank_set_output_fstreamout(pipe, output);