node_modules\react-native\react.gradle' line: 286 - react-native

i am trying to build my app but i am getting error building it
errors are:
Task :app:bundleReleaseJsAndAssets FAILED
FAILURE: Build completed with 2 failures.
1: Task failed with an exception.
Where:
Script 'C:\Users\Ali Yousafzai\Desktop\ProjectFiver\BluetoothPlanner\node_modules\react-native\react.gradle' line: 286
What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
Process 'command 'cmd'' finished with non-zero exit value 1
2: Task failed with an exception.
What went wrong:
java.lang.StackOverflowError (no error message)
this is my react.gradle file
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.internal.jvm.Jvm
def config = project.hasProperty("react") ? project.react : [:];
def detectEntryFile(config) {
if (System.getenv('ENTRY_FILE')) {
return System.getenv('ENTRY_FILE')
} else if (config.entryFile) {
return config.entryFile
} else if ((new File("${projectDir}/../../index.android.js")).exists()) {
return "index.android.js"
}
return "index.js";
}
def composeSourceMapsPath = config.composeSourceMapsPath ?: "node_modules/react-native/scripts/compose-source-maps.js"
def bundleAssetName = config.bundleAssetName ?: "index.android.bundle"
def entryFile = detectEntryFile(config)
def bundleCommand = config.bundleCommand ?: "bundle"
def reactRoot = file(config.root ?: "../../")
def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"]
def bundleConfig = config.bundleConfig ? "${reactRoot}/${config.bundleConfig}" : null ;
def enableVmCleanup = config.enableVmCleanup == null ? true : config.enableVmCleanup
def hermesCommand = config.hermesCommand
/**
* Detects CLI location in a similar fashion to the React Native CLI
*/
def detectCliPath(config, reactRoot) {
// 1. preconfigured path
if (config.cliPath) {
def cliJsAbsolute = new File(config.cliPath)
if (cliJsAbsolute.exists()) {
return cliJsAbsolute.getAbsolutePath()
}
def cliJsRelativeToRoot = new File("${rootDir}/${config.cliPath}")
if (cliJsRelativeToRoot.exists()) {
return cliJsRelativeToRoot.getAbsolutePath()
}
def cliJsRelativeToProject = new File("${projectDir}/${config.cliPath}")
if (cliJsRelativeToProject.exists()) {
return cliJsRelativeToProject.getAbsolutePath()
}
}
// 2. node module path
def cliJsFromNode = new File(["node", "--print", "require.resolve('react-native/cli').bin"].execute(null, rootDir).text.trim())
if (cliJsFromNode.exists()) {
return cliJsFromNode.getAbsolutePath()
}
// 3. cli.js in the root folder
def rootCliJs = new File(reactRoot, "node_modules/react-native/cli.js")
if (rootCliJs.exists()) {
return rootCliJs.getAbsolutePath()
}
throw new Exception("Couldn't determine CLI location. " +
"Please set `project.ext.react.cliPath` to the path of the react-native cli.js file. " +
"This file typically resides in `node_modules/react-native/cli.js`");
}
def reactNativeDevServerPort() {
def value = project.getProperties().get("reactNativeDevServerPort")
return value != null ? value : "8081"
}
def reactNativeInspectorProxyPort() {
def value = project.getProperties().get("reactNativeInspectorProxyPort")
return value != null ? value : reactNativeDevServerPort()
}
def getHermesOSBin() {
if (Os.isFamily(Os.FAMILY_WINDOWS)) return "win64-bin";
if (Os.isFamily(Os.FAMILY_MAC)) return "osx-bin";
if (Os.isOs(null, "linux", "amd64", null)) return "linux64-bin";
throw new Exception("OS not recognized. Please set project.ext.react.hermesCommand " +
"to the path of a working Hermes compiler.");
}
// Make sure not to inspect the Hermes config unless we need it,
// to avoid breaking any JSC-only setups.
def getHermesCommand = {
// 1. If the project specifies a Hermes command, don't second guess it.
if (config.hermesCommand?.trim()) {
if (hermesCommand.contains("%OS-BIN%")) {
return hermesCommand
.replaceAll("%OS-BIN%", getHermesOSBin())
.replace('/' as char, File.separatorChar)
} else {
return hermesCommand
.replace('/' as char, File.separatorChar)
}
}
def hermescBin = Os.isFamily(Os.FAMILY_WINDOWS) ? 'hermesc.exe' : 'hermesc'
// 2. If the project is building hermes-engine from source, use hermesc from there
// Also note that user can override the hermes source location with
// the `REACT_NATIVE_OVERRIDE_HERMES_DIR` env variable.
def hermesOverrideDir = System.getenv("REACT_NATIVE_OVERRIDE_HERMES_DIR")
def builtHermesc = hermesOverrideDir ?
new File(hermesOverrideDir, "build/bin/$hermescBin") :
new File(reactRoot, "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/$hermescBin")
if (builtHermesc.exists()) {
return builtHermesc.getAbsolutePath()
}
// 3. If the react-native contains a pre-built hermesc, use it.
def prebuiltHermesPath = "node_modules/react-native/sdks/hermesc/%OS-BIN%/$hermescBin"
.replaceAll("%OS-BIN%", getHermesOSBin())
.replace('/' as char, File.separatorChar);
def prebuiltHermes = new File(reactRoot, prebuiltHermesPath)
if (prebuiltHermes.exists()) {
return prebuiltHermes.getAbsolutePath()
}
throw new Exception("Couldn't determine Hermesc location. " +
"Please set `project.ext.react.hermesCommand` to the path of the hermesc binary file. " +
"node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc");
}
// Set enableHermesForVariant to a function to configure per variant,
// or set `enableHermes` to True/False to set all of them
def enableHermesForVariant = config.enableHermesForVariant ?: {
def variant -> config.enableHermes ?: false
}
// Set hermesFlagsForVariant to a function to configure per variant,
// or set `hermesFlagsRelease` and `hermesFlagsDebug` to an array
def hermesFlagsForVariant = config.hermesFlagsForVariant ?: {
def variant ->
def hermesFlags;
if (variant.name.toLowerCase().contains("release")) {
// Can't use ?: since that will also substitute valid empty lists
hermesFlags = config.hermesFlagsRelease
if (hermesFlags == null) hermesFlags = ["-O", "-output-source-map"]
} else {
hermesFlags = config.hermesFlagsDebug
if (hermesFlags == null) hermesFlags = []
}
return hermesFlags
}
// Set disableDevForVariant to a function to configure per variant,
// defaults to `devDisabledIn${targetName}` or True for Release variants and False for debug variants
def disableDevForVariant = config.disableDevForVariant ?: {
def variant ->
config."devDisabledIn${variant.name.capitalize()}" ||
variant.name.toLowerCase().contains("release")
}
// Set bundleForVariant to a function to configure per variant,
// defaults to `bundleIn${targetName}` or True for Release variants and False for debug variants
def bundleForVariant = config.bundleForVariant ?: {
def variant ->
config."bundleIn${variant.name.capitalize()}" ||
config."bundleIn${variant.buildType.name.capitalize()}" ||
variant.name.toLowerCase().contains("release")
}
// Set deleteDebugFilesForVariant to a function to configure per variant,
// defaults to True for Release variants and False for debug variants
def deleteDebugFilesForVariant = config.deleteDebugFilesForVariant ?: {
def variant -> variant.name.toLowerCase().contains("release")
}
android {
buildTypes.all {
resValue "integer", "react_native_dev_server_port", reactNativeDevServerPort()
resValue "integer", "react_native_inspector_proxy_port", reactNativeInspectorProxyPort()
}
}
def jvmVersion = Jvm.current().javaVersion.majorVersion
if (jvmVersion.toInteger() <= 8) {
println "\n\n\n"
println "**************************************************************************************************************"
println "\n\n"
println "ERROR: requires JDK11 or higher."
println "Incompatible major version detected: '" + jvmVersion + "'"
println "\n\n"
println "**************************************************************************************************************"
println "\n\n\n"
System.exit(1)
}
afterEvaluate {
def isAndroidLibrary = plugins.hasPlugin("com.android.library")
def variants = isAndroidLibrary ? android.libraryVariants : android.applicationVariants
variants.all { def variant ->
// Create variant and target names
def targetName = variant.name.capitalize()
def targetPath = variant.dirName
// React js bundle directories
def jsBundleDir = file("$buildDir/generated/assets/react/${targetPath}")
def resourcesDir = file("$buildDir/generated/res/react/${targetPath}")
def jsBundleFile = file("$jsBundleDir/$bundleAssetName")
def jsSourceMapsDir = file("$buildDir/generated/sourcemaps/react/${targetPath}")
def jsIntermediateSourceMapsDir = file("$buildDir/intermediates/sourcemaps/react/${targetPath}")
def jsPackagerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.packager.map")
def jsCompilerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.compiler.map")
def jsOutputSourceMapFile = file("$jsSourceMapsDir/${bundleAssetName}.map")
// Additional node and packager commandline arguments
def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"]
def cliPath = detectCliPath(config, reactRoot)
def execCommand = []
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
execCommand.addAll(["cmd", "/c", *nodeExecutableAndArgs, cliPath])
} else {
execCommand.addAll([*nodeExecutableAndArgs, cliPath])
}
def enableHermes = enableHermesForVariant(variant)
def currentBundleTask = tasks.create(
name: "bundle${targetName}JsAndAssets",
type: Exec) {
group = "react"
description = "bundle JS and assets for ${targetName}."
// Create dirs if they are not there (e.g. the "clean" task just ran)
doFirst {
jsBundleDir.deleteDir()
jsBundleDir.mkdirs()
resourcesDir.deleteDir()
resourcesDir.mkdirs()
jsIntermediateSourceMapsDir.deleteDir()
jsIntermediateSourceMapsDir.mkdirs()
jsSourceMapsDir.deleteDir()
jsSourceMapsDir.mkdirs()
}
// Set up inputs and outputs so gradle can cache the result
inputs.files fileTree(dir: reactRoot, excludes: inputExcludes)
outputs.dir(jsBundleDir)
outputs.dir(resourcesDir)
// Set up the call to the react-native cli
workingDir(reactRoot)
// Set up dev mode
def devEnabled = !disableDevForVariant(variant)
def extraArgs = []
if (bundleConfig) {
extraArgs.add("--config")
extraArgs.add(bundleConfig)
}
// Hermes doesn't require JS minification.
if (enableHermes && !devEnabled) {
extraArgs.add("--minify")
extraArgs.add("false")
}
if (config.extraPackagerArgs) {
extraArgs.addAll(config.extraPackagerArgs)
}
commandLine(*execCommand, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
"--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir,
"--sourcemap-output", enableHermes ? jsPackagerSourceMapFile : jsOutputSourceMapFile, *extraArgs)
if (enableHermes) {
doLast {
def hermesFlags = hermesFlagsForVariant(variant)
def hbcTempFile = file("${jsBundleFile}.hbc")
exec {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine("cmd", "/c", getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
} else {
commandLine(getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
}
}
ant.move(
file: hbcTempFile,
toFile: jsBundleFile
);
if (hermesFlags.contains("-output-source-map")) {
ant.move(
// Hermes will generate a source map with this exact name
file: "${jsBundleFile}.hbc.map",
tofile: jsCompilerSourceMapFile
);
exec {
// TODO: set task dependencies for caching
// Set up the call to the compose-source-maps script
workingDir(reactRoot)
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine("cmd", "/c", *nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
} else {
commandLine(*nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
}
}
}
}
}
enabled bundleForVariant(variant)
}
// Expose a minimal interface on the application variant and the task itself:
variant.ext.bundleJsAndAssets = currentBundleTask
currentBundleTask.ext.generatedResFolders = files(resourcesDir).builtBy(currentBundleTask)
currentBundleTask.ext.generatedAssetsFolders = files(jsBundleDir).builtBy(currentBundleTask)
// registerGeneratedResFolders for Android plugin 3.x
if (variant.respondsTo("registerGeneratedResFolders")) {
variant.registerGeneratedResFolders(currentBundleTask.generatedResFolders)
} else {
variant.registerResGeneratingTask(currentBundleTask)
}
variant.mergeResourcesProvider.get().dependsOn(currentBundleTask)
// packageApplication for Android plugin 3.x
def packageTask = variant.hasProperty("packageApplication")
? variant.packageApplicationProvider.get()
: tasks.findByName("package${targetName}")
if (variant.hasProperty("packageLibrary")) {
packageTask = variant.packageLibrary
}
// pre bundle build task for Android plugin 3.2+
def buildPreBundleTask = tasks.findByName("build${targetName}PreBundle")
def resourcesDirConfigValue = config."resourcesDir${targetName}"
if (resourcesDirConfigValue) {
def currentCopyResTask = tasks.create(
name: "copy${targetName}BundledResources",
type: Copy) {
group = "react"
description = "copy bundled resources into custom location for ${targetName}."
from(resourcesDir)
into(file(resourcesDirConfigValue))
dependsOn(currentBundleTask)
enabled(currentBundleTask.enabled)
}
packageTask.dependsOn(currentCopyResTask)
if (buildPreBundleTask != null) {
buildPreBundleTask.dependsOn(currentCopyResTask)
}
}
def currentAssetsCopyTask = tasks.create(
name: "copy${targetName}BundledJs",
type: Copy) {
group = "react"
description = "copy bundled JS into ${targetName}."
from(jsBundleDir)
if (config."jsBundleDir${targetName}") {
into(file(config."jsBundleDir${targetName}"))
} else {
into ("$buildDir/intermediates")
if (isAndroidLibrary) {
into ("library_assets/${variant.name}/out")
} else {
into ("assets/${targetPath}")
// Workaround for Android Gradle Plugin 3.2+ new asset directory
into ("merged_assets/${variant.name}/merge${targetName}Assets/out")
// Workaround for Android Gradle Plugin 3.4+ new asset directory
into ("merged_assets/${variant.name}/out")
// Workaround for Android Gradle Plugin 7.1 asset directory
into("$buildDir/intermediates/assets/${variant.name}/merge${targetName}Assets")
}
}
// mergeAssets must run first, as it clears the intermediates directory
dependsOn(variant.mergeAssetsProvider.get())
enabled(currentBundleTask.enabled)
dependsOn(currentBundleTask)
}
// mergeResources task runs before the bundle file is copied to the intermediate asset directory from Android plugin 4.1+.
// This ensures to copy the bundle file before mergeResources task starts
def mergeResourcesTask = tasks.findByName("merge${targetName}Resources")
mergeResourcesTask.dependsOn(currentAssetsCopyTask)
packageTask.dependsOn(currentAssetsCopyTask)
if (buildPreBundleTask != null) {
buildPreBundleTask.dependsOn(currentAssetsCopyTask)
}
// Delete the VM related libraries that this build doesn't need.
// The application can manage this manually by setting 'enableVmCleanup: false'
//
// This should really be done by packaging all Hermes related libs into
// two separate HermesDebug and HermesRelease AARs, but until then we'll
// kludge it by deleting the .so files out of the /transforms/ directory.
def cleanup = deleteDebugFilesForVariant(variant)
def vmSelectionAction = { libDir ->
fileTree(libDir).matching {
if (enableHermes) {
// For Hermes, delete all the libjsc* files
include "**/libjsc*.so"
if (cleanup) {
// Reduce size by deleting the debugger/inspector
include '**/libhermes-executor-debug.so'
} else {
// Release libs take precedence and must be removed
// to allow debugging
include '**/libhermes-executor-release.so'
}
} else {
// For JSC, delete all the libhermes* files
include "**/libhermes*.so"
}
}.visit { details ->
def targetVariant1 = ".*/transforms/[^/]*/${variant.name}/.*"
def targetVariant2 = ".*/merged_native_libs/${variant.name}/out/lib/.*"
def targetVariant3 = ".*/stripped_native_libs/${variant.name}/out/lib/.*"
def path = details.file.getAbsolutePath().replace(File.separatorChar, '/' as char)
if ((path.matches(targetVariant1) || path.matches(targetVariant2) || path.matches(targetVariant3)) && details.file.isFile()) {
details.file.delete()
}
}
}
if (enableVmCleanup) {
def task = tasks.findByName("package${targetName}")
if (task != null) {
def transformsLibDir = "$buildDir/intermediates/transforms/"
task.doFirst { vmSelectionAction(transformsLibDir) }
}
def sTask = tasks.findByName("strip${targetName}DebugSymbols")
if (sTask != null) {
def strippedLibDir = "$buildDir/intermediates/stripped_native_libs/${variant.name}/out/lib/"
sTask.doLast { vmSelectionAction(strippedLibDir) }
}
def mTask = tasks.findByName("merge${targetName}NativeLibs")
if (mTask != null) {
def mergedLibDir = "$buildDir/intermediates/merged_native_libs/${variant.name}/out/lib/"
mTask.doLast { vmSelectionAction(mergedLibDir) }
}
}
}
}
// Patch needed for https://github.com/facebook/react-native/issues/35210
// This is a patch to short-circuit the "+" dependencies inside the
// users' app/build.gradle file and the various .gradle files of libraries.
// As using plain "+" dependencies causes Gradle to always download the latest,
// this logic forces Gradle to use latest release in the minor series.
project.rootProject.allprojects {
configurations.all {
resolutionStrategy {
force "com.facebook.react:react-native:0.70.+"
force "com.facebook.react:hermes-engine:0.70.+"
}
}
}

I was in the same situation, the problem is when you have a space in the directory path.
This only happens on Windows + Hermes + folders that have a space in the path
For more details check this post
A quick fix is ​​to remove the space from the path
C:\Users\Ali Yousafzai\ -> C:\Users\AliYousafzai\
or
Just zip your project and move the file to a folder with no space
C:\yourproject

Related

Terraform flappy state

I have created a Terraform project in order to create s3-buckets, cross region replication, versioning and a livecycle rule to delete old versions.
The problem is, that whenever I run terraform, it want's to delete the cross region replication and livecycle rule, if it exists in AWS, and whenever it does not exist anymore, it wants to readd it. This happens without any code change.
It seems that the state is not accurate.
I already deleted everything from scratch in AWS and started from the beginning, but it didn't help. I always run into the flappy situation.
All the details:
$ terraform init && terraform plan -var-file xyz.tfvars
...
Terraform will perform the following actions:
# module.test_s3_bucket["bnpl-docs"].aws_s3_bucket.s3_bucket will be updated in-place
~ resource "aws_s3_bucket" "s3_bucket" {
id = "bnpl-docs"
tags = {}
# (11 unchanged attributes hidden)
- replication_configuration {
- role = "arn:aws:iam::....:role/bnpl-docs-s3-bucket-replication" -> null
- rules {
- id = "version-replication" -> null
- priority = 0 -> null
- status = "Enabled" -> null
- destination {
- bucket = "arn:aws:s3:::bnpl-docs-crr" -> null
- storage_class = "STANDARD" -> null
}
}
}
# (1 unchanged block hidden)
}
# module.test_s3_bucket["bnpl-docs"].aws_s3_bucket_lifecycle_configuration.s3_bucket[0] will be created
+ resource "aws_s3_bucket_lifecycle_configuration" "s3_bucket" {
+ bucket = "bnpl-docs"
+ id = (known after apply)
+ rule {
+ id = "version-retention"
+ status = "Enabled"
+ expiration {
+ days = 0
+ expired_object_delete_marker = true
}
+ noncurrent_version_expiration {
+ noncurrent_days = 30
}
}
}
Plan: 1 to add, 1 to change, 0 to destroy.
But result is both is missing in AWS after running apply.
When I rerun, i get the same output:
Terraform will perform the following actions:
# module.test_s3_bucket["bnpl-docs"].aws_s3_bucket.s3_bucket will be updated in-place
~ resource "aws_s3_bucket" "s3_bucket" {
id = "bnpl-docs"
tags = {}
# (11 unchanged attributes hidden)
- replication_configuration {
- role = "arn:aws:iam::......:role/bnpl-docs-s3-bucket-replication" -> null
- rules {
- id = "version-replication" -> null
- priority = 0 -> null
- status = "Enabled" -> null
- destination {
- bucket = "arn:aws:s3:::bnpl-docs-crr" -> null
- storage_class = "STANDARD" -> null
}
}
}
# (1 unchanged block hidden)
}
# module.test_s3_bucket["bnpl-docs"].aws_s3_bucket_lifecycle_configuration.s3_bucket[0] will be created
+ resource "aws_s3_bucket_lifecycle_configuration" "s3_bucket" {
+ bucket = "bnpl-docs"
+ id = (known after apply)
+ rule {
+ id = "version-retention"
+ status = "Enabled"
+ expiration {
+ days = 0
+ expired_object_delete_marker = true
}
+ noncurrent_version_expiration {
+ noncurrent_days = 30
}
}
}
Plan: 1 to add, 1 to change, 0 to destroy.
But result is both is created in AWS after running apply.
I have created several modules to realize what I want. The involved code:
module "test_s3_bucket" {
source = "./modules/test-s3-bucket"
for_each = local.aws_s3_bucket_map
bucket_name = each.key
versioning = each.value.version_config
}
module "test_s3_bucket_repli" {
source = "./modules/test-s3-bucket"
providers = {
aws = aws.repli
}
for_each = local.aws_s3_bucket_map_repli
bucket_name = each.key
versioning = each.value.version_config
}
module "test_s3_bucket_repli_config" {
source = "./modules/test-s3-bucket-replication"
for_each = local.aws_s3_bucket_map_repli
src_bucket = {
name = module.test_s3_bucket[each.value.src_bucket_name].name
arn = module.test_s3_bucket[each.value.src_bucket_name].arn
}
dest_bucket = {
name = module.test_s3_bucket_repli[each.key].name
arn = module.test_s3_bucket_repli[each.key].arn
}
}
Contents of test_s3_bucket-Module:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
##
# Bucket with configuration
##
resource "aws_s3_bucket" "s3_bucket" {
bucket = var.bucket_name
}
resource "aws_s3_bucket_acl" "s3_bucket" {
bucket = aws_s3_bucket.s3_bucket.id
acl = "private"
}
resource "aws_s3_bucket_versioning" "s3_bucket" {
bucket = aws_s3_bucket.s3_bucket.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_lifecycle_configuration" "s3_bucket" {
count = var.versioning == null ? 0 : 1
bucket = aws_s3_bucket.s3_bucket.id
rule {
id = var.versioning.rule_id
expiration {
expired_object_delete_marker = true
}
noncurrent_version_expiration {
noncurrent_days = var.versioning.expiration_days
}
status = "Enabled"
}
}
resource "aws_s3_bucket_public_access_block" "s3_bucket" {
bucket = aws_s3_bucket.s3_bucket.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
The contents of the test-s3-bucket-replication module:
erraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
resource "aws_s3_bucket_replication_configuration" "bucket_main" {
bucket = var.src_bucket.name
role = aws_iam_role.s3_bucket_main_replication.arn
rule {
id = "version-replication"
status = "Enabled"
destination {
bucket = var.dest_bucket.arn
storage_class = "STANDARD"
}
}
}
resource "aws_iam_role" "s3_bucket_main_replication" {
name = "${var.src_bucket.name}-s3-bucket-replication"
assume_role_policy = file("${path.module}/files/policies/sts-s3-assume.json")
}
resource "aws_iam_policy" "s3_bucket_main_replication" {
name = "${var.src_bucket.name}-s3-bucket-replication"
policy = templatefile("${path.module}/files/policies/s3-bucket-replication.json", {
source_bucket_arn = var.src_bucket.arn,
destination_bucket_arn = var.dest_bucket.arn,
})
}
resource "aws_iam_role_policy_attachment" "s3_bucket_main_replication" {
role = aws_iam_role.s3_bucket_main_replication.name
policy_arn = aws_iam_policy.s3_bucket_main_replication.arn
}
You see the two configuration parts which kind of seem to be in conflict are spread over two modules. I'm unsure if this is a problem. I'm kinda new to terraform :)
After increasing the Loglevel via TF_LOG="DEBUG", I found out that those two ressources conflicted with the bucket configuration - the aws_s3_bucket-configuration did not include any configuration for lifecycle or replication (as suggested by the documentation), but terraform expected this legacy declaration somehow.
I was using AWS Provider 3.75 and upgraded to 4.X. After this upgrade, everything works as expected.

Regenerate missing package-lock.json file from node_modules

The original developers for my project didn't commit the package-lock.json file, only the package.json file. I created my own package-lock.json file when I did npm install, but that was 5 years ago and I didn't realise at the time that I needed to check the file into Git because I stupidly assumed that the original developers knew what they were doing.
Now we have a second developer, plus I need to add a new package. Both of these things require that I have the "original" package-lock.json file.
Is there a way to reconstruct the package-lock.json file using npm from the contents of my node_modules directory which is now the only source of truth? I have looked at various answers and tried a few npm commands, such as npm i --package-lock-only, but that gave me a file as it would be created today, not the file based on my node_modules directory.
So, not finding an answer, I've spent the last two days writing some PHP code to do the job for me. The code is not complete, for example it assumes that the only production modules will be angular and angular-ui-router because I didn't need anything more complicated with my project. However, it's good enough to create an exact copy of the package-lock.json file, minus optional dependencies that weren't installed, because it can't resolve versions of packages it can't find.
The code was written to work, not necessarily to be easy to understand, so it might be a little opaque.
It's run with:
<?php
$package_lock = new PackageLock();
// or
$package_lock = new PackageLock('path/to/packages');
The code:
<?php
class PackageLock {
protected const MY_PACKAGE = 'my-package';
protected const MY_VERSION = '0.0.0';
//
protected const FILE_NAME = 'package-lock-recreated.json';
protected const NODE_MODULES = 'node_modules';
//
protected array $modules = [];
protected array $packages = [
'name' => PackageLock::MY_PACKAGE,
'version' => PackageLock::MY_VERSION,
'lockfileVersion' => 1,
'requires' => true,
];
protected string $dir;
public function __construct(string $dir = '.') {
$this->dir = $dir;
$this->packages['dependencies'] = $this->parse();
file_put_contents(PackageLock::FILE_NAME, preg_replace('/^( +)\1/m', '$1', json_encode($this->packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)));
}
protected function parse(array $priors = []): array {
$nm = PackageLock::NODE_MODULES;
$requests = $priors;
array_unshift($requests, '');
$current_priors = $requests;
$current_priors[] = '';
$main_path = $this->dir . implode("/{$nm}/", $current_priors);
$dir_pattern = $main_path . '*';
$dirs = glob($dir_pattern);
$current_dir = dirname($dir_pattern, 2);
$dependencies = [];
foreach ($dirs as $dir) {
$module_name = basename($dir);
if (in_array($module_name, ['angular-moment-picker', 'json-loader', 'moment-timezone'])) {
continue;
}
$this->modules[$dir] = json_decode(file_get_contents("{$dir}/package.json"));
}
foreach ($this->modules as $dir => $module) {
if (strpos($dir, $main_path) !== 0) {
continue;
}
$module_name = basename($dir);
$dependencies[$module_name] = [
'version' => $module->version,
'resolved' => $module->_resolved,
'integrity' => $module->_integrity,
];
if (!$this->is_prod($module_name)) {
$dependencies[$module_name]['dev'] = true;
}
if ($this->is_optional($main_path . $module_name)) {
$dependencies[$module_name]['optional'] = true;
}
if (!empty($module->dependencies) && (array)$module->dependencies) {
$dependencies[$module_name]['requires'] = $module->dependencies;
}
if (is_dir("{$current_dir}/{$nm}/{$module_name}/{$nm}")) {
$dependencies[$module_name]['dependencies'] = $this->parse_dependencies($priors, $module_name);
}
}
return $dependencies;
}
protected function is_prod($module_name): bool {
return in_array($module_name, ['angular', 'angular-ui-router']);
}
protected function parse_dependencies(array $priors, string $module_name): array {
$priors[] = $module_name;
return $this->parse($priors);
}
protected function is_optional($key): bool {
$module_name = basename($key);
$is_optional = false;
if (!array_key_exists($key, $this->modules)) {
var_dump("Key does not exist: {$key}");
}
if ($this->modules[$key]) {
foreach ($this->modules[$key]->_requiredBy as $parent_module_path) {
if (in_array($parent_module_path, ['/', '#USER', '#DEV:/'])) {
break;
}
$parent_module_path = $this->module_to_file_path($parent_module_path);
if (array_key_exists($parent_module_path, $this->modules)) {
$is_optional = $this->check_optional($parent_module_path, $module_name);
}
else {
$file_name = "{$parent_module_path}/package.json";
if (!file_exists($file_name)) {
$is_optional = true;
}
else {
$this->modules[$parent_module_path] = json_decode(file_get_contents($file_name));
$is_optional = $this->check_optional($parent_module_path, $module_name);
unset($this->modules[$parent_module_path]);
}
}
if (!$is_optional) {
break;
}
}
}
return $is_optional;
}
protected function module_to_file_path($module_path): string {
return $this->dir . str_replace('/', '/' . PackageLock::NODE_MODULES . '/', $module_path);
}
protected function check_optional(string $parent_module_path, $module_name): bool {
if (
!empty($this->modules[$parent_module_path]->optionalDependencies)
&& property_exists($this->modules[$parent_module_path]->optionalDependencies, $module_name)
) {
$is_optional = true;
}
else {
$is_optional = $this->is_optional($parent_module_path);
}
return $is_optional;
}
}

Is it possible call a javascript function inside karate-config.js file using karate.callSingle method?

reqres.feature
Feature: Reqres api test cases
Background: base url
Given url base_url
* def validateResponse = read('classpath:helpers/common_assertions.js')
Scenario: list single user get request
Given path single_user_path
When method get
Then status 200
* validateResponse()
common_assertion.js
function common_assertions() {
var contentType = karate.get("responseHeaders['Content-Type'][0]");
if (contentType !== 'application/json; charset=utf-8') {
karate.fail('content type is not json');
}
var responseType = karate.get('responseType');
if (responseType !== 'json') {
karate.fail('response type is not json');
}
var responseTime = karate.get('responseTime');
if (responseTime > 5000) {
karate.fail('response is too slow');
}
}
karate-config.js
function fn() {
var env = karate.env; // get system property 'karate.env'
karate.log('karate.env system property was:', env);
if (!env) {
env = 'dev';
}
var config = {
base_url: 'https://reqres.in/api',
single_user_path: '/users/2'
};
if (env == 'dev') {
// customize
// e.g. config.foo = 'bar';
} else if (env == 'e2e') {
// customize
}
return config;
}
I would like to use common_assertions.js file in karate-config.js file rather than using in the background section so that i can reuse * validateResponse() method across all feature files. Is there a way?Please help

ListDir which contains only pdf files

I need a help regarding Ionic-4 code.I want to list the directories which contains only PDF files in it using lisDir method.
Thanks in advance.
Try the following code, this should work in Android, I didn't get time to test this but should work;
constructor(public navCtrl: NavController, public platform: Platform,
private filePath: FilePath, private file: File) {
this.platform.ready().then(() => {
this.file.listDir(file.externalDataDirectory, '').then((result) => {
console.log(result);
for (const fl of result) {
if (fl.isDirectory == true && fl.name != '.' && fl.name != '..') {
// Code if its a folder
} else if (fl.isFile == true) {
const fName = fl.name; // File name
const path = fl.fullPath; // File path
if(fName.toLowerCase().endsWith('.pdf')) {
// do Something
}
}
}
});
});
}

What is the syntax of keybinds.settings?

What is the syntax of the keybinds.settings? I am a vim user, and I would ultimately like to:
bind shift-j to go down 8 lines (nnoremap J 8j)
the same with k (nnoremak J 8k)
Use , as a "leader", i.e. I would like to bind ",b" to "build", and perhaps ",g" to run "ghci file-name" in a terminal.
keybinding.settings file works only for cloud9 commands for now, for customizing vim commands you will have to use init script (see Open Your Init Script item in Cloud9 menu)
You can use following snippet
require(["plugins/c9.ide.ace.keymaps/vim/keymap"], function(vim) {
var defaultKeymap = vim.aceKeyboardHandler.defaultKeymap;
function ideCommand() { services.commands.exec(this.name); }
function map(keys, action, context) {
var mapping;
if (!action) {
return defaultKeymap.forEach(function(x) {
if (x.keys == keys) {
x.defaultKeys = keys;
x.keys = "";
}
});
} else if (/^c9:/.test(action)) {
var commandName = action.substr(3);
mapping = {
keys: keys, type: "action", action: "aceCommand",
actionArgs: { exec: ideCommand, name: commandName }
};
} else {
mapping = { keys: keys, type: "keyToKey", toKeys: action };
}
if (context)
mapping.context = context;
mapping.user = true;
defaultKeymap.unshift(mapping);
}
map("J", "8j", "normal");
map("K", "8k", "normal");
map(",", ""); // remove default mapping of ,
map(",b", "c9:build", "normal");
map(",g", "c9:run", "normal");
});
note that for ,g you need to create ghci runner, see https://docs.c9.io/custom_runners.html for details.