prettier#Options TypeScript Examples

The following examples show how to use prettier#Options. 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: prettier-utils.ts    From utopia with MIT License 7 votes vote down vote up
PrettierConfig: Options = {
  parser: 'typescript',
  plugins: [parserTypescript],
  printWidth: 60,
  trailingComma: 'all',
  tabWidth: 2,
  semi: false,
  singleQuote: true,
  quoteProps: 'as-needed',
  bracketSpacing: true,
  jsxSingleQuote: true,
  jsxBracketSameLine: false,
  arrowParens: 'always',
}
Example #2
Source File: code-utils.ts    From plasmic with MIT License 7 votes vote down vote up
formatAsLocal = (
  content: string,
  filePath: string,
  baseDir: string,
  defaultOpts: Options = {}
) => {
  const opts = resolveConfig.sync(baseDir) || defaultOpts;
  opts.filepath = filePath;

  // Running Prettier multiple times may actually yield different results!
  // Here we run it twice, just to be safe... :-/
  const res = Prettier.format(content, opts);
  const res2 = Prettier.format(res, opts);
  return res2;
}
Example #3
Source File: utils.ts    From prettier-plugin-jsdoc with MIT License 6 votes vote down vote up
function formatType(type: string, options?: Options): string {
  try {
    const TYPE_START = "type name = ";

    let pretty = type;

    // Rest parameter types start with "...". This is supported by TS and JSDoc
    // but it's implemented in a weird way in TS. TS will only acknowledge the
    // "..." if the function parameter is a rest parameter. In this case, TS
    // will interpret `...T` as `T[]`. But we can't just convert "..." to arrays
    // because of @callback types. In @callback types `...T` and `T[]` are not
    // equivalent, so we have to support "..." as is.
    //
    // This formatting itself is rather simple. If `...T` is detected, it will
    // be replaced with `T[]` and formatted. At the end, the outer array will
    // be removed and "..." will be added again.
    //
    // As a consequence, union types will get an additional pair of parentheses
    // (e.g. `...A|B` -> `...(A|B)`). This is technically unnecessary but it
    // makes the operator precedence very clear.
    //
    // https://www.typescriptlang.org/docs/handbook/functions.html#rest-parameters
    let rest = false;
    if (pretty.startsWith("...")) {
      rest = true;
      pretty = `(${pretty.slice(3)})[]`;
    }

    pretty = format(`${TYPE_START}${pretty}`, {
      ...options,
      parser: "typescript",
      plugins: [],
      filepath: "file.ts",
    });
    pretty = pretty.slice(TYPE_START.length);
    pretty = pretty.replace(/^\s*/g, "");
    pretty = pretty.replace(/[;\n]*$/g, "");
    pretty = pretty.trim();

    if (rest) {
      pretty = "..." + pretty.replace(/\[\s*\]$/, "");
    }

    return pretty;
  } catch (error) {
    // console.log("jsdoc-parser", error);
    return type;
  }
}
Example #4
Source File: abi-generator.ts    From ethereum-abi-types-generator with MIT License 6 votes vote down vote up
/**
   * Get prettier options
   */
  private getPrettierOptions(): Options {
    const usersPrettierrConfig = this.findPrettierrcContent(
      this.buildExecutingPath(this.getOutputPathDirectory())
    );
    if (usersPrettierrConfig) {
      usersPrettierrConfig.parser = 'typescript';
      usersPrettierrConfig.plugins = [prettierTS];
      return usersPrettierrConfig;
    }

    return this.getDefaultPrettierOptions();
  }
Example #5
Source File: abi-generator.ts    From ethereum-abi-types-generator with MIT License 6 votes vote down vote up
/**
   * Loop through all the of dir to try to fine the .prettierrc file
   * @param dirPath The path
   */
  private findPrettierrcContent(dirPath: string): Options | null {
    const files = fs.readdirSync(dirPath);
    for (let i = 0; i < files.length; i++) {
      if (files[i] === '.prettierrc') {
        try {
          return JSON.parse(
            fs.readFileSync(path.join(dirPath, '.prettierrc'), 'utf8')
          ) as Options;
        } catch (error) {
          // mute it
        }
      }
    }

    const nextPath = path.join(dirPath, '..');
    if (nextPath !== dirPath) {
      return this.findPrettierrcContent(nextPath);
    }

    return null;
  }
Example #6
Source File: abi-generator.ts    From ethereum-abi-types-generator with MIT License 6 votes vote down vote up
/**
   * Get default prettier options
   */
  private getDefaultPrettierOptions(): Options {
    return {
      parser: 'typescript',
      trailingComma: 'es5',
      singleQuote: true,
      bracketSpacing: true,
      printWidth: 80,
      plugins: [prettierTS],
    };
  }
Example #7
Source File: solita.ts    From solita with Apache License 2.0 6 votes vote down vote up
constructor(
    private readonly idl: Idl,
    {
      formatCode = false,
      formatOpts = {},
      prependGeneratedWarning = true,
      typeAliases = {},
      serializers = {},
      projectRoot = process.cwd(),
    }: {
      formatCode?: boolean
      formatOpts?: Options
      prependGeneratedWarning?: boolean
      typeAliases?: TypeAliases
      serializers?: Serializers
      projectRoot?: string
    } = {}
  ) {
    this.projectRoot = projectRoot
    this.formatCode = formatCode
    this.formatOpts = { ...DEFAULT_FORMAT_OPTS, ...formatOpts }
    this.prependGeneratedWarning = prependGeneratedWarning
    this.accountsHaveImplicitDiscriminator = !isShankIdl(idl)
    this.typeAliases = new Map(Object.entries(typeAliases))
    this.serializers = CustomSerializers.create(
      this.projectRoot,
      new Map(Object.entries(serializers))
    )
  }
Example #8
Source File: solita.ts    From solita with Apache License 2.0 6 votes vote down vote up
DEFAULT_FORMAT_OPTS: Options = {
  semi: false,
  singleQuote: true,
  trailingComma: 'es5',
  useTabs: false,
  tabWidth: 2,
  arrowParens: 'always',
  printWidth: 80,
  parser: 'typescript',
}
Example #9
Source File: prettyfy.ts    From open-source with MIT License 6 votes vote down vote up
prettierOptions: Options = {
  printWidth: 120,
  tabWidth: 2,
  useTabs: false,
  semi: true,
  singleQuote: true,
  trailingComma: 'none',
  htmlWhitespaceSensitivity: 'strict',
  bracketSpacing: true,
  arrowParens: 'always',
  proseWrap: 'always',
  endOfLine: 'auto',
  parser: 'angular',
}
Example #10
Source File: JoplinNoteParser.ts    From joplin-blog with MIT License 6 votes vote down vote up
/**
   * 转换笔记中的 joplin 内部链接
   * @param content
   * @param map
   */
  convertResource(content: string, map: Map<string, string>) {
    const tree = unistUtilMap(this.processor.parse(content), (node) => {
      if (node.type !== 'link' && node.type !== 'image') {
        return node
      }
      const link = node as Link
      if (!link.url.startsWith(':/')) {
        return link
      }
      return {
        ...node,
        url: map.get(link.url.slice(2)),
      } as Link
    })
    const options: Options = { parser: 'markdown', tabWidth: 2 }
    return format(this.processor.stringify(tree), options)
  }
Example #11
Source File: remark.test.ts    From joplin-blog with MIT License 6 votes vote down vote up
it('测试任务列表序列化', () => {
  const text = `
# test

- [x] task 1
- [ ] task 2
  `
  const tree = md.parse(text)
  const res = md.stringify(tree)

  console.log(text)
  console.log(res)
  console.log(format(res, { parser: 'markdown', tabWidth: 2 } as Options))
})
Example #12
Source File: write.ts    From vite-plugin-sass-dts with MIT License 5 votes vote down vote up
writeToFile = async (
  prettierOptions: Options,
  fileName: string,
  classNameKeys: Map<string, boolean>,
  globalOutFile?: string
) => {
  let exportTypes = '',
    exportClassNames = 'export type ClassNames = '
  const exportStyle = 'export default classNames;'
  for (const classNameKey of classNameKeys.keys()) {
    exportTypes = `${exportTypes}\n${formatExportType(classNameKey)}`
    exportClassNames =
      exportClassNames !== 'export type ClassNames = '
        ? `${exportClassNames} | '${classNameKey}'`
        : `${exportClassNames} '${classNameKey}'`
  }

  let outputFileString = ''
  if (globalOutFile) {
    const relativePath = getRelativePath(
      path.dirname(fileName),
      path.dirname(globalOutFile)
    )
    const exportTypeFileName = formatExportTypeFileName(globalOutFile)
    const globalClassNamesPrefix = classNameKeys.size === 0 ? '' : '| '
    outputFileString = `import globalClassNames, { ClassNames as GlobalClassNames } from '${relativePath}${exportTypeFileName}'\n`
    outputFileString = `${outputFileString}declare const classNames: typeof globalClassNames & {${exportTypes}\n};\n${exportStyle}\n${exportClassNames} ${globalClassNamesPrefix}GlobalClassNames`
  } else {
    outputFileString = `declare const classNames: {${exportTypes}\n};\n${exportStyle}\n${exportClassNames}`
  }

  const prettierdOutputFileString = prettier.format(
    outputFileString,
    prettierOptions
  )

  fs.writeFile(
    formatWriteFileName(fileName),
    `${prettierdOutputFileString}`,
    (err) => {
      if (err) {
        console.log(err)
        throw err
      }
    }
  )
}
Example #13
Source File: solita.ts    From solita with Apache License 2.0 5 votes vote down vote up
private readonly formatOpts: Options
Example #14
Source File: JoplinNoteHandler.ts    From joplin-blog with MIT License 5 votes vote down vote up
static format(node: Node) {
    return format(this.md.stringify(node), {
      parser: 'markdown',
      tabWidth: 2,
    } as Options)
  }
Example #15
Source File: JoplinNoteHandler.ts    From joplin-utils with MIT License 5 votes vote down vote up
static format(node: Node) {
    return format(this.md.stringify(node), {
      parser: 'markdown',
      tabWidth: 2,
    } as Options)
  }
Example #16
Source File: main.ts    From jekyll-action-ts with MIT License 4 votes vote down vote up
async function run(): Promise<void> {
	try {
		let jekyllSrc = "",
			gemSrc = "",
			gemArr: string[],
			jekyllArr: string[],
			hash: string,
			exactKeyMatch: boolean,
			installFailure = false,
			restoreKeys: string[],
			key: string;
		const INPUT_JEKYLL_SRC = core.getInput("jekyll_src", {}),
			SRC = core.getInput("src", {}),
			INPUT_GEM_SRC = core.getInput("gem_src", {}),
			INPUT_CUSTOM_OPTS = core.getInput("custom_opts", {}),
			INPUT_ENABLE_CACHE = core.getInput("enable_cache", {}),
			INPUT_KEY = core.getInput("key", {}),
			INPUT_RESTORE_KEYS = getInputAsArray("restore-keys"),
			INPUT_FORMAT_OUTPUT = core.getInput("format_output"),
			INPUT_PRETTIER_OPTS = core.getInput("prettier_opts"),
			INPUT_PRETTIER_IGNORE = getInputAsArray("prettier_ignore"),
			paths = ["vendor/bundle"];
		if (INPUT_RESTORE_KEYS.length > 0) restoreKeys = INPUT_RESTORE_KEYS;
		else restoreKeys = ["Linux-gems-", "bundle-use-ruby-Linux-gems-"];

		await measure({
			name: "resolve directories",
			block: async () => {
				// Resolve Jekyll directory
				if (INPUT_JEKYLL_SRC) {
					jekyllSrc = INPUT_JEKYLL_SRC;
					core.debug(
						`Using parameter value ${jekyllSrc} as a source directory`
					);
				} else if (SRC) {
					jekyllSrc = SRC;
					core.debug(
						`Using ${jekyllSrc} environment var value as a source directory`
					);
				} else {
					jekyllArr = await (
						await glob.create(
							["**/_config.yml", "!**/vendor/bundle/**"].join("\n")
						)
					).glob();
					for (let i = 0; i < jekyllArr.length; i++) {
						jekyllArr[i] = jekyllArr[i].replace(/_config\.yml/, "");
					}
					if (jekyllArr.length > 1) {
						throw new Error(
							`error: found ${jekyllArr.length} _config.yml! Please define which to use with input variable "JEKYLL_SRC"`
						);
					} else {
						jekyllSrc = jekyllArr[0];
					}
				}
				core.debug(`Resolved ${jekyllSrc} as source directory`);

				// Resolve Gemfile directory
				if (INPUT_GEM_SRC) {
					gemSrc = INPUT_GEM_SRC;
					if (!gemSrc.endsWith("Gemfile")) {
						if (!gemSrc.endsWith("/")) {
							gemSrc = gemSrc.concat("/");
						}
						gemSrc = gemSrc.concat("Gemfile");
					}
				} else {
					gemArr = await (
						await glob.create(["**/Gemfile", "!**/vendor/bundle/**"].join("\n"))
					).glob();
					if (gemArr.length > 1) {
						if (!jekyllSrc.endsWith("/")) {
							jekyllSrc = jekyllSrc.concat("/");
						}
						if (jekyllSrc.startsWith(".")) {
							jekyllSrc = jekyllSrc.replace(
								/\.\/|\./,
								`${process.env.GITHUB_WORKSPACE}/`
							);
						} else if (!jekyllSrc.startsWith("/")) {
							jekyllSrc = `${process.env.GITHUB_WORKSPACE}/`.concat(jekyllSrc);
						}
						for (const element of gemArr) {
							if (element.replace(/Gemfile/, "") === jekyllSrc) {
								gemSrc = element;
							}
						}
						if (!gemSrc) {
							throw new Error(
								`found ${gemArr.length} Gemfiles, and failed to resolve them! Please define which to use with input variable "GEM_SRC"`
							);
						} else {
							core.warning(`found ${gemArr.length} Gemfiles!`);
						}
					} else {
						gemSrc = gemArr[0];
					}
				}
				core.debug(`Resolved ${gemSrc} as Gemfile`);
				core.exportVariable("BUNDLE_GEMFILE", `${gemSrc}`);
			},
		});

		if (INPUT_ENABLE_CACHE) {
			await measure({
				name: "restore bundler cache",
				block: async () => {
					if (!INPUT_KEY) {
						hash = crypto
							.createHash("sha256")
							.update(fs.readFileSync(`${gemSrc}.lock`))
							.digest("hex");
						core.debug(`Hash of Gemfile.lock: ${hash}`);
						key = `Linux-gems-${hash}`;
					} else key = INPUT_KEY;
					try {
						const cacheKey = await cache.restoreCache(paths, key, restoreKeys);
						if (!cacheKey) {
							core.info(
								`Cache not found for input keys: ${[key, ...restoreKeys].join(
									", "
								)}`
							);
							return;
						}
						exactKeyMatch = isExactKeyMatch(key, cacheKey);
					} catch (error) {
						if (error.name === cache.ValidationError.name) {
							throw error;
						} else {
							core.warning(error.message);
						}
					}
					return;
				},
			});
		}

		await measure({
			name: "bundle install",
			block: async () => {
				await exec.exec("bundle config set deployment true");
				await exec.exec(
					`bundle config path ${process.env.GITHUB_WORKSPACE}/vendor/bundle`
				);
				try {
					await exec.exec(
						`bundle install --jobs=4 --retry=3 --gemfile=${gemSrc}`
					);
				} catch (error) {
					installFailure = true;
					core.error(
						'Gemfile.lock probably needs updating. Run "bundle install" locally and commit changes. Exiting action'
					);
					throw error;
				}
				return;
			},
		});

		if (!installFailure) {
			await measure({
				name: "jekyll build",
				block: async () => {
					core.exportVariable("JEKYLL_ENV", "production");
					return await exec.exec(
						`bundle exec jekyll build -s ${jekyllSrc} ${INPUT_CUSTOM_OPTS}`
					);
				},
			});

			// maybe run this async with saving cache
			if (INPUT_FORMAT_OUTPUT || INPUT_PRETTIER_OPTS) {
				await measure({
					name: "format output html files",
					block: async () => {
						const globFiles = ["_site/**/*.html"];
						if (INPUT_PRETTIER_IGNORE) {
							globFiles.push(
								...INPUT_PRETTIER_IGNORE.map((i) => "!_site/" + i)
							);
						}
						const formatFileArray = await (
							await glob.create(globFiles.join("\n"))
						).glob();
						let defaultOpts: Options = {
							parser: "html",
							plugins: [parserHTML, parserCSS, parserJS],
						};
						if (INPUT_PRETTIER_OPTS) {
							defaultOpts = {
								...defaultOpts,
								...JSON.parse(INPUT_PRETTIER_OPTS),
							};
						}

						const cacheHTMLPath = ["_site/**/*.cache"],
							formatCacheList = [],
							HTMLFiles: {
								[key: string]: string;
							} = {};
						let exactHTMLKeyMatch = false,
							filesConcat = "";
						for (const element of formatFileArray) {
							HTMLFiles[element] = fs.readFileSync(element, "utf8");
							filesConcat = filesConcat + HTMLFiles[element];
						}
						const cacheHTMLKey = `Linux-cacheFormatHTML-${crypto
							.createHash("sha256")
							.update(filesConcat)
							.digest("hex")}`;
						try {
							const cacheKey = await cache.restoreCache(
								cacheHTMLPath,
								cacheHTMLKey,
								["Linux-cacheFormatHTML-"]
							);
							if (!cacheKey) {
								core.info("No HTML cache");
							} else
								exactHTMLKeyMatch = isExactKeyMatch(cacheHTMLKey, cacheKey);
						} catch (error) {
							if (error.name === cache.ValidationError.name) {
								throw error;
							} else {
								core.warning(error.message);
							}
						}
						for (const element of formatFileArray) {
							core.debug(element);
							if (fs.existsSync(`${element}.cache`)) {
								const cachedFile = fs.readFileSync(`${element}.cache`, "utf8");
								if (HTMLFiles[element] === cachedFile) {
									await io.cp(`${element}.prettier.cache`, element);
									formatCacheList.push(element);
									continue;
								}
							}
							const formatted = prettier.format(
								HTMLFiles[element],
								defaultOpts
							);
							if (HTMLFiles[element].length > 10000) {
								formatCacheList.push(element);
								fs.writeFileSync(`${element}.cache`, HTMLFiles[element]);
								fs.writeFileSync(`${element}.prettier.cache`, formatted);
							}
							fs.writeFileSync(element, formatted);
						}
						if (formatCacheList.length >= 1) {
							if (!exactHTMLKeyMatch) {
								try {
									await cache.saveCache(cacheHTMLPath, cacheHTMLKey);
								} catch (error) {
									if (error.name === cache.ValidationError.name) {
										throw error;
									} else if (error.name === cache.ReserveCacheError.name) {
										core.info(error.message);
									} else {
										core.warning(error.message);
									}
								}
							}
							for (const element of formatCacheList) {
								await io.rmRF(`${element}.cache`);
								await io.rmRF(`${element}.prettier.cache`);
							}
						}
						return;
					},
				});
			}

			if (INPUT_ENABLE_CACHE) {
				await measure({
					name: "save bundler cache",
					block: async () => {
						if (exactKeyMatch) {
							core.info(
								`Cache hit occurred on the primary key ${key}, not saving cache.`
							);
							return;
						}
						try {
							await cache.saveCache(paths, key);
						} catch (error) {
							if (error.name === cache.ValidationError.name) {
								throw error;
							} else if (error.name === cache.ReserveCacheError.name) {
								core.info(error.message);
							} else {
								core.warning(error.message);
							}
						}
						return;
					},
				});
			}
		}
	} catch (error) {
		core.setFailed(error.message);
	}
}