#!/usr/bin/env conda-execute

# conda execute
# env:
#  - git
#  - python
#  - conda-smithy
#  - gitpython
# channels:
#  - conda-forge
# run_with: python

import os
import shutil

import conda_smithy.feedstocks as feedstocks
from git import Repo
from git.exc import GitCommandError

import argparse

import warnings

parser = argparse.ArgumentParser(description='Update the conda-forge/feedstocks repo.')
parser.add_argument('feedstocks_repo', help="The location of the checked out conda-forge/feedstocks repo.")

args = parser.parse_args()

feedstocks_repo = Repo(args.feedstocks_repo)

forge_feedstocks = feedstocks.feedstock_repos('conda-forge')

# Identify the submodule names which lie withing the repo.
submodules = {sm.name: sm for sm in feedstocks_repo.submodules}

for feedstock in forge_feedstocks:
    repo_subdir = os.path.join('feedstocks', feedstock.package_name)
    abs_subdir = os.path.join(feedstocks_repo.working_tree_dir, repo_subdir)
    if not os.path.exists(abs_subdir):
        print('Adding {} to submodules.'.format(feedstock.package_name))

        # For situations where the submodule already exists, but not in the expected locations, just
        # remove it, and re-add.
        if feedstock.package_name in submodules:
            feedstocks_repo.submodules[feedstock.package_name].remove()

        # Add the new submodule.
        try:
            feedstocks_repo.git.submodule(
                "add",
                "--name",
                feedstock.package_name,
                feedstock.clone_url,
                repo_subdir
            )
        except GitCommandError:
            warnings.warn(
                    "Unable to add the submodule {}. "
                    "This is likely because the repo has no commits, "
                    "which likely means something went wrong with feedstock generation. "
                    "Will skip adding this submodule and continue.".format(feedstock.package_name)
            )
            shutil.rmtree(abs_subdir)


# Pick out the feedstocks which exist on the repo, but are no longer on conda-forge.
to_be_deleted = set(submodules.keys()) - set(repo.package_name for repo in forge_feedstocks)
for package_name in to_be_deleted:
    print("Removing {}.".format(package_name))
    submodule = submodules[package_name].remove()

feedstocks_repo.submodule_update(recursive=False)
feedstocks_repo.git.submodule('foreach', 'git', 'fetch', 'origin', 'master')
feedstocks_repo.git.submodule('foreach', 'git', 'reset', '--hard', 'origin/master')

if feedstocks_repo.is_dirty():
    feedstocks_repo.git.commit('-a', '-m', 'Updated feedstocks submodules. [ci skip]')

@@ -2310,24 +2310,46 @@
 %5D.remove()%0A%0A
+for each_submodule in 
 feedstocks_r
@@ -2365,192 +2365,239 @@
 dule
-_update(recursive=False)%0Afeedstocks_repo.git.submodule('foreach', 'git', 'fetch', 'origin', 'master')%0Afeedstocks_repo.git.submodule('foreach', 'git', 'reset', '--hard', 'origin/master'
+s:%0A    print(%22Updating %7B%7D.%22.format(each_submodule.name))%0A    each_submodule.branch.checkout(force=True)%0A    each_submodule.update(%0A        init=True,%0A        recursive=False,%0A        force=True,%0A        to_latest_revision=True%0A    
 )%0A%0Ai

Update feedstock submodules manually