13
13
* See the License for the specific language governing permissions and
14
14
* limitations under the License.
15
15
*/
16
+ import * as fs from 'fs' ;
17
+ import * as path from 'path' ;
16
18
import { Options } from './cli' ;
17
19
import { createProgram } from './lint' ;
18
20
19
21
const clangFormat = require ( 'clang-format' ) ;
20
22
21
- const baseArgs = [ '-style=file' ] ;
23
+ const BASE_ARGS_FILE = [ '-style=file' ] ;
24
+ const BASE_ARGS_INLINE =
25
+ [ '-style' , '{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}' ] ;
22
26
23
27
/**
24
28
* Run tslint fix and clang fix with the default configuration
@@ -33,6 +37,13 @@ export async function format(
33
37
fix = false ;
34
38
}
35
39
40
+ // If the project has a .clang-format – use it. Else use the default as an
41
+ // inline argument.
42
+ const baseClangFormatArgs =
43
+ fs . existsSync ( path . join ( options . targetRootDir , '.clang-format' ) ) ?
44
+ BASE_ARGS_FILE :
45
+ BASE_ARGS_INLINE ;
46
+
36
47
const program = createProgram ( options ) ;
37
48
// Obtain a list of source files to format.
38
49
// We use program.getRootFileNames to get only the files that match the
@@ -45,9 +56,9 @@ export async function format(
45
56
program . getRootFileNames ( ) . filter ( f => ! f . endsWith ( '.d.ts' ) ) ;
46
57
47
58
if ( fix ) {
48
- return await fixFormat ( srcFiles ) ;
59
+ return await fixFormat ( srcFiles , baseClangFormatArgs ) ;
49
60
} else {
50
- const result = await checkFormat ( srcFiles ) ;
61
+ const result = await checkFormat ( srcFiles , baseClangFormatArgs ) ;
51
62
if ( ! result ) {
52
63
options . logger . log (
53
64
'clang-format reported errors... run `gts fix` to address.' ) ;
@@ -61,7 +72,7 @@ export async function format(
61
72
*
62
73
* @param srcFiles list of source files
63
74
*/
64
- function fixFormat ( srcFiles : string [ ] ) : Promise < boolean > {
75
+ function fixFormat ( srcFiles : string [ ] , baseArgs : string [ ] ) : Promise < boolean > {
65
76
return new Promise < boolean > ( ( resolve , reject ) => {
66
77
const args = baseArgs . concat ( [ '-i' ] , srcFiles ) ;
67
78
clangFormat . spawnClangFormat ( args , ( err ?: Error ) => {
@@ -80,7 +91,7 @@ function fixFormat(srcFiles: string[]): Promise<boolean> {
80
91
*
81
92
* @param srcFiles list of source files
82
93
*/
83
- function checkFormat ( srcFiles : string [ ] ) : Promise < boolean > {
94
+ function checkFormat ( srcFiles : string [ ] , baseArgs : string [ ] ) : Promise < boolean > {
84
95
return new Promise < boolean > ( ( resolve , reject ) => {
85
96
let output = '' ;
86
97
const args = baseArgs . concat ( [ '-output-replacements-xml' ] , srcFiles ) ;
0 commit comments