Skip to content

Commit 9a09258

Browse files
cortinicometa-codesync[bot]
authored andcommitted
Add Swift to yarn format
Summary: Add `yarn format-swift` and `yarn format-check-swift` using Apple swift-format, and compose them into the repository-wide commands. The wrapper selects a repository-provided formatter when available or uses swift-format 6.3 or newer from the Swift toolchain. Missing tools produce environment-specific setup guidance before Swift is skipped. Changelog: [Internal] Differential Revision: D119487615
1 parent 769c00e commit 9a09258

3 files changed

Lines changed: 206 additions & 2 deletions

File tree

‎.swift-format‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
{
2+
"fileScopedDeclarationPrivacy": {
3+
"accessLevel": "private"
4+
},
5+
"indentConditionalCompilationBlocks": false,
6+
"indentSwitchCaseLabels": false,
7+
"indentation": {
8+
"spaces": 2
9+
},
10+
"lineBreakAroundMultilineExpressionChainComponents": false,
11+
"lineBreakBeforeControlFlowKeywords": false,
12+
"lineBreakBeforeEachArgument": false,
13+
"lineBreakBeforeEachGenericRequirement": false,
14+
"lineBreakBetweenDeclarationAttributes": false,
15+
"lineLength": 2000,
16+
"maximumBlankLines": 1,
17+
"multiElementCollectionTrailingCommas": true,
18+
"orderedImports": {
19+
"includeConditionalImports": false,
20+
"shouldGroupImports": false
21+
},
22+
"noAssignmentInExpressions": {
23+
"allowedFunctions": [
24+
"XCTAssertNoThrow"
25+
]
26+
},
27+
"prioritizeKeepingFunctionOutputTogether": true,
28+
"reflowMultilineStringLiterals": {
29+
"never": {}
30+
},
31+
"respectsExistingLineBreaks": true,
32+
"rules": {
33+
"AllPublicDeclarationsHaveDocumentation": false,
34+
"AlwaysUseLiteralForEmptyCollectionInit": false,
35+
"AlwaysUseLowerCamelCase": false,
36+
"AmbiguousTrailingClosureOverload": false,
37+
"AvoidRetroactiveConformances": false,
38+
"BeginDocumentationCommentWithOneLineSummary": false,
39+
"DoNotUseSemicolons": true,
40+
"DontRepeatTypeInStaticProperties": false,
41+
"FileScopedDeclarationPrivacy": false,
42+
"FullyIndirectEnum": false,
43+
"GroupNumericLiterals": false,
44+
"IdentifiersMustBeASCII": false,
45+
"NeverForceUnwrap": false,
46+
"NeverUseForceTry": false,
47+
"NeverUseImplicitlyUnwrappedOptionals": false,
48+
"NoAccessLevelOnExtensionDeclaration": false,
49+
"NoAssignmentInExpressions": true,
50+
"NoBlockComments": false,
51+
"NoCasesWithOnlyFallthrough": false,
52+
"NoEmptyLinesOpeningClosingBraces": false,
53+
"NoEmptyTrailingClosureParentheses": false,
54+
"NoLabelsInCasePatterns": false,
55+
"NoLeadingUnderscores": false,
56+
"NoParensAroundConditions": true,
57+
"NoPlaygroundLiterals": false,
58+
"NoVoidReturnOnFunctionSignature": true,
59+
"OmitExplicitReturns": false,
60+
"OneCasePerLine": false,
61+
"OneVariableDeclarationPerLine": true,
62+
"OnlyOneTrailingClosureArgument": false,
63+
"OrderedImports": true,
64+
"ReplaceForEachWithForLoop": false,
65+
"ReturnVoidInsteadOfEmptyTuple": true,
66+
"TypeNamesShouldBeCapitalized": false,
67+
"UseEarlyExits": false,
68+
"UseExplicitNilCheckInConditions": false,
69+
"UseLetInEveryBoundCaseVariable": false,
70+
"UseShorthandTypeNames": false,
71+
"UseSingleLinePropertyGetter": false,
72+
"UseSynthesizedInitializer": false,
73+
"UseTripleSlashForDocumentationComments": false,
74+
"UseWhereClausesInForLoops": false,
75+
"ValidateDocumentationComments": false
76+
},
77+
"spacesAroundRangeFormationOperators": false,
78+
"spacesBeforeEndOfLineComments": 1,
79+
"tabWidth": 8,
80+
"version": 1
81+
}

‎package.json‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,20 @@
1414
"cxx-api-validate": "python -m scripts.cxx-api.parser --validate",
1515
"flow-check": "flow full-check",
1616
"flow": "flow",
17-
"format-check": "yarn format-check-javascript && yarn format-check-cpp && yarn format-check-kotlin && yarn format-check-java && yarn format-check-python",
17+
"format-check": "yarn format-check-javascript && yarn format-check-cpp && yarn format-check-kotlin && yarn format-check-java && yarn format-check-python && yarn format-check-swift",
1818
"format-check-cpp": "node ./scripts/clang-format.js --check",
1919
"format-check-java": "node ./scripts/format-java.js --check",
2020
"format-check-javascript": "prettier --check \"./**/*.{cjs,cts,flow,js,jsx,md,mjs,mts,ts,tsx,yaml,yml}\"",
2121
"format-check-kotlin": "node ./scripts/format-kotlin.js --check",
2222
"format-check-python": "node ./scripts/format-python.js --check",
23-
"format": "yarn format-javascript && yarn format-cpp && yarn format-kotlin && yarn format-java && yarn format-python",
23+
"format-check-swift": "node ./scripts/format-swift.js --check",
24+
"format": "yarn format-javascript && yarn format-cpp && yarn format-kotlin && yarn format-java && yarn format-python && yarn format-swift",
2425
"format-cpp": "node ./scripts/clang-format.js",
2526
"format-java": "node ./scripts/format-java.js",
2627
"format-javascript": "prettier --write \"./**/*.{cjs,cts,flow,js,jsx,md,mjs,mts,ts,tsx,yaml,yml}\"",
2728
"format-kotlin": "node ./scripts/format-kotlin.js",
2829
"format-python": "node ./scripts/format-python.js",
30+
"format-swift": "node ./scripts/format-swift.js",
2931
"featureflags": "yarn --cwd packages/react-native featureflags",
3032
"js-api-diff": "node ./scripts/js-api/diff-api-snapshot",
3133
"lint-markdown": "markdownlint-cli2 2>&1",

‎scripts/format-swift.js‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @noflow
8+
* @format
9+
*/
10+
11+
'use strict';
12+
13+
const {
14+
IS_META_CHECKOUT,
15+
commandVersion,
16+
findMetaTool,
17+
} = require('./format-utils');
18+
const {spawnSync} = require('node:child_process');
19+
const fs = require('node:fs');
20+
const path = require('node:path');
21+
const {globSync} = require('tinyglobby');
22+
23+
const REPO_ROOT = path.resolve(__dirname, '..');
24+
const CONFIG = path.join(REPO_ROOT, '.swift-format');
25+
const GENERATED_MARKER = Buffer.from('@' + 'generated');
26+
const MINIMUM_SWIFT_FORMAT_MAJOR = 6;
27+
const MINIMUM_SWIFT_FORMAT_MINOR = 3;
28+
const MAX_FILES_PER_PROCESS = 100;
29+
const MAX_HEADER_BYTES = 4096;
30+
const IGNORE = ['**/Pods/**', '**/build/**', '**/node_modules/**'];
31+
32+
function isGenerated(file) {
33+
const fd = fs.openSync(path.resolve(REPO_ROOT, file), 'r');
34+
try {
35+
const header = Buffer.alloc(MAX_HEADER_BYTES);
36+
const bytesRead = fs.readSync(fd, header, 0, header.length, 0);
37+
return header.subarray(0, bytesRead).includes(GENERATED_MARKER);
38+
} finally {
39+
fs.closeSync(fd);
40+
}
41+
}
42+
43+
function findSwiftFormat() {
44+
const candidates = [];
45+
if (process.env.SWIFT_FORMAT != null) {
46+
candidates.push([process.env.SWIFT_FORMAT, []]);
47+
} else {
48+
const metaSwiftFormat = findMetaTool(
49+
'tools',
50+
'lint',
51+
'swift-format',
52+
'swift-format',
53+
);
54+
if (metaSwiftFormat != null) {
55+
candidates.push([
56+
metaSwiftFormat.command,
57+
metaSwiftFormat.prefixArguments,
58+
]);
59+
}
60+
candidates.push(['swift-format', []], ['swift', ['format']]);
61+
}
62+
for (const [command, prefixArguments] of candidates) {
63+
const result = commandVersion(command, prefixArguments);
64+
const version = /(\d+)\.(\d+)(?:\.\d+)?/.exec(result.output);
65+
if (
66+
result.status === 0 &&
67+
version != null &&
68+
(Number(version[1]) > MINIMUM_SWIFT_FORMAT_MAJOR ||
69+
(Number(version[1]) === MINIMUM_SWIFT_FORMAT_MAJOR &&
70+
Number(version[2]) >= MINIMUM_SWIFT_FORMAT_MINOR))
71+
) {
72+
return {command, prefixArguments};
73+
}
74+
}
75+
const instructions = IS_META_CHECKOUT
76+
? 'Meta: unset SWIFT_FORMAT and run `tools/lint/swift-format/swift-format --version` from the fbsource root. If that fails, repair your Meta DotSlash setup.'
77+
: 'Please install Swift 6.3 or newer and make sure `swift-format` or `swift` is in your PATH, or set SWIFT_FORMAT=/path/to/swift-format.';
78+
console.warn(
79+
'warning: Skipping Swift formatting because swift-format 6.3 or newer was not found.\n' +
80+
instructions,
81+
);
82+
return null;
83+
}
84+
85+
function main() {
86+
const check = process.argv[2] === '--check';
87+
const files = globSync('**/*.swift', {cwd: REPO_ROOT, ignore: IGNORE}).filter(
88+
file => !isGenerated(file),
89+
);
90+
const swiftFormat = findSwiftFormat();
91+
if (swiftFormat == null) {
92+
return;
93+
}
94+
95+
for (let i = 0; i < files.length; i += MAX_FILES_PER_PROCESS) {
96+
const result = spawnSync(
97+
swiftFormat.command,
98+
[
99+
...swiftFormat.prefixArguments,
100+
check ? 'lint' : 'format',
101+
'--configuration',
102+
CONFIG,
103+
...(check ? ['--strict'] : ['--in-place']),
104+
...files.slice(i, i + MAX_FILES_PER_PROCESS),
105+
],
106+
{cwd: REPO_ROOT, stdio: 'inherit'},
107+
);
108+
if (result.error != null) {
109+
throw result.error;
110+
}
111+
if (result.signal != null) {
112+
process.kill(process.pid, result.signal);
113+
return;
114+
}
115+
if (result.status !== 0) {
116+
process.exit(result.status ?? 1);
117+
}
118+
}
119+
}
120+
121+
main();

0 commit comments

Comments
 (0)