Skip to content

Latest commit

 

History

History
438 lines (332 loc) · 14.8 KB

File metadata and controls

438 lines (332 loc) · 14.8 KB

Git and GitHub Setup Guide

This guide walks through the process of creating a local Git repository and connecting it to GitHub.

Creating a Local Git Repository

  1. Navigate to your project directory:

    cd ~/sites/your-project-name
  2. Initialize a new Git repository:

    • Note: This works in both empty folders and folders with existing code
    git init
  3. Rename the default branch to "main" (modern standard):

    git branch -m main
  4. Add your files to the repository:

    git status
    
    git add .
    # or with list of files added
    git add . --verbose
    • The '.' is to add all files. Instead of all files, you can add specific files:
    git add filename1 filename2
    • Tip: Always run git status before git add . to verify what will be added
  5. Check the status of your repository:

    git status
  6. Create a basic README.md file (if you don't have one already):

    echo "# Project Name\n\nBrief description of your project" > README.md
    git add README.md
  7. Create your initial commit:

    git commit -m "Initial commit: Brief description of your project"

Creating a GitHub Repository

  1. Go to GitHub.com and sign in
  2. Click "New" to create a new repository
  3. Name your repository (use the same name as your local project for clarity)
  4. Add an optional description
  5. Choose public or private visibility
  6. Do not initialize with README, license, or .gitignore (since we already have a local repository, create locally)
  7. Click "Create repository"

Connecting Local Repository to GitHub

  1. Authenticate with GitHub over HTTPS using a Personal Access Token (PAT)

    GitHub removed password authentication for Git over HTTPS. Use a PAT (or other token-based methods) instead of your GitHub account password.

    Which to pick?

    This guide documents HTTPS + PAT because it's straightforward and works well for interactive use and automation.

    SSH authentication is also available on GitHub, but for solo developers and small teams publishing from a local computer, HTTPS + PAT is usually the simplest approach.

    If you have many repositories under one GitHub account (for example, separate repos for each theme and plugin), one Personal Access Token (classic) can usually be used across all of them (depending on the token scopes and your org settings). This is convenient, but it also means you should treat the token like a password and store it securely.

  2. Set up GitHub authentication using a Personal Access Token (PAT):

    • Go to GitHub.com → Settings → Developer settings → Personal access tokens → Tokens (classic)

    • Click "Generate new token (classic)"

    • Give it a descriptive name (e.g., "Local Development Machine")

    • Set an expiration date (e.g., 90 days)

    • Select scopes:

      • At minimum, check repo for repository access
      • Add other scopes as needed (e.g., workflow for GitHub Actions)

      Recommended Scopes for WordPress Developers:

      • repo - Full control of private repositories (includes all repo sub-scopes)
      • workflow - If using GitHub Actions for CI/CD or deployments
      • read:packages - If consuming GitHub packages

      Recommended Scopes for Small Teams:

      • Consider using fine-grained tokens instead of classic tokens
      • If using classic tokens, limit to specific repositories when possible
      • For organization-wide access: repo, workflow, read:org
    • Click "Generate token"

    • IMPORTANT: Copy the token immediately - you won't be able to see it again!

    • Store the token securely (e.g., in a password manager like Bitwarden, LastPass, or iPassword)

    Personal Access Token Strategy

    You have two main options for managing Personal Access Tokens:

    Option 1: Single PAT for All Repositories (Simpler)

    • Pros: Easier to manage, only need to remember/update one token
    • Cons: If compromised, attacker gains access to all your repositories
    • Best for: Individual developers or small teams with trusted environments
    • Implementation: Use a single token with appropriate scopes for all your repositories
    • Storage: Save in your global Git credential helper

    Option 2: Separate PATs per Project or Project Group (More Secure)

    • Pros: Better security through isolation, limits potential damage if compromised
    • Cons: More tokens to manage and update when they expire
    • Best for: Sensitive projects, team environments, or professional settings
    • Implementation: Create tokens with names like "Project X Access" with minimal required scopes
    • Storage: Store in project-specific credential files or use different credential helpers, or store each in your Password Keeper software to paste each time

    Security Best Practices

    • Always set an expiration date (30-90 days recommended)
    • Use the minimum required scopes for each token
    • Never commit tokens to your repository
    • Regularly audit and revoke unused tokens
    • Consider using GitHub's fine-grained tokens for more granular control
  3. Add the GitHub repository as a remote:

    # If you need to remove an existing remote
    git remote remove origin
    
    # Add the GitHub repository as "origin" using HTTPS, exactly as given you by GitHub
    git remote add origin https://github.com/yourusername/your-repository-name.git
    # git remote add origin https://github.com/glerner/wp-theme-variation-display.git
  4. Push your local repository to GitHub:

    git push -u origin main
    • When prompted, use your GitHub username and your Personal Access Token as the password
    • The -u (or --set-upstream) flag sets up tracking between your local and remote branches
    • This only needs to be done once; after this, you can simply use git push for future pushes
    • The tracking information is stored in your .git/config file

Note: if the GitHub repository isn't empty (even creating LICENSE) then the repositories are "out of sync".

$ git push -u origin main
To https://github.com/glerner/floot-color-palette-generator.git
 ! [rejected]        main -> main (non-fast-forward)
error: failed to push some refs to 'https://github.com/glerner/floot-color-palette-generator.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Lat3410: ~/sites/floot-palette
$ git fetch origin
From https://github.com/glerner/floot-color-palette-generator
 * [new branch]      main       -> origin/main
Lat3410: ~/sites/floot-palette
$ git log --oneline --graph --decorate --all
$ git merge origin/main --allow-unrelated-histories
Merge made by the 'ort' strategy.
 LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 674 insertions(+)
 create mode 100644 LICENSE
Lat3410: ~/sites/floot-palette
$ git status
On branch main
nothing to commit, working tree clean

Now try git push -u origin main again

  1. Verify your repository settings:

    git config --list
    
    # To see where each setting comes from (global vs. local)
    git config --list --show-origin --show-scope

    Recommended Git Configuration

    Global Settings (in ~/.gitconfig)

    These settings should be applied globally as they apply to all repositories. Run these from your Shell or Bash:

    # Identity settings
    git config --global user.name "Your Name"
    git config --global user.email "your.email@example.com"
    
    # Credential helper to avoid typing your password repeatedly
    git config --global credential.helper store
    
    # Default pull behavior (prevents unintended merges)
    git config --global pull.rebase true
    
    # Enable helpful coloring in Git output
    git config --global color.ui auto
    
    # Line ending normalization
    git config --global core.autocrlf input  # For Linux/Mac
    # git config --global core.autocrlf true # For Windows

    Local Settings (in .git/config)

    These settings are automatically created for each repository or should be set per-project:

    [core]
    	repositoryformatversion = 0
    	filemode = true
    	bare = false
    	logallrefupdates = true
    [remote "origin"]
    	url = https://github.com/username/repository.git
    	fetch = +refs/heads/*:refs/remotes/origin/*
    [branch "main"]
    	remote = origin
    	merge = refs/heads/main

    Checking Your Configuration

    A properly configured repository will show both global and local settings:

    global  file:/home/username/.gitconfig    user.name=Your Name
    global  file:/home/username/.gitconfig    user.email=your.email@example.com
    global  file:/home/username/.gitconfig    credential.helper=store
    global  file:/home/username/.gitconfig    pull.rebase=true
    global  file:/home/username/.gitconfig    color.ui=auto
    local   file:.git/config                  core.repositoryformatversion=0
    local   file:.git/config                  core.filemode=true
    local   file:.git/config                  core.bare=false
    local   file:.git/config                  core.logallrefupdates=true
    local   file:.git/config                  remote.origin.url=https://github.com/username/repository.git
    local   file:.git/config                  remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
    local   file:.git/config                  branch.main.remote=origin
    local   file:.git/config                  branch.main.merge=refs/heads/main
    

Daily Workflow

Viewing Commit History (Local)

To see your commit history with ISO dates (year-month-day), one line per commit:

git log --pretty='format:%C(auto)%h (%as, %s)'

Example output:

a8b6939 (2026-01-08, Refresh theme CSS + theme.json + editor support)

Making Changes

  1. Make changes to your files

  2. Review your changes:

    # First check what files have changed
    git status
    
    # Then examine the actual changes in detail
    git diff
    
    # Optionally save the diff to a file for AI assistance with commit messages
    git diff >changes.diff
    
    # after a git add . or git add some files
    git diff --staged >changes.diff
    • Tip: After saving the diff to changes.diff, ask AI "Make a git commit message for these changes:" followed by the full text of the diff. Review the AI's result.
    • Note: It's best to do this review BEFORE running git add, as it's easier to see what's changed
  3. Stage your changes:

    git add .
  4. Commit your changes:

    git commit -m "Descriptive message about your changes"
    • For multi-line commit messages, just use git commit and a text editor will open

    Suggestion: Have AI review all the changes in the entire changes.diff and make a detailed commit message

  5. Push your changes to GitHub:

    git push

Viewing Commit History (GitHub)

To see the full commit history on GitHub (not limited to the last year):

  1. Open your repository on GitHub
  2. Click the "Code" tab
  3. Click the "__ Commits" link (next to the branch selector)

That page shows the total number of commits on the selected branch and lets you filter by branch, author, and date.

Getting Changes from GitHub

If you're working across multiple machines or with collaborators:

git pull

Helpful Git Configurations

Set your identity:

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Store credentials to avoid typing your token repeatedly:

git config --global credential.helper store

Troubleshooting

Remove a file from Staged that shouldn't be

git rm --cached filename

"Remote origin already exists" error

git remote remove origin
git remote add origin https://github.com/yourusername/your-repository-name.git

Checking your remote URL

git remote -v

"Permission denied (publickey)" when pushing

If you see an error like:

git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

That means your repository remote is currently using SSH (git@github.com:...) but your SSH key authentication is not working on this machine.

Fix: Switch the remote to HTTPS (use PAT authentication):

git remote set-url origin https://github.com/yourusername/your-repository-name.git
git push

Ensure your remote URL is HTTPS

git remote -v

"The current branch main has no upstream branch"

If you see:

fatal: The current branch main has no upstream branch.

Run this once to set the upstream tracking branch:

git push -u origin main

Updating GitHub Personal Access Token

GitHub Personal Access Tokens expire after 90 days (or less if you configure that). You will get an email from GitHub reminding you to regenerate your token.

Regenerate a token on the same page you generated it (see above, ## Connecting Local Repository to GitHub). Save it immediately in a password manager.

If you've generated a new Personal Access Token and are getting authentication errors:

  1. Clear your stored credentials based on your token strategy:

    If you use one token for all repositories (recommended for most users):

    # Clears credentials for all GitHub repositories
    echo "url=https://github.com" | git credential reject

    If you use separate tokens per repository (advanced usage):

    # Replace with your repository's full URL
    echo "url=https://github.com/username/repository-name.git" | git credential reject

    Alternative format using attributes (works for both cases):

    git credential reject <<EOF
    protocol=https
    host=github.com
    # Optional: Uncomment and add path for per-repository tokens
    # path=username/repository-name.git
    EOF

    The URL format is preferred as it's more concise and handles all URL components automatically.

  2. The next time you push or pull, Git will prompt for your credentials. Use:

    • Username: your GitHub username
    • Password: your new Personal Access Token

Alternatively, you can update the token in your credential helper:

  1. Open Keychain Access (macOS) or Credential Manager (Windows)
  2. Search for 'github.com'
  3. Update the password with your new token

For a more permanent solution, consider using the credential cache:

git config --global credential.helper 'cache --timeout=3600'  # Stores credentials for 1 hour
# OR
git config --global credential.helper 'store'  # Stores credentials permanently (less secure)
  • Note: GitHub supports both SSH keys and HTTPS+PAT. If you want to use a PAT, make sure your remote URL is HTTPS.