Search code examples
githubwebhookscodeship

Automatically copy a file from one GitHub repository to another via Codehip


I have two repositories: S1, S2

I would like to automatically push a file from S1 to S2 if it is changed or created.

For example:

I push translation.en.json to /translations/translation.en.json in S1. translation.en.json should automatically pushed to /dashboard/translation.en.json in S2.

When I push something to master branch in S1 then the codeship build will be run.

I want to write a script in codeship steps which can do this automatic push.

I tried something like this:

#!/bin/bash
set -e
mkdir -p _translations/dashboard/
cd _translations
git fetch --unshallow || true
git fetch origin "+refs/heads/*:refs/remotes/origin/*"
git push git@github.com:company/translations.git "${CI_COMMIT_ID}:master"

Solution

  • We have a script based deployment for pushing to a different git repository available at https://github.com/codeship/scripts/blob/master/deployments/git_push.sh

    You can add that to your deployment pipeline by adding a Script Deployment by setting the required environment variables and adding the curl command, e.g.

    export REMOTE_REPOSITORY="git@github.com:company/s2.git"
    export REMOTE_BRANCH="master"
    \curl -sSL https://raw.githubusercontent.com/codeship/scripts/master/deployments/git_push.sh | bash -s
    

    You will also need to make sure that the Codeship projects SSH key (available via the project settings) is allowed to push to the second repository. See https://documentation.codeship.com/general/projects/access-to-other-repositories-fails-during-build/ for how to configure this.

    However, this will push the complete contents for S1 to the other repository. If you only want to push a specific file (or a set of files) I'd recommend cloning the second repository, copying the files over and then committing and pushing. A sample script could look like this:

    cd "${HOME}"
    git clone git@github.com:company/s2.git
    # "${HOME}/clone" is the default checkout path on Codeship
    cp ./clone/translation.en.json ./s2/
    cd ./s2
    git commit -a "Automatic commit, based on "company/s1@${CI_COMMIT_ID}"
    git push origin master
    

    Please note, that this script is not tested and definitely needs to be adapted to your specific needs. The note regarding authentication and access to the second repository applies to this use case as well.