/*
 * Copyright (C) 2018-2021 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Logger} from '@openstapps/logger';
import path from 'path';
import {existsSync} from 'fs';

/**
 * Get path that contains a tsconfig.json
 * @param startPath Path from where to start searching "upwards"
 */
export function getTsconfigPath(startPath: string): string {
  let tsconfigPath = startPath;

  while (!existsSync(path.join(tsconfigPath, 'tsconfig.json'))) {
    const parent = path.resolve(tsconfigPath, '..');
    if (tsconfigPath === parent) {
      throw new Error(
        `Reached file system root ${parent} while searching for 'tsconfig.json' in ${startPath}!`,
      );
    }

    tsconfigPath = parent;
  }

  Logger.info(`Using 'tsconfig.json' from ${tsconfigPath}.`);

  return tsconfigPath;
}
