name: 'Build Electron'
description: 'Builds Electron & Friends'
inputs:
  target-arch:
    description: 'Target arch'
    required: true
  target-platform:
    description: 'Target platform, should be linux, win, macos'
    required: true
  artifact-platform:
    description: 'Artifact platform, should be linux, win, darwin or mas'
    required: true
  step-suffix:
    description: 'Suffix for build steps'
    required: false
    default: ''
  is-release:
    description: 'Is release build'
    required: true
  generate-symbols:
    description: 'Generate symbols'
    required: true
  upload-to-storage:
    description: 'Upload to storage'
    required: true
  is-asan:
    description: 'The ASan Linux build'
    required: false
runs:
  using: "composite"
  steps:
    - name: Set GN_EXTRA_ARGS for MacOS x64 Builds
      shell: bash
      if: ${{ inputs.target-arch == 'x64' && inputs.target-platform == 'macos' }}
      run: |
        GN_APPENDED_ARGS="$GN_EXTRA_ARGS target_cpu=\"x64\" v8_snapshot_toolchain=\"//build/toolchain/mac:clang_x64\""
        echo "GN_EXTRA_ARGS=$GN_APPENDED_ARGS" >> $GITHUB_ENV
    - name: Set GN_EXTRA_ARGS for Windows
      shell: bash
      if: ${{inputs.target-arch != 'x64' && inputs.target-platform == 'win' }}
      run: |
        GN_APPENDED_ARGS="$GN_EXTRA_ARGS target_cpu=\"${{ inputs.target-arch }}\""
        echo "GN_EXTRA_ARGS=$GN_APPENDED_ARGS" >> $GITHUB_ENV
    - name: Add Clang problem matcher
      shell: bash
      run: echo "::add-matcher::src/electron/.github/problem-matchers/clang.json"
    - name: Build Electron ${{ inputs.step-suffix }}
      if: ${{ inputs.target-platform != 'win' }}
      shell: bash
      run: |
        rm -rf "src/out/Default/Electron Framework.framework"
        rm -rf src/out/Default/Electron*.app

        cd src/electron
        # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing
        git pack-refs
        cd ..

        if [ "`uname`" = "Darwin" ]; then
          ulimit -n 10000
          sudo launchctl limit maxfiles 65536 200000
        fi

        if [ "${{ inputs.is-release }}" = "true" ]; then
          NINJA_SUMMARIZE_BUILD=1 e build --target electron:release_build
        else
          NINJA_SUMMARIZE_BUILD=1 e build --target electron:testing_build
        fi
        cp out/Default/.ninja_log out/electron_ninja_log
        node electron/script/check-symlinks.js

        # Upload build stats to Datadog
        if ! [ -z $DD_API_KEY ]; then
          npx node electron/script/build-stats.mjs out/Default/siso.INFO --upload-stats || true          
        else
          echo "Skipping build-stats.mjs upload because DD_API_KEY is not set"
        fi
    - name: Build Electron (Windows) ${{ inputs.step-suffix }}
      if: ${{ inputs.target-platform == 'win' }}
      shell: powershell
      run: |
        cd src\electron
        git pack-refs
        cd ..

        $env:NINJA_SUMMARIZE_BUILD = 1
        if ("${{ inputs.is-release }}" -eq "true") {          
          e build --target electron:release_build
        } else {
          e build --target electron:testing_build
        }
        Copy-Item out\Default\.ninja_log out\electron_ninja_log
        node electron\script\check-symlinks.js

        # Upload build stats to Datadog
        if ($env:DD_API_KEY) {
          try {
            npx node electron\script\build-stats.mjs out\Default\siso.exe.INFO --upload-stats ; $LASTEXITCODE = 0
          } catch {
            Write-Host "Build stats upload failed, continuing..."
          }
        } else {
          Write-Host "Skipping build-stats.mjs upload because DD_API_KEY is not set"
        }
    - name: Verify dist.zip ${{ inputs.step-suffix }}
      shell: bash
      run: |
        cd src        
        if [ "${{ inputs.is-asan }}" != "true" ]; then
          target_os=${{ inputs.target-platform == 'macos' && 'mac' || inputs.target-platform }}
          if [ "${{ inputs.artifact-platform }}" = "mas" ]; then
            target_os="${target_os}_mas"
          fi
          electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ inputs.target-arch }}.manifest
        fi
    - name: Fixup Mksnapshot ${{ inputs.step-suffix }}
      shell: bash
      run: |
        cd src
        ELECTRON_DEPOT_TOOLS_DISABLE_LOG=1 e d gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args
        # Remove unused args from mksnapshot_args
        SEDOPTION="-i"
        if [ "`uname`" = "Darwin" ]; then
          SEDOPTION="-i ''"
        fi
        sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args
        sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args
        sed $SEDOPTION '/--reorder-builtins/d' out/Default/mksnapshot_args
        sed $SEDOPTION '/--warn-about-builtin-profile-data/d' out/Default/mksnapshot_args
        sed $SEDOPTION '/--abort-on-bad-builtin-profile-data/d' out/Default/mksnapshot_args

        if [ "${{ inputs.target-platform }}" = "win" ]; then
          cd out/Default
          powershell Compress-Archive -update mksnapshot_args mksnapshot.zip
          powershell mkdir mktmp\\gen\\v8
          powershell Copy-Item gen\\v8\\embedded.S mktmp\\gen\\v8
          powershell Compress-Archive -update -Path mktmp\\gen mksnapshot.zip
        else
          (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S)
        fi
    - name: Generate Cross-Arch Snapshot (arm/arm64)  ${{ inputs.step-suffix }}
      shell: bash
      if: ${{ (inputs.target-arch == 'arm' || inputs.target-arch == 'arm64') && inputs.target-platform == 'linux' }}
      run: |
        cd src
        if [ "${{ inputs.target-arch }}" = "arm" ]; then
          MKSNAPSHOT_PATH="clang_x86_v8_arm"
        elif [ "${{ inputs.target-arch }}" = "arm64" ]; then
          MKSNAPSHOT_PATH="clang_x64_v8_arm64"
        fi

        cp "out/Default/$MKSNAPSHOT_PATH/mksnapshot" out/Default
        cp "out/Default/$MKSNAPSHOT_PATH/v8_context_snapshot_generator" out/Default
        cp "out/Default/$MKSNAPSHOT_PATH/libffmpeg.so" out/Default

        python3 electron/script/verify-mksnapshot.py --source-root "$PWD" --build-dir out/Default --create-snapshot-only
        mkdir cross-arch-snapshots
        cp out/Default-mksnapshot-test/*.bin cross-arch-snapshots
        # Clean up so that ninja does not get confused
        rm -f out/Default/libffmpeg.so
    - name: Build Chromedriver ${{ inputs.step-suffix }}
      shell: bash
      run: |
        cd src
        e build --target electron:electron_chromedriver_zip

        if [ "${{ inputs.is-asan }}" != "true" ]; then
          target_os=${{ inputs.target-platform == 'macos' && 'mac' || inputs.target-platform }}
          if [ "${{ inputs.artifact-platform }}" = "mas" ]; then
            target_os="${target_os}_mas"
          fi
          electron/script/zip_manifests/check-zip-manifest.py out/Default/chromedriver.zip electron/script/zip_manifests/chromedriver_zip.$target_os.${{ inputs.target-arch }}.manifest
        fi
    - name: Create installed_software.json ${{ inputs.step-suffix }}
      shell: powershell
      if: ${{ inputs.is-release == 'true' && inputs.target-platform == 'win' }}
      run: |
        cd src
        Get-CimInstance -Namespace root\cimv2 -Class Win32_product | Select vendor, description, @{l='install_location';e='InstallLocation'}, @{l='install_date';e='InstallDate'}, @{l='install_date_2';e='InstallDate2'}, caption, version, name, @{l='sku_number';e='SKUNumber'} | ConvertTo-Json | Out-File -Encoding utf8 -FilePath .\installed_software.json
    - name: Profile Windows Toolchain ${{ inputs.step-suffix }}
      shell: bash
      if: ${{ inputs.is-release == 'true' && inputs.target-platform == 'win' }}
      run: |
        cd src
        python3 electron/build/profile_toolchain.py --output-json=out/Default/windows_toolchain_profile.json
    - name: Add msdia140.dll to Path ${{ inputs.step-suffix }}
      shell: bash
      if: ${{ inputs.is-release == 'true' && inputs.target-platform == 'win' }}
      run: |
        # Needed for msdia140.dll on 64-bit windows
        cd src
        export PATH="$PATH:$(pwd)/third_party/llvm-build/Release+Asserts/bin"
    - name: Zip Symbols ${{ inputs.step-suffix }}
      shell: bash
      run: |
        cd src
        export BUILD_PATH="$(pwd)/out/Default"
        if [ "${{ inputs.is-release }}" = "true" ]; then
          DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH
        else
          electron/script/zip-symbols.py -b $BUILD_PATH
        fi
    - name: Generate FFMpeg ${{ inputs.step-suffix }}
      shell: bash
      if: ${{ inputs.is-release == 'true' }}
      run: |
        cd src
        # Reuse the hermetic mac_sdk_path that `e build` wrote for out/Default so
        # out/ffmpeg builds against the same SDK instead of the runner's system Xcode.
        # The path has to live under root_build_dir, so copy the symlink tree and
        # rewrite Default -> ffmpeg.
        MAC_SDK_ARG=""
        if [ "$(uname)" = "Darwin" ]; then
          mkdir -p out/ffmpeg
          cp -a out/Default/xcode_links out/ffmpeg/
          MAC_SDK_ARG=$(sed -n 's|^\(mac_sdk_path = "//out/\)Default/|\1ffmpeg/|p' out/Default/args.gn)
        fi
        gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true use_siso=true $MAC_SDK_ARG $GN_EXTRA_ARGS"
        e build --target electron:electron_ffmpeg_zip -C ../../out/ffmpeg
    - name: Remove Clang problem matcher
      shell: bash
      run: echo "::remove-matcher owner=clang::"
    - name: Generate TypeScript Definitions ${{ inputs.step-suffix }}
      if: ${{ inputs.is-release == 'true' }}
      shell: bash
      run: |
        cd src/electron
        node script/yarn.js create-typescript-definitions
    - name: Publish Electron Dist ${{ inputs.step-suffix }}
      if: ${{ inputs.is-release == 'true' }}
      shell: bash
      id: github-upload
      run: |
        rm -rf src/out/Default/obj
        cd src/electron
        if [ "${{ inputs.upload-to-storage }}" = "1" ]; then
          echo 'Uploading Electron release distribution to Azure'
          script/release/uploaders/upload.py --verbose --upload_to_storage
        else
          echo 'Uploading Electron release distribution to GitHub releases'
          script/release/uploaders/upload.py --verbose
        fi
    - name: Generate artifact attestation
      if: ${{ inputs.is-release == 'true' }}
      uses: actions/attest-build-provenance@96278af6caaf10aea03fd8d33a09a777ca52d62f # v3.2.0
      with:
        subject-path: ${{ steps.github-upload.outputs.UPLOADED_PATHS }}
    - name: Generate siso report
      if: ${{ inputs.target-platform != 'win' && !cancelled() }}
      shell: bash
      run: |
        cd src
        e d siso report -C out/Default > siso_report.txt
        SISO_REPORT_PATH=$(grep -o '/.*siso-report-[^ ]*' siso_report.txt)
        echo "SISO_REPORT_PATH=$SISO_REPORT_PATH" >> $GITHUB_ENV
        cat siso_report.txt
        echo "SISO REPORT AT $SISO_REPORT_PATH"
    - name: Generate siso report (Windows)
      if: ${{ inputs.target-platform == 'win' && !cancelled() }}
      shell: powershell
      run: |
        cd src
        e d siso report -C out\Default > siso_report.txt
        $SISO_REPORT_PATH = Get-Content "siso_report.txt" | Select-String "report file:\s*(.+)" | ForEach-Object { 
          $_.Matches.Groups[1].Value.Trim() 
        }
        echo "SISO_REPORT_PATH=$SISO_REPORT_PATH"
        echo "SISO_REPORT_PATH=$SISO_REPORT_PATH" >> $env:GITHUB_ENV
    - name: Generate Artifact Key
      if: always() && !cancelled()
      shell: bash
      run: |
        if [ "${{ inputs.is-asan }}" = "true" ]; then 
          ARTIFACT_KEY=${{ inputs.artifact-platform }}_${{ inputs.target-arch }}_asan
        else
          ARTIFACT_KEY=${{ inputs.artifact-platform }}_${{ inputs.target-arch }}
        fi
        echo "ARTIFACT_KEY=$ARTIFACT_KEY" >> $GITHUB_ENV
    # The current generated_artifacts_<< artifact.key >> name was taken from CircleCI
    # to ensure we don't break anything, but we may be able to improve that.
    - name: Move all Generated Artifacts to Upload Folder ${{ inputs.step-suffix }}
      if: always() && !cancelled()
      shell: bash
      run: ./src/electron/script/actions/move-artifacts.sh
    - name: Upload Generated Artifacts ${{ inputs.step-suffix }}
      if: always() && !cancelled()
      uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f #v7.0.0
      with:
        name: generated_artifacts_${{ env.ARTIFACT_KEY }}
        path: ./generated_artifacts_${{ inputs.artifact-platform }}_${{ inputs.target-arch }}
    - name: Upload Src Artifacts ${{ inputs.step-suffix }}
      uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f #v7.0.0
      with:
        name: src_artifacts_${{ env.ARTIFACT_KEY }}
        path: ./src_artifacts_${{ inputs.artifact-platform }}_${{ inputs.target-arch }}
