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

chore: Refactore gradle task to JS scripts #3001

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
26 changes: 26 additions & 0 deletions .github/workflows/check-archs-consistency.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Test consistency between Paper & Fabric
on:
pull_request:
branches:
- main
paths:
- src/specs/**
- android/paper/src/java/com/facebook/react/viewmanagers/**
maciekstosio marked this conversation as resolved.
Show resolved Hide resolved
jobs:
check:
runs-on: ubuntu-latest
concurrency:
group: check-archs-consistency-${{ github.ref }}
cancel-in-progress: true
steps:
- name: checkout
uses: actions/checkout@v4
- name: Use Node.js 18
uses: actions/setup-node@v4
with:
node-version: 18
cache: 'yarn'
- name: Install node dependencies
run: yarn
- name: Check Android Paper & Fabric generated interfaces consistency
run: yarn check-archs-consistency
57 changes: 0 additions & 57 deletions .github/workflows/check-paper-integrity.yml

This file was deleted.

2 changes: 0 additions & 2 deletions FabricExample/android/gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,3 @@ newArchEnabled=true
# Use this property to enable or disable the Hermes JS engine.
# If set to false, you will be using JSC instead.
hermesEnabled=true

isGHExampleApp=true
103 changes: 0 additions & 103 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -207,106 +207,3 @@ dependencies {
implementation "androidx.core:core-ktx:1.6.0"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

def isGHExampleApp() {
return project.hasProperty('isGHExampleApp') && project.property('isGHExampleApp') == "true"
}

def getAbsoluteCodegenArtifactsPaperDestination() {
if (!project.hasProperty('codegenArtifactsPaperDestination')) {
throw new Exception('[react-native-gesture-handler] Please fill codegenArtifactsPaperDestination variable in android/gradle.properties to point to the correct path to generated specs for paper')
}

return "${project.rootDir}/../../${project.property('codegenArtifactsPaperDestination')}"
}

def getAbsoluteCodegenArtifactsSource() {
if (!project.hasProperty('codegenArtifactsSource')) {
throw new Exception('[react-native-gesture-handler] Please fill codegenArtifactsSource variable in android/gradle.properties to point to the correct path to codegenerated artifacts')
}

return "${project.rootDir}/../../${project.property('codegenArtifactsSource')}"
}


tasks.register('copyCodegenArtifacts') {
group 'After build tasks'
description 'Task which copies codegen artifacts to paper architecture'

if (!isGHExampleApp() || !isNewArchitectureEnabled()) {
return
}

dependsOn tasks.generateCodegenArtifactsFromSchema

doLast {

def absoluteCodegenArtifactsPaperDestination = getAbsoluteCodegenArtifactsPaperDestination()
def absoluteCodegenArtifactsSource = getAbsoluteCodegenArtifactsSource()

def existingFiles = fileTree(absoluteCodegenArtifactsPaperDestination).matching {
include '**/*.java'
}

def generatedFiles = fileTree(absoluteCodegenArtifactsSource).matching {
include '**/*.java'
}

def existingFilesMap = [:]

existingFiles.forEach { existingFile ->
println existingFile
existingFilesMap[existingFile.name] = 1
}

generatedFiles.forEach { generatedFile ->
if (!existingFilesMap.containsKey(generatedFile.name)) {
logger.warn("[react-native-gesture-handler] ${generatedFile.name} not found in paper dir, if it's used on Android you need to copy it manually and implement yourself before using auto-copy feature.")
}
}

if (existingFiles.size() == 0) {
logger.warn("[react-native-gesture-handler] Paper destination with codegen interfaces is empty. This might be okay if you don't have any interfaces/delegates used on Android, but if that's not the case please check if codegenArtifactsPaperDestination property in android/gradle.properties is correct.")
}

existingFiles.forEach { existingFile ->
def generatedFile = new File("${absoluteCodegenArtifactsSource}/${existingFile.name}")

if (!generatedFile.exists()) {
logger.warn("[react-native-gesture-handler] ${existingFile.name} file does not exist in codegen artifacts source destination. Please check if you still need this interface/delagete.")
}
}

copy {
from absoluteCodegenArtifactsSource
include existingFiles.collect { it.name }
into absoluteCodegenArtifactsPaperDestination
}
}
}

if (isGHExampleApp() && isNewArchitectureEnabled() && !project.hasProperty('skipCodegenCopyTask')) {
tasks.generateCodegenArtifactsFromSchema.finalizedBy('copyCodegenArtifacts')
}

if (project == rootProject) {
tasks.register('checkIntegrityBetweenArchitectures') {
group 'Verification tasks'
description 'Task to check integrity between fabric and paper architecture in terms of codegen generated interfaces/delegates'

def absoluteCodegenArtifactsPaperDestination = "../${project.property('codegenArtifactsPaperDestination')}"
def absoluteCodegenArtifactsSource = "../${project.property('codegenArtifactsSource')}"

def existingFiles = fileTree(absoluteCodegenArtifactsPaperDestination).matching {
include '**/*.java'
}

existingFiles.forEach { existingFile ->
def generatedFile = new File("${absoluteCodegenArtifactsSource}/${existingFile.name}")

if (existingFile.text != generatedFile.text) {
throw new RuntimeException("[react-native-gesture-handler] The source of ${existingFile.name} does not match with the one generated by codegen. Please check if you commited changes produced by copyCodegenArtifacts task.")
}
}
}
}
7 changes: 0 additions & 7 deletions android/gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,3 @@ org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemor
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
RNGH_kotlinVersion=1.6.21

# Path to codegen output directory with this library view managers' interfaces & delegates. Used by `copyCodegenArtifacts` task that helps to synchronize newly generated files with their Paper counterparts.
codegenArtifactsSource=android/build/generated/source/codegen/java/com/facebook/react/viewmanagers

# Path to directory with view managers' interfaces & delegates used while running on Paper architecture. This property is used as the output path for `copyCodegenArtifacts` task.
# Used by copyCodegenArtifacts task that automates copying those interfaces/delegates after codegen is run.
codegenArtifactsPaperDestination=android/paper/src/main/java/com/facebook/react/viewmanagers
12 changes: 7 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
"lint:js": "eslint --ext '.js,.ts,.tsx' src/ example/src FabricExample/src MacOSExample/src && yarn prettier --check './{src,example,FabricExample,MacOSExample}/**/*.{js,jsx,ts,tsx}'",
"lint:js-root": "eslint --ext '.js,.ts,.tsx' src/ && yarn prettier --check './src/**/*.{js,jsx,ts,tsx}'",
"lint:android": "./android/gradlew -p android spotlessCheck -q",
"cross-arch-integrity-check": "(cd ./FabricExample/android && ./gradlew generateCodegenArtifactsFromSchema -PskipCodegenCopyTask) && (cd ./android && ./gradlew checkIntegrityBetweenArchitectures)",
"circular-dependency-check": "yarn madge --extensions js,ts,tsx --circular src"
"circular-dependency-check": "yarn madge --extensions js,ts,tsx --circular src",
"check-archs-consistency": "node ./scripts/codegen-check-consistency.js",
maciekstosio marked this conversation as resolved.
Show resolved Hide resolved
"sync-archs": "node ./scripts/codegen-sync-archs.js"
maciekstosio marked this conversation as resolved.
Show resolved Hide resolved
},
"react-native": "src/index.ts",
"main": "lib/commonjs/index.js",
Expand Down Expand Up @@ -98,13 +99,13 @@
"eslint-plugin-jest": "^26.0.0",
"expo": "^35.0.1",
"husky": "^8.0.1",
"jest": "^26.6.3",
"jest": "^28.1.0",
"lint-staged": "^12.3.2",
"madge": "^6.1.0",
"prettier": "2.7.1",
"react": "18.2.0",
"react-dom": "^16.12.0",
"react-native": "0.74.1",
"react-native": "0.74.3",
"react-native-builder-bob": "^0.17.1",
"react-native-reanimated": "^3.12.0",
"react-native-web": "^0.11.7",
Expand All @@ -119,7 +120,8 @@
"lint-staged": {
"./{src,example,FabricExample,MacOSExample}/**/*.{ts,tsx}": "yarn format:js",
"android/**/*.kt": "yarn format:android",
"apple/**/*.{h,m,mm,cpp}": "yarn format:ios"
"apple/**/*.{h,m,mm,cpp}": "yarn format:ios",
"src/specs/*.ts": "yarn sync-archs"
maciekstosio marked this conversation as resolved.
Show resolved Hide resolved
},
"release-it": {
"hooks": {
Expand Down
3 changes: 3 additions & 0 deletions scripts/codegen-check-consistency.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { checkCodegenIntegrity } = require('./codegen-utils');

checkCodegenIntegrity();
3 changes: 3 additions & 0 deletions scripts/codegen-sync-archs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { generateCodegenJavaOldArch } = require('./codegen-utils');

generateCodegenJavaOldArch();
122 changes: 122 additions & 0 deletions scripts/codegen-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const packageJSON = require('../package.json');

const ERROR_PREFIX = 'react-native-gesture-handler';
const ROOT_DIR = path.resolve(__dirname, '..');
const ANDROID_DIR = path.resolve(ROOT_DIR, 'android');
const GENERATED_DIR = path.resolve(ANDROID_DIR, 'build/generated');
const OLD_ARCH_DIR = path.resolve(ANDROID_DIR, 'paper/src/main');
const SPECS_DIR = path.resolve(ROOT_DIR, packageJSON.codegenConfig.jsSrcsDir);
const PACKAGE_NAME = packageJSON.codegenConfig.android.javaPackageName;
const RN_DIR = path.resolve(ROOT_DIR, 'node_modules/react-native');
const RN_CODEGEN_DIR = path.resolve(
ROOT_DIR,
'node_modules/@react-native/codegen'
);

const SOURCE_FOLDERS = 'java/com/facebook/react/viewmanagers';
maciekstosio marked this conversation as resolved.
Show resolved Hide resolved
const CODEGEN_FILES_DIR = `${GENERATED_DIR}/source/codegen/${SOURCE_FOLDERS}`;
const OLD_ARCH_FILES_DIR = `${OLD_ARCH_DIR}/${SOURCE_FOLDERS}`;

function exec(command) {
console.log(`[${ERROR_PREFIX}]> ` + command);
execSync(command);
}

function fixOldArchJavaForRN72Compat(dir) {
// see https://github.com/rnmapbox/maps/issues/3193
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
const fileExtension = path.extname(file);
if (fileExtension === '.java') {
let fileContent = fs.readFileSync(filePath, 'utf-8');
let newFileContent = fileContent.replace(
/extends ReactContextBaseJavaModule implements TurboModule/g,
'extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule'
);
if (fileContent !== newFileContent) {
// also insert an import line with `import com.facebook.react.bridge.ReactModuleWithSpec;`
newFileContent = newFileContent.replace(
/import com.facebook.react.bridge.ReactMethod;/,
'import com.facebook.react.bridge.ReactMethod;\nimport com.facebook.react.bridge.ReactModuleWithSpec;'
);

console.log(' => fixOldArchJava applied to:', filePath);
fs.writeFileSync(filePath, newFileContent, 'utf-8');
}
} else if (fs.lstatSync(filePath).isDirectory()) {
fixOldArchJavaForRN72Compat(filePath);
}
});
}

async function generateCodegen() {
exec(`rm -rf ${GENERATED_DIR}`);
exec(`mkdir -p ${GENERATED_DIR}/source/codegen/`);

exec(
`node ${RN_CODEGEN_DIR}/lib/cli/combine/combine-js-to-schema-cli.js --platform android ${GENERATED_DIR}/source/codegen/schema.json ${SPECS_DIR}`
);
exec(
`node ${RN_DIR}/scripts/generate-specs-cli.js --platform android --schemaPath ${GENERATED_DIR}/source/codegen/schema.json --outputDir ${GENERATED_DIR}/source/codegen --javaPackageName ${PACKAGE_NAME}`
);

fixOldArchJavaForRN72Compat(`${GENERATED_DIR}/source/codegen/java/`);
}

async function generateCodegenJavaOldArch() {
await generateCodegen();

const generatedFiles = fs.readdirSync(CODEGEN_FILES_DIR);
const oldArchFiles = fs.readdirSync(OLD_ARCH_FILES_DIR);
const existingFilesSet = new Set(oldArchFiles.map(fileName => fileName));

generatedFiles.forEach(generatedFile => {
if (!existingFilesSet.has(generatedFile)) {
console.warn(
`[${ERROR_PREFIX}] ${generatedFile} not found in paper dir, if it's used on Android you need to copy it manually and implement yourself before using auto-copy feature.`
);
}
});

if (oldArchFiles.length === 0) {
console.warn(
`[${ERROR_PREFIX}] Paper destination with codegen interfaces is empty. This might be okay if you don't have any interfaces/delegates used on Android, otherwise please check if OLD_ARCH_DIR and SOURCE_FOLDERS are set properly.`
);
}

oldArchFiles.forEach(file => {
if (!fs.existsSync(`${CODEGEN_FILES_DIR}/${file}`)) {
console.warn(
`[${ERROR_PREFIX}] ${file} file does not exist in codegen artifacts source destination. Please check if you still need this interface/delagete.`
);
} else {
exec(`cp -rf ${CODEGEN_FILES_DIR}/${file} ${OLD_ARCH_FILES_DIR}/${file}`);
}
});
}

function compareFileAtTwoPaths(filename, firstPath, secondPath) {
const fileA = fs.readFileSync(`${firstPath}/${filename}`, 'utf-8');
const fileB = fs.readFileSync(`${secondPath}/${filename}`, 'utf-8');

if (fileA !== fileB) {
throw new Error(
`[${ERROR_PREFIX}] File ${filename} is different at ${firstPath} and ${secondPath}. Make sure you commited codegen autogenerated files.`
);
}
}

async function checkCodegenIntegrity() {
await generateCodegen();

const oldArchFiles = fs.readdirSync(OLD_ARCH_FILES_DIR);
oldArchFiles.forEach(file => {
compareFileAtTwoPaths(file, CODEGEN_FILES_DIR, OLD_ARCH_FILES_DIR);
});
}

module.exports = { generateCodegenJavaOldArch, checkCodegenIntegrity };
Loading
Loading