about summary refs log tree commit diff stats
path: root/c/src/main.c
blob: 1b9afcd28ff4dd44d767f01b37d26297ebe329fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <assert.h>
#include <stdio.h>
#include <sys/types.h>

#include <stdlib.h>

#include <readline/readline.h>
#include <readline/rlconf.h>

#include <libgen.h>
#include <stdbool.h>
#include <unistd.h>

#include "rename.h"

bool file_exists(const char *filename) { return (access(filename, F_OK) == 0); }

char *update_file_name(char *old_file_name, FILE *newin) {
  fprintf(newin, "%s", old_file_name);

  char *new_file_name = readline("New name: ");

  return new_file_name;
}

bool ask_for_confirmation(char *prompt) {
  bool return_value = false;
  char *confirmation = readline(prompt);

  if (strcmp(confirmation, "y") == 0)
    return_value = true;

  free(confirmation);
  return return_value;
}

int main() {
  const char *newin_name = tempnam(NULL, NULL);
  FILE *newin = fopen(newin_name, "w");
  if (!newin)
    perror("Failed to create tempfile");
  FILE *_ = freopen(newin_name, "r", stdin);

  char *old_file_name = getenv("f");
  old_file_name = basename(old_file_name);
  char *new_file_name = (char *)NULL;
  char *current_file_name = (char *)malloc(sizeof(char) * 255);
  const char *original_file_name = getenv("f");

  int done = false;

  while (!done) {
    if (old_file_name) {
      new_file_name = update_file_name(old_file_name, newin);
      old_file_name = (char *)NULL;
    } else {
      new_file_name = update_file_name(current_file_name, newin);
    }
    if (file_exists(new_file_name)) {
      char *prompt = malloc(sizeof(char) * (255 + 43));
      snprintf(prompt, 43 + 255,
               "Name (`%s`) already exists, overwrite [y|N]: ", new_file_name);
      if (ask_for_confirmation(prompt))
        done = true;
      free(prompt);
    } else if (new_file_name[0] == '\0') {
      /* new_file_name is emtpy */
      if (ask_for_confirmation("Name is empty, accept nevertheless [y|N]: "))
        done = true;
    } else {
      done = true;
    }
    if (!done) {
      strcpy(current_file_name, new_file_name);
      free(new_file_name);
      new_file_name = (char *)NULL;
    }
  }

  // rename old file with new name
  if (rename(original_file_name, new_file_name) == 0) {
    printf("File renamed successfully.\n");
  } else {
    perror("Unable to rename files. Please check files exist and you have "
           "permissions to modify files");
  }
  free(new_file_name);
}