File size: 1,658 Bytes
b39afbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Copyright (c) 2023 MERCENARIES.AI PTE. LTD.
 * All rights reserved.
 */

//@ts-check

import { Utils } from 'omni-shared';
import fs from 'fs/promises';
import path from 'path';

// @ts-ignore
async function fetchJsonFromUrl(url) {
  const json = await Utils.fetchJSON(url);
  return json;
}

// @ts-ignore
async function walkDirForExtension(filePaths, directory_path, extension) {
  const files = await fs.readdir(directory_path);
  for (const file of files) {
    const filepath = path.join(directory_path, file);
    const stats = await fs.stat(filepath);

    if (stats.isDirectory()) {
      filePaths = await walkDirForExtension(filePaths, filepath, extension);
    } else {
      if (path.extname(filepath) === extension) {
        filePaths.push(filepath);
      }
    }
  }

  return filePaths;
}

// @ts-ignore
async function readJsonFromDisk(jsonPath) {
  const jsonContent = JSON.parse(await fs.readFile(jsonPath, 'utf8'));
  return jsonContent;
}

// Function to validate directory existence
// @ts-ignore
async function validateDirectoryExists(path) {
  try {
    const stats = await fs.stat(path);
    return stats.isDirectory(); // Returns true if directory exists
  } catch {
    return false; // Returns false if directory doesn't exist
  }
}

// Function to validate file existence
// @ts-ignore
async function validateFileExists(path) {
  try {
    const stats = await fs.stat(path);
    return stats.isFile(); // Returns true if file exists
  } catch {
    return false; // Returns false if file doesn't exist
  }
}

export { walkDirForExtension, validateDirectoryExists, validateFileExists, readJsonFromDisk, fetchJsonFromUrl };