fs#lstatSync TypeScript Examples

The following examples show how to use fs#lstatSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: spUtils.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export function checkMainPath(mainPath: string): boolean {
  if (!existsSync(mainPath)) {
    return false;
  }
  if (!lstatSync(mainPath).isFile()) {
    return false;
  }
  return extname(mainPath) === ".sp";
}
Example #2
Source File: util.ts    From attranslate with MIT License 6 votes vote down vote up
function isDirectory(path: string): boolean {
  try {
    const stat = lstatSync(path);
    return stat.isDirectory();
  } catch (e) {
    return false;
  }
}
Example #3
Source File: virustotal.ts    From ghaction-virustotal with MIT License 5 votes vote down vote up
asset = (path: string): Asset => {
  return {
    name: basename(path),
    mime: mimeOrDefault(path),
    size: lstatSync(path).size,
    file: readFileSync(path)
  };
}
Example #4
Source File: converter.spec.ts    From proto2graphql with MIT License 5 votes vote down vote up
function tests() {
  return readdirSync(DIR)
    .filter(dirent => lstatSync(join(DIR, dirent)).isDirectory())
    .filter(subdir => existsSync(join(DIR, subdir, "input.proto")));
}
Example #5
Source File: search.ts    From checkstyle-github-action with MIT License 5 votes vote down vote up
export async function findResults(
  searchPath: string,
  globOptions?: glob.GlobOptions
): Promise<SearchResult> {
  const searchResults: string[] = []
  const globber = await glob.create(
    searchPath,
    globOptions || getDefaultGlobOptions()
  )
  const rawSearchResults: string[] = await globber.glob()

  /*
      Directories will be rejected if attempted to be uploaded. This includes just empty
      directories so filter any directories out from the raw search results
    */
  for (const searchResult of rawSearchResults) {
    if (!lstatSync(searchResult).isDirectory()) {
      debug(`File:${searchResult} was found using the provided searchPath`)
      searchResults.push(searchResult)
    } else {
      debug(
        `Removing ${searchResult} from rawSearchResults because it is a directory`
      )
    }
  }

  /*
      Only a single search pattern is being included so only 1 searchResult is expected. In the future if multiple search patterns are
      simultaneously supported this will change
    */
  const searchPaths: string[] = globber.getSearchPaths()
  if (searchPaths.length > 1) {
    throw new Error('Only 1 search path should be returned')
  }

  /*
      Special case for a single file artifact that is uploaded without a directory or wildcard pattern. The directory structure is
      not preserved and the root directory will be the single files parent directory
    */
  if (searchResults.length === 1 && searchPaths[0] === searchResults[0]) {
    return {
      filesToUpload: searchResults,
      rootDirectory: dirname(searchResults[0])
    }
  }

  return {
    filesToUpload: searchResults,
    rootDirectory: searchPaths[0]
  }
}
Example #6
Source File: search.ts    From upload-artifact-as-is with MIT License 5 votes vote down vote up
export async function findFilesToUpload(
    searchPath: string,
    globOptions?: glob.GlobOptions
): Promise<SearchResult> {
    const searchResults: string[] = []
    const globber = await glob.create(
        searchPath,
        globOptions || getDefaultGlobOptions()
    )
    const rawSearchResults: string[] = await globber.glob()

    /*
      Directories will be rejected if attempted to be uploaded. This includes just empty
      directories so filter any directories out from the raw search results
    */
    for (const searchResult of rawSearchResults) {
        if (!lstatSync(searchResult).isDirectory()) {
            debug(`File:${searchResult} was found using the provided searchPath`)
            searchResults.push(searchResult)
        } else {
            debug(
                `Removing ${searchResult} from rawSearchResults because it is a directory`
            )
        }
    }

    /*
      Only a single search pattern is being included so only 1 searchResult is expected. In the future if multiple search patterns are
      simultaneously supported this will change
    */
    const searchPaths: string[] = globber.getSearchPaths()
    if (searchPaths.length > 1) {
        throw new Error('Only 1 search path should be returned')
    }

    /*
      Special case for a single file artifact that is uploaded without a directory or wildcard pattern. The directory structure is
      not preserved and the root directory will be the single files parent directory
    */
    if (searchResults.length === 1 && searchPaths[0] === searchResults[0]) {
        return {
            filesToUpload: searchResults,
            rootDirectory: dirname(searchResults[0])
        }
    }

    return {
        filesToUpload: searchResults,
        rootDirectory: searchPaths[0]
    }
}
Example #7
Source File: new-trongate-module.command.ts    From trongate-vscode with MIT License 4 votes vote down vote up
newModule = async (uri: Uri) => {

    // check if it is a trongate project
    const GLOBAL_SETTINGS = {
      projectPath: '',
      isTrongateProject: false,
      config: {},
    }
    try {
      GLOBAL_SETTINGS['projectPath'] = workspace.workspaceFolders[0].uri.fsPath
      GLOBAL_SETTINGS['isTrongateProject'] = checkIsTrongateProject(GLOBAL_SETTINGS.projectPath)
      if (GLOBAL_SETTINGS['isTrongateProject']) {
        //read all the configs from config file
        const configFilePath = path.join(GLOBAL_SETTINGS['projectPath'], 'config', 'config.php')
        const configFileContent = readFileSync(configFilePath, { encoding: 'utf8' });
        const regexMatch = /define\(\s*('\w+'|"\w+"\1)\s*,\s*('\w+'|"\w+"\2)\s*\)/
        configFileContent.split('\n').map(item => {
          const match = item.match(regexMatch)
          if (match) {
            const configKey = match[1].split('').filter(item => item !== '\'' && item !== '"').join('')
            const configValue = match[2].split('').filter(item => item !== '\'' && item !== '"').join('')
            GLOBAL_SETTINGS['config'][configKey] = configValue
          }
        })
      }
    } catch (error) {
      console.log(error)
    }

    if (!GLOBAL_SETTINGS['isTrongateProject']) {
      window.showErrorMessage("The current workspace does not contain a valid Trongate Project");
      return
    }

  // console.log('===================')
  // console.log(uri) 
  // console.log(GLOBAL_SETTINGS) 
  // console.log('===================')

  /**
   * The function starts from here
   */
  const moduleName = await prompForInput(inputPrompOptionForModuleName);
  console.log(moduleName);
  if (_.isNil(moduleName) || moduleName.trim() === "") {
    window.showErrorMessage("The module name must not be empty");
    return;
  }

  // check if the module name contains the assets trigger phase
  const validName = validateModuleName(moduleName)
  if (validName.includes(GLOBAL_SETTINGS['config']['MODULE_ASSETS_TRIGGER'])) {
    window.showErrorMessage(`Your module name contained the MODULE_ASSETS_TRIGGER: ${GLOBAL_SETTINGS['config']['MODULE_ASSETS_TRIGGER']}, please rename your module`);
    return
  }

  let targetDirectory;
  if (_.isNil(_.get(uri, "fsPath")) || !lstatSync(uri.fsPath).isDirectory()) {
    targetDirectory = await promptForTargetDirectory();
    if (_.isNil(targetDirectory)) {
      window.showErrorMessage("Please select a valid directory");
      return;
    }
  } else {
    targetDirectory = uri.fsPath;
  }

  const isViewTemplate = await dropDownList(itemOptions, quickPickOptions);

  // There is a possibility that the user presses ESC then we cancel the process
  // and return an error message to the user
  if (isViewTemplate === undefined) {
    window.showErrorMessage("Process cancelled, no new module created");
    return;
  }

  let viewFileName;
  if (isViewTemplate === "yes") {
    // promp window for a view file name
    viewFileName = await prompForInput(inputPrompOptionForViewName);
    if (_.isNil(viewFileName) || viewFileName.trim() === "") {
      window.showErrorMessage("The view file name must not be empty");
      return;
    }
    viewFileName = viewFileName.split(" ").join("_");
  }

  const genObj = {
    moduleName,
    targetDirectory,
    isViewTemplate,
    viewFileName,
    GLOBAL_SETTINGS
  };
  try {
    await generateModuleCode(genObj);
    // Open the controller file and put curosr at the correct position
    openEditorAndPutCursorAtGoodPosition(
      targetDirectory,
      moduleName,
      isViewTemplate
    );

    const pascalCaseBlocName = validateModuleName(moduleName); // implement this later - change all the space to underscore
    window.showInformationMessage(
      `Successfully Generated ${pascalCaseBlocName} Module`
    );
  } catch (error) {
    window.showErrorMessage(
      `Error:
        ${error instanceof Error ? error.message : JSON.stringify(error)}`
    );
    console.log(error);
  }
}
Example #8
Source File: convertFilesInDirectory.ts    From joi-to-typescript with MIT License 4 votes vote down vote up
/**
 * Create types from schemas from a directory
 * @param settings Settings
 */
export async function convertFilesInDirectory(
  appSettings: Settings,
  ogTypeOutputDir: string,
  fileTypesToExport: GenerateTypeFile[] = []
): Promise<GenerateTypesDir> {
  // Check and resolve directories
  const resolvedSchemaDirectory = Path.resolve(appSettings.schemaDirectory);
  if (!existsSync(resolvedSchemaDirectory)) {
    throw new Error(`schemaDirectory "${resolvedSchemaDirectory}" does not exist`);
  }
  const resolvedTypeOutputDirectory = Path.resolve(appSettings.typeOutputDirectory);
  if (!existsSync(resolvedTypeOutputDirectory)) {
    mkdirSync(resolvedTypeOutputDirectory, { recursive: true });
  }

  let fileNamesToExport: string[] = [];
  const currentDirFileTypesToExport: GenerateTypeFile[] = fileTypesToExport;

  // Load files and get all types
  const files = readdirSync(resolvedSchemaDirectory);
  for (const schemaFileName of files) {
    const subDirectoryPath = Path.join(resolvedSchemaDirectory, schemaFileName);
    if (!appSettings.rootDirectoryOnly && lstatSync(subDirectoryPath).isDirectory()) {
      if (appSettings.ignoreFiles.includes(`${schemaFileName}/`)) {
        if (appSettings.debug) {
          // eslint-disable-next-line no-console
          console.debug(`Skipping ${subDirectoryPath} because it's in your ignore files list`);
        }
        continue;
      }
      const typeOutputDirectory = appSettings.flattenTree
        ? resolvedTypeOutputDirectory
        : Path.join(resolvedTypeOutputDirectory, schemaFileName);

      const thisDirsFileNamesToExport = await convertFilesInDirectory(
        {
          ...appSettings,
          schemaDirectory: subDirectoryPath,
          typeOutputDirectory
        },
        ogTypeOutputDir,
        currentDirFileTypesToExport
      );

      if (appSettings.indexAllToRoot || appSettings.flattenTree) {
        fileNamesToExport = fileNamesToExport.concat(thisDirsFileNamesToExport.typeFileNames);
      }
    } else {
      if (!appSettings.inputFileFilter.test(schemaFileName)) {
        if (appSettings.debug) {
          // eslint-disable-next-line no-console
          console.debug(`Skipping ${schemaFileName} because it's excluded via inputFileFilter`);
        }
        continue;
      }
      if (appSettings.ignoreFiles.includes(schemaFileName)) {
        if (appSettings.debug) {
          // eslint-disable-next-line no-console
          console.debug(`Skipping ${schemaFileName} because it's in your ignore files list`);
        }
        continue;
      }
      const exportType = await analyseSchemaFile(appSettings, schemaFileName);
      if (exportType) {
        let dirTypeFileName = exportType.typeFileName;
        if (appSettings.indexAllToRoot) {
          const findIndexEnd = resolvedTypeOutputDirectory.indexOf(ogTypeOutputDir) + ogTypeOutputDir.length + 1;
          dirTypeFileName = Path.join(
            resolvedTypeOutputDirectory.substring(findIndexEnd),
            getTypeFileNameFromSchema(schemaFileName, appSettings)
          );
        }
        fileNamesToExport.push(dirTypeFileName);
        currentDirFileTypesToExport.push(exportType);
      }
    }
  }

  if (!appSettings.indexAllToRoot && !appSettings.flattenTree) {
    // Write index.ts
    writeIndexFile(appSettings, fileNamesToExport);
  }

  return { typeFileNames: fileNamesToExport, types: currentDirFileTypesToExport };
}