<commit_before>#!/usr/bin/env python

# Copyright 2020 Google
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Standalone self-sufficient (no external dependencies) python script that can ease
building desktop apps depending on firebase, by either using the firebase cpp
source (firebase-cpp-sdk github repo) or the prebuilt release firebase libraries.

Note that this script works with only Python3 (3.6+).
Known side effects:
If building against firebase cpp source, this script might checkout a specific
branch on github containing vcpkg. This will not be required once vcpkg is in the
main branch.

Example usage:
Let's say we want to build the quickstart cpp example for firebase database.
As specified above, there are 2 options - build against the firebase source or
prebuilt firebase libraries.

# Build against the firebase cpp sdk source
python3 scripts/build_desktop_app_with_firebase.py --app_dir ~/quickstart-cpp/database/testapp
                                                   --sdk_dir . --build_dir build_source

(or)

# Build against the prebuilt released firebase libraries
python3 scripts/build_desktop_app_with_firebase.py --app_dir ~/quickstart-cpp/database/testapp
                                                   --sdk_dir ~/prebuilt/firebase_cpp_sdk_6.15.1/
                                                   --build_dir build_prebuilt

# If the script ran successfully, it will print the path to the build directory.
Build successful!
Please find your executables in build directory: /Users/<user>/quickstart-cpp/database/testapp/build_source

# Running the built example
$ ./Users/<user>/quickstart-cpp/database/testapp/build_source/desktop_testapp
"""
import argparse
import distutils.spawn
import os
import platform
import subprocess
import sys

def is_path_valid_for_cmake(path):
  """Check if specified path is setup for cmake"""
  return os.path.exists(os.path.join(path, 'CMakeLists.txt'))

def is_sdk_path_source(sdk_dir):
  """Validate if firebase sdk dir is firebase cpp source dir"""
  # Not the most reliable way to detect if the sdk path is source or prebuilt but
  # should work for our purpose.
  return os.path.exists(os.path.join(sdk_dir, 'build_tools'))

def validate_prebuilt_args(arch, config):
  """Validate cmd line args for build with prebuilt libraries"""
  # Some options are not available when using prebuilt libraries"""
  if platform.system() == 'Darwin':
    if arch == 'x86' or config == 'Debug':
      raise ValueError("Prebuilt mac firebase libraries are built for x64 and Release mode only. "
                       "Please fix the command line arguments and try again")

  if platform.system() == 'Linux':
    if config == 'Debug':
      raise ValueError("Prebuilt linux firebase libraries are built with Release mode only. "
                       "Please fix the --config command line argument and try again.")

def get_vcpkg_triplet(arch, msvc_runtime_library='static'):
  """ Get vcpkg target triplet (platform definition).

  Args:
    arch (str): Architecture (eg: 'x86', 'x64').
    msvc_runtime_library (str): Runtime library for MSVC (eg: 'static', 'dynamic').

  Raises:
    ValueError: If current OS is not win,mac or linux.

  Returns:
    (str): Triplet name.
       Eg: "x64-windows-static".
  """
  triplet_name = [arch]
  if platform.system() == 'Windows':
    triplet_name.append('windows')
    triplet_name.append('static')
    if msvc_runtime_library == 'dynamic':
      triplet_name.append('md')
  elif platform.system() == 'Darwin':
    triplet_name.append('osx')
  elif platform.system() == 'Linux':
    triplet_name.append('linux')
  else:
    raise ValueError("Unsupported platform. "
                     "This function works only on Windows, Linux or Mac platforms.")

  triplet_name = '-'.join(triplet_name)
  print("Using vcpkg triplet: {0}".format(triplet_name))
  return triplet_name

def build_source_vcpkg_dependencies(sdk_source_dir, arch, msvc_runtime_library):
  """Build C++ dependencies for firebase source SDK using vcpkg.

  Args:
   sdk_source_dir (str): Path to Firebase C++ source directory.
   arch (str): Platform Architecture (example: 'x64').
   msvc_runtime_library (str): Runtime library for MSVC (eg: 'static', 'dynamic').
  """
  # TODO: Remove this once dev branch of firebase-cpp-sdk repo has been merged
  # onto main branch. This is required because vcpkg lives only in dev branch currently.
  subprocess.run(['git', 'checkout', 'feature/python-tool-build-apps-with-firebase'],
                 cwd=sdk_source_dir, check=True)
  subprocess.run(['git', 'pull'], cwd=sdk_source_dir, check=True)

  python_exe = 'python3' if distutils.spawn.find_executable('python3') else 'python'
  subprocess.run([python_exe, "scripts/gha/install_prereqs_desktop.py"],
                 cwd=sdk_source_dir, check=True)
  subprocess.run([python_exe, "scripts/gha/build_desktop.py", "--arch", arch,
                              "--msvc_runtime_library", msvc_runtime_library,
                              "--vcpkg_step_only"], cwd=sdk_source_dir, check=True)

def build_app_with_source(app_dir, sdk_source_dir, build_dir, arch,
                          msvc_runtime_library='static', config=None,
                          target_format=None):
  """Build desktop app directly against the firebase C++ SDK source.
<commit_msg>checkout dev branch instead of temporary feature branch<commit_after>#!/usr/bin/env python

# Copyright 2020 Google
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Standalone self-sufficient (no external dependencies) python script that can ease
building desktop apps depending on firebase, by either using the firebase cpp
source (firebase-cpp-sdk github repo) or the prebuilt release firebase libraries.

Note that this script works with only Python3 (3.6+).
Known side effects:
If building against firebase cpp source, this script might checkout a specific
branch on github containing vcpkg. This will not be required once vcpkg is in the
main branch.

Example usage:
Let's say we want to build the quickstart cpp example for firebase database.
As specified above, there are 2 options - build against the firebase source or
prebuilt firebase libraries.

# Build against the firebase cpp sdk source
python3 scripts/build_desktop_app_with_firebase.py --app_dir ~/quickstart-cpp/database/testapp
                                                   --sdk_dir . --build_dir build_source

(or)

# Build against the prebuilt released firebase libraries
python3 scripts/build_desktop_app_with_firebase.py --app_dir ~/quickstart-cpp/database/testapp
                                                   --sdk_dir ~/prebuilt/firebase_cpp_sdk_6.15.1/
                                                   --build_dir build_prebuilt

# If the script ran successfully, it will print the path to the build directory.
Build successful!
Please find your executables in build directory: /Users/<user>/quickstart-cpp/database/testapp/build_source

# Running the built example
$ ./Users/<user>/quickstart-cpp/database/testapp/build_source/desktop_testapp
"""
import argparse
import distutils.spawn
import os
import platform
import subprocess
import sys

def is_path_valid_for_cmake(path):
  """Check if specified path is setup for cmake"""
  return os.path.exists(os.path.join(path, 'CMakeLists.txt'))

def is_sdk_path_source(sdk_dir):
  """Validate if firebase sdk dir is firebase cpp source dir"""
  # Not the most reliable way to detect if the sdk path is source or prebuilt but
  # should work for our purpose.
  return os.path.exists(os.path.join(sdk_dir, 'build_tools'))

def validate_prebuilt_args(arch, config):
  """Validate cmd line args for build with prebuilt libraries"""
  # Some options are not available when using prebuilt libraries"""
  if platform.system() == 'Darwin':
    if arch == 'x86' or config == 'Debug':
      raise ValueError("Prebuilt mac firebase libraries are built for x64 and Release mode only. "
                       "Please fix the command line arguments and try again")

  if platform.system() == 'Linux':
    if config == 'Debug':
      raise ValueError("Prebuilt linux firebase libraries are built with Release mode only. "
                       "Please fix the --config command line argument and try again.")

def get_vcpkg_triplet(arch, msvc_runtime_library='static'):
  """ Get vcpkg target triplet (platform definition).

  Args:
    arch (str): Architecture (eg: 'x86', 'x64').
    msvc_runtime_library (str): Runtime library for MSVC (eg: 'static', 'dynamic').

  Raises:
    ValueError: If current OS is not win,mac or linux.

  Returns:
    (str): Triplet name.
       Eg: "x64-windows-static".
  """
  triplet_name = [arch]
  if platform.system() == 'Windows':
    triplet_name.append('windows')
    triplet_name.append('static')
    if msvc_runtime_library == 'dynamic':
      triplet_name.append('md')
  elif platform.system() == 'Darwin':
    triplet_name.append('osx')
  elif platform.system() == 'Linux':
    triplet_name.append('linux')
  else:
    raise ValueError("Unsupported platform. "
                     "This function works only on Windows, Linux or Mac platforms.")

  triplet_name = '-'.join(triplet_name)
  print("Using vcpkg triplet: {0}".format(triplet_name))
  return triplet_name

def build_source_vcpkg_dependencies(sdk_source_dir, arch, msvc_runtime_library):
  """Build C++ dependencies for firebase source SDK using vcpkg.

  Args:
   sdk_source_dir (str): Path to Firebase C++ source directory.
   arch (str): Platform Architecture (example: 'x64').
   msvc_runtime_library (str): Runtime library for MSVC (eg: 'static', 'dynamic').
  """
  # TODO: Remove this once dev branch of firebase-cpp-sdk repo has been merged
  # onto main branch. This is required because vcpkg lives only in dev branch currently.
  subprocess.run(['git', 'checkout', 'dev'],
                 cwd=sdk_source_dir, check=True)
  subprocess.run(['git', 'pull'], cwd=sdk_source_dir, check=True)

  python_exe = 'python3' if distutils.spawn.find_executable('python3') else 'python'
  subprocess.run([python_exe, "scripts/gha/install_prereqs_desktop.py"],
                 cwd=sdk_source_dir, check=True)
  subprocess.run([python_exe, "scripts/gha/build_desktop.py", "--arch", arch,
                              "--msvc_runtime_library", msvc_runtime_library,
                              "--vcpkg_step_only"], cwd=sdk_source_dir, check=True)

def build_app_with_source(app_dir, sdk_source_dir, build_dir, arch,
                          msvc_runtime_library='static', config=None,
                          target_format=None):
  """Build desktop app directly against the firebase C++ SDK source.

{'fraction_non_alphanumeric': 0.09367761859826713, 'fraction_numerical': 0.005661834091104058, 'mean_word_length': 3.449618320610687, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '358227', 'n_tokens_mistral': 3352, 'n_tokens_neox': 3255, 'n_words': 1161}