From 7cc8951c6929506d415d90ad29e30a5842b821d0 Mon Sep 17 00:00:00 2001
From: Kir_Antipov <kp.antipov@gmail.com>
Date: Wed, 22 Sep 2021 19:28:22 +0300
Subject: [PATCH] Made `getInputAsObject` method that transforms action inputs
 into an object

---
 src/utils/input-utils.ts | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
 create mode 100644 src/utils/input-utils.ts

diff --git a/src/utils/input-utils.ts b/src/utils/input-utils.ts
new file mode 100644
index 0000000..f3df1ae
--- /dev/null
+++ b/src/utils/input-utils.ts
@@ -0,0 +1,28 @@
+import process from "process";
+
+// eslint-disable-next-line @typescript-eslint/no-empty-interface
+interface InputObject extends Record<string, string | InputObject> { }
+
+export function getInputAsObject(): Record<string, InputObject> {
+    const inputs = Object.entries(process.env).filter(([key, _]) => key.startsWith("INPUT_"));
+    const input = {};
+    for (const [name, value] of inputs) {
+        const words = name.substring(6).toLowerCase().split(/[\W_]/).filter(x => x);
+        init(input, words, value);
+    }
+    return input;
+}
+
+function init(root: InputObject, path: string[], value: string): void {
+    const name = path.reduce((a, b, i) => a + (i === 0 ? b : (b.substring(0, 1).toUpperCase() + b.substring(1))), "");
+    root[name] = value;
+    if (path.length === 1) {
+        return;
+    }
+
+    const innerPath = path[0];
+    const inner = root[innerPath] ? root[innerPath] : (root[innerPath] = {});
+    if (typeof inner === "object") {
+        init(inner, path.slice(1), value);
+    }
+}