#!/usr/bin/env python
#
# Copyright 2020 Google LLC.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


"""Create the asset."""


import argparse
import subprocess
import os
import shutil


REPO_URL = "https://github.com/vektra/mockery.git"
REPO_DIR = "mockery_repo"
BINARY_NAME = "mockery"


def create_asset(target_dir):
  """Create the asset."""
  os.chdir(target_dir)

  # We build mockery 2.4.0 from source to fix an issue with Go 1.18. Read the
  # comments below for details.
  output = subprocess.check_output(["git", "clone", REPO_URL, REPO_DIR])
  print(output)
  os.chdir(os.path.join(target_dir, REPO_DIR))
  output = subprocess.check_output(["git", "checkout", "v2.4.0"])

  # Under Go 1.18, mockery v2.4.0 through v2.10.0 fails with errors such as:
  #
  #     internal error: package "fmt" without types was imported from ...
  #
  # This can be fixed by updating golang.org/x/tools to a more recent version.
  # For more details, please see https://github.com/vektra/mockery/issues/434
  # and https://github.com/golang/go/issues/49608.
  output = subprocess.check_output(["go", "get", "golang.org/x/tools@v0.1.10"])
  print(output)
  output = subprocess.check_output(["go", "mod", "tidy"])
  print(output)

  # Build mockery with the same flags as in release builds.
  #
  # If we don't specify a SemVer value, mockery will generate files with a
  # "Code generated by mockery v0.0.0-dev. DO NOT EDIT." comment at the top,
  # which causes diffs due to the changed version. Thus, it is important to set
  # the SemVer value to the correct version.
  #
  # See
  # https://github.com/vektra/mockery/blob/271c74610ef710a4c30e19a42733796c50e7ea3f/.goreleaser.yml#L9.
  ldflags = "-s -w -X github.com/vektra/mockery/v2/pkg/config.SemVer=2.4.0"
  build_command = ["go", "build", "-ldflags=\"%s\"" % ldflags]
  print("Building with command:", build_command)
  output = subprocess.check_output(["go", "build", "-ldflags=" + ldflags])
  print(output)

  # Copy binary outside of the cloned repository directory and clean up.
  output = subprocess.check_output(["cp", BINARY_NAME, ".."])
  shutil.copy(os.path.join(target_dir, REPO_DIR, BINARY_NAME), target_dir)
  shutil.rmtree(os.path.join(target_dir, REPO_DIR))
  os.chdir(target_dir)


def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--target_dir', '-t', required=True)
  args = parser.parse_args()
  create_asset(args.target_dir)


if __name__ == '__main__':
  main()
