#include <stdio.h>
#include <string.h>
#include "oscore.h"
int help()
{
printf("GitIgnore-Adder\n"
"Adds entries to the .gitignore of a Git repository.\n"
"Usage: ./git-ign <entry1> <entry2> ...\n"
"Example: ./git-ign build/ temp.log\n"
"-h shows this help.\n\n"
"More Infos are here:\n"
"https://samengine.vercel.app/r/p/ign\n"
"https://samengine.js.org/r/p/ign\n"
"https://github.com/shadowdara/samengine#ign"
);
return 0;
}
int file_exists(const char *filename)
{
FILE *file = fopen(filename, "r");
if (file)
{
fclose(file);
return 1;
}
return 0;
}
void normalize_path(char *path)
{
for (int i = 0; path[i]; i++) {
if (path[i] == '\\') {
path[i] = '/';
}
}
}
int make_relative(const char *base, const char *full, char *out, int out_len)
{
size_t base_len = strlen(base);
if (strncmp(base, full, base_len) != 0) {
return 0;
}
const char *relative = full + base_len;
if (*relative == PATH_SEPARATOR[0]) {
relative++;
}
snprintf(out, out_len, "%s", relative);
return 1;
}
int find_git_root(char *found_path, int maxlen) {
char *cwd = get_current_path();
if (!cwd) return 0;
while (1) {
char git_path[PATH_MAX_LEN];
snprintf(git_path, PATH_MAX_LEN, "%s%s.git", cwd, PATH_SEPARATOR);
if (is_directory(git_path)) {
strncpy(found_path, cwd, maxlen);
free(cwd);
return 1;
}
char *last_sep = strrchr(cwd, PATH_SEPARATOR[0]);
if (!last_sep || last_sep == cwd) break;
*last_sep = '\0';
}
free(cwd);
return 0;
}
int app_main(int argc, char *argv[])
{
if (argc < 2) {
printf("Please run with at least one argument or -h.\n");
return 1;
}
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) {
return help();
}
char *cwd = get_current_path();
normalize_path(cwd);
char git_root[PATH_MAX_LEN] = {0};
if (!find_git_root(git_root, PATH_MAX_LEN)) {
printf("No .git folder found in the current or any parent directory.\n");
return 1;
}
normalize_path(git_root);
char relative[PATH_MAX_LEN] = {0};
if (!make_relative(git_root, cwd, relative, sizeof(relative))) {
printf("Failed to compute relative path.\n");
free(cwd);
return 1;
}
normalize_path(relative);
char gitignore_path[PATH_MAX_LEN];
snprintf(gitignore_path, PATH_MAX_LEN, "%s%s.gitignore", git_root, PATH_SEPARATOR);
if (!file_exists(gitignore_path)) {
FILE *file = fopen(gitignore_path, "w");
if (!file) {
perror("Error creating .gitignore file");
return 1;
}
fclose(file);
printf(".gitignore was created in directory: %s\n", git_root);
} else {
printf(".gitignore found in directory: %s\n", git_root);
}
FILE *file = fopen(gitignore_path, "a");
if (!file) {
perror("Error opening .gitignore file for appending");
return 1;
}
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--help") == 0) continue;
char entry[PATH_MAX_LEN];
snprintf(entry, sizeof(entry), "%s/%s", relative, argv[i]);
normalize_path(entry);
if (strlen(relative) > 0) {
fprintf(file, "%s\n", entry);
} else {
fprintf(file, "%s\n", argv[i]);
}
printf("%s added to .gitignore.\n",
strlen(relative) > 0 ? entry : argv[i]);
}
fclose(file);
return 0;
}