How to use the prettier.resolveConfig function in prettier

To help you get started, we’ve selected a few prettier examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github apollographql / apollo-tooling / packages / apollo / src / commands / service / codegen.ts View on Github external
return sdl;
        case "graphql":
          return { sdl: inputText, loc: 0 };
        default:
          throw new Error(
            `Unknown input file type ${inputFileType}, supported file types are: .js(x), .ts(x), .gql, or .graphql`
          );
      }
    };

    const { sdl, loc } = getSDL();

    try {
      const translated = translate(sdl, target);

      const prettierOptions = await prettier.resolveConfig(output);
      const formatted = prettier.format(translated, {
        parser: "typescript",
        ...prettierOptions
      });

      await new Promise(resolve => writeFile(output, formatted, resolve));
    } catch (e) {
      let message: string = e.message;

      if (message && message.includes("Syntax Error")) {
        // error in gql parse. Are they maybe passing an introspection result?
        message +=
          ".\nIs the input in SDL format?\nSee https://bit.ly/2SzrSMk for help with schema formats";
      } else if (message && message.match(/\(\d+,\d+\).*/)) {
        message = message
          .split("\n")
github prisma-labs / graphqlgen / packages / graphqlgen / src / index.ts View on Github external
...config.models,
    files: handleGlobPattern(config.models.files),
  }

  if (!validateConfig(config, parsedSchema)) {
    return false
  }

  const modelMap = parseModels(
    config.models,
    parsedSchema,
    config.output,
    config.language,
  )

  const options = (await prettier.resolveConfig(process.cwd())) || {} // TODO: Abstract this TS specific behavior better

  if (JSON.stringify(options) !== '{}') {
    console.log(chalk.blue(`Found a prettier configuration to use`))
  }

  const { generatedTypes, generatedResolvers } = generateCode({
    schema: parsedSchema!,
    language: config.language,
    prettify: true,
    prettifyOptions: options,
    config,
    modelMap,
  })

  Project.writeTypes(generatedTypes, config)
github jhipster / generator-jhipster / generators / generator-transforms.js View on Github external
const transform = (file, encoding, callback) => {
        /* resolve from the projects config */
        prettier.resolveConfig(file.relative).then(options => {
            if (file.state !== 'deleted') {
                const str = file.contents.toString('utf8');
                if (!options || Object.keys(options).length === 0) {
                    options = defaultOptions;
                }
                // for better errors
                options.filepath = file.relative;
                const data = prettier.format(str, options);
                file.contents = Buffer.from(data);
            }
            callback(null, file);
        });
    };
    return through.obj(transform);
github ethereum-ts / TypeChain / test / integration / Formatting.spec.ts View on Github external
it("should be done based on prettier config", async () => {
    const config = await resolveConfig(__dirname);

    const files = glob.sync(join(__dirname, "./abis/*.ts"), { absolute: true });

    files.forEach(filePath => {
      expect(check(readFileSync(filePath, "utf-8"), config!)).to.be.ok;
    });
  });
});
github uber / baseweb / src / icon / build-icons.js View on Github external
async function generateNewIcons() {
  const iconTemplate = fs.readFileSync(
    path.resolve(__dirname, './icon-template.txt'),
    'utf8',
  );
  const svgs = fs
    .readdirSync(path.resolve(__dirname, './svg'))
    .filter(f => f.endsWith('.svg'));

  const prettierOptions = (await prettier.resolveConfig(__dirname)) || {};
  const iconExports = [];

  svgs.forEach(async svgFilename => {
    const svgFile = svgFilename.split('.')[0];
    const componentName = pascalCase(svgFile);
    iconExports.push(
      `export {default as ${componentName}} from './${svgFile}.js';`,
    );

    const svgFileContents = fs.readFileSync(
      path.resolve(__dirname, `./svg/${svgFilename}`),
      'utf8',
    );

    const iconProps = [`title="${titleCase(svgFile)}"`];
github wx-minapp / minapp-vscode / src / plugin / PrettierProvider.ts View on Github external
async _provideEdits(document: TextDocument): Promise {
        try {
            const prettierOptions = await resolveConfig(document.uri.fsPath, { editorconfig: true })
            const prettierifiedCode = prettierify(document, Object.assign({}, this.options, prettierOptions))
            return [TextEdit.replace(fullDocumentRange(document), prettierifiedCode)]
        } catch (error) {
            console.log('Prettier format failed')
            console.error(error.message)
            window.showErrorMessage(error.message)
            return []
        }
    }
}
github prisma-labs / yoga2 / packages / create-yoga / src / scaffold.ts View on Github external
async function resolvePrettierOptions(path: string): Promise {
  const options = (await prettier.resolveConfig(path)) || {}

  return options
}
github anoaland / anoa-cli / src / services / core / source.ts View on Github external
async prettifySoureFile(sourceFile: SourceFile) {
    const {
      filesystem: { cwd }
    } = this.context

    sourceFile.organizeImports()

    const opt = await resolveConfig(cwd())
    sourceFile.replaceWithText(
      format(sourceFile.getFullText(), {
        ...opt,
        parser: 'typescript'
      })
    )
  }
}
github Flood-UI / flood / scripts / prettier.js View on Github external
sourceFilePaths.map(async filePath => {
        const fileContent = await readFile(filePath);
        const prettierConfig = await prettier.resolveConfig(filePath);
        const isCompliant = prettier.check(fileContent, {...prettierConfig, filepath: filePath});

        if (!isCompliant) {
          throw filePath;
        }
      }),
    );
github buildbuddy-io / buildbuddy / tools / prettier / fix.ts View on Github external
async function main() {
  const paths = await getFilePathsToFormat();
  const workspacePath = getWorkspacePath();
  for (const path of paths) {
    const absolutePath = `${workspacePath}/${path}`;
    const config = await prettier.resolveConfig(absolutePath);
    const source = fs.readFileSync(absolutePath, { encoding: "utf-8" });
    const options = { ...config, filepath: path };
    if (!prettier.check(source, options)) {
      fs.writeFileSync(absolutePath, prettier.format(source, options));
      process.stdout.write(`${path} ${chalk.blue("FIXED")}\n`);
    }
  }
}