"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliPathWalker = void 0;
const fxs = require("fs");
const path = require("path");
const ops_constants_1 = require("./ops-constants");
/** Stateless utilities for awareness of significant paths
 * relative to the working directory of the process,
 * such as the project root, repo root, docker root, etc.
 */
class CliPathWalker {
    /** Determines whether the given path is the root folder of the drive/volume. */
    static isDriveRoot(fullyQualifiedPath) {
        return (path.resolve(fullyQualifiedPath, "../") == fullyQualifiedPath);
    }
    /** Gets the project root folder
     * that is in scope for the current working directory
     * or the given folder.
     * IMPORTANT: Throws by default when no Toyhauler config file exists up the parent folder chain.
     * @param folder (optional, defaults to current working directory) The folder containing the thaul config file, or any folder underneath that one.
     * @param errorWhenNotFound Setting to false will return an empty string if folder is not contained in a project root.
     */
    static getProjectRoot(folder, errorWhenNotFound = true) {
        if (!folder) {
            folder = process.cwd();
        }
        else if (!fxs.statSync(folder).isDirectory()) {
            folder = path.resolve(folder, './');
        }
        let priorFolder = "";
        while (folder != priorFolder) {
            if (CliPathWalker.isConfigRoot(folder)) {
                return folder; // FOUND IT.
            }
            priorFolder = folder;
            folder = path.resolve(folder, '../');
        }
        if (errorWhenNotFound) {
            throw new Error(`No ${ops_constants_1.OpsConstants.PROJECT_CONFIG_FILENAME} found in the current path; Please run ` + 'init' + ' from the root folder of your project to declare it.');
        }
        else {
            return "";
        }
    }
    /** Determines if the given path is a Toyhauler project root. */
    static isConfigRoot(folder) {
        let candidate = path.join(folder, ops_constants_1.OpsConstants.PROJECT_CONFIG_FILENAME);
        // this.log('Checking ' + chalk.default.blue(folder) + ' as config root...')
        try {
            fxs.accessSync(candidate);
            return true;
        }
        catch /*(err)*/ (_a) {
            // this.log(`${candidate} doesnt exist: ` + err)
            return false;
        }
    }
}
exports.CliPathWalker = CliPathWalker;
//# sourceMappingURL=cli-path-walker.js.map