From 63c2201dabd3e65779233c18bea3a7bb922a8b3e Mon Sep 17 00:00:00 2001
From: "tanguy.cavagna" <tanguy.cavagna@etu.hesge.ch>
Date: Mon, 27 Jun 2022 15:13:31 +0200
Subject: [PATCH] Added argument parser

---
 main.c          | 30 +++++++++++++++++++++++++++---
 parser/parser.c |  7 ++++++-
 parser/parser.h |  3 ++-
 3 files changed, 35 insertions(+), 5 deletions(-)

diff --git a/main.c b/main.c
index 6023e7a..ab9e9bc 100644
--- a/main.c
+++ b/main.c
@@ -1,15 +1,39 @@
 #include "parser/parser.h"
 #include "ultra-cp/ultra-cp.h"
-#include <ctype.h>
 #include <linux/limits.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <unistd.h>
 
 int main(int argc, char **argv) {
-    printf("aflag = %d\n", get_opt(argc, argv, "af"));
+    // Arguments parsing
+    int source_count = 0;
+    uint8_t opt = get_opt(argc, argv, "af", &source_count);
 
-    char source_path[PATH_MAX];
+    // Destination parsing
+    char *destination_path = argv[argc - 1];
+
+    // Source parsing
+    char **source_paths = malloc(source_count * sizeof(char *));
+    for (int i = 0; i < source_count; i++) {
+        source_paths[i] = malloc(PATH_MAX * sizeof(char));
+        strcpy(source_paths[i], argv[optind - source_count + i]);
+
+        // Trim ending slash if present
+        if (source_paths[i][strlen(source_paths[i]) - 1] == '/')
+            source_paths[i][strlen(source_paths[i]) - 1] = '\0';
+    }
+
+    // TODO: Copy files form sources to destination
+
+    // Free sources
+    for (int i = 0; i < source_count; i++)
+        free(source_paths[i]);
+    free(source_paths);
+
+    list_dir("/home/toguy/Documents/source");
 
     return EXIT_SUCCESS;
 }
diff --git a/parser/parser.c b/parser/parser.c
index 25b279d..9d0341d 100644
--- a/parser/parser.c
+++ b/parser/parser.c
@@ -1,8 +1,9 @@
 #include "parser.h"
 
-uint8_t get_opt(int argc, char **argv, char *args) {
+uint8_t get_opt(int argc, char **argv, char *args, int *source_count) {
     uint8_t opt = 0b00;
 
+    // Parse optional arguments
     int c;
     while ((c = getopt(argc, argv, args)) != -1) {
         switch (c) {
@@ -19,5 +20,9 @@ uint8_t get_opt(int argc, char **argv, char *args) {
         }
     }
 
+    // Arguments which was not parsed by getopt
+    for (; optind < argc - 1; optind++)
+        (*source_count)++;
+
     return opt;
 }
diff --git a/parser/parser.h b/parser/parser.h
index 01ca25a..41f4d1d 100644
--- a/parser/parser.h
+++ b/parser/parser.h
@@ -10,9 +10,10 @@
  * @param argc Arg count
  * @param argv Arg values
  * @param args Arg expected
+ * @param source_count Number of source files
  *
  * @returns Options
  */
-uint8_t get_opt(int argc, char **argv, char *args);
+uint8_t get_opt(int argc, char **argv, char *args, int *source_count);
 
 #endif // !PARSER_H_
-- 
GitLab