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

Auto format on save #815

Merged
merged 5 commits into from
Jan 14, 2016
Merged
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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ JavaScript developers can now just open a `.ts` file and start hacking away like
* Project Build Support
* `package.json` Support
* React Support
* Format code
* Format code (configurable to be on save)
* Goto Declaration
* Find References
* Block comment and uncomment
Expand Down Expand Up @@ -107,6 +107,8 @@ Covered here : http://basarat.gitbooks.io/typescript/content/docs/jsx/tsx.html
## Format Code
Shortcut : `ctrl+alt+l` or `cmd+alt+l`. Will format just the selection if you have something selected otherwise it will format the entire file.

Format on save is covered [here](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#formatOnSave)

## Go to Declaration
Shortcut : `F12`. Will open the *first* declaration of the said item for now. (Note: some people call it Go to Definition)

Expand Down
3 changes: 3 additions & 0 deletions dist/main/atom/onSaveHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ function handle(event) {
if (fileDetails.project.buildOnSave) {
atom.commands.dispatch(atom.views.getView(event.editor), 'typescript:build');
}
if (fileDetails.project.atom.formatOnSave) {
atom.commands.dispatch(atom.views.getView(event.editor), 'typescript:format-code');
}
});
}
exports.handle = handle;
4 changes: 2 additions & 2 deletions dist/main/tsconfig/tsconfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ function getDefaultInMemoryProject(srcFile) {
compileOnSave: true,
buildOnSave: false,
scripts: {},
atom: { rewriteTsconfig: true },
atom: { rewriteTsconfig: true, formatOnSave: false },
};
return {
projectFileDirectory: dir,
Expand Down Expand Up @@ -253,7 +253,7 @@ function getProjectSync(pathOrSrcFile) {
externalTranspiler: projectSpec.externalTranspiler == undefined ? undefined : projectSpec.externalTranspiler,
scripts: projectSpec.scripts || {},
buildOnSave: !!projectSpec.buildOnSave,
atom: { rewriteTsconfig: true }
atom: { rewriteTsconfig: true, formatOnSave: !!projectSpec.atom.formatOnSave }
};
var validationResult = validator.validate(projectSpec.compilerOptions);
if (validationResult.errorMessage) {
Expand Down
17 changes: 15 additions & 2 deletions docs/tsconfig.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ i.e. an empty JSON file at the *root* of your project :heart: This will be suffi
* [`compileOnSave`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#compileonsave) : Should AtomTS compile on save
* [`buildOnSave`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#buildonsave) : Should AtomTS build on save
* [`scripts`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#scripts) : Sometimes its useful to have post build scripts
* [`atom`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#rewriteTsconfig) : Configuration specific to Atom. Currently
only contains `rewriteTsconfig` which prevents Atom from rewriting a project's `tsconfig.json`.
* [`atom`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#atom) : Configuration specific to Atom.
* [`rewriteTsconfig`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#rewriteTsconfig) which prevents Atom from rewriting a project's `tsconfig.json`
* [`formatOnSave`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#formatOnSave) which will format the Typescript file on save.

## Examples

Expand Down Expand Up @@ -134,5 +135,17 @@ to `false` (this defaults to `true`).
}
```

**formatOnSave**

Setting this to `true` will format the entire file exactly like `ctrl+alt+l` or `cmd+alt+l` does on save. (this defaults to `false`)

```json
{
"atom": {
"formatOnSave": true
}
}
```

## Additional Notes
FWIW [a json schema is also available](http://json.schemastore.org/tsconfig)
7 changes: 7 additions & 0 deletions lib/main/atom/onSaveHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,12 @@ export function handle(event: { filePath: string; editor: AtomCore.IEditor }) {
'typescript:build');
}

if (fileDetails.project.atom.formatOnSave) {
// Trigger a format
atom.commands.dispatch(
atom.views.getView(event.editor),
'typescript:format-code');
}

});
}
36 changes: 18 additions & 18 deletions lib/main/tsconfig/tsconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ interface TypeScriptProjectRawSpecification {
buildOnSave?: boolean;
externalTranspiler?: string | { name: string; options?: any };
scripts?: { postbuild?: string };
atom?: { rewriteTsconfig?: boolean };
atom?: { rewriteTsconfig?: boolean, formatOnSave?: boolean };
}

/**
Expand All @@ -157,7 +157,7 @@ export interface TypeScriptProjectSpecification {
package?: UsefulFromPackageJson;
externalTranspiler?: string | { name: string; options?: any };
scripts: { postbuild?: string };
atom: { rewriteTsconfig: boolean };
atom: { rewriteTsconfig: boolean, formatOnSave: boolean };
}

///////// FOR USE WITH THE API /////////////
Expand Down Expand Up @@ -290,7 +290,7 @@ function mixin(target: any, source: any): any {

function rawToTsCompilerOptions(jsonOptions: CompilerOptions, projectDir: string): ts.CompilerOptions {
// Cannot use Object.create because the compiler checks hasOwnProperty
var compilerOptions = <ts.CompilerOptions> mixin({}, defaults);
var compilerOptions = <ts.CompilerOptions>mixin({}, defaults);
for (var key in jsonOptions) {
if (typescriptEnumMap[key]) {
compilerOptions[key] = typescriptEnumMap[key][jsonOptions[key].toLowerCase()];
Expand Down Expand Up @@ -322,7 +322,7 @@ function rawToTsCompilerOptions(jsonOptions: CompilerOptions, projectDir: string

function tsToRawCompilerOptions(compilerOptions: ts.CompilerOptions): CompilerOptions {
// Cannot use Object.create because JSON.stringify will only serialize own properties
var jsonOptions = <CompilerOptions> mixin({}, compilerOptions);
var jsonOptions = <CompilerOptions>mixin({}, compilerOptions);

Object.keys(compilerOptions).forEach((key) => {
if (jsonEnumMap[key] && compilerOptions[key]) {
Expand Down Expand Up @@ -350,7 +350,7 @@ export function getDefaultInMemoryProject(srcFile: string): TypeScriptProjectFil
compileOnSave: true,
buildOnSave: false,
scripts: {},
atom: { rewriteTsconfig: true },
atom: { rewriteTsconfig: true, formatOnSave: false },
};

return {
Expand All @@ -375,8 +375,8 @@ export function getProjectSync(pathOrSrcFile: string): TypeScriptProjectFileDeta
var projectFile = tsconfig.resolveSync(dir);

if (!projectFile) {
throw errorWithDetails<GET_PROJECT_NO_PROJECT_FOUND_Details>(
new Error(errors.GET_PROJECT_NO_PROJECT_FOUND), { projectFilePath: fsu.consistentPath(pathOrSrcFile), errorMessage: 'not found' });
throw errorWithDetails<GET_PROJECT_NO_PROJECT_FOUND_Details>(
new Error(errors.GET_PROJECT_NO_PROJECT_FOUND), { projectFilePath: fsu.consistentPath(pathOrSrcFile), errorMessage: 'not found' });
}

var projectFileDirectory = path.dirname(projectFile) + path.sep;
Expand Down Expand Up @@ -442,7 +442,7 @@ export function getProjectSync(pathOrSrcFile: string): TypeScriptProjectFileDeta
externalTranspiler: projectSpec.externalTranspiler == undefined ? undefined : projectSpec.externalTranspiler,
scripts: projectSpec.scripts || {},
buildOnSave: !!projectSpec.buildOnSave,
atom: { rewriteTsconfig: true }
atom: { rewriteTsconfig: true, formatOnSave: !!projectSpec.atom.formatOnSave }
};

// Validate the raw compiler options before converting them to TS compiler options
Expand Down Expand Up @@ -521,7 +521,7 @@ function increaseProjectForReferenceAndImports(files: string[]): string[] {
}
}

var getReferencedOrImportedFiles = (files: string[]): string[]=> {
var getReferencedOrImportedFiles = (files: string[]): string[] => {
var referenced: string[][] = [];

files.forEach(file => {
Expand Down Expand Up @@ -553,7 +553,7 @@ function increaseProjectForReferenceAndImports(files: string[]): string[] {
return file;
}
return getIfExists(file);
}).filter(file=> !!file)
}).filter(file => !!file)
.concat(
preProcessedFileInfo.importedFiles
.filter((fileReference) => pathIsRelative(fileReference.fileName))
Expand All @@ -564,7 +564,7 @@ function increaseProjectForReferenceAndImports(files: string[]): string[] {
file = getIfExists(`${file}/index`);
}
return file;
}).filter(file=> !!file)
}).filter(file => !!file)
)
);
});
Expand Down Expand Up @@ -610,9 +610,9 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou
// Find our `typings` (anything in a typings folder with extension `.d.ts` is considered a typing)
// These are INF powerful
var ourTypings = files
.filter(f=> path.basename(path.dirname(f)) == 'typings' && endsWith(f, '.d.ts')
.filter(f => path.basename(path.dirname(f)) == 'typings' && endsWith(f, '.d.ts')
|| path.basename(path.dirname(path.dirname(f))) == 'typings' && endsWith(f, '.d.ts'));
ourTypings.forEach(f=> typings[path.basename(f)] = { filePath: f, version: Infinity });
ourTypings.forEach(f => typings[path.basename(f)] = { filePath: f, version: Infinity });
var existing = createMap(files.map(fsu.consistentPath));

function addAllReferencedFilesWithMaxVersion(file: string) {
Expand All @@ -635,7 +635,7 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou
if (fs.existsSync(file + '.d.ts')) {
return file + '.d.ts';
}
}).filter(f=> !!f);
}).filter(f => !!f);

// Only ones we don't have by name yet
// TODO: replace INF with an actual version
Expand All @@ -644,7 +644,7 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou
// Add these
files.forEach(f => typings[path.basename(f)] = { filePath: f, version: Infinity });
// Keep expanding
files.forEach(f=> addAllReferencedFilesWithMaxVersion(f));
files.forEach(f => addAllReferencedFilesWithMaxVersion(f));
}

// Keep going up till we find node_modules
Expand Down Expand Up @@ -691,11 +691,11 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou

var all = Object.keys(typings)
.map(typing => typings[typing].filePath)
.map(x=> fsu.consistentPath(x));
.map(x => fsu.consistentPath(x));
var implicit = all
.filter(x=> !existing[x]);
.filter(x => !existing[x]);
var ours = all
.filter(x=> existing[x]);
.filter(x => existing[x]);

return { implicit, ours, packagejson };
}
Expand Down
3 changes: 2 additions & 1 deletion lib/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@
],
"exclude": [],
"atom": {
"rewriteTsconfig": true
"rewriteTsconfig": true,
"formatOnSave": false
}
}