#!/bin/bash
# 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.

set -e

# Compatibility settings with MacOS.
if [[ "${MACHTYPE}" = *apple* ]]; then
  READLINK=greadlink
else
  READLINK=readlink
fi

SCRIPTS_DIRECTORY="$(dirname "$("${READLINK}" -f "$0")")"

# Gather build information.
if [[ "${1}" == 'development' ]]; then
  # Use a less precise date to avoid rebuilding the binary at every
  # 'make' invocation during development.
  BUILD_INFO="$(uname -s -m) @ $(date "+%a %b %d %Y") (development build)"
  shift
else
  BUILD_INFO="$(uname -s -m) @ $(date)"
fi
echo "Build info: ${BUILD_INFO}"

# Buck builds pass a `--out-dir <DIR>` argument indicating where to write
# artifacts.
while [ $# -gt 0 ]; do
  if [[ "$1" =~ ^--out-dir=(.*)$ ]]; then
    _OUT_DIR="${BASH_REMATCH[1]}"
  else
    echo "Unexpected arg: $1" && exit 1
  fi
  shift
done

# Gather version information.
VERSION=""
if HG_VERSION="$(hg log -r . -T '{node}')"; then
  VERSION="${HG_VERSION}"
  echo "HG revision: ${VERSION}"
elif GIT_VERSION="$(git rev-parse HEAD)"; then
  VERSION="${GIT_VERSION}"
  echo "Git commit: ${VERSION}"
else
  echo 'Cannot determine version information'
  exit 1
fi

OUT_DIR="${_OUT_DIR:-"$SCRIPTS_DIRECTORY"/../source}"
cat > "$OUT_DIR"/version.ml <<EOF
open Core

let build_info () =
  "${BUILD_INFO}"

let version () =
  "${VERSION}"

let log_version_banner () =
  Log.info "Running as pid: %d" (Pid.to_int (Core_unix.getpid ()));
  Log.info "Version: %s" (version ());
  Log.info "Build info: %s" (build_info ())
EOF

# Note: [Embedded Build Info]
# ===========================
#
# Buck executables automatically link build info that defines the symbols
# `BuildInfo_kRevision` and `BuildInfo_kRevisionCommitTimeUnix` and so there's
# no need to generate `get_build_id.c` for buck builds.
#
# See [1^] for details. For example, try
# ```
#  buck2 build @fbcode//mode/opt \
#   -c build_info.revision="$(hg log -r . -T {node})" \
#      fbcode//tools/pyre/source:main --show-output
# ```
# and inspect the results with something like
# ```
#  fbcode/tools/build_info/build_info -binary \
#     buck-out/v2/gen/fbcode/ca1f7c2b2d91f85d/tools/pyre/source/__main__/main.opt
# ```
#
# [^1]: [Build Info](https://www.internalfb.com/intern/wiki/Buck-users/fbcode-build-info/).

if [[ -n "$_OUT_DIR" ]]; then
  :
else
  OUT_DIR="$SCRIPTS_DIRECTORY"/../source/hack_parallel/hack_parallel/utils
  cat > "$OUT_DIR"/get_build_id.c <<EOF
const char* const BuildInfo_kRevision = "${VERSION}";
const unsigned long BuildInfo_kRevisionCommitTimeUnix = 0ul;
EOF
fi


#!/bin/bash
# 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.

set -e

SCRIPTS_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# For open-source tests to work, we have to run them from one directory
# higher than the project root, so that the project root is treated as a
# valid package for relative imports.
#
# We also want to be sure the tests work regardless of the project directory name
# (particularly because both `pyre-check` and `pyre` are sometimes used).
cd "${SCRIPTS_DIRECTORY}/.."
ROOT_DIRECTORY="$(pwd)"
ROOT_DIRECTORY_BASE="$(basename "${ROOT_DIRECTORY}")"

# run pyre-extensions tests first: we want to test lower-level code
# first since higher-level test failures are less informative

cd "${ROOT_DIRECTORY}"

files=$(find pyre_extensions -name '*_test.py')
echo "Found these test files in the pyre_extensions code:
${files}
---"
if [[ -z "${files}" ]]; then
  echo 'No test files found, exiting.'
  exit 2
fi

echo ' Running all tests:'
echo "${files}" | xargs testslide

# Test pyre client code last since that's the highest-level code.

cd "${ROOT_DIRECTORY}/.."

files=$(find "${ROOT_DIRECTORY_BASE}/client" -name '*_test.py' ! -name 'watchman_test.py')
echo "Found these test files in the client code:
${files}
---"
if [[ -z "${files}" ]]; then
  echo 'No test files found, exiting.'
  exit 2
fi

echo ' Running client tests:'
echo "${files}" | xargs testslide


#!/bin/bash
# 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.

# Switch to pyre directory.
cd "$(dirname "$0")/.."

./scripts/setup.py "${@}"


#!/usr/bin/env bash
# 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.

# Script to install pyre playground on a fresh ubuntu server.

set -e
set -x

sudo apt-get update

sudo apt-get install -y \
  build-essential \
  python3 \
  python3-venv \
  python3-dev \
  watchman \
  git \
  nginx

# Grab the code and link it to ~/playground
git clone https://github.com/facebook/pyre-check.git
ln -s pyre-check/tools/playground/ ~/playground
cd ~/playground

# Set up the environment. You can verify the python app works with:
#   python application.py --debug
python3 -m venv ~/play-env
source ~/play-env/bin/activate
pip install -r requirements.txt

# Start the service. You can verify it is up with:
#   curl "http://0.0.0.0:5000/check?input=reveal_type(1)"
sudo cp system/playground.service /etc/systemd/system/
sudo systemctl start playground
sudo systemctl enable playground

# Set up nginx proxy. We need to remove the default config for
# it to take effect. You can verify it is up with:
#    curl "http://0.0.0.0:80/check?input=reveal_type(1)"
sudo cp system/playground.nginx /etc/nginx/sites-available/playground
sudo ln -s /etc/nginx/sites-{available,enabled}/playground
sudo rm /etc/nginx/sites-enabled/default
sudo systemctl restart nginx

# verify that it is up
sleep 5
curl "http://0.0.0.0:80/check?input=reveal_type(1)"
echo "Server is up!"


#!/bin/bash

# This is an example script that shows how to pull the latest version
# of Rapid and replace the version string with a git short hash.
#
# To use this on your own site, you'll want to change the `cp` and `chgrp`
# lines at the end to match your web server's documentroot folder and security group.

git checkout -q main
git remote update > /dev/null

rev=`git rev-parse --short HEAD`
orig=`git rev-parse --short origin/main`

# pull latest code
if [[ "${rev}" != "${orig}" ]] ; then
  # avoid issues with local untracked locale files
  rm -f dist/locales/*.json
  git reset --hard HEAD
  git pull origin main

  rev=`git rev-parse --short HEAD`
  sed -i "s/context.version = .*;/context.version = '${rev}';/" modules/core/context.js

  npm prune
  npm install > /dev/null 2>&1
fi

# pull latest imagery
rm -rf node_modules/editor-layer-index/
git clone https://github.com/osmlab/editor-layer-index.git node_modules/editor-layer-index > /dev/null 2>&1
rm -rf node_modules/editor-layer-index/.git/

# build everything
npm run imagery
npm run all

# pull latest translations
if [[ -f transifex.auth ]] ; then
  npm run translations
fi

cp -Rf dist/* /var/www/path/to/rapid/
chgrp -R www-data /var/www/path/to/rapid/


#!/bin/bash
(cd ../.. && yarn build eslint --type=NODE_DEV)
(cd ../.. && watchman-make --make 'yarn build eslint --type=NODE_DEV' -p 'packages/eslint-plugin-*/**/*' -t ignored)


#!/bin/bash

set -e

# Make sure we don't introduce accidental references to PATENTS.
EXPECTED='scripts/circleci/check_license.sh'
ACTUAL=$(git grep -l PATENTS)

if [ "$EXPECTED" != "$ACTUAL" ]; then
  echo "PATENTS crept into some new files?"
  diff -u <(echo "$EXPECTED") <(echo "$ACTUAL") || true
  exit 1
fi


#!/bin/bash

set -e

# Make sure we don't introduce accidental @providesModule annotations.
EXPECTED='scripts/rollup/wrappers.js'
ACTUAL=$(git grep -l @providesModule -- './*.js' ':!scripts/rollup/shims/*.js')

# Colors
red=$'\e[1;31m'
end=$'\e[0m'

if [ "$EXPECTED" != "$ACTUAL" ]; then
  printf "%s\n" "${red}ERROR: @providesModule crept into some new files?${end}"
  diff -u <(echo "$EXPECTED") <(echo "$ACTUAL") || true
  exit 1
fi


#!/bin/bash

set -e

mkdir -p build/devtools

cd packages/react-devtools
npm pack
mv ./react-devtools*.tgz ../../build/devtools/

cd ../react-devtools-core
npm pack
mv ./react-devtools-core*.tgz ../../build/devtools/

cd ../react-devtools-inline
npm pack
mv ./react-devtools-inline*.tgz ../../build/devtools/

cd ../react-devtools-extensions
yarn build
mv ./chrome/build/ReactDevTools.zip ../../build/devtools/chrome-extension.zip
mv ./firefox/build/ReactDevTools.zip ../../build/devtools/firefox-extension.zip

# Compress all DevTools artifacts into a single tarball for easy download
cd ../../build/devtools
tar -zcvf ../devtools.tgz .


#!/bin/bash

set -e

WARNINGS=$(node scripts/print-warnings/print-warnings.js)
echo "$WARNINGS"
test ! -z "$WARNINGS"


#!/bin/bash
# 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.

# This script should be run from the react-native root

THIS_DIR=$(cd -P "$(dirname "$(realpath "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd)
source "scripts/.tests.env"

if [ -n "$1" ]
  then
    echo "Overriding..."
    IOS_TARGET_OS="${1}"
    SDK="iphonesimulator${1}"
    DESTINATION="platform=iOS Simulator,OS=${IOS_TARGET_OS},name=${IOS_DEVICE}"
fi

xcodebuild \
  -workspace "packages/rn-tester/RNTesterPods.xcworkspace" \
  -scheme $SCHEME \
  -sdk $SDK \
  -destination "$DESTINATION" \
  build test


#!/bin/sh
# 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.

dot -Tpdf InspectorFSM.gv -o InspectorFSM.pdf


#!/bin/bash
# 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.

THIS_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
source "$THIS_DIR/setup.sh"

buck test //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:chrome &&
  buck test //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:detail &&
  buck test //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:inspectorlib &&
  buck build //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:hermes-chrome-debug-server


#!/bin/bash
# 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.

#
# Basic setup for xplat testing in sandcastle. Based on
# xplat/hermes/facebook/sandcastle/setup.sh.

set -x
set -e
set -o pipefail

THIS_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
ROOT_DIR=$(cd "$THIS_DIR" && hg root)

# Enter xplat
cd "$ROOT_DIR"/xplat || exit 1

# Setup env
export TITLE
TITLE=$(hg log -l 1 --template "{desc|strip|firstline}")
export REV
REV=$(hg log -l 1 --template "{node}")
export AUTHOR
AUTHOR=$(hg log -l 1 --template "{author|emailuser}")

if [ -n "$SANDCASTLE" ]; then
  source automation/setup_buck.sh
fi


#!/bin/bash
# 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.

set -e

#Â WHY WE NEED THIS:
# This script is used to find a valid instance of `node` installed in the machine.
# This script is sourced by other scripts to get access to node.
# Specifically, it is used by the `react-native-xcode.sh` script, invoked by a
# post-build phase in Xcode, to build the js files required by React Native.
#
# DEPRECATION NOTE:
# React Native should not make assumptions on your current node environment.
# This file is deprecated and will be removed in a future release in favor of something
# node-agnostic and configurable by the developers.

# remove global prefix if it's already set
# the running shell process will choose a node binary and a global package directory breaks version managers
unset PREFIX

# Support Homebrew on M1
HOMEBREW_M1_BIN=/opt/homebrew/bin
if [[ -d $HOMEBREW_M1_BIN && ! $PATH =~ $HOMEBREW_M1_BIN ]]; then
  export PATH="$HOMEBREW_M1_BIN:$PATH"
fi

# Define NVM_DIR and source the nvm.sh setup script
[ -z "$NVM_DIR" ] && export NVM_DIR="$HOME/.nvm"

# Source nvm with '--no-use' and then `nvm use` to respect .nvmrc
# See: https://github.com/nvm-sh/nvm/issues/2053
if [[ -s "$HOME/.nvm/nvm.sh" ]]; then
  # shellcheck source=/dev/null
  . "$HOME/.nvm/nvm.sh" --no-use
  nvm use 2> /dev/null || nvm use default
elif [[ -x "$(command -v brew)" && -s "$(brew --prefix nvm)/nvm.sh" ]]; then
  # shellcheck source=/dev/null
  . "$(brew --prefix nvm)/nvm.sh" --no-use
  nvm use 2> /dev/null || nvm use default
fi

# Set up the nodenv node version manager if present
if [[ -x "$HOME/.nodenv/bin/nodenv" ]]; then
  eval "$("$HOME/.nodenv/bin/nodenv" init -)"
elif [[ -x "$(command -v brew)" && -x "$(brew --prefix nodenv)/bin/nodenv" ]]; then
  eval "$("$(brew --prefix nodenv)/bin/nodenv" init -)"
fi

# Set up the ndenv of anyenv if preset
if [[ ! -x node && -d ${HOME}/.anyenv/bin ]]; then
  export PATH=${HOME}/.anyenv/bin:${PATH}
  if [[ "$(anyenv envs | grep -c ndenv )" -eq 1 ]]; then
    eval "$(anyenv init -)"
  fi
fi

# Set up asdf-vm if present
if [[ -f "$ASDF_DIR/asdf.sh" ]]; then
  # shellcheck source=/dev/null
  . "$ASDF_DIR/asdf.sh"
elif [[ -f "$HOME/.asdf/asdf.sh" ]]; then
  # shellcheck source=/dev/null
  . "$HOME/.asdf/asdf.sh"
elif [[ -x "$(command -v brew)" && -f "$(brew --prefix asdf)/asdf.sh" ]]; then
  # shellcheck source=/dev/null
  . "$(brew --prefix asdf)/asdf.sh"
fi

# Set up volta if present
if [[ -x "$HOME/.volta/bin/node" ]]; then
  export VOLTA_HOME="$HOME/.volta"
  export PATH="$VOLTA_HOME/bin:$PATH"
fi

# Set up the fnm node version manager if present
if [[ -x "$HOME/.fnm/fnm" ]]; then
  eval "$("$HOME/.fnm/fnm" env)"
elif [[ -x "$(command -v brew)" && -x "$(brew --prefix fnm)/bin/fnm" ]]; then
  eval "$("$(brew --prefix fnm)/bin/fnm" env)"
fi


#!/bin/bash
# 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.

set -e

PLATFORM_NAME="${PLATFORM_NAME:-iphoneos}"
CURRENT_ARCH="${CURRENT_ARCH}"

if [ -z "$CURRENT_ARCH" ] || [ "$CURRENT_ARCH" == "undefined_arch" ]; then
    # Xcode 10 beta sets CURRENT_ARCH to "undefined_arch", this leads to incorrect linker arg.
    # it's better to rely on platform name as fallback because architecture differs between simulator and device

    if [[ "$PLATFORM_NAME" == *"simulator"* ]]; then
        CURRENT_ARCH="x86_64"
    else
        CURRENT_ARCH="arm64"
    fi
fi

# @lint-ignore-every TXT2 Tab Literal
if [ "$CURRENT_ARCH" == "arm64" ]; then
    cat <<\EOF >>fix_glog_0.3.5_apple_silicon.patch
diff --git a/config.sub b/config.sub
index 1761d8b..43fa2e8 100755
--- a/config.sub
+++ b/config.sub
@@ -1096,6 +1096,9 @@ case $basic_machine in
 		basic_machine=z8k-unknown
 		os=-sim
 		;;
+	arm64-*)
+		basic_machine=$(echo $basic_machine | sed 's/arm64/aarch64/')
+		;;
 	none)
 		basic_machine=none-none
 		os=-none
EOF

    patch -p1 config.sub fix_glog_0.3.5_apple_silicon.patch
fi

export CC="$(xcrun -find -sdk $PLATFORM_NAME cc) -arch $CURRENT_ARCH -isysroot $(xcrun -sdk $PLATFORM_NAME --show-sdk-path)"
export CXX="$CC"

# Remove automake symlink if it exists
if [ -h "test-driver" ]; then
    rm test-driver
fi

# Manually disable gflags include to fix issue https://github.com/facebook/react-native/issues/28446
sed -i.bak -e 's/\@ac_cv_have_libgflags\@/0/' src/glog/logging.h.in && rm src/glog/logging.h.in.bak
sed -i.bak -e 's/HAVE_LIB_GFLAGS/HAVE_LIB_GFLAGS_DISABLED/' src/config.h.in && rm src/config.h.in.bak

./configure --host arm-apple-darwin

cat << EOF >> src/config.h
/* Add in so we have Apple Target Conditionals */
#ifdef __APPLE__
#include <TargetConditionals.h>
#include <Availability.h>
#endif

/* Special configuration for ucontext */
#undef HAVE_UCONTEXT_H
#undef PC_FROM_UCONTEXT
#if defined(__x86_64__)
#define PC_FROM_UCONTEXT uc_mcontext->__ss.__rip
#elif defined(__i386__)
#define PC_FROM_UCONTEXT uc_mcontext->__ss.__eip
#endif
EOF

# Prepare exported header include
EXPORTED_INCLUDE_DIR="exported/glog"
mkdir -p exported/glog
cp -f src/glog/log_severity.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/raw_logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/stl_logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/vlog_is_on.h "$EXPORTED_INCLUDE_DIR/"


#!/bin/bash
# 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.

[ -z "$NODE_BINARY" ] && export NODE_BINARY="node"

nodejs_not_found()
{
  echo "error: Can't find the '$NODE_BINARY' binary to build the React Native bundle. " \
       "If you have a non-standard Node.js installation, select your project in Xcode, find " \
       "'Build Phases' - 'Bundle React Native code and images' and change NODE_BINARY to an " \
       "absolute path to your node executable. You can find it by invoking 'which node' in the terminal." >&2
  exit 2
}

type "$NODE_BINARY" >/dev/null 2>&1 || nodejs_not_found


#!/bin/bash
# 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.

# scripts directory
THIS_DIR=$(cd -P "$(dirname "$(readlink "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd)
REACT_NATIVE_ROOT="$THIS_DIR/.."
# Application root directory - General use case: react-native is a dependency
PROJECT_ROOT=${PROJECT_ROOT:-"$THIS_DIR/../../.."}

# check and assign NODE_BINARY env
# shellcheck disable=SC1090
source "${THIS_DIR}/node-binary.sh"

# Start packager from PROJECT_ROOT
cd "$PROJECT_ROOT" || exit
"$NODE_BINARY" "$REACT_NATIVE_ROOT/cli.js" start --custom-log-reporter-path "$THIS_DIR/packager-reporter.js" "$@"


#!/bin/bash
# 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.

# Bundle React Native app's code and image assets.
# This script is supposed to be invoked as part of Xcode build process
# and relies on environment variables (including PWD) set by Xcode

# Print commands before executing them (useful for troubleshooting)
set -x
DEST=$CONFIGURATION_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH

# Enables iOS devices to get the IP address of the machine running Metro
if [[ ! "$SKIP_BUNDLING_METRO_IP" && "$CONFIGURATION" = *Debug* && ! "$PLATFORM_NAME" == *simulator ]]; then
  for num in 0 1 2 3 4 5 6 7 8; do
    IP=$(ipconfig getifaddr en${num})
    if [ ! -z "$IP" ]; then
      break
    fi
  done
  if [ -z "$IP" ]; then
    IP=$(ifconfig | grep 'inet ' | grep -v ' 127.' | grep -v ' 169.254.' |cut -d\   -f2  | awk 'NR==1{print $1}')
  fi

  echo "$IP" > "$DEST/ip.txt"
fi

if [[ "$SKIP_BUNDLING" ]]; then
  echo "SKIP_BUNDLING enabled; skipping."
  exit 0;
fi

case "$CONFIGURATION" in
  *Debug*)
    if [[ "$PLATFORM_NAME" == *simulator ]]; then
      if [[ "$FORCE_BUNDLING" ]]; then
        echo "FORCE_BUNDLING enabled; continuing to bundle."
      else
        echo "Skipping bundling in Debug for the Simulator (since the packager bundles for you). Use the FORCE_BUNDLING flag to change this behavior."
        exit 0;
      fi
    else
      echo "Bundling for physical device. Use the SKIP_BUNDLING flag to change this behavior."
    fi

    DEV=true
    ;;
  "")
    echo "$0 must be invoked by Xcode"
    exit 1
    ;;
  *)
    DEV=false
    ;;
esac

# Path to react-native folder inside node_modules
REACT_NATIVE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Most projects have their project root, one level up from their Xcode project dir (the "ios" directory)
PROJECT_ROOT=${PROJECT_ROOT:-"$PROJECT_DIR/.."}

cd "$PROJECT_ROOT" || exit

# Define entry file
if [[ "$ENTRY_FILE" ]]; then
  # Use ENTRY_FILE defined by user
  :
elif [[ -s "index.ios.js" ]]; then
  ENTRY_FILE=${1:-index.ios.js}
else
  ENTRY_FILE=${1:-index.js}
fi

# check and assign NODE_BINARY env
# shellcheck source=/dev/null
source "$REACT_NATIVE_DIR/scripts/node-binary.sh"

# If hermes-engine is in the Podfile.lock, it means that Hermes is a dependency of the project
# and it is enabled. If not, it means that hermes is disabled.
HERMES_ENABLED=$(grep hermes-engine $PODS_PODFILE_DIR_PATH/Podfile.lock)

# If hermes-engine is not in the Podfile.lock, it means that the app is not using Hermes.
# Setting USE_HERMES is no the only way to set whether the app can use hermes or not: users
# can also modify manually the Podfile.
if [[ -z "$HERMES_ENABLED" ]]; then
  USE_HERMES=false
fi

HERMES_ENGINE_PATH="$PODS_ROOT/hermes-engine"
[ -z "$HERMES_CLI_PATH" ] && HERMES_CLI_PATH="$HERMES_ENGINE_PATH/destroot/bin/hermesc"

# Hermes is enabled in new projects by default, so we cannot assume that USE_HERMES=1 is set as an envvar.
# If hermes-engine is found in Pods, we can assume Hermes has not been disabled.
# If hermesc is not available and USE_HERMES is either unset or true, show error.
if [[  ! -z "$HERMES_ENABLED" && -f "$HERMES_ENGINE_PATH" && ! -f "$HERMES_CLI_PATH" ]]; then
  echo "error: Hermes is enabled but the hermesc binary could not be found at ${HERMES_CLI_PATH}." \
       "Perhaps you need to run 'bundle exec pod install' or otherwise " \
       "point the HERMES_CLI_PATH variable to your custom location." >&2
  exit 2
fi

[ -z "$NODE_ARGS" ] && export NODE_ARGS=""

[ -z "$CLI_PATH" ] && export CLI_PATH="$REACT_NATIVE_DIR/cli.js"

[ -z "$BUNDLE_COMMAND" ] && BUNDLE_COMMAND="bundle"

[ -z "$COMPOSE_SOURCEMAP_PATH" ] && COMPOSE_SOURCEMAP_PATH="$REACT_NATIVE_DIR/scripts/compose-source-maps.js"

if [[ -z "$BUNDLE_CONFIG" ]]; then
  CONFIG_ARG=""
else
  CONFIG_ARG="--config $BUNDLE_CONFIG"
fi

BUNDLE_FILE="$CONFIGURATION_BUILD_DIR/main.jsbundle"

EXTRA_ARGS=

case "$PLATFORM_NAME" in
  "macosx")
    BUNDLE_PLATFORM="macos"
    ;;
  *)
    BUNDLE_PLATFORM="ios"
    ;;
esac

if [ "${IS_MACCATALYST}" = "YES" ]; then
  BUNDLE_PLATFORM="ios"
fi

EMIT_SOURCEMAP=
if [[ ! -z "$SOURCEMAP_FILE" ]]; then
  EMIT_SOURCEMAP=true
fi

PACKAGER_SOURCEMAP_FILE=
if [[ $EMIT_SOURCEMAP == true ]]; then
  if [[ $USE_HERMES != false ]]; then
    PACKAGER_SOURCEMAP_FILE="$CONFIGURATION_BUILD_DIR/$(basename $SOURCEMAP_FILE)"
  else
    PACKAGER_SOURCEMAP_FILE="$SOURCEMAP_FILE"
  fi
  EXTRA_ARGS="$EXTRA_ARGS --sourcemap-output $PACKAGER_SOURCEMAP_FILE"
fi

# Hermes doesn't require JS minification.
if [[ $USE_HERMES != false && $DEV == false ]]; then
  EXTRA_ARGS="$EXTRA_ARGS --minify false"
fi

"$NODE_BINARY" $NODE_ARGS "$CLI_PATH" $BUNDLE_COMMAND \
  $CONFIG_ARG \
  --entry-file "$ENTRY_FILE" \
  --platform "$BUNDLE_PLATFORM" \
  --dev $DEV \
  --reset-cache \
  --bundle-output "$BUNDLE_FILE" \
  --assets-dest "$DEST" \
  $EXTRA_ARGS \
  $EXTRA_PACKAGER_ARGS

if [[ $USE_HERMES == false ]]; then
  cp "$BUNDLE_FILE" "$DEST/"
  BUNDLE_FILE="$DEST/main.jsbundle"
else
  EXTRA_COMPILER_ARGS=
  if [[ $DEV == true ]]; then
    EXTRA_COMPILER_ARGS=-Og
  else
    EXTRA_COMPILER_ARGS=-O
  fi
  if [[ $EMIT_SOURCEMAP == true ]]; then
    EXTRA_COMPILER_ARGS="$EXTRA_COMPILER_ARGS -output-source-map"
  fi
  "$HERMES_CLI_PATH" -emit-binary -max-diagnostic-width=80 "$EXTRA_COMPILER_ARGS" -out "$DEST/main.jsbundle" "$BUNDLE_FILE"
  if [[ $EMIT_SOURCEMAP == true ]]; then
    HBC_SOURCEMAP_FILE="$DEST/main.jsbundle.map"
    "$NODE_BINARY" "$COMPOSE_SOURCEMAP_PATH" "$PACKAGER_SOURCEMAP_FILE" "$HBC_SOURCEMAP_FILE" -o "$SOURCEMAP_FILE"
    rm "$HBC_SOURCEMAP_FILE"
    rm "$PACKAGER_SOURCEMAP_FILE"
  fi
  BUNDLE_FILE="$DEST/main.jsbundle"
fi

if [[ $DEV != true && ! -f "$BUNDLE_FILE" ]]; then
  echo "error: File $BUNDLE_FILE does not exist. Your environment is misconfigured as Metro was not able to produce the bundle so your release application won't work!" >&2
  exit 2
fi


#!/bin/bash
# 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.

set -f

basepath=$(dirname "${0}")

# shellcheck disable=SC2207
files=( $(find . -name '*-test.rb') )

test_suite="${basepath}/all_tests.rb"
touch "${test_suite}"

echo "require \"test/unit\"" > "${test_suite}"
echo "discovered the following files:"
for i in "${files[@]}"
do
    filename="${i#"${basepath}/"}"
    echo "${filename}"
    echo "require_relative \"${filename}\"" >> "${test_suite}"
done

ruby -Itest "${test_suite}"
RES=$?
rm "${test_suite}"
exit $RES


#!/bin/bash
# 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.

set -o pipefail
set -e

GENERATED_SRCS_DIR="$DERIVED_FILE_DIR/generated/source/codegen"
TEMP_OUTPUT_DIR="$GENERATED_SRCS_DIR/out"
GENERATED_SCHEMA_FILE="$GENERATED_SRCS_DIR/schema.json"

cd "$RCT_SCRIPT_RN_DIR"

CODEGEN_CLI_PATH=""

error () {
    echo "$1"
    "[Codegen] $1" >> "${SCRIPT_OUTPUT_FILE_0}" 2>&1
    exit 1
}

find_node () {
    NODE_BINARY="${NODE_BINARY:-$(command -v node || true)}"
    if [ -z "$NODE_BINARY" ]; then
        error "[Error] Could not find node. It looks like that the .xcode.env or .xcode.env.local " \
"files are misconfigured. Please check that they are exporting a valid NODE_BINARY " \
"variable, pointing to a node executable."
    fi
}

find_codegen () {
    CODEGEN_CLI_PATH=$("$NODE_BINARY" --print "require('path').dirname(require.resolve('@react-native/codegen/package.json'))")
    if ! [ -d "$CODEGEN_CLI_PATH" ]; then
        error "error: Could not determine @react-native/codegen location, using node module resolution. Try running 'yarn install' or 'npm install' in your project root."
    fi
}

setup_dirs () {
    set +e
    rm -rf "$GENERATED_SRCS_DIR"
    set -e

    mkdir -p "$GENERATED_SRCS_DIR" "$TEMP_OUTPUT_DIR"

    # Clear output files
    true > "${SCRIPT_OUTPUT_FILE_0}"
}

describe () {
    message="

    >>>>> $1

    "
    echo "$message" >> "${SCRIPT_OUTPUT_FILE_0}" 2>&1
}

runSpecCodegen () {
    "$NODE_BINARY" "scripts/generate-specs-cli.js" --platform ios --schemaPath "$GENERATED_SCHEMA_FILE" --outputDir "$1" --libraryName "$RCT_SCRIPT_LIBRARY_NAME" --libraryType "$2"
}

generateCodegenSchemaFromJavaScript () {
    describe "Generating codegen schema from JavaScript"

    SRCS_PATTERN="$RCT_SCRIPT_JS_SRCS_PATTERN"
    SRCS_DIR="$RCT_SCRIPT_JS_SRCS_DIR"
    if [ "$SRCS_PATTERN" ]; then
        JS_SRCS=$(find "$PODS_TARGET_SRCROOT/$SRCS_DIR" -type f -name "$SRCS_PATTERN" -print0 | xargs -0)
        echo "$RCT_SCRIPT_FILE_LIST" >> "${SCRIPT_OUTPUT_FILE_0}" 2>&1
    else
        JS_SRCS="$PODS_TARGET_SRCROOT/$SRCS_DIR"
        echo "$RCT_SCRIPT_JS_SRCS_DIR" >> "${SCRIPT_OUTPUT_FILE_0}" 2>&1
    fi

    # shellcheck disable=SC2086
    # $JS_SRCS not having double quotations is intentional
    "$NODE_BINARY" "$CODEGEN_CLI_PATH/lib/cli/combine/combine-js-to-schema-cli.js" "$GENERATED_SCHEMA_FILE" $JS_SRCS
}

generateCodegenArtifactsFromSchema () {
    describe "Generating codegen artifacts from schema"
    pushd "$RN_DIR" >/dev/null || exit 1
        if [ "$RCT_SCRIPT_LIBRARY_TYPE" = "all" ]; then
            runSpecCodegen "$TEMP_OUTPUT_DIR" "modules"
            runSpecCodegen "$TEMP_OUTPUT_DIR" "components"
        elif [ "$RCT_SCRIPT_LIBRARY_TYPE" = "components" ]; then
            runSpecCodegen "$TEMP_OUTPUT_DIR" "$RCT_SCRIPT_LIBRARY_TYPE"
        elif [ "$RCT_SCRIPT_LIBRARY_TYPE" = "modules" ]; then
            runSpecCodegen "$TEMP_OUTPUT_DIR" "$RCT_SCRIPT_LIBRARY_TYPE"
        fi
    popd >/dev/null || exit 1
}

generateArtifacts () {
    describe "Generating codegen artifacts"
    pushd "$RCT_SCRIPT_RN_DIR" >/dev/null || exit 1
        "$NODE_BINARY" "scripts/generate-codegen-artifacts.js" --path "$RCT_SCRIPT_APP_PATH" --outputPath "$TEMP_OUTPUT_DIR" --fabricEnabled "$RCT_SCRIPT_FABRIC_ENABLED" --configFileDir "$RCT_SCRIPT_CONFIG_FILE_DIR" --nodeBinary "$NODE_BINARY"
    popd >/dev/null || exit 1
}

moveOutputs () {
    mkdir -p "$RCT_SCRIPT_OUTPUT_DIR"

    # Copy all output to output_dir
    cp -R "$TEMP_OUTPUT_DIR/." "$RCT_SCRIPT_OUTPUT_DIR" || exit 1
    echo "$LIBRARY_NAME output has been written to $RCT_SCRIPT_OUTPUT_DIR:" >> "${SCRIPT_OUTPUT_FILE_0}" 2>&1
    ls -1 "$RCT_SCRIPT_OUTPUT_DIR" >> "${SCRIPT_OUTPUT_FILE_0}" 2>&1
}

withCodegenDiscovery () {
    setup_dirs
    find_node
    find_codegen
    generateArtifacts
    moveOutputs
}

noCodegenDiscovery () {
    setup_dirs
    find_node
    find_codegen
    generateCodegenSchemaFromJavaScript
    generateCodegenArtifactsFromSchema
    moveOutputs
}

if [ "$RCT_SCRIPT_TYPE" = "withCodegenDiscovery" ]; then
    withCodegenDiscovery "$@"
else
    noCodegenDiscovery "$@"
fi

echo 'Done.' >> "${SCRIPT_OUTPUT_FILE_0}" 2>&1


#!/bin/bash
# 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.

# This script is used to source in Xcode the environment settings required to run properly.
#Â The script first sources the base `.xcode.env` file.
# Then it sources the `.xcode.env.local` file if present, to override some local config
# Finally, it will execute the command passed i input if any.
#
# USAGE:
# ./with-environment.sh command

# Start with a default
NODE_BINARY=$(command -v node)
export NODE_BINARY

# Override the default with the global environment
ENV_PATH="$PODS_ROOT/../.xcode.env"
if [ -f "$ENV_PATH" ]; then
    source "$ENV_PATH"
fi

# Override the global with the local environment
LOCAL_ENV_PATH="${ENV_PATH}.local"
if [ -f "$LOCAL_ENV_PATH" ]; then
    source "$LOCAL_ENV_PATH"
fi

# Check whether NODE_BINARY has been properly set, otherwise help the users with a meaningful error.
if [ -n "$NODE_BINARY" ]; then
    echo "Node found at: ${NODE_BINARY}"
else
    echo '[Warning] You need to configure your node path in the `".xcode.env" file` environment. ' \
       'You can set it up quickly by running: ' \
       '`echo export NODE_BINARY=$(command -v node) > .xcode.env` ' \
       'in the ios folder. This is needed by React Native to work correctly. ' \
       'We fallback to the DEPRECATED behavior of finding `node`. This will be REMOVED in a future version. ' \
       'You can read more about this here: https://reactnative.dev/docs/environment-setup#optional-configuring-your-environment' >&2
    source "${REACT_NATIVE_PATH}/scripts/find-node-for-xcode.sh"
fi

# Execute argument, if present
if [ -n "$1" ]; then
  $1
fi


#!/bin/bash
# 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.

# Defines functions for building various Hermes frameworks.
# See build-ios-framework.sh and build-mac-framework.sh for usage examples.

CURR_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"

IMPORT_HERMESC_PATH=${HERMES_OVERRIDE_HERMESC_PATH:-$PWD/build_host_hermesc/ImportHermesc.cmake}
BUILD_TYPE=${BUILD_TYPE:-Debug}

HERMES_PATH="$CURR_SCRIPT_DIR/.."
REACT_NATIVE_PATH=${REACT_NATIVE_PATH:-$CURR_SCRIPT_DIR/../../..}

NUM_CORES=$(sysctl -n hw.ncpu)

if [[ -z "$JSI_PATH" ]]; then
  JSI_PATH="$REACT_NATIVE_PATH/ReactCommon/jsi"
fi

function use_env_var_or_ruby_prop {
  if [[ -n "$1" ]]; then
    echo "$1"
  else
    ruby -rcocoapods-core -rjson -e "puts Pod::Specification.from_file('hermes-engine.podspec').$2"
  fi
}

function get_release_version {
  use_env_var_or_ruby_prop "${RELEASE_VERSION}" "version"
}

function get_ios_deployment_target {
  use_env_var_or_ruby_prop "${IOS_DEPLOYMENT_TARGET}" "deployment_target('ios')"
}

function get_mac_deployment_target {
  use_env_var_or_ruby_prop "${MAC_DEPLOYMENT_TARGET}" "deployment_target('osx')"
}

# Build host hermes compiler for internal bytecode
function build_host_hermesc {
  echo "Building hermesc"
  pushd "$HERMES_PATH" > /dev/null || exit 1
    cmake -S . -B build_host_hermesc -DJSI_DIR="$JSI_PATH"
    cmake --build ./build_host_hermesc --target hermesc -j "${NUM_CORES}"
  popd > /dev/null || exit 1
}

# Utility function to configure an Apple framework
function configure_apple_framework {
  local enable_debugger cmake_build_type

  if [[ $BUILD_TYPE == "Debug" ]]; then
    enable_debugger="true"
  else
    enable_debugger="false"
  fi
  if [[ $BUILD_TYPE == "Debug" ]]; then
    # JS developers aren't VM developers.
    # Therefore we're passing as build type Release, to provide a faster build.
    cmake_build_type="Release"
  else
    cmake_build_type="MinSizeRel"
  fi

  pushd "$HERMES_PATH" > /dev/null || exit 1
    cmake -S . -B "build_$1" \
      -DHERMES_APPLE_TARGET_PLATFORM:STRING="$1" \
      -DCMAKE_OSX_ARCHITECTURES:STRING="$2" \
      -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING="$3" \
      -DHERMES_ENABLE_DEBUGGER:BOOLEAN="$enable_debugger" \
      -DHERMES_ENABLE_INTL:BOOLEAN=true \
      -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \
      -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \
      -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \
      -DHERMES_ENABLE_BITCODE:BOOLEAN=false \
      -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \
      -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \
      -DIMPORT_HERMESC:PATH="$IMPORT_HERMESC_PATH" \
      -DJSI_DIR="$JSI_PATH" \
      -DHERMES_RELEASE_VERSION="for RN $(get_release_version)" \
      -DCMAKE_BUILD_TYPE="$cmake_build_type"
    popd > /dev/null || exit 1
}

# Utility function to build an Apple framework
function build_apple_framework {
  # Only build host HermesC if no file found at $IMPORT_HERMESC_PATH
  [ ! -f "$IMPORT_HERMESC_PATH" ] &&
  build_host_hermesc

  # Confirm ImportHermesc.cmake is now available.
  [ ! -f "$IMPORT_HERMESC_PATH" ] &&
  echo "Host hermesc is required to build apple frameworks!"

  # $1: platform, $2: architectures, $3: deployment target
  echo "Building $BUILD_TYPE framework for $1 with architectures: $2"
  configure_apple_framework "$1" "$2" "$3"

  pushd "$HERMES_PATH" > /dev/null || exit 1
    mkdir -p "destroot/Library/Frameworks/$1"
    cmake --build "./build_$1" --target libhermes -j "${NUM_CORES}"
    cp -R "./build_$1"/API/hermes/hermes.framework* "destroot/Library/Frameworks/$1"

    # In a MacOS build, also produce the hermes and hermesc CLI tools.
    if [[ $1 == macosx ]]; then
      cmake --build "./build_$1" --target hermesc hermes -j "${NUM_CORES}"
      mkdir -p destroot/bin
      cp "./build_$1/bin"/* "destroot/bin"
    fi

    # Copy over Hermes and JSI API headers.
    mkdir -p destroot/include/hermes/Public destroot/include/jsi
    cp public/hermes/Public/*.h destroot/include/hermes/Public
    cp API/hermes/*.h destroot/include/hermes
    cp "$JSI_PATH"/jsi/*.h destroot/include/jsi
  popd > /dev/null || exit 1
}

# Accepts an array of frameworks and will place all of
# the architectures into an universal folder and then remove
# the merged frameworks from destroot
function create_universal_framework {
  pushd "$HERMES_PATH/destroot/Library/Frameworks" > /dev/null || exit 1

  local platforms=("$@")
  local args=""

  echo "Creating universal framework for platforms: ${platforms[*]}"

  for i in "${!platforms[@]}"; do
    local platform="${platforms[$i]}"
    local hermes_framework_path="${platform}/hermes.framework"
    local dSYM_path="$hermes_framework_path"
    local dSYM_base_path="$HERMES_PATH/destroot/Library/Frameworks"

    # If the dSYM rename has failed, the dSYM are generated as 0.dSYM
    # (Apple default name) rather then hermes.framework.dSYM.
    if [[ -e "$dSYM_base_path/${platform}/0.dSYM" ]]; then
      dSYM_path="${platform}/0"
    fi

    args+="-framework $hermes_framework_path "

    # Path to dSYM must be absolute
    args+="-debug-symbols $dSYM_base_path/$dSYM_path.dSYM "
  done

  mkdir -p universal
  # shellcheck disable=SC2086
  if xcodebuild -create-xcframework $args -output "universal/hermes.xcframework"
  then
    # # Remove the thin iOS hermes.frameworks that are now part of the universal
    # XCFramework
    for platform in "${platforms[@]}"; do
      rm -r "$platform"
    done
  fi

  popd > /dev/null || exit 1
}


#!/bin/bash
# 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.

set -x

release_version="$1"; shift
hermesc_path="$1"; shift

enable_debugger="false"
if [[ "$CONFIGURATION" == "Debug" ]]; then
  enable_debugger="true"
fi

cmake_build_type=""
if [[ $CONFIGURATION == "Debug" ]]; then
  # JS developers aren't VM developers.
  # Therefore we're passing as build type Release, to provide a faster build.
  cmake_build_type="Release"
else
  cmake_build_type="MinSizeRel"
fi

deployment_target=${IPHONEOS_DEPLOYMENT_TARGET}
if [ -z "$deployment_target" ]; then
  deployment_target=${MACOSX_DEPLOYMENT_TARGET}
fi

architectures=$( echo "$ARCHS" | tr  " " ";" )

echo "Configure Apple framework"

"$CMAKE_BINARY" \
  -S "${PODS_ROOT}/hermes-engine" \
  -B "${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}" \
  -DHERMES_APPLE_TARGET_PLATFORM:STRING="$PLATFORM_NAME" \
  -DCMAKE_OSX_ARCHITECTURES:STRING="$architectures" \
  -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING="$deployment_target" \
  -DHERMES_ENABLE_DEBUGGER:BOOLEAN="$enable_debugger" \
  -DHERMES_ENABLE_INTL:BOOLEAN=true \
  -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \
  -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \
  -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \
  -DHERMES_ENABLE_BITCODE:BOOLEAN=false \
  -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \
  -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \
  -DIMPORT_HERMESC:PATH="${hermesc_path}" \
  -DHERMES_RELEASE_VERSION="for RN $release_version" \
  -DCMAKE_BUILD_TYPE="$cmake_build_type"

echo "Build Apple framework"

"$CMAKE_BINARY" \
  --build "${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}" \
  --target libhermes \
  -j "$(sysctl -n hw.ncpu)"

echo "Copy Apple framework to destroot/Library/Frameworks"

cp -pfR \
  "${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}/API/hermes/hermes.framework" \
  "${PODS_ROOT}/hermes-engine/destroot/Library/Frameworks/ios"


#!/bin/bash
# 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.

set -x

hermesc_dir_path="$1"

# This script is supposed to be executed from Xcode "run script" phase.
# Xcode sets up its build environment based on the build target.
# Here we override relevant envvars to make sure that we build hermesc for macosx,
# even if Xcode build target is iphone, iponesimulator, etc.
MACOSX_DEPLOYMENT_TARGET=$(sw_vers -productVersion)
export MACOSX_DEPLOYMENT_TARGET=$MACOSX_DEPLOYMENT_TARGET
SDKROOT=$(xcode-select -p)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk
export SDKROOT=$SDKROOT

if ! "$CMAKE_BINARY" -S "${PODS_ROOT}/hermes-engine" -B "$hermesc_dir_path"
then
    echo "Failed to configure Hermesc cmake project."
    exit 1
fi
if ! "$CMAKE_BINARY" --build "$hermesc_dir_path" --target hermesc -j "$(sysctl -n hw.ncpu)"
then
    echo "Failed to build Hermesc cmake project."
    exit 1
fi


#!/bin/bash
# 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.

# shellcheck source=xplat/js/react-native-github/sdks/hermes-engine/utils/build-apple-framework.sh
CURR_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
. "${CURR_SCRIPT_DIR}/build-apple-framework.sh"

if [ ! -d destroot/Library/Frameworks/universal/hermes.xcframework ]; then
    ios_deployment_target=$(get_ios_deployment_target)

    build_apple_framework "iphoneos" "arm64" "$ios_deployment_target"
    build_apple_framework "iphonesimulator" "x86_64;arm64" "$ios_deployment_target"
    build_apple_framework "catalyst" "x86_64;arm64" "$ios_deployment_target"

    create_universal_framework "iphoneos" "iphonesimulator" "catalyst"
else
    echo "Skipping; Clean \"destroot\" to rebuild".
fi


#!/bin/bash
# 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.

# shellcheck source=xplat/js/react-native-github/sdks/hermes-engine/utils/build-apple-framework.sh
CURR_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
. "${CURR_SCRIPT_DIR}/build-apple-framework.sh"

if [ ! -d destroot/Library/Frameworks/macosx/hermes.framework ]; then
    mac_deployment_target=$(get_mac_deployment_target)

    build_apple_framework "macosx" "x86_64;arm64" "$mac_deployment_target"
else
    echo "Skipping; Clean \"destroot\" to rebuild".
fi


#!/bin/bash
# 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.

echo "This file is no-op now. Remove \"[RN] Copy Hermes Framework\" script phase from your main target if you don't want to see this message."


#!/bin/bash
# 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.

set -x

# CocoaPods requires vendored frameworks to exist before `pod install` is run,
# and to be proper Moch-O binaries in order to auto-link them to the user's Xcode project.
# This script creates dummy hermes.framework for macosx and ios.
# They are then get rewritten by `build-hermes-xcode.sh` during Xcode build.

rm -rf destroot

mkdir -p destroot/Library/Frameworks

pushd destroot/Library/Frameworks > /dev/null || exit 1

echo '' > dummy.c

mkdir -p macosx/hermes.framework
clang dummy.c -dynamiclib -o macosx/hermes.framework/hermes

mkdir -p ios/hermes.framework
clang dummy.c -dynamiclib -o ios/hermes.framework/hermes

rm dummy.c

popd > /dev/null || exit 1


#!/bin/bash
# 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.

# Note: To be invoked by Buck sh_binary() in OSS environment.
# DO NOT USE outside of Buck!

set -e
set -u

pushd "$BUCK_DEFAULT_RUNTIME_RESOURCES" >/dev/null
node "build/lib/cli/combine/combine-js-to-schema-cli.js" "$@"
popd >/dev/null


#!/bin/bash
# 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.

# Note: To be invoked by Buck sh_binary() in OSS environment.
# DO NOT USE outside of Buck!

set -e
set -u

pushd "$BUCK_DEFAULT_RUNTIME_RESOURCES" >/dev/null
node "build/lib/cli/generators/generate-all.js" "$@"
popd >/dev/null


#!/bin/bash
# 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.

# This script assumes yarn is already installed.

THIS_DIR=$(cd -P "$(dirname "$(realpath "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd)

set -e
set -u

CODEGEN_DIR="$THIS_DIR/../.."

rm -rf "${CODEGEN_DIR:?}/lib" "${CODEGEN_DIR:?}/node_modules"

# Fallback to npm if yarn is not available
if [ -x "$(command -v yarn)" ]; then
  YARN_OR_NPM=$(command -v yarn)
else
  YARN_OR_NPM=$(command -v npm)
fi
YARN_BINARY="${YARN_BINARY:-$YARN_OR_NPM}"

if [[ ${FBSOURCE_ENV:-0} -eq 1 ]]; then
  # Custom FB-specific setup
  pushd "$CODEGEN_DIR" >/dev/null

  "$YARN_BINARY" install 2> >(grep -v '^warning' 1>&2)
  # Note: Within FBSOURCE_ENV, this has to explicitly run build.
  "$YARN_BINARY" run build

  popd >/dev/null

else
  # Run yarn install in a separate tmp dir to avoid conflict with the rest of the repo.
  # Note: OSS-only.
  TMP_DIR=$(mktemp -d)

  # On Windows this script gets run by a seprate Git Bash instance, which cannot perform the copy
  # due to file locks created by the host process. Need to exclude .lock files while copying.
  # Using in-memory tar operation because piping `find` and `grep` doesn't preserve folder structure
  # during recursive copying, and `rsync` is not installed by default in Git Bash.
  # As an added benefit, blob copy is faster.
  if [ "$OSTYPE" = "msys" ] || [ "$OSTYPE" = "cygwin" ]; then
    tar cf - --exclude='*.lock' "$CODEGEN_DIR" | (cd "$TMP_DIR" && tar xvf - );
  else
    cp -R "$CODEGEN_DIR/." "$TMP_DIR";
  fi

  pushd "$TMP_DIR" >/dev/null

  # Note: this automatically runs build as well.
  "$YARN_BINARY" install 2> >(grep -v '^warning' 1>&2)

  popd >/dev/null

  mv "$TMP_DIR/lib" "$TMP_DIR/node_modules" "$CODEGEN_DIR"
  rm -rf "$TMP_DIR"
fi


#!/bin/bash
# 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.

set -e
set -u

THIS_DIR=$(cd -P "$(dirname "$(realpath "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd)

# shellcheck source=xplat/js/env-utils/setup_env_vars.sh
source "$THIS_DIR/../../../../../../env-utils/setup_env_vars.sh"

exec "$FLOW_NODE_BINARY" "$THIS_DIR/parser.js" "$@"


#!/bin/bash
# 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.

THIS_DIR=$(cd -P "$(dirname "$(readlink "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd)
pushd "$THIS_DIR" || exit
./websocket_integration_test_server.js
popd || exit

echo "Process terminated."


#!/bin/bash
# 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.

# inspired by https://github.com/Originate/guide/blob/master/android/guide/Continuous%20Integration.md

# shellcheck disable=SC1091
source "scripts/.tests.env"

# NOTE: This doesn't run in Circle CI currently!
function getAndroidPackages {
  export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$ANDROID_HOME/tools.bin:$PATH"

  DEPS="$ANDROID_HOME/installed-dependencies"

  # Package names can be obtained using `sdkmanager --list`
  if [ ! -e "$DEPS" ] || [ ! "$CI" ]; then
    echo "Installing Android API level $ANDROID_SYSTEM_IMAGE_API_LEVEL, Google APIs, $AVD_ABI system image..."
    sdkmanager "system-images;android-$ANDROID_SYSTEM_IMAGE_API_LEVEL;google_apis;$AVD_ABI"
    echo "Installing build SDK for Android API level $ANDROID_SDK_BUILD_API_LEVEL..."
    sdkmanager "platforms;android-$ANDROID_SDK_BUILD_API_LEVEL"
    echo "Installing target SDK for Android API level $ANDROID_SDK_TARGET_API_LEVEL..."
    sdkmanager "platforms;android-$ANDROID_SDK_TARGET_API_LEVEL"
    echo "Installing SDK build tools, revision $ANDROID_SDK_BUILD_TOOLS_REVISION..."
    sdkmanager "build-tools;$ANDROID_SDK_BUILD_TOOLS_REVISION"
    # These moved to "system-images;android-$ANDROID_SDK_BUILD_API_LEVEL;google_apis;x86" starting with API level 25, but there is no ARM version.
    echo "Installing Google APIs $ANDROID_GOOGLE_API_LEVEL..."
    sdkmanager "add-ons;addon-google_apis-google-$ANDROID_GOOGLE_API_LEVEL"
    echo "Installing Android Support Repository"
    sdkmanager "extras;android;m2repository"
    $CI && touch "$DEPS"
  fi
}

function getAndroidNDK {
  NDK_HOME="/opt/ndk"
  DEPS="$NDK_HOME/installed-dependencies"

  if [ ! -e $DEPS ]; then
    cd $NDK_HOME || exit
    echo "Downloading NDK..."
    curl -o ndk.zip https://dl.google.com/android/repository/android-ndk-r19c-linux-x86_64.zip
    unzip -o -q ndk.zip
    echo "Installed Android NDK at $NDK_HOME"
    touch $DEPS
    rm ndk.zip
  fi
}

function createAVD {
  if [ -z "$ANDROID_DISABLE_AVD_TESTS" ]
  then
    AVD_PACKAGES="system-images;android-$ANDROID_IMAGE_API_LEVEL;google_apis;$AVD_ABI"
    echo "Creating AVD with packages $AVD_PACKAGES"
    echo no | avdmanager create avd --name "$AVD_NAME" --force --package "$AVD_PACKAGES" --tag google_apis --abi "$AVD_ABI"
  else
    echo "Skipping AVD-related test setup..."
  fi
}

function launchAVD {
  # Force start adb server
  adb start-server

  if [ -z "$ANDROID_DISABLE_AVD_TESTS" ]
  then
    # The AVD name here should match the one created in createAVD
    if [ "$CI" ]
    then
      "$ANDROID_HOME/emulator/emulator" -avd "$AVD_NAME" -no-audio -no-window
    else
      "$ANDROID_HOME/emulator/emulator" -avd "$AVD_NAME"
    fi
  else
    echo "Skipping AVD-related test setup..."
  fi
}

function waitForAVD {
  if [ -z "$ANDROID_DISABLE_AVD_TESTS" ]
  then
    echo "Waiting for Android Virtual Device to finish booting..."
    local bootanim=""
    export PATH=$(dirname $(dirname $(command -v android)))/platform-tools:$PATH
    until [[ "$bootanim" =~ "stopped" ]]; do
      sleep 5
      bootanim=$(adb -e shell getprop init.svc.bootanim 2>&1)
      echo "boot animation status=$bootanim"
    done
    echo "Android Virtual Device is ready."
  else
    echo "Skipping AVD-related test setup..."
  fi
}


#!/bin/bash
# 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.

# Script used to run iOS tests.
# If no arguments are passed to the script, it will only compile
# the RNTester.
# If the script is called with a single argument "test", we'll
# run the RNTester unit and integration tests
# ./objc-test.sh test

SCRIPTS=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
ROOT=$(dirname "$SCRIPTS")

SKIPPED_TESTS=()
SKIPPED_TESTS+=("-skip-testing:RNTesterIntegrationTests/RNTesterSnapshotTests")
# TODO: T60408036 This test crashes iOS 13 for bad access, please investigate
# and re-enable. See https://gist.github.com/0xced/56035d2f57254cf518b5.
SKIPPED_TESTS+=("-skip-testing:RNTesterUnitTests/RCTJSONTests/testNotUTF8Convertible")

# Create cleanup handler
cleanup() {
  EXIT=$?
  set +e

  if [ $EXIT -ne 0 ];
  then
    WATCHMAN_LOGS=/usr/local/Cellar/watchman/3.1/var/run/watchman/$USER.log
    [ -f "$WATCHMAN_LOGS" ] && cat "$WATCHMAN_LOGS"
  fi
  # kill whatever is occupying port 8081 (packager)
  lsof -i tcp:8081 | awk 'NR!=1 {print $2}' | xargs kill
  # kill whatever is occupying port 5555 (web socket server)
  lsof -i tcp:5555 | awk 'NR!=1 {print $2}' | xargs kill
}

# Wait for the package to start
waitForPackager() {
  local -i max_attempts=60
  local -i attempt_num=1

  until curl -s http://localhost:8081/status | grep "packager-status:running" -q; do
    if (( attempt_num == max_attempts )); then
      echo "Packager did not respond in time. No more attempts left."
      exit 1
    else
      (( attempt_num++ ))
      echo "Packager did not respond. Retrying for attempt number $attempt_num..."
      sleep 1
    fi
  done

  echo "Packager is ready!"
}

waitForWebSocketServer() {
  local -i max_attempts=60
  local -i attempt_num=1

  until curl -s http://localhost:5555 | grep "Upgrade Required" -q; do
    if (( attempt_num == max_attempts )); then
      echo "WebSocket Server did not respond in time. No more attempts left."
      exit 1
    else
      (( attempt_num++ ))
      echo "WebSocket Server did not respond. Retrying for attempt number $attempt_num..."
      sleep 1
    fi
  done

  echo "WebSocket Server is ready!"
}

runTests() {
  # shellcheck disable=SC1091
  source "$ROOT/scripts/.tests.env"
  xcodebuild build test \
    -workspace RNTesterPods.xcworkspace \
    -scheme RNTester \
    -sdk iphonesimulator \
    -destination "platform=iOS Simulator,name=$IOS_DEVICE,OS=$IOS_TARGET_OS" \
      "${SKIPPED_TESTS[@]}"
}

buildProject() {
  xcodebuild build \
    -workspace RNTesterPods.xcworkspace \
    -scheme RNTester \
    -sdk iphonesimulator
}

xcbeautifyFormat() {
  if [ "$CI" ]; then
    # Circle CI expects JUnit reports to be available here
    REPORTS_DIR="$HOME/react-native/reports/junit"
  else
    THIS_DIR=$(cd -P "$(dirname "$(realpath "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd)

    # Write reports to the react-native root dir
    REPORTS_DIR="$THIS_DIR/../build/reports"
  fi

  xcbeautify --report junit --report-path "$REPORTS_DIR/ios/results.xml"
}

preloadBundlesRNIntegrationTests() {
  # Preload IntegrationTests bundles (packages/rn-tester/)
  curl -s 'http://localhost:8081/IntegrationTests/IntegrationTestsApp.bundle?platform=ios&dev=true' -o /dev/null
  curl -s 'http://localhost:8081/IntegrationTests/RCTRootViewIntegrationTestApp.bundle?platform=ios&dev=true' -o /dev/null
}

preloadBundlesRNTester() {
  # Preload RNTesterApp bundles (packages/rn-tester/)
  curl -s 'http://localhost:8081/js/RNTesterApp.ios.bundle?platform=ios&dev=true' -o /dev/null
  curl -s 'http://localhost:8081/js/RNTesterApp.ios.bundle?platform=ios&dev=true&minify=false' -o /dev/null
}

main() {
  cd "$ROOT/packages/rn-tester" || exit

  # If first argument is "test", actually start the packager and run tests.
  # Otherwise, just build RNTester and exit
  if [ "$1" = "test" ]; then

    # Start the WebSocket test server
    echo "Launch WebSocket Server"
    sh "./IntegrationTests/launchWebSocketServer.sh" &
    waitForWebSocketServer

    # Start the packager
    yarn start --max-workers=1 || echo "Can't start packager automatically" &
    waitForPackager
    preloadBundlesRNTester
    preloadBundlesRNIntegrationTests

    # Build and run tests.
    if [ -x "$(command -v xcbeautify)" ]; then
      runTests | xcbeautifyFormat && exit "${PIPESTATUS[0]}"
    else
      echo 'Warning: xcbeautify is not installed. Install xcbeautify to generate JUnit reports.'
      runTests
    fi
  else
    # Build without running tests.
    if [ -x "$(command -v xcbeautify)" ]; then
      buildProject | xcbeautifyFormat && exit "${PIPESTATUS[0]}"
    else
      buildProject
    fi
  fi
}

trap cleanup EXIT
main "$@"


#!/bin/bash
# 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.

set -ex

SCRIPTS="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(dirname "$SCRIPTS")"

# Specify `SPEC_REPO` as an env variable if you want to push to a specific spec repo.
# Defaults to `react-test`, which is meant to be a dummy repo used to test that the specs fully lint.
: "${SPEC_REPO:=react-test}"
SPEC_REPO_DIR="$HOME/.cocoapods/repos/$SPEC_REPO"

# If the `SPEC_REPO` does not exist yet, assume this is purely for testing and create a dummy repo.
if ! [ -d "$SPEC_REPO_DIR" ]; then
  mkdir -p "$SPEC_REPO_DIR"
  cd "$SPEC_REPO_DIR"
  touch .gitkeep
  git init
  git add .
  git commit -m "init"
  git remote add origin "https://example.com/$SPEC_REPO.git"
fi

cd "$SPEC_REPO_DIR"
SPEC_REPOS="$(git remote get-url origin),https://github.com/CocoaPods/Specs.git"

POD_LINT_OPT=(--verbose --allow-warnings --fail-fast --private "--swift-version=3.0" "--sources=$SPEC_REPOS")

# Get the version from a podspec.
version() {
  ruby -rcocoapods-core -rjson -e "puts Pod::Specification.from_file('$1').version"
}

# Lint both framework and static library builds.
lint() {
  local SUBSPEC="$1"
  if [ "${SUBSPEC:-}" ]; then
    local SUBSPEC_OPT="--subspec=$SUBSPEC"
  fi
  bundle exec pod lib lint "$SUBSPEC_OPT" "${POD_LINT_OPT[@]}"
  bundle exec pod lib lint "$SUBSPEC_OPT" "${POD_LINT_OPT[@]}" --use-libraries
}

# Push the spec in arg `$1`, which is expected to be in the cwd, to the `SPEC_REPO` in JSON format.
push() {
  local SPEC_NAME POD_NAME SPEC_DIR SPEC_PATH
  SPEC_NAME="$1"
  POD_NAME=$(basename "$SPEC_NAME" .podspec)
  SPEC_DIR="$SPEC_REPO_DIR/$POD_NAME/$(version "$SPEC_NAME")"
  SPEC_PATH="$SPEC_DIR/$SPEC_NAME.json"
  mkdir -p "$SPEC_DIR"
  env INSTALL_YOGA_WITHOUT_PATH_OPTION=1 INSTALL_YOGA_FROM_LOCATION="$ROOT" bundle exec pod ipc spec "$SPEC_NAME" > "$SPEC_PATH"
}

# Perform linting and publishing of podspec in cwd.
# Skip linting with `SKIP_LINT` if e.g. publishing to a private spec repo.
process() {
  cd "$1"
  if [ -z "$SKIP_LINT" ]; then
    lint "$2"
  fi
  local SPEC_NAME=(*.podspec)
  push "${SPEC_NAME[0]}"
}

# Make third-party deps accessible
cd "$ROOT/third-party-podspecs"
push Folly.podspec
push DoubleConversion.podspec
push glog.podspec

process "$ROOT/ReactCommon/yoga"
process "$ROOT" _ignore_me_subspec_for_linting_


#!/bin/bash
# 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.

# Runs an Android emulator locally.
# If there already is a running emulator, this just uses that.
# The only reason to use this config is that it represents a known-good
# virtual device configuration.
# This is useful for running integration tests on a local machine.

THIS_DIR=$(cd -P "$(dirname "$(realpath "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd)

STATE=`adb get-state`

if [ -n "$STATE" ]; then
    echo "An emulator is already running."
    exit 1
fi

echo "Installing packages"
source "${THIS_DIR}/android-setup.sh" && getAndroidPackages

echo "Creating Android virtual device..."
source "${THIS_DIR}/android-setup.sh" && createAVD

echo "Launching Android virtual device..."
source "${THIS_DIR}/android-setup.sh" && launchAVD


#!/bin/bash
# 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.

# Runs all Android integration tests locally.
# See https://reactnative.dev/docs/testing

source $(dirname $0)/validate-android-sdk.sh
source $(dirname $0)/validate-android-test-env.sh
source $(dirname $0)/validate-android-device-env.sh

set -e

echo "Compiling native code..."
./gradlew :ReactAndroid:packageReactNdkLibsForBuck

echo "Building JS bundle..."
node cli.js bundle --platform android --dev true --entry-file ReactAndroid/src/androidTest/js/TestBundle.js --bundle-output ReactAndroid/src/androidTest/assets/AndroidTestBundle.js

echo "Installing test app on the device..."
buck fetch ReactAndroid/src/androidTest/buck-runner:instrumentation-tests
buck install ReactAndroid/src/androidTest/buck-runner:instrumentation-tests

echo "Running integration tests..."
# Use the JS script that runs all tests in a loop and is easy to tweak
node ./scripts/run-android-ci-instrumentation-tests.js --path ./ReactAndroid/src/androidTest/java/com/facebook/react/tests --package com.facebook.react.tests


#!/bin/bash
# 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.

# Runs all Android unit tests locally.
# See https://reactnative.dev/docs/testing

source $(dirname $0)/validate-android-sdk.sh
source $(dirname $0)/validate-android-test-env.sh

set -e

echo "Fetching dependencies..."
buck fetch ReactAndroid/src/test/...

echo "Running unit tests..."
buck test ReactAndroid/src/test/...


#!/bin/bash
# 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.

# Python script to run instrumentation tests, copied from https://github.com/circleci/circle-dummy-android
# Example: ./scripts/run-android-instrumentation-tests.sh com.facebook.react.tests com.facebook.react.tests.ReactPickerTestCase

export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"

# clear the logs
adb logcat -c

# run tests and check output
python - $1 $2 << END

import re
import subprocess as sp
import sys
import threading
import time

done = False

test_app = sys.argv[1]
test_class = None

if len(sys.argv) > 2:
  test_class = sys.argv[2]

def update():
  # prevent CircleCI from killing the process for inactivity
  while not done:
    time.sleep(5)
    print "Running in background.  Waiting for 'adb' command response..."

t = threading.Thread(target=update)
t.dameon = True
t.start()

def run():
  sp.Popen(['adb', 'wait-for-device']).communicate()
  if (test_class != None):
    p = sp.Popen('adb shell am instrument -w -e class %s %s/androidx.test.runner.AndroidJUnitRunner'
      % (test_class, test_app), shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)
  else :
    p = sp.Popen('adb shell am instrument -w %s/androidx.test.runner.AndroidJUnitRunner'
      % (test_app), shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)
  return p.communicate()

success = re.compile(r'OK \(\d+ test(s)?\)')
stdout, stderr = run()

done = True
print stderr
print stdout

if success.search(stderr + stdout):
  sys.exit(0)
else:
  # dump the logs
  sp.Popen(['adb', 'logcat', '-d']).communicate()
  sys.exit(1) # make sure we fail if the test failed
END

RETVAL=$?

exit $RETVAL


#!/usr/bin/env bash
# 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.

function usage {
  echo "usage: sync-css-layout.sh <pathToGithubRepo> <pathToFbSourceRepo>";
}

function patchfile {
  # Add React Native copyright
  printf "/**\n"  > /tmp/yogasync.tmp
  printf " * Copyright (c) 2014-present, Facebook, Inc.\n"  >> /tmp/yogasync.tmp
  printf " *\n" >> /tmp/yogasync.tmp
  printf " * This source code is licensed under the MIT license found in the\n"  >> /tmp/yogasync.tmp
  printf " * LICENSE file in the root directory of this source tree.\n"  >> /tmp/yogasync.tmp
  printf " */\n\n"  >> /tmp/yogasync.tmp
  printf "// NOTE: this file is auto-copied from https://github.com/facebook/css-layout\n" >> /tmp/yogasync.tmp
  # The following is split over four lines so Phabricator doesn't think this file is generated
  printf "// @g" >> /tmp/yogasync.tmp
  printf "enerated <<S" >> /tmp/yogasync.tmp
  printf "ignedSource::*O*zOeWoEQle#+L" >> /tmp/yogasync.tmp
  printf "!plEphiEmie@IsG>>\n\n" >> /tmp/yogasync.tmp
  tail -n +9 $1 >> /tmp/yogasync.tmp
  mv /tmp/yogasync.tmp $1
  "$ROOT"/tools/signedsource.py sign "$1"
}

if [ -z $1 ]; then
  usage
  exit 1
fi

if [ -z $2 ]; then
  usage
  exit 1
fi

GITHUB=$1
ROOT=$2

set -e # exit if any command fails

echo "Making github project..."
pushd $GITHUB
COMMIT_ID=$(git rev-parse HEAD)
popd

C_SRC=$GITHUB/src/
JAVA_SRC=$GITHUB/src/java/src/com/facebook/yoga
TESTS=$GITHUB/src/java/tests/com/facebook/yoga
FBA_SRC=$ROOT/xplat/js/react-native-github/packages/react-native/ReactAndroid/src/main/java/com/facebook/yoga/
FBA_TESTS=$ROOT/fbandroid/javatests/com/facebook/yoga/
FBO_SRC=$ROOT/xplat/js/react-native-github/packages/react-native/React/Layout/

echo "Copying fbandroid src files over..."
cp $JAVA_SRC/*.java $FBA_SRC
echo "Copying fbandroid test files over..."
cp $TESTS/*.java $FBA_TESTS
echo "Copying fbobjc src files over..."
cp $C_SRC/Layout.{c,h} $FBO_SRC

echo "Patching files..."
for sourcefile in $FBA_SRC/*.java; do
  patchfile $sourcefile
done
for testfile in $FBA_TESTS/*.java; do
  patchfile $testfile
done
for sourcefile in $FBO_SRC/Layout.{c,h}; do
  patchfile $sourcefile
done

echo "Writing README"

echo "The source of truth for css-layout is: https://github.com/facebook/css-layout

The code here should be kept in sync with GitHub.
HEAD at the time this code was synced: https://github.com/facebook/css-layout/commit/$COMMIT_ID

There is generated code in:
 - README (this file)
 - fbandroid/java/com/facebook/yoga
 - fbandroid/javatests/com/facebook/yoga
 - xplat/js/react-native-github/React/Layout

The code was generated by running 'make' in the css-layout folder and running:

  scripts/sync-css-layout.sh <pathToGithubRepo> <pathToFbSourceRepo>
" > /tmp/yogasync.tmp

cp /tmp/yogasync.tmp "$FBA_SRC/README"
cp /tmp/yogasync.tmp "$FBO_SRC/README"


#!/bin/bash
# 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.

# This script updates RNTester Podfile.lock after verifying the CocoaPods environment.
# Usage:
#   source scripts/update_podfile_lock && update_pods

THIS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RNTESTER_DIR="$THIS_DIR/../packages/rn-tester"

# Keep this separate for FB internal access.
validate_env () {
  cd "$RNTESTER_DIR" || exit
  bundle check || exit
  cd "$THIS_DIR" || exit
}

update_pods () {
  cd "$RNTESTER_DIR" || exit
  bundle install || exit
  bundle check || exit
  bundle exec pod install
  cd "$THIS_DIR" || exit
}


#!/bin/bash
# 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.

# This script validates that the Android environment is set up to run
# tests on a device or emulator (as opposed to a plain Java environment).

# This requires that the Android NDK is set up correctly and it also
# requires that you are currently either running an emulator or have
# an Android device plugged in.

if [ -z "$ANDROID_NDK" ]; then
  echo "Error: \$ANDROID_NDK is not configured."
  echo "You must first install the Android NDK and then set \$ANDROID_NDK."
  echo "If you already installed the Android SDK, well, the NDK is a different thing that you also need to install."
  echo "See https://reactnative.dev/contributing/how-to-build-from-source for instructions."
  exit 1
fi

if [ -z "$(adb get-state)" ]; then
  echo "Error: you must either run an emulator or connect a device."
  echo "You can check what devices are running with 'adb get-state'."
  echo "You can run scripts/run-android-emulator.sh to get a known-good emulator config."
  exit 1
fi

while :
do
    BOOTANIM=$(adb -e shell getprop init.svc.bootanim)
    # shellcheck disable=SC2143
    if [[ -n $(echo "$BOOTANIM" | grep stopped) ]]; then
        break
    fi
    echo "Waiting for the emulator to finish booting..."
    sleep 3
done


#!/bin/bash
# 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.

# This script validates that the Android SDK is installed correctly.
# This means setting ANDROID_HOME and adding its subdirectories to PATH.
# If the Android SDK is not installed correctly, this script exits
# with an error and a helpful message is printed.

if [ -z "$ANDROID_HOME" ]; then
  echo "Error: \$ANDROID_HOME is not configured."
  echo "You must first install the Android SDK and then set \$ANDROID_HOME."
  echo "If you already installed the Android SDK, the problem is that you need to export ANDROID_HOME from your .bashrc or equivalent."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi

if [ ! -d "$ANDROID_HOME" ]; then
  echo "Error: \$ANDROID_HOME = $ANDROID_HOME but that directory does not exist."
  echo "It is possible that you installed then uninstalled the Android SDK."
  echo "In that case, you should reinstall it."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi

if [ ! -e "$ANDROID_HOME/tools/emulator" ]; then
  echo "Error: could not find an emulator at \$ANDROID_HOME/tools/emulator."
  echo "Specifically, $ANDROID_HOME/tools/emulator does not exist."
  echo "This indicates something is broken with your Android SDK install."
  echo "One possibility is that you have \$ANDROID_HOME set to the wrong value."
  echo "If that seems correct, you might want to try reinstalling the Android SDK."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi

if [ -z `which emulator` ]; then
  echo "Error: could not find 'emulator'. Specifically, 'which emulator' was empty."
  echo "However, the emulator seems to be installed at \$ANDROID_HOME/tools/emulator already."
  echo "This means that the problem is that you are not adding \$ANDROID_HOME/tools to your \$PATH."
  echo "You should do that, and then rerun this command."
  echo "Sorry for not fixing this automatically - we just didn't want to mess with your \$PATH automatically because that can break things."
  exit 1
fi

if [ -z `which adb` ]; then
  echo "Error: could not find 'adb'. Specifically, 'which adb' was empty."
  echo "This indicates something is broken with your Android SDK install."
  echo "The most likely problem is that you are not adding \$ANDROID_HOME/platform-tools to your \$PATH."
  echo "If all else fails, try reinstalling the Android SDK."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi


#!/bin/bash
# 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.

# This script validates that Android is set up correctly for the
# testing environment.
#
# In particular, the config in ReactAndroid/build.gradle must match
# the android sdk that is actually installed. Also, we must have the
# right version of Java.

# Check that Buck is working.
if [ -z "$(which buck)" ]; then
  echo "You need to install Buck."
  echo "See https://buckbuild.com/setup/getting_started.html for instructions."
  exit 1
fi

if [ -z "$(buck --version)" ]; then
  echo "Your Buck install is broken."

  if [ -d "/opt/facebook" ]; then
    BUCK_SUGGESTED_COMMIT_FB="b9b76a3a5a086eb440a26d1db9b0731875975099"
    echo "FB laptops ship with a Buck config that is not compatible with open "
    echo "source. FB Buck requires the environment to set a buck version, but "
    echo "the open source version of Buck forbids that."
    echo
    echo "You can try setting:"
    echo
    echo "export BUCKVERSION=${BUCK_SUGGESTED_COMMIT_FB}"
    echo
    echo "in your .bashrc or .bash_profile to fix this."
    echo
    echo "If you don't want to alter BUCKVERSION for other things running on"
    echo "your machine, you can just scope it to a single script, for example"
    echo "by running something like:"
    echo
    echo "BUCKVERSION=${BUCK_SUGGESTED_COMMIT_FB} $0"
    echo
  else
    echo "I don't know what's wrong, but calling 'buck --version' should work."
  fi
  exit 1
else
  BUCK_EXPECTED_VERSION="buck version d743d2d0229852ce7c029ec257532d8916f6b2b7"
  if [ "$(buck --version)" != "$BUCK_EXPECTED_VERSION" ]; then
    if [ ! -d "/opt/facebook" ]; then
      echo "Warning: The test suite expects ${BUCK_EXPECTED_VERSION} to be installed"
    fi
  fi
fi

# MAJOR is something like "23"
MAJOR=`grep compileSdkVersion $(dirname $0)/../ReactAndroid/build.gradle | sed 's/[^[:digit:]]//g'`

# Check that we have the right major version of the Android SDK.
PLATFORM_DIR="$ANDROID_HOME/platforms/android-$MAJOR"
if [ ! -e "$PLATFORM_DIR" ]; then
  echo "Error: could not find version $ANDROID_VERSION of the Android SDK."
  echo "Specifically, the directory $PLATFORM_DIR does not exist."
  echo "You probably need to specify the right version using the SDK Manager from within Android Studio."
  echo "See https://reactnative.dev/docs/getting-started.html for details."
  echo "If you are using Android SDK Tools from the command line, you may need to run:"
  echo
  echo "  sdkmanager \"platform-tools\" \"platform-tools;android-$MAJOR\""
  echo
  echo "Check out https://developer.android.com/studio/command-line/sdkmanager.html for details."
  exit 1
fi

# Check that we have the right version of the build tools.
BT_DIR="$ANDROID_HOME/build-tools/$ANDROID_SDK_BUILD_TOOLS_REVISION"
if [ ! -e "$BT_DIR" ]; then
  echo "Error: could not find version $ANDROID_SDK_BUILD_TOOLS_REVISION of the Android build tools."
  echo "Specifically, the directory $BT_DIR does not exist."
  echo "You probably need to explicitly install the correct version of the Android SDK Build Tools from within Android Studio."
  echo "See https://reactnative.dev/docs/getting-started.html for details."
  echo "If you are using Android SDK Tools from the command line, you may need to run:"
  echo
  echo "  sdkmanager \"platform-tools\" \"build-tools;android-$ANDROID_SDK_BUILD_TOOLS_REVISION\""
  echo
  echo "Check out https://developer.android.com/studio/command-line/sdkmanager.html for details."
  exit 1
fi

if [ -n "$(which csrutil)" ]; then
  # This is a SIP-protected machine (recent OSX).
  # Check that we are not using SIP-protected Java.
  JAVA=`which java`
  if [ "$JAVA" = "/usr/bin/java" ]; then
    echo "Error: we can't use this Java version."
    echo "Currently, Java runs from $JAVA."
    echo "The operating-system-provided Java doesn't work with React Native because of SIP protection."
    echo "Please install the Oracle Java Development Kit 8."
    if [ -d "/opt/facebook" ]; then
      echo "See https://our.intern.facebook.com/intern/dex/installing-java-8/ for instructions on installing Java 8 on FB laptops."
    else
      echo "Check out http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html ."
      echo "Be sure that you set JAVA_HOME and PATH correctly in your .bashrc or equivalent. Example:"
      echo
      echo "  export JAVA_HOME=path/to/java"
      echo "  export PATH=\$PATH:\$JAVA_HOME/bin"
      echo
    fi
    echo "After installing Java, run 'buck kill' and 'buck clean'."
    exit 1
  fi
fi

if [ -z "$JAVA_HOME" ]; then
  echo "Error: \$JAVA_HOME is not configured."
  echo "Try adding export JAVA_HOME=\$(/usr/libexec/java_home) to your .bashrc or equivalent."
  echo "You will also want to add \$JAVA_HOME/bin to your path."
  exit 1
fi


#!/bin/bash
# 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.

# This script validates that iOS is set up correctly for the
# testing environment.
#
# In particular, it checks that the minimum required Xcode version is installed.
# It also checks that the correct Node version is installed.

# Function used to compare dot separated version numbers
function version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }

# Check that node is installed.
if [ -z "$(which node)" ]; then
  echo "Could not find Node binary. Please check your nodejs install."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi

# Check that the correct version of node is installed
NODE_VERSION="$(command node --version | sed 's/[-/a-zA-Z]//g' |sed 's/.\{2\}$//')"

if (( $(echo "${NODE_VERSION} < 14.0" | bc -l) )); then
  echo "Node ${NODE_VERSION} detected. This version of Node is not supported."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi

# Check that Xcode is installed.
if [ -z "$(which xcodebuild)" ]; then
  echo "Could not find Xcode build tools. Please check your Xcode install."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi

MIN_XCODE_VERSION=9.4
# Check that the correct version of Xcode is installed
XCODE_VERSION="$(command xcodebuild -version | sed '$ d' | sed 's/[-/a-zA-Z]//g')"
if (version_gt $MIN_XCODE_VERSION $XCODE_VERSION) && [ "$XCODE_VERSION" != "$MIN_XCODE_VERSION" ]; then
  echo "Xcode ${XCODE_VERSION} detected. React Native requires ${MIN_XCODE_VERSION} or newer."
  echo "Older versions of Xcode may cause cryptic build errors."
  echo "See https://reactnative.dev/docs/getting-started for instructions."
  exit 1
fi


#!/bin/bash
# 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.

GITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook}
GITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native}
export GITHUB_OWNER
export GITHUB_REPO

cat <(echo eslint; npm run lint --silent -- --format=json; echo flow; npm run flow-check-ios --silent --json; echo flow; npm run flow-check-android --silent --json; echo google-java-format; node scripts/lint-java.js --diff) | GITHUB_PR_NUMBER="$CIRCLE_PR_NUMBER" node packages/react-native-bots/code-analysis-bot.js

STATUS=$?
if [ $STATUS == 0 ]; then
  echo "Code analyzed successfully."
else
  echo "Code analysis failed, error status $STATUS."
fi


#!/bin/bash
# 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.

GITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook}
GITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native}
export GITHUB_OWNER
export GITHUB_REPO

if [ -x "$(command -v shellcheck)" ]; then
  IFS=$'\n'

  if [ -n "$CIRCLE_CI" ]; then
    results=( "$(find . -type f -not -path "*node_modules*" -not -path "*third-party*" -name '*.sh' -exec sh -c  'shellcheck "$1" -f json' -- {} \;)" )

    cat <(echo shellcheck; printf '%s\n' "${results[@]}" | jq .,[] | jq -s . | jq --compact-output --raw-output '[ (.[] | .[] | . ) ]') | GITHUB_PR_NUMBER="$CIRCLE_PR_NUMBER" node scripts/circleci/code-analysis-bot.js

    # check status
    STATUS=$?
    if [ $STATUS == 0 ]; then
      echo "Shell scripts analyzed successfully."
    else
      echo "Shell script analysis failed, error status $STATUS."
    fi

  else
    find . \
      -type f \
      -not -path "*node_modules*" \
      -not -path "*third-party*" \
      -name '*.sh' \
    -exec sh -c 'shellcheck "$1"' -- {} \;
  fi

else
  echo 'shellcheck is not installed. See https://github.com/facebook/react-native/wiki/Development-Dependencies#shellcheck for instructions.'
  exit 1
fi


#!/bin/bash
# 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.

set -e

echo "Downloading package lists..."
sudo apt-get update -y

if ! [[ -d ~/vendor/apt ]]; then
  mkdir -p ~/vendor/apt
fi

# First check for archives cache
if ! [[ -d ~/vendor/apt/archives ]]; then
  # It doesn't so download the packages
  echo "Downloading build dependencies..."
  sudo apt-get install --download-only ant autoconf automake g++ gcc libqt5widgets5 lib32z1 lib32stdc++6 make maven python-dev python3-dev qml-module-qtquick-controls qtdeclarative5-dev libpulse0 file -y
  # Then move them to our cache directory
  sudo cp -R /var/cache/apt ~/vendor/
  # Making sure our user has ownership, in order to cache
  sudo chown -R ${USER:=$(/usr/bin/id -run)}:$USER ~/vendor/apt
fi

# Install all packages in the cache
echo "Installing build dependencies..."
sudo dpkg -i ~/vendor/apt/archives/*.deb


#!/bin/bash
# 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.

set -e

# Make sure we don't introduce accidental references to PATENTS.
EXPECTED='scripts/circleci/check_license.sh'
ACTUAL=$(git grep -l PATENTS)

if [ "$EXPECTED" != "$ACTUAL" ]; then
  echo "PATENTS crept into some new files?"
  diff -u <(echo "$EXPECTED") <(echo "$ACTUAL") || true
  exit 1
fi


#!/bin/bash
# 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.

# execute command
"$@"

# check status
STATUS=$?
if [ $STATUS == 0 ]; then
  echo "Command " "$@" " completed successfully"
else
  echo "Command " "$@" " exited with error status $STATUS"
fi


#!/bin/bash
# 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.

GITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook} \
GITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native} \
GITHUB_PR_NUMBER="${CIRCLE_PR_NUMBER:-${CIRCLE_PULL_REQUEST##*/}}" \
GITHUB_REF=${CIRCLE_BRANCH} \
GITHUB_SHA=${CIRCLE_SHA1} \
exec node packages/react-native-bots/post-artifacts-link.js


#!/bin/bash
# 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.

case $1 in
  "android" | "ios")
    GITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook} \
    GITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native} \
    GITHUB_PR_NUMBER="${CIRCLE_PR_NUMBER:-${CIRCLE_PULL_REQUEST##*/}}" \
    GITHUB_REF=${CIRCLE_BRANCH} \
    GITHUB_SHA=${CIRCLE_SHA1} \
    exec node packages/react-native-bots/report-bundle-size.js "$1"
    ;;
  *)
    echo "Syntax: $0 [android | ios]"
    exit 1
esac


#!/bin/bash
# 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.

# Abort the mission if any command fails
set -e

# Allow the script to be invoked from various environments
if [[ -z "${OVERRIDE_YARN_BINARY}" ]]; then
  YARN_BINARY=$(command -v yarn)
else
  YARN_BINARY="${OVERRIDE_YARN_BINARY}"
fi

REACT_NATIVE_TEMP_DIR=$(mktemp -d /tmp/react-native-XXXXXXXX)

function cleanup {
  set +e
  rm -rf "$REACT_NATIVE_TEMP_DIR"
  set -e
}

function msg {
  echo -e " "
  echo -e "\\x1B[36m${1}\\x1B[0m";
  echo -e "\\x1B[36m${1//?/=}\\x1B[0m"
}

trap cleanup EXIT

cp -R ./package.json "$REACT_NATIVE_TEMP_DIR"
cp -R ./yarn.lock "$REACT_NATIVE_TEMP_DIR"
pushd "$REACT_NATIVE_TEMP_DIR" >/dev/null

if ! $YARN_BINARY --ignore-scripts --silent --non-interactive --mutex network --frozen-lockfile; then
  msg "Yarn validation failed."
  echo "This means the package.json and yarn.lock disagree in some way."
  echo "Try fixing it by running \`yarn\` and committing the changes."
fi

popd >/dev/null


#!/bin/bash
# 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.

if [ -f "generated_apilevels.py" ] ; then
  GEN_APILEVELS_INPUT="generated_apilevels.py"
else
  GEN_APILEVELS_INPUT=
fi

tar czf redex.tar.gz redex-all redex.py pyredex/*.py $GEN_APILEVELS_INPUT
cat selfextract.sh redex.tar.gz > redex
chmod +x redex


#!/usr/bin/env bash
# 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.

BOOST_VERSION="1.71.0"

BOOST_VERSION_UNDERSCORE="${BOOST_VERSION//./_}"
BOOST_FILE="boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2"
BOOST_TAR_URL="https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION}/source/${BOOST_FILE}"
BOOST_CACHE_DIR="boost_cache"
BOOST_TAR_LOCAL="${BOOST_CACHE_DIR}/${BOOST_FILE}"
BOOST_DIR="boost_${BOOST_VERSION_UNDERSCORE}"

set -e

# Check for cached artifacts.
if [ ! -d "$BOOST_CACHE_DIR" ] ; then
  mkdir boost_cache
fi
if [ ! -f "$BOOST_TAR_LOCAL" ] ; then
  wget "$BOOST_TAR_URL" -O "$BOOST_TAR_LOCAL"
fi

tar --bzip2 -xf "$BOOST_TAR_LOCAL"

cd "$BOOST_DIR"
./bootstrap.sh --with-libraries=filesystem,iostreams,program_options,regex,system,thread
./b2 -j 4 -d0 install


#!/bin/bash
# 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.

export TMPDIR=`mktemp -d /tmp/redex.XXXXXX`
ARCHIVE=`awk '/^__ARCHIVE_BELOW__/ { print NR + 1; exit 0 }' $0`
tail -n+$ARCHIVE $0 | tar xz -C $TMPDIR

$TMPDIR/redex.py $@

rm -rf $TMPDIR
exit 0

__ARCHIVE_BELOW__


#!/usr/bin/env bash
# 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.

# Set-up the dependencies necessary to build and run Redex on Ubuntu 16.04
# Xenial, using APT for software management.

# Exit on any command failing
set -e

# Root directory of repository
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"

# Temporary directory for toolchain sources. Build artifacts will be
# installed to /usr/local.
TMP=$(mktemp -d 2>/dev/null)
trap 'rm -r $TMP' EXIT

if [ "$1" = "32" ] ; then
  BITNESS="32"
  BITNESS_SUFFIX=":i386"
  BITNESS_CONFIGURE="--host=i686-linux-gnu CFLAGS=-m32 CXXFLAGS=-m32 LDFLAGS=-m32"
  BITNESS_PKGS="gcc-multilib g++-multilib"

  echo "Use --host=i686-linux-gnu CFLAGS=-m32 CXXFLAGS=-m32 LDFLAGS=-m32 for ./configure"
else
  BITNESS="64"  # Assumption here, really means host-preferred arch.
  BITNESS_SUFFIX=":"
  BITNESS_CONFIGURE=""
  BITNESS_PKGS=""
fi

BOOST_DEB_UBUNTU_PKGS="libboost-filesystem-dev$BITNESS_SUFFIX
                       libboost-iostreams-dev$BITNESS_SUFFIX
                       libboost-program-options-dev$BITNESS_SUFFIX
                       libboost-regex-dev$BITNESS_SUFFIX
                       libboost-system-dev$BITNESS_SUFFIX
                       libboost-thread-dev$BITNESS_SUFFIX"

function install_python36_from_source {
    pushd "$TMP"
    wget https://www.python.org/ftp/python/3.6.10/Python-3.6.10.tgz
    tar -xvf Python-3.6.10.tgz
    pushd Python-3.6.10

    # Always compile Python as host-preferred.
    ./configure
    make V=0 && make install V=0
}

function install_boost_from_source {
    pushd "$TMP"
    "$ROOT"/get_boost.sh
}

function install_protobuf3_from_source {
    pushd "$TMP"
    wget https://github.com/protocolbuffers/protobuf/releases/download/v3.17.3/protobuf-cpp-3.17.3.tar.gz
    tar -xvf protobuf-cpp-3.17.3.tar.gz --no-same-owner

    pushd protobuf-3.17.3
    ./configure $BITNESS_CONFIGURE
    make -j 4 V=0 && make install V=0
}

function install_from_apt {
  PKGS="autoconf
        autoconf-archive
        automake
        binutils-dev
        bzip2
        ca-certificates
        g++
        libiberty-dev$BITNESS_SUFFIX
        libjemalloc-dev$BITNESS_SUFFIX
        libjsoncpp-dev$BITNESS_SUFFIX
        liblz4-dev$BITNESS_SUFFIX
        liblzma-dev$BITNESS_SUFFIX
        libtool
        make
        wget
        zlib1g-dev$BITNESS_SUFFIX $BITNESS_PKGS $*"
  apt-get update
  apt-get install --no-install-recommends -y ${PKGS}
}

function handle_debian {
    case $1 in
        [1-9])
            echo "Unsupported Debian version $1"
            exit 1
            ;;
        10)
            if [ "$BITNESS" == "32" ] ; then
                echo "32-bit compile unsupported because of boost"
                exit 1
            fi
            install_from_apt python3
            install_boost_from_source
            install_protobuf3_from_source
            ;;
        *)
            install_from_apt ${BOOST_DEB_UBUNTU_PKGS} python3
            install_protobuf3_from_source
            ;;
    esac
}

function handle_ubuntu {
    case $1 in
        1[7-9]*)
            if [ "$BITNESS" == "32" ] ; then
                echo "32-bit compile unsupported because of boost"
                exit 1
            fi
            install_from_apt python3
            install_boost_from_source
            install_protobuf3_from_source
            ;;
        2*)
            install_from_apt ${BOOST_DEB_UBUNTU_PKGS} python3
            install_protobuf3_from_source
            ;;
        *)
            echo "Unsupported Ubuntu version $1"
            exit 1
            ;;
    esac
}

# Read ID and VERSION_ID from /etc/os-release.
declare $(grep -E '^(ID|VERSION_ID)=' /etc/os-release | xargs)

case $ID in
ubuntu)
    handle_ubuntu "$VERSION_ID"
    ;;
debian)
    handle_debian "$VERSION_ID"
    ;;
*)
    echo "Unsupported OS $ID - $VERSION_ID"
    exit 1
esac


#!/usr/bin/env bash
# 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.

# Ensure the toolchain has been set-up on entry into the container.  Intended
# for use with the "run" script, which correctly sets up the volume.

[[ -f "$HOME/.setup_complete" ]] || (
  pushd /redex >/dev/null &&
  ./setup_oss_toolchain.sh &&
  autoreconf -ivf &&
  ./configure CXX='g++-5' &&
  touch "$HOME/.setup_complete"
)

exec "$@"


#!/usr/bin/env bash
# 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.

BOOST_VERSION="1.71.0"

BOOST_VERSION_UNDERSCORE="${BOOST_VERSION//./_}"
BOOST_FILE="boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2"
BOOST_TAR_URL="https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION}/source/${BOOST_FILE}"
BOOST_DIR="boost_${BOOST_VERSION_UNDERSCORE}"

set -e

wget "$BOOST_TAR_URL" -O "$BOOST_FILE"
tar --bzip2 -xf "$BOOST_FILE"
cd "$BOOST_DIR"
./bootstrap.sh --with-libraries=thread
./b2 -d0 install


#!/bin/bash -x
# 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.

set -e

pwd

PASSES=$(../redex-all --show-passes | grep 'Registered passes' | sed -e 's/.* //')
if [ "$PASSES" -eq 0 ] ; then
  echo "No passes!"
  exit 1
fi


#!/bin/bash
# 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.

REDEX=$(dirname $0)/../redex.py
if [ ! -f "$REDEX" ]; then
    echo "Couldn't find redex"
    exit 1
fi

if [ $# != 2 ]; then
    echo "Usage: compare_bits.sh apk1 apk2"
    exit 1
fi

DEX1=$($REDEX -u $1 2>&1 | grep ^DEX | cut -d' ' -f 2)
DEX2=$($REDEX -u $2 2>&1 | grep ^DEX | cut -d' ' -f 2)

diff -r $DEX1 $DEX2


#!/bin/bash
# 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.

if [ $# -ne 1 ]; then
  echo "usage: compare_diff_bits.sh <apk>"
  exit 1
fi

APK=$1

# REDEX_ROOT will be "native/redex" or "native/redex-stable"
REDEX_ROOT=native/$(basename "$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )")
if [ "$REDEX_ROOT" != "native/redex" ] && [ "$REDEX_ROOT" != "native/redex-stable" ]; then
  echo "Unexpected REDEX_ROOT: $REDEX_ROOT"
  exit 1
fi

SCRIPT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

DIFF_HASH="$(hg log -l1 -T{node})"
DIFF_OUT="$(mktemp).diff.apk"

hg up -q -r 'ancestor(master, .)'

if [ $? -ne 0 ]; then
  echo "Failed to hg up to base commit"
  exit 1
fi

BASE_HASH="$(hg log -l1 -T{node})"
BASE_OUT="$(mktemp).base.apk"

echo "Will compare base $BASE_HASH to diff $DIFF_HASH"

echo "Redexing with base $BASE_HASH"

buck build $REDEX_ROOT:redex-all 2> /dev/null > /dev/null

if [ $? -ne 0 ]; then
  echo "Failed to build base redex"
  exit 1
fi

$REDEX_ROOT/facebook/fb-redex  --redex-binary buck-out/gen/$REDEX_ROOT/redex-all  -c $REDEX_ROOT/facebook/config/fb4a.config --o $BASE_OUT $APK 2> /dev/null > /dev/null

if [ $? -ne 0 ]; then
  echo "Failed to redex apk with base"
  exit 1
fi

hg up -q -r $DIFF_HASH

if [ $? -ne 0 ]; then
  echo "Failed to hg up to diff commit"
  exit 1
fi

echo "Redexing with diff $DIFF_HASH"

buck build $REDEX_ROOT:redex-all 2> /dev/null > /dev/null

if [ $? -ne 0 ]; then
  echo "Failed to build diff redex"
  exit 1
fi

$REDEX_ROOT/facebook/fb-redex  --redex-binary buck-out/gen/$REDEX_ROOT/redex-all  -c $REDEX_ROOT/facebook/config/fb4a.config --o $DIFF_OUT $APK 2> /dev/null > /dev/null

if [ $? -ne 0 ]; then
  echo "Failed to redex apk with diff"
  exit 1
fi

echo "Comparing bits of base apk $BASE_OUT to diff apk $DIFF_OUT"

ESC="\x1b["
RESET="39;49;00m"
RED="31;01m"
GREEN="32;01m"

$SCRIPT_PATH/compare_bits.sh $BASE_OUT $DIFF_OUT 2> /dev/null > /dev/null

if [ $? -ne 0 ]; then
    echo -e $ESC$RED"Diff changes the output APK relative to base."$ESC$RESET
else
    echo -e $ESC$GREEN"Diff does not change the output APK relative to base."$ESC$RESET
fi


#!/bin/bash
# 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.

set -o pipefail

# This script takes either two dexes, two APKs, or two text files which have
# the output of dexdump, and returns a diff of the two with extraneous info
# (like addresses) filtered out .

INPUT_A=$1
INPUT_B=$2

IGNORE_RENAME=false
if [[ "$3" == '--ignore-rename' ]]
then
  IGNORE_RENAME=true
fi

# The script requires dexdump.
command -v dexdump >/dev/null 2>&1 || { echo "Dexdump not found!" ; exit 2; }

TEMPDIR=`mktemp -d 2>/dev/null || mktemp -d -t 'extractdexdump'`

function strip_cruft() {
    local GET_DUMP_CMD="$1"
    local OUT="$2"
    local RENAME_CLASS=''
    local RENAME_CLASS_DEFINITION=''
    if [ $IGNORE_RENAME == true ]
    then
        RENAME_CLASS='s/LX\/...;/LX\/xxx;/g'
        RENAME_CLASS_DEFINITION='s/X\..../X\.xxx/g'
    fi
    echo Running $GET_DUMP_CMD
    $GET_DUMP_CMD | \
        sed 's/^Processing .*dex//' | \
        sed 's/^Opened .*dex//' | \
        sed 's/^  source_file_idx   : [0-9]* /  source_file_idx   : /' | \
        sed 's/^.*|/|/' | \
        sed 's/|\[[0-9a-f]*\]/|\[\]/' | \
        sed 's/^Class #[0-9]*/Class/' | \
        sed 's/type@[0-9a-f]*/type@/' | \
        sed 's/string@[0-9a-f]*/string@/' | \
        sed 's/method@[0-9a-f]*/method@/' | \
        sed 's/field@[0-9a-f]*/field@/' | \
        sed "$RENAME_CLASS" | \
        sed "$RENAME_CLASS_DEFINITION" | \
        sed 's/0x[0-9a-f]* line=[0-9]*//' | \
        sed 's/^|[0-9a-f]*:/|:/' | \
        sed '/^\s*$/d' \
        > "$OUT"
}

# Compare dexfiles in the folder1 and folder2.
function compare_ir_folder() {
    folder1=$1
    folder2=$2
    dex_count1=$(find "$folder1" -name '*.dex'|wc -l)
    dex_count2=$(find "$folder2" -name '*.dex'|wc -l)
    if [ "$dex_count1" -ne "$dex_count2" ]
    then
        echo "[x] Different dex files count, $dex_count1 in $folder1, $dex_count2 in $folder2"
        exit 1
    fi

    for folder in $folder1 $folder2
    do
        for file in irmeta.bin entry.json
        do
            if [ ! -f "$folder/$file" ]
            then
                echo "[x] $folder/$file is missing"
                exit 1
            fi
        done
    done

    # Compare dex files and irmeta.bin. Check md5sum before running dexdump.
    EXIT_STATUS=0
    cd "$folder1" || exit
    md5sum ./*.dex irmeta.bin > "$TEMPDIR/md5.txt"
    cd "$folder2" || exit
    files=$(md5sum -c "$TEMPDIR/md5.txt" --quiet 2>/dev/null | awk -F: '{print $1}')

    cd "$TEMPDIR" || exit
    for f in $files
    do
        if [ "$f" = irmeta.bin ]; then
            echo "[x] irmeta.bin are different"
            EXIT_STATUS=1
            continue
        fi
        strip_cruft "dexdump -d $folder1/$f" "$f.txt.1" >/dev/null
        strip_cruft "dexdump -d $folder2/$f" "$f.txt.2" >/dev/null
        if ! diff --speed-large-files -u "$f.txt.1" "$f.txt.2" > "$f.txt.diff"
        then
            echo "[x] See difference in $TEMPDIR/$f.txt.diff"
            EXIT_STATUS=1
        fi
    done

    test $EXIT_STATUS -eq 0 && echo "[OK] All the dex files and meta data are the same!"
    exit $EXIT_STATUS
}

export LC_ALL=C

if [ -d "$INPUT_A" ]; then
    # Inputs are IR folders, compare the files in the folders and exit.
    compare_ir_folder "$INPUT_A" "$INPUT_B"
    exit 1;
elif [ ! -f "$INPUT_A" ]; then
    echo "No such file $INPUT_A, bailing"
    exit 1;
fi

OUTA=$TEMPDIR/alpha.filt.dexdump
OUTB=$TEMPDIR/beta.filt.dexdump
OUTDIFF=$TEMPDIR/diff
DEXDUMP=
if [[ "$INPUT_A" =~ dex$ ]]; then
    DEXDUMP="dexdump -d"
elif [[ "$INPUT_A" =~ apk$ ]]; then
    FBANDROID="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../../.."
    DEXDUMP="$(realpath "$FBANDROID/scripts/ordering/extractdexdump")"
else
    DEXDUMP="cat"
fi

strip_cruft "$DEXDUMP $INPUT_A" "$OUTA"
strip_cruft "$DEXDUMP $INPUT_B" "$OUTB"

diff --speed-large-files -u $OUTA $OUTB > $OUTDIFF
if [ $? == 0 ]; then
	echo "The dexes are equivalent"
	exit 0;
else
	echo "The dexes have significant differences"
	echo "The differences are recorded in $OUTDIFF"
	exit 1;
fi


#!/bin/bash -x
# 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.

set -e

TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
pushd "$TEST_DIR"

# Note: Use at least 1.10 as we need googlemock, too.

test -e gtest-1.10.0.zip || {
    curl https://codeload.github.com/google/googletest/zip/release-1.10.0 \
         -o gtest-1.10.0.zip
    unzip -o gtest-1.10.0.zip
}


#!/bin/bash
# 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.

set -e

# Take a zip file path, and a variable number of file paths that should be
# tested to make sure they are not entries in the zip.
if [ "$#" -le 1 ]; then
    echo "Zip and target file(s) required"
    exit 1
fi
ZIP_FILE=$1
shift
TMP_FILE=$(mktemp)
unzip -l "$ZIP_FILE" > "$TMP_FILE"
while test $# -gt 0
do
    if grep -q "$1" "$TMP_FILE"; then
      echo "File $1 was found in zip and should not be there." >&2
      echo "" >&2
      cat "$TMP_FILE" >&2
      exit 1
    fi
    shift
done


#!/bin/bash
# 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.

set -e

# Expects the executable and an .apk file, which will have its manifest
# attribute values rewritten to new values
if [ "$#" -le 1 ]; then
    echo "xml_editor binary and target apk required"
    exit 1
fi
EDITOR_BIN=$1
APK=$2
TMP_DIR=$(mktemp -d)

unzip "$APK" AndroidManifest.xml -d "$TMP_DIR"
MANIFEST="$TMP_DIR/AndroidManifest.xml"

echo "Rewriting package attribute"
"$EDITOR_BIN" "$MANIFEST" manifest package com.facebook.bananas
pushd "$TMP_DIR"
zip test_str.zip AndroidManifest.xml
popd

aapt d --values xmltree "$TMP_DIR/test_str.zip" AndroidManifest.xml | grep -q "package=\"com.facebook.bananas\""
echo "package attribute was rewritten successfully"

echo "Rewriting versionCode"
"$EDITOR_BIN" "$MANIFEST" manifest 0x0101021b 0x200
pushd "$TMP_DIR"
zip test_ver.zip AndroidManifest.xml
popd

aapt d --values xmltree "$TMP_DIR/test_ver.zip" AndroidManifest.xml | grep -q -E "android:versionCode.*0x200$"
echo "versionCode was rewritten successfully"

rm -rf "$TMP_DIR"


#! /bin/bash
# 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.

# XXX(jezng): I tried running these commands as part of the Buck build, but I'm
# having trouble getting the Buck-given versions of AAPT and the SDK libraries
# to work together -- in particular, running the AAPT from v23 against the SDK
# from v26 causes AAPT to crash. Rather than spending time figuring out how to
# get Buck to use the versions I want, I'm just going to run the command
# locally and commit the result...

SCRIPT_DIR=$(dirname "$(realpath "${BASH_SOURCE[0]}")")

for SRC in $(find "$SCRIPT_DIR" -type f -name "*.xml"); do
  TMP=$(mktemp -d)
  MANIFEST="$TMP/AndroidManifest.xml"
  cp "$SRC" "$MANIFEST"
  /opt/android_sdk/build-tools/23.0.1/aapt package -M "$MANIFEST" -F "$TMP/out.apk" -I /opt/android_sdk/platforms/android-25/android.jar
  unzip "$TMP/out.apk" -d "$TMP/out"
  mv "$TMP/out/AndroidManifest.xml" "$SRC.bin"
  rm -rf "$TMP"
done