|
| 1 | +name: Backup to GitLab |
| 2 | + |
| 3 | +on: |
| 4 | + push: |
| 5 | + branches: [main] |
| 6 | + workflow_dispatch: |
| 7 | + |
| 8 | +jobs: |
| 9 | + backup: |
| 10 | + runs-on: ubuntu-latest |
| 11 | + |
| 12 | + steps: |
| 13 | + - name: Checkout code |
| 14 | + uses: actions/checkout@v4 |
| 15 | + with: |
| 16 | + fetch-depth: 0 |
| 17 | + |
| 18 | + - name: Compute repo names |
| 19 | + run: | |
| 20 | + REPO_DISPLAY_NAME="${GITHUB_REPOSITORY#*/}" |
| 21 | + REPO_PATH=$(echo "$REPO_DISPLAY_NAME" | tr '[:upper:]' '[:lower:]') |
| 22 | +
|
| 23 | + echo "REPO_DISPLAY_NAME=$REPO_DISPLAY_NAME" >> $GITHUB_ENV |
| 24 | + echo "REPO_PATH=$REPO_PATH" >> $GITHUB_ENV |
| 25 | +
|
| 26 | + - name: Fetch GitLab token from KeyManagement |
| 27 | + run: | |
| 28 | + TS=$(date +%s%3N) |
| 29 | + TOKEN=$(curl -s -X POST https://keymanagement.joeljollyhere.workers.dev \ |
| 30 | + -H "Content-Type: application/json" \ |
| 31 | + -d "{ |
| 32 | + \"accessKey\": \"${{ secrets.ACCESS_KEY }}\", |
| 33 | + \"key\": \"gitlab\", |
| 34 | + \"ts\": $TS |
| 35 | + }") |
| 36 | +
|
| 37 | + if [ -z "$TOKEN" ]; then |
| 38 | + echo "Failed to fetch GitLab token" |
| 39 | + exit 1 |
| 40 | + fi |
| 41 | +
|
| 42 | + echo "GITLAB_TOKEN=$TOKEN" >> $GITHUB_ENV |
| 43 | +
|
| 44 | + - name: Ensure GitLab repo exists |
| 45 | + run: | |
| 46 | + PROJECT_PATH="withinjoel/${REPO_PATH}" |
| 47 | + ENCODED_PATH=$(echo "$PROJECT_PATH" | sed 's/\//%2F/g') |
| 48 | +
|
| 49 | + STATUS=$(curl -s -o /dev/null -w "%{http_code}" \ |
| 50 | + -H "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \ |
| 51 | + "https://gitlab.com/api/v4/projects/${ENCODED_PATH}") |
| 52 | +
|
| 53 | + if [ "$STATUS" = "404" ]; then |
| 54 | + echo "GitLab repo does not exist. Creating..." |
| 55 | +
|
| 56 | + USER_ID=$(curl -s \ |
| 57 | + -H "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \ |
| 58 | + https://gitlab.com/api/v4/user | jq '.id') |
| 59 | +
|
| 60 | + curl -s -X POST https://gitlab.com/api/v4/projects \ |
| 61 | + -H "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \ |
| 62 | + -H "Content-Type: application/json" \ |
| 63 | + -d "{ |
| 64 | + \"name\": \"${REPO_DISPLAY_NAME}\", |
| 65 | + \"path\": \"${REPO_PATH}\", |
| 66 | + \"namespace_id\": ${USER_ID}, |
| 67 | + \"visibility\": \"private\" |
| 68 | + }" |
| 69 | + else |
| 70 | + echo "GitLab repo already exists." |
| 71 | + fi |
| 72 | +
|
| 73 | + - name: Push to GitLab |
| 74 | + run: | |
| 75 | + git config --global user.name "GitHub Backup Bot" |
| 76 | + git config --global user.email "bot@example.com" |
| 77 | +
|
| 78 | + git remote add gitlab \ |
| 79 | + https://oauth2:${GITLAB_TOKEN}@gitlab.com/withinjoel/${REPO_PATH}.git |
| 80 | +
|
| 81 | + git push gitlab main --force |
0 commit comments