Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add prettier.config setting #433

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ All notable changes to the "prettier-vscode" extension will be documented in thi

## [Unreleased]

- New setting `config`. Specify path to prettier config file.

## [1.5.0]

- Revert notification popup: remove it.
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ Require a 'prettierconfig' to format
Supply the path to an ignore file such as `.gitignore` or `.prettierignore`.
Files which match will not be formatted. Set to `null` to not read ignore files. Restart required.

#### prettier.config (default: setting is not used)
Supply the path to a prettier config file such as `.prettierrc`. Restart required.

#### prettier.disableLanguages (default: ["vue"])
A list of languages IDs to disable this extension on. Restart required.
*Note: Disabling a language enabled in a parent folder will prevent formatting instead of letting any other formatter to run*
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@
"description": "Path to a .prettierignore or similar file",
"scope": "resource"
},
"prettier.config": {
"type": "string",
"description": "Path to prettier config file",
"scope": "resource"
},
"prettier.printWidth": {
"type": "integer",
"default": 80,
Expand Down
13 changes: 8 additions & 5 deletions src/PrettierEditProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
} from 'vscode';

import { safeExecution, addToOutput, setUsedModule } from './errorHandler';
import { getGroup, getParsersFromLanguageId, getConfig } from './utils';
import { getGroup, getParsersFromLanguageId, getConfig, getAbsolutePath } from './utils';
import { requireLocalPkg } from './requirePkg';

import {
Expand All @@ -30,8 +30,8 @@ const STYLE_PARSERS: ParserOption[] = ['postcss', 'css', 'less', 'scss'];
* Check if a given file has an associated prettierconfig.
* @param filePath file's path
*/
async function hasPrettierConfig(filePath: string) {
const { config } = await resolveConfig(filePath);
async function hasPrettierConfig(filePath: string, configPath?: string) {
const { config } = await resolveConfig(filePath, { config: configPath });
return config !== null;
}

Expand All @@ -44,7 +44,7 @@ type ResolveConfigResult = { config: PrettierConfig | null; error?: Error };
*/
async function resolveConfig(
filePath: string,
options?: { editorconfig?: boolean }
options?: { editorconfig?: boolean, config?: string }
): Promise<ResolveConfigResult> {
try {
const config = await bundledPrettier.resolveConfig(filePath, options);
Expand Down Expand Up @@ -128,14 +128,17 @@ async function format(
lang.parsers.includes(parser)
);

const hasConfig = await hasPrettierConfig(fileName);
const config = getAbsolutePath(uri, getConfig(uri).config);

const hasConfig = await hasPrettierConfig(fileName, config);

if (!hasConfig && vscodeConfig.requireConfig) {
return text;
}

const { config: fileOptions, error } = await resolveConfig(fileName, {
editorconfig: true,
config,
});

if (error) {
Expand Down
8 changes: 8 additions & 0 deletions src/configCacheHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { basename } from 'path';
import { workspace } from 'vscode';
import { Prettier } from './types';
import { getConfig } from './utils';

const prettier = require('prettier') as Prettier;
/**
Expand All @@ -15,6 +17,12 @@ const PRETTIER_CONFIG_FILES = [
'prettier.config.js',
];

const prettierConfigPath = getConfig().config;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There may be multiple config files, one per workspace folder.
This is just reading one.

To do it correctly, we would need to set up file change hooks for every files. And remove them when needed.

When a workspace folder is added, check the config and register a hook for it if needed
When a workspace folder is removed, remove the file watcher if it exists


if (prettierConfigPath) {
PRETTIER_CONFIG_FILES.push(basename(prettierConfigPath));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It shouldn't be in this array, see previous comment.

}

/**
* Create a file watcher. Clears prettier's configuration cache on
* file change, create, delete.
Expand Down
28 changes: 3 additions & 25 deletions src/ignoreFileHandler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { readFileSync, existsSync } from 'fs';
import * as path from 'path';
import { workspace, Uri, Disposable } from 'vscode';
import { getConfig } from './utils';
import { getConfig, getAbsolutePath } from './utils';
import { addToOutput } from './errorHandler';

const ignore = require('ignore');
Expand Down Expand Up @@ -32,10 +32,8 @@ function ignoreFileHandler(disposables: Disposable[]) {
function getIgnorerForFile(
fsPath: string
): { ignorer: Ignorer; ignoreFilePath: string } {
const absolutePath = getIgnorePathForFile(
fsPath,
getConfig(Uri.file(fsPath)).ignorePath
);
const uri = Uri.file(fsPath);
const absolutePath = getAbsolutePath(uri, getConfig(uri).ignorePath);

if (!absolutePath) {
return { ignoreFilePath: '', ignorer: nullIgnorer };
Expand Down Expand Up @@ -86,24 +84,4 @@ function ignoreFileHandler(disposables: Disposable[]) {
}
}

function getIgnorePathForFile(
filePath: string,
ignorePath: string
): string | null {
// Configuration `prettier.ignorePath` is set to `null`
if (!ignorePath) {
return null;
}
if (workspace.workspaceFolders) {
const folder = workspace.getWorkspaceFolder(Uri.file(filePath));
return folder ? getPath(ignorePath, folder.uri.fsPath) : null;
}

return null;
}

function getPath(fsPath: string, relativeTo: string) {
return path.isAbsolute(fsPath) ? fsPath : path.join(relativeTo, fsPath);
}

export default ignoreFileHandler;
8 changes: 8 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ interface ExtensionConfig {
* Path to '.prettierignore' or similar.
*/
ignorePath: string;
/**
* Path to prettier config file.
*/
config: string;
/**
* If true will skip formatting if a prettierconfig isn't found.
*/
Expand Down Expand Up @@ -95,6 +99,10 @@ export interface Prettier {
* read editorconfig, defaults to false.
*/
editorconfig?: boolean;
/**
* Path to the config file to use, optional.
*/
config?: string;
}
) => Promise<PrettierConfig>;
clearConfigCache: () => void;
Expand Down
19 changes: 19 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isAbsolute, join } from 'path';
import { workspace, Uri } from 'vscode';
import { basename } from 'path';
import {
Expand Down Expand Up @@ -54,3 +55,21 @@ export function getGroup(group: string): PrettierSupportInfo['languages'] {
function getSupportLanguages(version?: string) {
return (require('prettier') as Prettier).getSupportInfo(version).languages;
}

/**
* Get absolute path for relative or absolute filePath.
* Relative to uri's workspace folder in relative case.
*/
export function getAbsolutePath(uri: Uri, filePath: string): string | undefined {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

if (!filePath) {
return undefined;
}
if (isAbsolute(filePath)) {
return filePath;
}
if (workspace.workspaceFolders) {
const folder = workspace.getWorkspaceFolder(uri);
return folder && join(folder.uri.fsPath, filePath);
}
return undefined;
}
3 changes: 3 additions & 0 deletions testProject/config/.foo
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"semi": false
}
3 changes: 3 additions & 0 deletions testProject/config/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"semi": false
}
3 changes: 3 additions & 0 deletions testProject/config/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"prettier.config": ".foo"
}
5 changes: 5 additions & 0 deletions testProject/config/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const x = 1

const f = () => {
return 1
}