# GitHub Actions CI/CD Pipeline

These are the steps that can be followed to setup a GitHub Actions CI CD Pipeline.

### Step 1: Create the Project Directory Structure

GitHub Actions requires your workflow files to be located in the `.github/workflows/` folder at the root of your repository.

```plaintext
my-app-repo/
├── .github/
│   └── workflows/
│       └── ci.yml             <-- GitHub Actions workflow configuration
├── src/
├── package.json
└── package-lock.json
```

**Commands to execute locally:**

```bash
# Create the workflows directory inside your repository
mkdir -p .github/workflows

# Create your primary workflow file
touch .github/workflows/ci.yml
```

### Step 2: Set Up a Basic CI Pipeline (`ci.yml`)

The workflow configuration defines **triggers** (when to run), **jobs** (where to run), and **steps** (what commands/actions to execute). GitHub provides limited free runner minutes per month for public repositories.

Open `.github/workflows/ci.yml` and paste the following baseline configuration:

```yaml
name: CI Pipeline

# Trigger pipeline on pushes or pull requests to main/master branches
on:
  push:
    branches: [ "main", "master" ]
  pull_request:
    branches: [ "main", "master" ]

jobs:
  run-tests:
    name: Run Unit Tests
    runs-on: ubuntu-latest # Uses GitHub-hosted Linux runner

    steps:
      # Step 1: Check out the repository source code
      - name: Check out GitHub code
        uses: actions/checkout@v4

      # Step 2: Set up the Node.js environment
      - name: Set up Node.js 20
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      # Step 3: Install dependencies and run tests
      - name: Install dependencies
        run: npm install

      - name: Run tests
        run: npm test
```

### Step 3: Implement Dependency Caching (3x–10x Faster Builds)

Without caching, GitHub Actions downloads all project dependencies from scratch on every push, taking **~45 seconds or longer**. Adding dependency caching stores `node_modules` in GitHub's cache storage and restores them on subsequent runs, reducing execution time down to **~8–9 seconds**.

Update your `ci.yml` steps to include `actions/cache@v4`:

```yaml
steps:
  # Step 1: Check out source code
  - name: Checkout GitHub repository
    uses: actions/checkout@v4

  # Step 2: Set up Node.js and enable npm dependency caching
  - name: Setup Node.js 20 with npm caching
    uses: actions/setup-node@v4
    with:
      node-version: '20'
      cache: 'npm'
      cache-dependency-path: package-lock.json

  # Step 3: Install dependencies
  - name: Install dependencies
    run: npm ci

  # Step 4: Run tests
  - name: Run tests
    run: npm test
```

### Step 4: Configure Matrix Strategy for Parallel Testing

To verify that your code runs cleanly across multiple Node.js versions and operating systems simultaneously, configure a **matrix strategy** under `jobs`. GitHub Actions will spawn parallel job runners automatically.

```yaml
jobs:
  matrix-test:
    name: Matrix Test (${{ matrix.os }} - Node ${{ matrix.node-version }})
    runs-on: ${{ matrix.os }}

    permissions:
      contents: read

    strategy:
      fail-fast: false
      matrix:
        os:
          - ubuntu-latest
          - windows-latest
        node-version:
          - 22
          - 24
          - 26

    steps:
      - name: Check out code
        uses: actions/checkout@v4

      - name: Set up Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
          cache: npm
          cache-dependency-path: package-lock.json

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test
```

*This configuration launches* ***6 parallel jobs*** *(2 Operating Systems × 3 Node versions) concurrently to detect environment-specific failures early.*

### Step 5: Build a Multi-Stage CI/CD Deployment Pipeline

To structure an end-to-end automated deployment pipeline:

1. **Chain jobs sequentially** using the `needs:` keyword so that builds run only after tests pass, and deployments wait for successful builds.
2. **Pass build artifacts** between stages using `actions/upload-artifact` and `actions/download-artifact` ("build once, deploy anywhere").
3. **Configure environments**: Enable automatic deployment for `staging` and require **manual approval rules** in GitHub settings for `production`.

#### Complete End-to-End `deploy.yml` Pipeline Code:

```yaml
name: CI/CD Deployment Pipeline

on:
  push:
    branches:
      - main

# Restrict the default GITHUB_TOKEN permissions.
permissions:
  contents: read

# Avoid overlapping deployment pipelines for the same branch.
concurrency:
  group: deployment-${{ github.ref }}
  cancel-in-progress: false

jobs:
  # Stage 1: Automated Unit Testing
  test:
    name: Run Unit Tests
    runs-on: ubuntu-latest

    steps:
      - name: Check out code
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: npm
          cache-dependency-path: package-lock.json

      - name: Install dependencies
        run: npm ci

      - name: Run unit tests
        run: npm test

  # Stage 2: Build Application and Upload Artifact
  build:
    name: Build Application
    needs: test
    runs-on: ubuntu-latest

    steps:
      - name: Check out code
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: npm
          cache-dependency-path: package-lock.json

      - name: Install dependencies
        run: npm ci

      - name: Build application
        run: npm run build

      - name: Verify build output
        run: test -d dist && test -n "$(ls -A dist)"

      - name: Upload build artifact
        uses: actions/upload-artifact@v4
        with:
          name: app-build
          path: dist/
          if-no-files-found: error
          retention-days: 7

  # Stage 3: Deploy to Staging
  deploy-staging:
    name: Deploy to Staging
    needs: build
    runs-on: ubuntu-latest
    environment: staging

    steps:
      - name: Check out deployment scripts
        uses: actions/checkout@v4
        with:
          ref: ${{ github.sha }}

      - name: Download build artifact
        uses: actions/download-artifact@v4
        with:
          name: app-build
          path: dist/

      - name: Deploy to staging
        env:
          DEPLOY_TOKEN: ${{ secrets.STAGING_DEPLOY_TOKEN }}
        run: |
          bash ./scripts/deploy.sh staging dist/

  # Stage 4: Manual Approval and Production Deployment
  deploy-production:
    name: Deploy to Production
    needs: deploy-staging
    runs-on: ubuntu-latest
    environment: production

    steps:
      - name: Check out deployment scripts
        uses: actions/checkout@v4
        with:
          ref: ${{ github.sha }}

      - name: Download build artifact
        uses: actions/download-artifact@v4
        with:
          name: app-build
          path: dist/

      - name: Deploy to production
        env:
          DEPLOY_TOKEN: ${{ secrets.PRODUCTION_DEPLOY_TOKEN }}
        run: |
          bash ./scripts/deploy.sh production dist/
```

### Step 6: Commit Code & Monitor Live Execution

1. **Commit and push your workflow to GitHub:**

   ```bash
   git add .github/workflows/ci.yml
   git commit -m "Add GitHub Actions CI/CD pipeline"
   git push origin main
   ```
2. **Verify pipeline execution on GitHub:**
   - Navigate to your repository.
   - Click on the **Actions** tab at the top navigation bar.
   - Select your workflow run (e.g., *"Add GitHub Actions CI/CD pipeline"*) to watch steps execute live, inspect step execution times, and view green status checkmarks upon completion.
