mirror of
https://github.com/yarlson/lnk.git
synced 2025-09-25 21:18:57 +02:00
Compare commits
30 Commits
v0.0.4
...
fix/dynami
Author | SHA1 | Date | |
---|---|---|---|
|
dc524607fa | ||
|
9bf2e70d13 | ||
|
65db5fe738 | ||
|
43b68bc071 | ||
|
ab97fa86dc | ||
|
4cd8191805 | ||
|
6830c06eb4 | ||
|
8a29b7fe43 | ||
|
a6852e5ad5 | ||
|
36d76c881c | ||
|
6de387797e | ||
|
9cbad5e593 | ||
|
150e8adf8b | ||
|
4b11563bdf | ||
|
b476ce503b | ||
|
ae9cc175ce | ||
|
1e2c9704f3 | ||
|
3cba309c05 | ||
|
3e6b426a19 | ||
|
02f342b02b | ||
|
92f2575090 | ||
|
0f74723a03 | ||
|
093cc8ebe7 | ||
|
ff3cddc065 | ||
|
4a275ce4ca | ||
|
69c1038f3e | ||
|
c670ac1fd8 | ||
|
27196e3341 | ||
|
84c507828d | ||
|
d02f112200 |
17
.github/dependabot.yml
vendored
Normal file
17
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/optimizing-pr-creation-version-updates#setting-up-a-cooldown-period-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference#groups--
|
||||
groups:
|
||||
actions:
|
||||
# Combine all images of last week
|
||||
patterns: ["*"]
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
20
.github/workflows/ci.yml
vendored
20
.github/workflows/ci.yml
vendored
@@ -6,6 +6,12 @@ on:
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
GO_VERSION: '1.24'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -16,10 +22,10 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
- name: Cache Go modules
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
@@ -41,9 +47,9 @@ jobs:
|
||||
run: go test -v -race -coverprofile=coverage.out ./...
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
uses: codecov/codecov-action@v3
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
file: ./coverage.out
|
||||
files: ./coverage.out
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -54,10 +60,10 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v3
|
||||
uses: golangci/golangci-lint-action@v8
|
||||
with:
|
||||
version: latest
|
||||
|
||||
@@ -71,7 +77,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
- name: Build
|
||||
run: go build -v ./...
|
||||
|
2
.gitignore
vendored
2
.gitignore
vendored
@@ -44,3 +44,5 @@ desktop.ini
|
||||
|
||||
# GoReleaser artifacts
|
||||
goreleaser/
|
||||
*.md
|
||||
!/README.md
|
||||
|
291
README.md
291
README.md
@@ -2,11 +2,18 @@
|
||||
|
||||
**Git-native dotfiles management that doesn't suck.**
|
||||
|
||||
Move your dotfiles to `~/.config/lnk`, symlink them back, and use Git like normal. That's it.
|
||||
Lnk makes managing your dotfiles straightforward, no tedious setups, no complex configurations. Just tell Lnk what files you want tracked, and it'll automatically move them into a tidy Git repository under `~/.config/lnk`. It then creates clean, portable symlinks back to their original locations. Easy.
|
||||
|
||||
Why bother with Lnk instead of plain old Git or other dotfile managers? Unlike traditional methods, Lnk automates the boring parts: safely relocating files, handling host-specific setups, bulk operations for multiple files, recursive directory processing, and even running your custom bootstrap scripts automatically. This means fewer manual steps and less chance of accidentally overwriting something important.
|
||||
|
||||
With Lnk, your dotfiles setup stays organized and effortlessly portable, letting you spend more time doing real work, not wrestling with configuration files.
|
||||
|
||||
```bash
|
||||
lnk init
|
||||
lnk add ~/.vimrc ~/.bashrc
|
||||
lnk init -r git@github.com:user/dotfiles.git # Clones & runs bootstrap automatically
|
||||
lnk add ~/.vimrc ~/.bashrc ~/.gitconfig # Multiple files at once
|
||||
lnk add --recursive ~/.config/nvim # Process directory contents
|
||||
lnk add --dry-run ~/.tmux.conf # Preview changes first
|
||||
lnk add --host work ~/.ssh/config # Host-specific config
|
||||
lnk push "setup"
|
||||
```
|
||||
|
||||
@@ -19,7 +26,6 @@ curl -sSL https://raw.githubusercontent.com/yarlson/lnk/main/install.sh | bash
|
||||
|
||||
```bash
|
||||
# Homebrew (macOS/Linux)
|
||||
brew tap yarlson/lnk
|
||||
brew install lnk
|
||||
```
|
||||
|
||||
@@ -42,108 +48,323 @@ git clone https://github.com/yarlson/lnk.git && cd lnk && go build . && sudo mv
|
||||
# Fresh start
|
||||
lnk init
|
||||
|
||||
# With existing repo
|
||||
# With existing repo (runs bootstrap automatically)
|
||||
lnk init -r git@github.com:user/dotfiles.git
|
||||
|
||||
# Skip automatic bootstrap
|
||||
lnk init -r git@github.com:user/dotfiles.git --no-bootstrap
|
||||
|
||||
# Force initialization (WARNING: overwrites existing managed files)
|
||||
lnk init -r git@github.com:user/dotfiles.git --force
|
||||
|
||||
# Run bootstrap script manually
|
||||
lnk bootstrap
|
||||
```
|
||||
|
||||
### Daily workflow
|
||||
|
||||
```bash
|
||||
# Add files/directories
|
||||
lnk add ~/.vimrc ~/.config/nvim ~/.gitconfig
|
||||
# Add multiple files at once (common config)
|
||||
lnk add ~/.vimrc ~/.bashrc ~/.gitconfig ~/.tmux.conf
|
||||
|
||||
# Add directory contents individually
|
||||
lnk add --recursive ~/.config/nvim ~/.config/zsh
|
||||
|
||||
# Preview changes before applying
|
||||
lnk add --dry-run ~/.config/git/config
|
||||
lnk add --dry-run --recursive ~/.config/kitty
|
||||
|
||||
# Add host-specific files (supports bulk operations)
|
||||
lnk add --host laptop ~/.ssh/config ~/.aws/credentials
|
||||
lnk add --host work ~/.gitconfig ~/.ssh/config
|
||||
|
||||
# List managed files
|
||||
lnk list # Common config only
|
||||
lnk list --host laptop # Laptop-specific config
|
||||
lnk list --all # All configurations
|
||||
|
||||
# Check status
|
||||
lnk status
|
||||
|
||||
# Sync changes
|
||||
lnk push "updated vim config"
|
||||
lnk pull
|
||||
lnk pull # Pull common config
|
||||
lnk pull --host laptop # Pull laptop-specific config
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
```
|
||||
Common files:
|
||||
Before: ~/.vimrc (file)
|
||||
After: ~/.vimrc -> ~/.config/lnk/.vimrc (symlink)
|
||||
|
||||
Host-specific files:
|
||||
Before: ~/.ssh/config (file)
|
||||
After: ~/.ssh/config -> ~/.config/lnk/laptop.lnk/.ssh/config (symlink)
|
||||
```
|
||||
|
||||
Your files live in `~/.config/lnk` (a Git repo). Lnk creates symlinks back to original locations. Edit files normally, use Git normally.
|
||||
Your files live in `~/.config/lnk` (a Git repo). Common files go in the root, host-specific files go in `<host>.lnk/` subdirectories. Lnk creates symlinks back to original locations. Edit files normally, use Git normally.
|
||||
|
||||
## Safety Features
|
||||
|
||||
Lnk includes built-in safety checks to prevent accidental data loss:
|
||||
|
||||
### Data Loss Prevention
|
||||
|
||||
```bash
|
||||
# This will be blocked if you already have managed files
|
||||
lnk init -r git@github.com:user/dotfiles.git
|
||||
# ❌ Directory ~/.config/lnk already contains managed files
|
||||
# 💡 Use 'lnk pull' to update from remote instead of 'lnk init -r'
|
||||
|
||||
# Use pull instead to safely update
|
||||
lnk pull
|
||||
|
||||
# Or force if you understand the risks (shows warning only when needed)
|
||||
lnk init -r git@github.com:user/dotfiles.git --force
|
||||
# ⚠️ Using --force flag: This will overwrite existing managed files
|
||||
# 💡 Only use this if you understand the risks
|
||||
```
|
||||
|
||||
### Smart Warnings
|
||||
|
||||
- **Contextual alerts**: Warnings only appear when there are actually managed files to overwrite
|
||||
- **Clear guidance**: Error messages suggest the correct command to use
|
||||
- **Force override**: Advanced users can bypass safety checks when needed
|
||||
|
||||
## Bootstrap Support
|
||||
|
||||
Lnk automatically runs bootstrap scripts when cloning dotfiles repositories, making it easy to set up your development environment. Just add a `bootstrap.sh` file to your dotfiles repo.
|
||||
|
||||
### Examples
|
||||
|
||||
**Simple bootstrap script:**
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# bootstrap.sh
|
||||
echo "Setting up development environment..."
|
||||
|
||||
# Install Homebrew (macOS)
|
||||
if ! command -v brew &> /dev/null; then
|
||||
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
|
||||
fi
|
||||
|
||||
# Install packages
|
||||
brew install git vim tmux
|
||||
|
||||
echo "✅ Setup complete!"
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
|
||||
```bash
|
||||
# Automatic bootstrap on clone
|
||||
lnk init -r git@github.com:you/dotfiles.git
|
||||
# → Clones repo and runs bootstrap script automatically
|
||||
|
||||
# Skip bootstrap if needed
|
||||
lnk init -r git@github.com:you/dotfiles.git --no-bootstrap
|
||||
|
||||
# Run bootstrap manually later
|
||||
lnk bootstrap
|
||||
```
|
||||
|
||||
## Multihost Support
|
||||
|
||||
Lnk supports both **common configurations** (shared across all machines) and **host-specific configurations** (unique per machine).
|
||||
|
||||
### File Organization
|
||||
|
||||
```
|
||||
~/.config/lnk/
|
||||
├── .lnk # Tracks common files
|
||||
├── .lnk.laptop # Tracks laptop-specific files
|
||||
├── .lnk.work # Tracks work-specific files
|
||||
├── .vimrc # Common file
|
||||
├── .gitconfig # Common file
|
||||
├── laptop.lnk/ # Laptop-specific storage
|
||||
│ ├── .ssh/
|
||||
│ │ └── config
|
||||
│ └── .tmux.conf
|
||||
└── work.lnk/ # Work-specific storage
|
||||
├── .ssh/
|
||||
│ └── config
|
||||
└── .gitconfig
|
||||
```
|
||||
|
||||
### Usage Patterns
|
||||
|
||||
```bash
|
||||
# Common config (shared everywhere) - supports multiple files
|
||||
lnk add ~/.vimrc ~/.bashrc ~/.gitconfig ~/.tmux.conf
|
||||
|
||||
# Process directory contents individually
|
||||
lnk add --recursive ~/.config/nvim ~/.config/zsh
|
||||
|
||||
# Preview operations before making changes
|
||||
lnk add --dry-run ~/.config/alacritty/alacritty.yml
|
||||
lnk add --dry-run --recursive ~/.config/i3
|
||||
|
||||
# Host-specific config (unique per machine) - supports bulk operations
|
||||
lnk add --host $(hostname) ~/.ssh/config ~/.aws/credentials
|
||||
lnk add --host work ~/.gitconfig ~/.npmrc
|
||||
|
||||
# List configurations
|
||||
lnk list # Common only
|
||||
lnk list --host work # Work host only
|
||||
lnk list --all # Everything
|
||||
|
||||
# Pull configurations
|
||||
lnk pull # Common config
|
||||
lnk pull --host work # Work-specific config
|
||||
```
|
||||
|
||||
## Why not just Git?
|
||||
|
||||
You could `git init ~/.config/lnk` and manually symlink everything. Lnk just automates the tedious parts:
|
||||
|
||||
- Moving files safely
|
||||
- Moving files safely (with atomic operations)
|
||||
- Creating relative symlinks
|
||||
- Handling conflicts
|
||||
- Handling conflicts and rollback
|
||||
- Tracking what's managed
|
||||
- Processing multiple files efficiently
|
||||
- Recursive directory traversal
|
||||
- Preview mode for safety
|
||||
|
||||
## Examples
|
||||
|
||||
### First time setup
|
||||
|
||||
```bash
|
||||
# Clone dotfiles and run bootstrap automatically
|
||||
lnk init -r git@github.com:you/dotfiles.git
|
||||
lnk add ~/.bashrc ~/.vimrc ~/.gitconfig
|
||||
# → Downloads dependencies, installs packages, configures environment
|
||||
|
||||
# Add common config (shared across all machines) - multiple files at once
|
||||
lnk add ~/.bashrc ~/.vimrc ~/.gitconfig ~/.tmux.conf
|
||||
|
||||
# Add configuration directories individually
|
||||
lnk add --recursive ~/.config/nvim ~/.config/zsh
|
||||
|
||||
# Preview before adding sensitive files
|
||||
lnk add --dry-run ~/.ssh/id_rsa.pub
|
||||
lnk add ~/.ssh/id_rsa.pub # Add after verification
|
||||
|
||||
# Add host-specific config (supports bulk operations)
|
||||
lnk add --host $(hostname) ~/.ssh/config ~/.aws/credentials
|
||||
|
||||
lnk push "initial setup"
|
||||
```
|
||||
|
||||
### On a new machine
|
||||
|
||||
```bash
|
||||
# Bootstrap runs automatically
|
||||
lnk init -r git@github.com:you/dotfiles.git
|
||||
lnk pull # auto-creates symlinks
|
||||
# → Sets up environment, installs dependencies
|
||||
|
||||
# Pull common config
|
||||
lnk pull
|
||||
|
||||
# Pull host-specific config (if it exists)
|
||||
lnk pull --host $(hostname)
|
||||
|
||||
# Or run bootstrap manually if needed
|
||||
lnk bootstrap
|
||||
```
|
||||
|
||||
### Daily edits
|
||||
|
||||
```bash
|
||||
vim ~/.vimrc # edit normally
|
||||
lnk list # see common config
|
||||
lnk list --host $(hostname) # see host-specific config
|
||||
lnk list --all # see everything
|
||||
lnk status # check what changed
|
||||
lnk push "new plugins" # commit & push
|
||||
```
|
||||
|
||||
### Multi-machine workflow
|
||||
|
||||
```bash
|
||||
# On your laptop - use bulk operations for efficiency
|
||||
lnk add --host laptop ~/.ssh/config ~/.aws/credentials ~/.npmrc
|
||||
lnk add ~/.vimrc ~/.bashrc ~/.gitconfig # Common config (multiple files)
|
||||
lnk push "laptop configuration"
|
||||
|
||||
# On your work machine
|
||||
lnk pull # Get common config
|
||||
lnk add --host work ~/.gitconfig ~/.ssh/config
|
||||
lnk add --recursive ~/.config/work-tools # Work-specific tools
|
||||
lnk push "work configuration"
|
||||
|
||||
# Back on laptop
|
||||
lnk pull # Get updates (work config won't affect laptop)
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
- `lnk init [-r remote]` - Create repo
|
||||
- `lnk add <files>` - Move files to repo, create symlinks
|
||||
- `lnk rm <files>` - Move files back, remove symlinks
|
||||
- `lnk init [-r remote] [--no-bootstrap] [--force]` - Create repo (runs bootstrap automatically)
|
||||
- `lnk add [--host HOST] [--recursive] [--dry-run] <files>...` - Move files to repo, create symlinks
|
||||
- `lnk rm [--host HOST] <files>` - Move files back, remove symlinks
|
||||
- `lnk list [--host HOST] [--all]` - List files managed by lnk
|
||||
- `lnk status` - Git status + sync info
|
||||
- `lnk push [msg]` - Stage all, commit, push
|
||||
- `lnk pull` - Pull + restore missing symlinks
|
||||
- `lnk pull [--host HOST]` - Pull + restore missing symlinks
|
||||
- `lnk bootstrap` - Run bootstrap script manually
|
||||
|
||||
### Command Options
|
||||
|
||||
- `--host HOST` - Manage files for specific host (default: common configuration)
|
||||
- `--recursive, -r` - Add directory contents individually instead of the directory as a whole
|
||||
- `--dry-run, -n` - Show what would be added without making changes
|
||||
- `--all` - Show all configurations (common + all hosts) when listing
|
||||
- `-r, --remote URL` - Clone from remote URL when initializing
|
||||
- `--no-bootstrap` - Skip automatic execution of bootstrap script after cloning
|
||||
- `--force` - Force initialization even if directory contains managed files (WARNING: overwrites existing content)
|
||||
|
||||
### Add Command Examples
|
||||
|
||||
```bash
|
||||
# Multiple files at once
|
||||
lnk add ~/.bashrc ~/.vimrc ~/.gitconfig
|
||||
|
||||
# Recursive directory processing
|
||||
lnk add --recursive ~/.config/nvim
|
||||
|
||||
# Preview changes first
|
||||
lnk add --dry-run ~/.ssh/config
|
||||
lnk add --dry-run --recursive ~/.config/kitty
|
||||
|
||||
# Host-specific bulk operations
|
||||
lnk add --host work ~/.gitconfig ~/.ssh/config ~/.npmrc
|
||||
```
|
||||
|
||||
## Technical bits
|
||||
|
||||
- **Single binary** (~8MB, no deps)
|
||||
- **Atomic operations** (rollback on failure)
|
||||
- **Relative symlinks** (portable)
|
||||
- **XDG compliant** (`~/.config/lnk`)
|
||||
- **20 integration tests**
|
||||
- **Multihost support** (common + host-specific configs)
|
||||
- **Bootstrap support** (automatic environment setup)
|
||||
- **Bulk operations** (multiple files, atomic transactions)
|
||||
- **Recursive processing** (directory contents individually)
|
||||
- **Preview mode** (dry-run for safety)
|
||||
- **Data loss prevention** (safety checks with contextual warnings)
|
||||
- **Git-native** (standard Git repo, no special formats)
|
||||
|
||||
## Alternatives
|
||||
|
||||
| Tool | Complexity | Why choose it |
|
||||
| ------- | ---------- | ------------------------------------- |
|
||||
| **lnk** | Minimal | Just works, no config, Git-native |
|
||||
| ------- | ---------- | ----------------------------------------------------------------------------------------- |
|
||||
| **lnk** | Minimal | Just works, no config, Git-native, multihost, bootstrap, bulk ops, dry-run, safety checks |
|
||||
| chezmoi | High | Templates, encryption, cross-platform |
|
||||
| yadm | Medium | Git power user, encryption |
|
||||
| dotbot | Low | YAML config, basic features |
|
||||
| stow | Low | Perl, symlink only |
|
||||
|
||||
## FAQ
|
||||
|
||||
**Q: What if I already have dotfiles in Git?**
|
||||
A: `git clone your-repo ~/.config/lnk && lnk add ~/.vimrc` (adopts existing files)
|
||||
|
||||
**Q: How do I handle machine-specific configs?**
|
||||
A: Git branches, or just don't manage machine-specific files with lnk
|
||||
|
||||
**Q: Windows support?**
|
||||
A: Symlinks work on Windows 10+, but untested
|
||||
|
||||
**Q: Production ready?**
|
||||
A: I use it daily. It won't break your files. API might change (pre-1.0).
|
||||
|
||||
## Contributing
|
||||
|
||||
```bash
|
||||
|
190
RELEASE.md
190
RELEASE.md
@@ -1,190 +0,0 @@
|
||||
# Release Process
|
||||
|
||||
This document describes how to create releases for the lnk project using GoReleaser.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Push access to the main repository
|
||||
- Git tags pushed to GitHub trigger releases automatically
|
||||
- GoReleaser is configured in `.goreleaser.yml`
|
||||
- GitHub Actions will handle the release process
|
||||
- Access to the [homebrew-lnk](https://github.com/yarlson/homebrew-lnk) tap repository
|
||||
- **Personal Access Token** set up as `HOMEBREW_TAP_TOKEN` secret (see Setup section)
|
||||
|
||||
## Setup (One-time)
|
||||
|
||||
### GitHub Personal Access Token
|
||||
|
||||
For GoReleaser to update the Homebrew formula, you need a Personal Access Token:
|
||||
|
||||
1. Go to GitHub Settings → Developer settings → Personal access tokens → Tokens (classic)
|
||||
2. Click "Generate new token" → "Generate new token (classic)"
|
||||
3. Name: "GoReleaser Homebrew Access"
|
||||
4. Scopes: Select `repo` (Full control of private repositories)
|
||||
5. Generate and copy the token
|
||||
6. In your `yarlson/lnk` repository:
|
||||
- Go to Settings → Secrets and variables → Actions
|
||||
- Add new repository secret: `HOMEBREW_TAP_TOKEN`
|
||||
- Paste the token as the value
|
||||
|
||||
This allows GoReleaser to automatically update the Homebrew formula in [homebrew-lnk](https://github.com/yarlson/homebrew-lnk).
|
||||
|
||||
## Creating a Release
|
||||
|
||||
### 1. Ensure everything is ready
|
||||
|
||||
```bash
|
||||
# Run all quality checks
|
||||
make check
|
||||
|
||||
# Test GoReleaser configuration
|
||||
make goreleaser-check
|
||||
|
||||
# Test build process
|
||||
make goreleaser-snapshot
|
||||
```
|
||||
|
||||
### 2. Create and push a version tag
|
||||
|
||||
```bash
|
||||
# Create a new tag (replace x.y.z with actual version)
|
||||
git tag -a v1.0.0 -m "Release v1.0.0"
|
||||
|
||||
# Push the tag to trigger the release
|
||||
git push origin v1.0.0
|
||||
```
|
||||
|
||||
### 3. Monitor the release
|
||||
|
||||
- GitHub Actions will automatically build and release when the tag is pushed
|
||||
- Check the [Actions tab](https://github.com/yarlson/lnk/actions) for build status
|
||||
- The release will appear in [GitHub Releases](https://github.com/yarlson/lnk/releases)
|
||||
- The Homebrew formula will be automatically updated in [homebrew-lnk](https://github.com/yarlson/homebrew-lnk)
|
||||
|
||||
## What GoReleaser Does
|
||||
|
||||
1. **Builds binaries** for multiple platforms:
|
||||
|
||||
- Linux (amd64, arm64)
|
||||
- macOS (amd64, arm64)
|
||||
- Windows (amd64)
|
||||
|
||||
2. **Creates archives** with consistent naming:
|
||||
|
||||
- `lnk_Linux_x86_64.tar.gz`
|
||||
- `lnk_Darwin_arm64.tar.gz`
|
||||
- etc.
|
||||
|
||||
3. **Generates checksums** for verification
|
||||
|
||||
4. **Creates GitHub release** with:
|
||||
|
||||
- Automatic changelog from conventional commits
|
||||
- Installation instructions
|
||||
- Download links for all platforms
|
||||
|
||||
5. **Updates Homebrew formula** automatically in the [homebrew-lnk](https://github.com/yarlson/homebrew-lnk) tap
|
||||
|
||||
## Manual Release (if needed)
|
||||
|
||||
If you need to create a release manually:
|
||||
|
||||
```bash
|
||||
# Export GitHub token
|
||||
export GITHUB_TOKEN="your_token_here"
|
||||
|
||||
# Create release (requires a git tag)
|
||||
goreleaser release --clean
|
||||
```
|
||||
|
||||
## Testing Releases Locally
|
||||
|
||||
```bash
|
||||
# Test the build process without releasing
|
||||
make goreleaser-snapshot
|
||||
|
||||
# Built artifacts will be in dist/
|
||||
ls -la dist/
|
||||
|
||||
# Test a binary
|
||||
./dist/lnk_<platform>/lnk --version
|
||||
```
|
||||
|
||||
## Installation Methods
|
||||
|
||||
After a release is published, users can install lnk using multiple methods:
|
||||
|
||||
### 1. Shell Script (Recommended)
|
||||
|
||||
```bash
|
||||
curl -sSL https://raw.githubusercontent.com/yarlson/lnk/main/install.sh | bash
|
||||
```
|
||||
|
||||
### 2. Homebrew (macOS/Linux)
|
||||
|
||||
```bash
|
||||
brew tap yarlson/lnk
|
||||
brew install lnk
|
||||
```
|
||||
|
||||
### 3. Manual Download
|
||||
|
||||
```bash
|
||||
# Download from GitHub releases
|
||||
wget https://github.com/yarlson/lnk/releases/latest/download/lnk_Linux_x86_64.tar.gz
|
||||
tar -xzf lnk_Linux_x86_64.tar.gz
|
||||
sudo mv lnk /usr/local/bin/
|
||||
```
|
||||
|
||||
## Version Numbering
|
||||
|
||||
We use [Semantic Versioning](https://semver.org/):
|
||||
|
||||
- `v1.0.0` - Major release (breaking changes)
|
||||
- `v1.1.0` - Minor release (new features, backward compatible)
|
||||
- `v1.1.1` - Patch release (bug fixes)
|
||||
|
||||
## Changelog
|
||||
|
||||
GoReleaser automatically generates changelogs from git commits using conventional commit format:
|
||||
|
||||
- `feat:` - New features
|
||||
- `fix:` - Bug fixes
|
||||
- `docs:` - Documentation changes (excluded from changelog)
|
||||
- `test:` - Test changes (excluded from changelog)
|
||||
- `ci:` - CI changes (excluded from changelog)
|
||||
|
||||
## Homebrew Tap
|
||||
|
||||
The Homebrew formula is automatically maintained in the [homebrew-lnk](https://github.com/yarlson/homebrew-lnk) repository. When a new release is created:
|
||||
|
||||
1. GoReleaser automatically creates/updates the formula
|
||||
2. The formula is committed to the tap repository
|
||||
3. Users can immediately install the new version via `brew install yarlson/lnk/lnk`
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Release failed to create
|
||||
|
||||
1. Check that the tag follows the format `vX.Y.Z`
|
||||
2. Ensure GitHub Actions has proper permissions
|
||||
3. Check the Actions log for detailed error messages
|
||||
|
||||
### Missing binaries in release
|
||||
|
||||
1. Verify GoReleaser configuration: `make goreleaser-check`
|
||||
2. Test build locally: `make goreleaser-snapshot`
|
||||
3. Check the build matrix in `.goreleaser.yml`
|
||||
|
||||
### Changelog is empty
|
||||
|
||||
1. Ensure commits follow conventional commit format
|
||||
2. Check that there are commits since the last tag
|
||||
3. Verify changelog configuration in `.goreleaser.yml`
|
||||
|
||||
### Homebrew formula not updated
|
||||
|
||||
1. Check that the GITHUB_TOKEN has access to the homebrew-lnk repository
|
||||
2. Verify the repository name and owner in `.goreleaser.yml`
|
||||
3. Check the release workflow logs for Homebrew-related errors
|
||||
4. Ensure the homebrew-lnk repository exists and is accessible
|
157
cmd/add.go
157
cmd/add.go
@@ -1,7 +1,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -9,25 +8,157 @@ import (
|
||||
)
|
||||
|
||||
func newAddCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "add <file>",
|
||||
Short: "✨ Add a file to lnk management",
|
||||
Long: "Moves a file to the lnk repository and creates a symlink in its place.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
SilenceUsage: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
filePath := args[0]
|
||||
cmd := &cobra.Command{
|
||||
Use: "add <file>...",
|
||||
Short: "✨ Add files to lnk management",
|
||||
Long: `Moves files to the lnk repository and creates symlinks in their place. Supports multiple files.
|
||||
|
||||
lnk := core.NewLnk()
|
||||
if err := lnk.Add(filePath); err != nil {
|
||||
return fmt.Errorf("failed to add file: %w", err)
|
||||
Examples:
|
||||
lnk add ~/.bashrc ~/.vimrc # Add multiple files at once
|
||||
lnk add --recursive ~/.config/nvim # Add directory contents individually
|
||||
lnk add --dry-run ~/.gitconfig # Preview what would be added
|
||||
lnk add --host work ~/.ssh/config # Add host-specific configuration
|
||||
|
||||
The --recursive flag processes directory contents individually instead of treating
|
||||
the directory as a single unit. This is useful for configuration directories where
|
||||
you want each file managed separately.
|
||||
|
||||
The --dry-run flag shows you exactly what files would be added without making any
|
||||
changes to your system - perfect for verification before bulk operations.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
host, _ := cmd.Flags().GetString("host")
|
||||
recursive, _ := cmd.Flags().GetBool("recursive")
|
||||
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
||||
lnk := core.NewLnk(core.WithHost(host))
|
||||
|
||||
// Handle dry-run mode
|
||||
if dryRun {
|
||||
files, err := lnk.PreviewAdd(args, recursive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Display preview output
|
||||
if recursive {
|
||||
printf(cmd, "🔍 \033[1mWould add %d files recursively:\033[0m\n", len(files))
|
||||
} else {
|
||||
printf(cmd, "🔍 \033[1mWould add %d files:\033[0m\n", len(files))
|
||||
}
|
||||
|
||||
// List files that would be added
|
||||
for _, file := range files {
|
||||
basename := filepath.Base(file)
|
||||
printf(cmd, " 📄 \033[90m%s\033[0m\n", basename)
|
||||
}
|
||||
|
||||
printf(cmd, "\n💡 \033[33mTo proceed:\033[0m run without --dry-run flag\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Handle recursive mode
|
||||
if recursive {
|
||||
// Get preview to count files first for better output
|
||||
previewFiles, err := lnk.PreviewAdd(args, recursive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create progress callback for CLI display
|
||||
progressCallback := func(current, total int, currentFile string) {
|
||||
printf(cmd, "\r⏳ Processing %d/%d: %s", current, total, currentFile)
|
||||
}
|
||||
|
||||
if err := lnk.AddRecursiveWithProgress(args, progressCallback); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Clear progress line and show completion
|
||||
printf(cmd, "\r")
|
||||
|
||||
// Store processed file count for display
|
||||
args = previewFiles // Replace args with actual files for display
|
||||
} else {
|
||||
// Use appropriate method based on number of files
|
||||
if len(args) == 1 {
|
||||
// Single file - use existing Add method for backward compatibility
|
||||
if err := lnk.Add(args[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Multiple files - use AddMultiple for atomic operation
|
||||
if err := lnk.AddMultiple(args); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Display results
|
||||
if recursive {
|
||||
// Recursive mode - show enhanced message with count
|
||||
if host != "" {
|
||||
printf(cmd, "✨ \033[1mAdded %d files recursively to lnk (host: %s)\033[0m\n", len(args), host)
|
||||
} else {
|
||||
printf(cmd, "✨ \033[1mAdded %d files recursively to lnk\033[0m\n", len(args))
|
||||
}
|
||||
|
||||
// Show some of the files that were added (limit to first few for readability)
|
||||
filesToShow := len(args)
|
||||
if filesToShow > 5 {
|
||||
filesToShow = 5
|
||||
}
|
||||
|
||||
for i := 0; i < filesToShow; i++ {
|
||||
basename := filepath.Base(args[i])
|
||||
if host != "" {
|
||||
printf(cmd, " 🔗 \033[90m%s\033[0m → \033[36m~/.config/lnk/%s.lnk/...\033[0m\n", basename, host)
|
||||
} else {
|
||||
printf(cmd, " 🔗 \033[90m%s\033[0m → \033[36m~/.config/lnk/...\033[0m\n", basename)
|
||||
}
|
||||
}
|
||||
|
||||
if len(args) > 5 {
|
||||
printf(cmd, " \033[90m... and %d more files\033[0m\n", len(args)-5)
|
||||
}
|
||||
} else if len(args) == 1 {
|
||||
// Single file - maintain existing output format for backward compatibility
|
||||
filePath := args[0]
|
||||
basename := filepath.Base(filePath)
|
||||
if host != "" {
|
||||
printf(cmd, "✨ \033[1mAdded %s to lnk (host: %s)\033[0m\n", basename, host)
|
||||
printf(cmd, " 🔗 \033[90m%s\033[0m → \033[36m~/.config/lnk/%s.lnk/%s\033[0m\n", filePath, host, filePath)
|
||||
} else {
|
||||
printf(cmd, "✨ \033[1mAdded %s to lnk\033[0m\n", basename)
|
||||
printf(cmd, " 🔗 \033[90m%s\033[0m → \033[36m~/.config/lnk/%s\033[0m\n", filePath, basename)
|
||||
printf(cmd, " 🔗 \033[90m%s\033[0m → \033[36m~/.config/lnk/%s\033[0m\n", filePath, filePath)
|
||||
}
|
||||
} else {
|
||||
// Multiple files - show summary
|
||||
if host != "" {
|
||||
printf(cmd, "✨ \033[1mAdded %d items to lnk (host: %s)\033[0m\n", len(args), host)
|
||||
} else {
|
||||
printf(cmd, "✨ \033[1mAdded %d items to lnk\033[0m\n", len(args))
|
||||
}
|
||||
|
||||
// List each added file
|
||||
for _, filePath := range args {
|
||||
basename := filepath.Base(filePath)
|
||||
if host != "" {
|
||||
printf(cmd, " 🔗 \033[90m%s\033[0m → \033[36m~/.config/lnk/%s.lnk/...\033[0m\n", basename, host)
|
||||
} else {
|
||||
printf(cmd, " 🔗 \033[90m%s\033[0m → \033[36m~/.config/lnk/...\033[0m\n", basename)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printf(cmd, " 📝 Use \033[1mlnk push\033[0m to sync to remote\n")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringP("host", "H", "", "Manage file for specific host (default: common configuration)")
|
||||
cmd.Flags().BoolP("recursive", "r", false, "Add directory contents individually instead of the directory as a whole")
|
||||
cmd.Flags().BoolP("dry-run", "n", false, "Show what would be added without making changes")
|
||||
return cmd
|
||||
}
|
||||
|
45
cmd/bootstrap.go
Normal file
45
cmd/bootstrap.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/yarlson/lnk/internal/core"
|
||||
)
|
||||
|
||||
func newBootstrapCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "bootstrap",
|
||||
Short: "🚀 Run the bootstrap script to set up your environment",
|
||||
Long: "Executes the bootstrap script from your dotfiles repository to install dependencies and configure your system.",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
lnk := core.NewLnk()
|
||||
|
||||
scriptPath, err := lnk.FindBootstrapScript()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if scriptPath == "" {
|
||||
printf(cmd, "💡 \033[33mNo bootstrap script found\033[0m\n")
|
||||
printf(cmd, " 📝 Create a \033[1mbootstrap.sh\033[0m file in your dotfiles repository:\n")
|
||||
printf(cmd, " \033[90m#!/bin/bash\033[0m\n")
|
||||
printf(cmd, " \033[90mecho \"Setting up environment...\"\033[0m\n")
|
||||
printf(cmd, " \033[90m# Your setup commands here\033[0m\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
printf(cmd, "🚀 \033[1mRunning bootstrap script\033[0m\n")
|
||||
printf(cmd, " 📄 Script: \033[36m%s\033[0m\n", scriptPath)
|
||||
printf(cmd, "\n")
|
||||
|
||||
if err := lnk.RunBootstrapScript(scriptPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
printf(cmd, "\n✅ \033[1;32mBootstrap completed successfully!\033[0m\n")
|
||||
printf(cmd, " 🎉 Your environment is ready to use\n")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
45
cmd/init.go
45
cmd/init.go
@@ -1,8 +1,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/yarlson/lnk/internal/core"
|
||||
)
|
||||
@@ -13,18 +11,55 @@ func newInitCmd() *cobra.Command {
|
||||
Short: "🎯 Initialize a new lnk repository",
|
||||
Long: "Creates the lnk directory and initializes a Git repository for managing dotfiles.",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
remote, _ := cmd.Flags().GetString("remote")
|
||||
noBootstrap, _ := cmd.Flags().GetBool("no-bootstrap")
|
||||
force, _ := cmd.Flags().GetBool("force")
|
||||
|
||||
lnk := core.NewLnk()
|
||||
if err := lnk.InitWithRemote(remote); err != nil {
|
||||
return fmt.Errorf("failed to initialize lnk: %w", err)
|
||||
|
||||
// Show warning when force is used and there are managed files to overwrite
|
||||
if force && remote != "" && lnk.HasUserContent() {
|
||||
printf(cmd, "⚠️ \033[33mUsing --force flag: This will overwrite existing managed files\033[0m\n")
|
||||
printf(cmd, " 💡 Only use this if you understand the risks\n\n")
|
||||
}
|
||||
|
||||
if err := lnk.InitWithRemoteForce(remote, force); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if remote != "" {
|
||||
printf(cmd, "🎯 \033[1mInitialized lnk repository\033[0m\n")
|
||||
printf(cmd, " 📦 Cloned from: \033[36m%s\033[0m\n", remote)
|
||||
printf(cmd, " 📁 Location: \033[90m~/.config/lnk\033[0m\n")
|
||||
|
||||
// Try to run bootstrap script if not disabled
|
||||
if !noBootstrap {
|
||||
printf(cmd, "\n🔍 \033[1mLooking for bootstrap script...\033[0m\n")
|
||||
|
||||
scriptPath, err := lnk.FindBootstrapScript()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if scriptPath != "" {
|
||||
printf(cmd, " ✅ Found bootstrap script: \033[36m%s\033[0m\n", scriptPath)
|
||||
printf(cmd, "\n🚀 \033[1mRunning bootstrap script...\033[0m\n")
|
||||
printf(cmd, "\n")
|
||||
|
||||
if err := lnk.RunBootstrapScript(scriptPath); err != nil {
|
||||
printf(cmd, "\n⚠️ \033[33mBootstrap script failed, but repository was initialized successfully\033[0m\n")
|
||||
printf(cmd, " 💡 You can run it manually with: \033[1mlnk bootstrap\033[0m\n")
|
||||
printf(cmd, " 🔧 Error: %v\n", err)
|
||||
} else {
|
||||
printf(cmd, "\n✅ \033[1;32mBootstrap completed successfully!\033[0m\n")
|
||||
}
|
||||
} else {
|
||||
printf(cmd, " 💡 No bootstrap script found\n")
|
||||
}
|
||||
}
|
||||
|
||||
printf(cmd, "\n💡 \033[33mNext steps:\033[0m\n")
|
||||
printf(cmd, " • Run \033[1mlnk pull\033[0m to restore symlinks\n")
|
||||
printf(cmd, " • Use \033[1mlnk add <file>\033[0m to manage new files\n")
|
||||
@@ -41,5 +76,7 @@ func newInitCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
cmd.Flags().StringP("remote", "r", "", "Clone from remote URL instead of creating empty repository")
|
||||
cmd.Flags().Bool("no-bootstrap", false, "Skip automatic execution of bootstrap script after cloning")
|
||||
cmd.Flags().Bool("force", false, "Force initialization even if directory contains managed files (WARNING: This will overwrite existing content)")
|
||||
return cmd
|
||||
}
|
||||
|
193
cmd/list.go
Normal file
193
cmd/list.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/yarlson/lnk/internal/core"
|
||||
)
|
||||
|
||||
func newListCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "📋 List files managed by lnk",
|
||||
Long: "Display all files and directories currently managed by lnk.",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
host, _ := cmd.Flags().GetString("host")
|
||||
all, _ := cmd.Flags().GetBool("all")
|
||||
|
||||
if host != "" {
|
||||
// Show specific host configuration
|
||||
return listHostConfig(cmd, host)
|
||||
}
|
||||
|
||||
if all {
|
||||
// Show all configurations (common + all hosts)
|
||||
return listAllConfigs(cmd)
|
||||
}
|
||||
|
||||
// Default: show common configuration
|
||||
return listCommonConfig(cmd)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringP("host", "H", "", "List files for specific host")
|
||||
cmd.Flags().BoolP("all", "a", false, "List files for all hosts and common configuration")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func listCommonConfig(cmd *cobra.Command) error {
|
||||
lnk := core.NewLnk()
|
||||
managedItems, err := lnk.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(managedItems) == 0 {
|
||||
printf(cmd, "📋 \033[1mNo files currently managed by lnk (common)\033[0m\n")
|
||||
printf(cmd, " 💡 Use \033[1mlnk add <file>\033[0m to start managing files\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
printf(cmd, "📋 \033[1mFiles managed by lnk (common)\033[0m (\033[36m%d item", len(managedItems))
|
||||
if len(managedItems) > 1 {
|
||||
printf(cmd, "s")
|
||||
}
|
||||
printf(cmd, "\033[0m):\n\n")
|
||||
|
||||
for _, item := range managedItems {
|
||||
printf(cmd, " 🔗 \033[36m%s\033[0m\n", item)
|
||||
}
|
||||
|
||||
printf(cmd, "\n💡 Use \033[1mlnk status\033[0m to check sync status\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
func listHostConfig(cmd *cobra.Command, host string) error {
|
||||
lnk := core.NewLnk(core.WithHost(host))
|
||||
managedItems, err := lnk.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(managedItems) == 0 {
|
||||
printf(cmd, "📋 \033[1mNo files currently managed by lnk (host: %s)\033[0m\n", host)
|
||||
printf(cmd, " 💡 Use \033[1mlnk add --host %s <file>\033[0m to start managing files\n", host)
|
||||
return nil
|
||||
}
|
||||
|
||||
printf(cmd, "📋 \033[1mFiles managed by lnk (host: %s)\033[0m (\033[36m%d item", host, len(managedItems))
|
||||
if len(managedItems) > 1 {
|
||||
printf(cmd, "s")
|
||||
}
|
||||
printf(cmd, "\033[0m):\n\n")
|
||||
|
||||
for _, item := range managedItems {
|
||||
printf(cmd, " 🔗 \033[36m%s\033[0m\n", item)
|
||||
}
|
||||
|
||||
printf(cmd, "\n💡 Use \033[1mlnk status\033[0m to check sync status\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
func listAllConfigs(cmd *cobra.Command) error {
|
||||
// List common configuration
|
||||
printf(cmd, "📋 \033[1mAll configurations managed by lnk\033[0m\n\n")
|
||||
|
||||
lnk := core.NewLnk()
|
||||
commonItems, err := lnk.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
printf(cmd, "🌐 \033[1mCommon configuration\033[0m (\033[36m%d item", len(commonItems))
|
||||
if len(commonItems) > 1 {
|
||||
printf(cmd, "s")
|
||||
}
|
||||
printf(cmd, "\033[0m):\n")
|
||||
|
||||
if len(commonItems) == 0 {
|
||||
printf(cmd, " \033[90m(no files)\033[0m\n")
|
||||
} else {
|
||||
for _, item := range commonItems {
|
||||
printf(cmd, " 🔗 \033[36m%s\033[0m\n", item)
|
||||
}
|
||||
}
|
||||
|
||||
// Find all host-specific configurations
|
||||
hosts, err := findHostConfigs()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, host := range hosts {
|
||||
printf(cmd, "\n🖥️ \033[1mHost: %s\033[0m", host)
|
||||
|
||||
hostLnk := core.NewLnk(core.WithHost(host))
|
||||
hostItems, err := hostLnk.List()
|
||||
if err != nil {
|
||||
printf(cmd, " \033[31m(error: %v)\033[0m\n", err)
|
||||
continue
|
||||
}
|
||||
|
||||
printf(cmd, " (\033[36m%d item", len(hostItems))
|
||||
if len(hostItems) > 1 {
|
||||
printf(cmd, "s")
|
||||
}
|
||||
printf(cmd, "\033[0m):\n")
|
||||
|
||||
if len(hostItems) == 0 {
|
||||
printf(cmd, " \033[90m(no files)\033[0m\n")
|
||||
} else {
|
||||
for _, item := range hostItems {
|
||||
printf(cmd, " 🔗 \033[36m%s\033[0m\n", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printf(cmd, "\n💡 Use \033[1mlnk list --host <hostname>\033[0m to see specific host configuration\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
func findHostConfigs() ([]string, error) {
|
||||
repoPath := getRepoPath()
|
||||
|
||||
// Check if repo exists
|
||||
if _, err := os.Stat(repoPath); os.IsNotExist(err) {
|
||||
return []string{}, nil
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(repoPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var hosts []string
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
// Look for .lnk.<hostname> files
|
||||
if strings.HasPrefix(name, ".lnk.") && name != ".lnk" {
|
||||
host := strings.TrimPrefix(name, ".lnk.")
|
||||
hosts = append(hosts, host)
|
||||
}
|
||||
}
|
||||
|
||||
return hosts, nil
|
||||
}
|
||||
|
||||
func getRepoPath() string {
|
||||
xdgConfig := os.Getenv("XDG_CONFIG_HOME")
|
||||
if xdgConfig == "" {
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
xdgConfig = "."
|
||||
} else {
|
||||
xdgConfig = filepath.Join(homeDir, ".config")
|
||||
}
|
||||
}
|
||||
return filepath.Join(xdgConfig, "lnk")
|
||||
}
|
23
cmd/pull.go
23
cmd/pull.go
@@ -1,27 +1,33 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/yarlson/lnk/internal/core"
|
||||
)
|
||||
|
||||
func newPullCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
cmd := &cobra.Command{
|
||||
Use: "pull",
|
||||
Short: "⬇️ Pull changes from remote and restore symlinks",
|
||||
Long: "Fetches changes from remote repository and automatically restores symlinks for all managed files.",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
lnk := core.NewLnk()
|
||||
host, _ := cmd.Flags().GetString("host")
|
||||
|
||||
lnk := core.NewLnk(core.WithHost(host))
|
||||
|
||||
restored, err := lnk.Pull()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to pull changes: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if len(restored) > 0 {
|
||||
if host != "" {
|
||||
printf(cmd, "⬇️ \033[1;32mSuccessfully pulled changes (host: %s)\033[0m\n", host)
|
||||
} else {
|
||||
printf(cmd, "⬇️ \033[1;32mSuccessfully pulled changes\033[0m\n")
|
||||
}
|
||||
printf(cmd, " 🔗 Restored \033[1m%d symlink", len(restored))
|
||||
if len(restored) > 1 {
|
||||
printf(cmd, "s")
|
||||
@@ -31,8 +37,12 @@ func newPullCmd() *cobra.Command {
|
||||
printf(cmd, " ✨ \033[36m%s\033[0m\n", file)
|
||||
}
|
||||
printf(cmd, "\n 🎉 Your dotfiles are synced and ready!\n")
|
||||
} else {
|
||||
if host != "" {
|
||||
printf(cmd, "⬇️ \033[1;32mSuccessfully pulled changes (host: %s)\033[0m\n", host)
|
||||
} else {
|
||||
printf(cmd, "⬇️ \033[1;32mSuccessfully pulled changes\033[0m\n")
|
||||
}
|
||||
printf(cmd, " ✅ All symlinks already in place\n")
|
||||
printf(cmd, " 🎉 Everything is up to date!\n")
|
||||
}
|
||||
@@ -40,4 +50,7 @@ func newPullCmd() *cobra.Command {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringP("host", "H", "", "Pull and restore symlinks for specific host (default: common configuration)")
|
||||
return cmd
|
||||
}
|
||||
|
@@ -1,8 +1,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/yarlson/lnk/internal/core"
|
||||
)
|
||||
@@ -14,6 +12,7 @@ func newPushCmd() *cobra.Command {
|
||||
Long: "Stages all changes, creates a sync commit with the provided message, and pushes to remote.",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
message := "lnk: sync configuration files"
|
||||
if len(args) > 0 {
|
||||
@@ -22,7 +21,7 @@ func newPushCmd() *cobra.Command {
|
||||
|
||||
lnk := core.NewLnk()
|
||||
if err := lnk.Push(message); err != nil {
|
||||
return fmt.Errorf("failed to push changes: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
printf(cmd, "🚀 \033[1;32mSuccessfully pushed changes\033[0m\n")
|
||||
|
18
cmd/rm.go
18
cmd/rm.go
@@ -1,7 +1,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -9,25 +8,36 @@ import (
|
||||
)
|
||||
|
||||
func newRemoveCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
cmd := &cobra.Command{
|
||||
Use: "rm <file>",
|
||||
Short: "🗑️ Remove a file from lnk management",
|
||||
Long: "Removes a symlink and restores the original file from the lnk repository.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
filePath := args[0]
|
||||
host, _ := cmd.Flags().GetString("host")
|
||||
|
||||
lnk := core.NewLnk(core.WithHost(host))
|
||||
|
||||
lnk := core.NewLnk()
|
||||
if err := lnk.Remove(filePath); err != nil {
|
||||
return fmt.Errorf("failed to remove file: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
basename := filepath.Base(filePath)
|
||||
if host != "" {
|
||||
printf(cmd, "🗑️ \033[1mRemoved %s from lnk (host: %s)\033[0m\n", basename, host)
|
||||
printf(cmd, " ↩️ \033[90m~/.config/lnk/%s.lnk/%s\033[0m → \033[36m%s\033[0m\n", host, basename, filePath)
|
||||
} else {
|
||||
printf(cmd, "🗑️ \033[1mRemoved %s from lnk\033[0m\n", basename)
|
||||
printf(cmd, " ↩️ \033[90m~/.config/lnk/%s\033[0m → \033[36m%s\033[0m\n", basename, filePath)
|
||||
}
|
||||
printf(cmd, " 📄 Original file restored\n")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringP("host", "H", "", "Remove file from specific host configuration (default: common configuration)")
|
||||
return cmd
|
||||
}
|
||||
|
24
cmd/root.go
24
cmd/root.go
@@ -20,17 +20,27 @@ func NewRootCommand() *cobra.Command {
|
||||
Long: `🔗 Lnk - Git-native dotfiles management that doesn't suck.
|
||||
|
||||
Move your dotfiles to ~/.config/lnk, symlink them back, and use Git like normal.
|
||||
That's it.
|
||||
Supports both common configurations, host-specific setups, and bulk operations for multiple files.
|
||||
|
||||
✨ Examples:
|
||||
lnk init # Fresh start
|
||||
lnk init -r <repo-url> # Clone existing dotfiles
|
||||
lnk add ~/.vimrc ~/.bashrc # Start managing files
|
||||
lnk init -r <repo-url> # Clone existing dotfiles (runs bootstrap automatically)
|
||||
lnk add ~/.vimrc ~/.bashrc # Start managing common files
|
||||
lnk add --recursive ~/.config/nvim # Add directory contents individually
|
||||
lnk add --dry-run ~/.gitconfig # Preview changes without applying
|
||||
lnk add --host work ~/.ssh/config # Manage host-specific files
|
||||
lnk list --all # Show all configurations
|
||||
lnk pull --host work # Pull host-specific changes
|
||||
lnk push "setup complete" # Sync to remote
|
||||
lnk pull # Get latest changes
|
||||
lnk bootstrap # Run bootstrap script manually
|
||||
|
||||
🎯 Simple, fast, and Git-native.`,
|
||||
🚀 Bootstrap Support:
|
||||
Automatically runs bootstrap.sh when cloning a repository.
|
||||
Use --no-bootstrap to disable.
|
||||
|
||||
🎯 Simple, fast, Git-native, and multi-host ready.`,
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
Version: fmt.Sprintf("%s (built %s)", version, buildTime),
|
||||
}
|
||||
|
||||
@@ -38,9 +48,11 @@ That's it.
|
||||
rootCmd.AddCommand(newInitCmd())
|
||||
rootCmd.AddCommand(newAddCmd())
|
||||
rootCmd.AddCommand(newRemoveCmd())
|
||||
rootCmd.AddCommand(newListCmd())
|
||||
rootCmd.AddCommand(newStatusCmd())
|
||||
rootCmd.AddCommand(newPushCmd())
|
||||
rootCmd.AddCommand(newPullCmd())
|
||||
rootCmd.AddCommand(newBootstrapCmd())
|
||||
|
||||
return rootCmd
|
||||
}
|
||||
@@ -54,7 +66,7 @@ func SetVersion(v, bt string) {
|
||||
func Execute() {
|
||||
rootCmd := NewRootCommand()
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
_, _ = fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
1469
cmd/root_test.go
1469
cmd/root_test.go
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/yarlson/lnk/internal/core"
|
||||
)
|
||||
@@ -11,46 +9,84 @@ func newStatusCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "status",
|
||||
Short: "📊 Show repository sync status",
|
||||
Long: "Display how many commits ahead/behind the local repository is relative to the remote.",
|
||||
Long: "Display how many commits ahead/behind the local repository is relative to the remote and check for uncommitted changes.",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
lnk := core.NewLnk()
|
||||
status, err := lnk.Status()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get status: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if status.Dirty {
|
||||
displayDirtyStatus(cmd, status)
|
||||
return nil
|
||||
}
|
||||
|
||||
if status.Ahead == 0 && status.Behind == 0 {
|
||||
printf(cmd, "✅ \033[1;32mRepository is up to date\033[0m\n")
|
||||
printf(cmd, " 📡 Synced with \033[36m%s\033[0m\n", status.Remote)
|
||||
} else {
|
||||
printf(cmd, "📊 \033[1mRepository Status\033[0m\n")
|
||||
printf(cmd, " 📡 Remote: \033[36m%s\033[0m\n", status.Remote)
|
||||
printf(cmd, "\n")
|
||||
|
||||
if status.Ahead > 0 {
|
||||
commitText := "commit"
|
||||
if status.Ahead > 1 {
|
||||
commitText = "commits"
|
||||
}
|
||||
printf(cmd, " ⬆️ \033[1;33m%d %s ahead\033[0m - ready to push\n", status.Ahead, commitText)
|
||||
}
|
||||
if status.Behind > 0 {
|
||||
commitText := "commit"
|
||||
if status.Behind > 1 {
|
||||
commitText = "commits"
|
||||
}
|
||||
printf(cmd, " ⬇️ \033[1;31m%d %s behind\033[0m - run \033[1mlnk pull\033[0m\n", status.Behind, commitText)
|
||||
}
|
||||
|
||||
if status.Ahead > 0 && status.Behind == 0 {
|
||||
printf(cmd, "\n💡 Run \033[1mlnk push\033[0m to sync your changes")
|
||||
} else if status.Behind > 0 {
|
||||
printf(cmd, "\n💡 Run \033[1mlnk pull\033[0m to get latest changes")
|
||||
}
|
||||
displayUpToDateStatus(cmd, status)
|
||||
return nil
|
||||
}
|
||||
|
||||
displaySyncStatus(cmd, status)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func displayDirtyStatus(cmd *cobra.Command, status *core.StatusInfo) {
|
||||
printf(cmd, "⚠️ \033[1;33mRepository has uncommitted changes\033[0m\n")
|
||||
printf(cmd, " 📡 Remote: \033[36m%s\033[0m\n", status.Remote)
|
||||
|
||||
if status.Ahead == 0 && status.Behind == 0 {
|
||||
printf(cmd, "\n💡 Run \033[1mgit add && git commit\033[0m in \033[36m~/.config/lnk\033[0m or \033[1mlnk push\033[0m to commit changes\n")
|
||||
return
|
||||
}
|
||||
|
||||
printf(cmd, "\n")
|
||||
displayAheadBehindInfo(cmd, status, true)
|
||||
printf(cmd, "\n💡 Run \033[1mgit add && git commit\033[0m in \033[36m~/.config/lnk\033[0m or \033[1mlnk push\033[0m to commit changes\n")
|
||||
}
|
||||
|
||||
func displayUpToDateStatus(cmd *cobra.Command, status *core.StatusInfo) {
|
||||
printf(cmd, "✅ \033[1;32mRepository is up to date\033[0m\n")
|
||||
printf(cmd, " 📡 Synced with \033[36m%s\033[0m\n", status.Remote)
|
||||
}
|
||||
|
||||
func displaySyncStatus(cmd *cobra.Command, status *core.StatusInfo) {
|
||||
printf(cmd, "📊 \033[1mRepository Status\033[0m\n")
|
||||
printf(cmd, " 📡 Remote: \033[36m%s\033[0m\n", status.Remote)
|
||||
printf(cmd, "\n")
|
||||
|
||||
displayAheadBehindInfo(cmd, status, false)
|
||||
|
||||
if status.Ahead > 0 && status.Behind == 0 {
|
||||
printf(cmd, "\n💡 Run \033[1mlnk push\033[0m to sync your changes\n")
|
||||
} else if status.Behind > 0 {
|
||||
printf(cmd, "\n💡 Run \033[1mlnk pull\033[0m to get latest changes\n")
|
||||
}
|
||||
}
|
||||
|
||||
func displayAheadBehindInfo(cmd *cobra.Command, status *core.StatusInfo, isDirty bool) {
|
||||
if status.Ahead > 0 {
|
||||
commitText := getCommitText(status.Ahead)
|
||||
if isDirty {
|
||||
printf(cmd, " ⬆️ \033[1;33m%d %s ahead\033[0m (excluding uncommitted changes)\n", status.Ahead, commitText)
|
||||
} else {
|
||||
printf(cmd, " ⬆️ \033[1;33m%d %s ahead\033[0m - ready to push\n", status.Ahead, commitText)
|
||||
}
|
||||
}
|
||||
|
||||
if status.Behind > 0 {
|
||||
commitText := getCommitText(status.Behind)
|
||||
printf(cmd, " ⬇️ \033[1;31m%d %s behind\033[0m - run \033[1mlnk pull\033[0m\n", status.Behind, commitText)
|
||||
}
|
||||
}
|
||||
|
||||
func getCommitText(count int) string {
|
||||
if count == 1 {
|
||||
return "commit"
|
||||
}
|
||||
return "commits"
|
||||
}
|
||||
|
@@ -18,7 +18,7 @@ INSTALL_DIR="/usr/local/bin"
|
||||
BINARY_NAME="lnk"
|
||||
|
||||
# Fallback version if redirect fails
|
||||
FALLBACK_VERSION="v0.0.2"
|
||||
FALLBACK_VERSION="v0.3.0"
|
||||
|
||||
# Detect OS and architecture
|
||||
detect_platform() {
|
||||
|
@@ -3,6 +3,7 @@ package core
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -14,18 +15,72 @@ import (
|
||||
// Lnk represents the main application logic
|
||||
type Lnk struct {
|
||||
repoPath string
|
||||
host string // Host-specific configuration
|
||||
git *git.Git
|
||||
fs *fs.FileSystem
|
||||
}
|
||||
|
||||
// NewLnk creates a new Lnk instance
|
||||
func NewLnk() *Lnk {
|
||||
type Option func(*Lnk)
|
||||
|
||||
// WithHost sets the host for host-specific configuration
|
||||
func WithHost(host string) Option {
|
||||
return func(l *Lnk) {
|
||||
l.host = host
|
||||
}
|
||||
}
|
||||
|
||||
// NewLnk creates a new Lnk instance with optional configuration
|
||||
func NewLnk(opts ...Option) *Lnk {
|
||||
repoPath := getRepoPath()
|
||||
return &Lnk{
|
||||
lnk := &Lnk{
|
||||
repoPath: repoPath,
|
||||
host: "",
|
||||
git: git.New(repoPath),
|
||||
fs: fs.New(),
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(lnk)
|
||||
}
|
||||
|
||||
return lnk
|
||||
}
|
||||
|
||||
// HasUserContent checks if the repository contains managed files
|
||||
// by looking for .lnk tracker files (common or host-specific)
|
||||
func (l *Lnk) HasUserContent() bool {
|
||||
// Check for common tracker file
|
||||
commonTracker := filepath.Join(l.repoPath, ".lnk")
|
||||
if _, err := os.Stat(commonTracker); err == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check for host-specific tracker files if host is set
|
||||
if l.host != "" {
|
||||
hostTracker := filepath.Join(l.repoPath, fmt.Sprintf(".lnk.%s", l.host))
|
||||
if _, err := os.Stat(hostTracker); err == nil {
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
// If no specific host is set, check for any host-specific tracker files
|
||||
// This handles cases where we want to detect any managed content
|
||||
pattern := filepath.Join(l.repoPath, ".lnk.*")
|
||||
matches, err := filepath.Glob(pattern)
|
||||
if err == nil && len(matches) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// GetCurrentHostname returns the current system hostname
|
||||
func GetCurrentHostname() (string, error) {
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get hostname: %w", err)
|
||||
}
|
||||
return hostname, nil
|
||||
}
|
||||
|
||||
// getRepoPath returns the path to the lnk repository directory
|
||||
@@ -43,12 +98,22 @@ func getRepoPath() string {
|
||||
return filepath.Join(xdgConfig, "lnk")
|
||||
}
|
||||
|
||||
// generateRepoName creates a unique repository filename from a relative path
|
||||
func generateRepoName(relativePath string) string {
|
||||
// Replace slashes and backslashes with underscores to create valid filename
|
||||
repoName := strings.ReplaceAll(relativePath, "/", "_")
|
||||
repoName = strings.ReplaceAll(repoName, "\\", "_")
|
||||
return repoName
|
||||
// getHostStoragePath returns the storage path for host-specific or common files
|
||||
func (l *Lnk) getHostStoragePath() string {
|
||||
if l.host == "" {
|
||||
// Common configuration - store in root of repo
|
||||
return l.repoPath
|
||||
}
|
||||
// Host-specific configuration - store in host subdirectory
|
||||
return filepath.Join(l.repoPath, l.host+".lnk")
|
||||
}
|
||||
|
||||
// getLnkFileName returns the appropriate .lnk tracking file name
|
||||
func (l *Lnk) getLnkFileName() string {
|
||||
if l.host == "" {
|
||||
return ".lnk"
|
||||
}
|
||||
return ".lnk." + l.host
|
||||
}
|
||||
|
||||
// getRelativePath converts an absolute path to a relative path from home directory
|
||||
@@ -69,9 +134,6 @@ func getRelativePath(absPath string) (string, error) {
|
||||
if strings.HasPrefix(relPath, "..") {
|
||||
// Use absolute path but remove leading slash and drive letter (for cross-platform)
|
||||
cleanPath := strings.TrimPrefix(absPath, "/")
|
||||
if len(cleanPath) > 1 && cleanPath[1] == ':' {
|
||||
// Windows drive letter, keep as is
|
||||
}
|
||||
return cleanPath, nil
|
||||
}
|
||||
|
||||
@@ -85,7 +147,18 @@ func (l *Lnk) Init() error {
|
||||
|
||||
// InitWithRemote initializes the lnk repository, optionally cloning from a remote
|
||||
func (l *Lnk) InitWithRemote(remoteURL string) error {
|
||||
return l.InitWithRemoteForce(remoteURL, false)
|
||||
}
|
||||
|
||||
// InitWithRemoteForce initializes the lnk repository with optional force override
|
||||
func (l *Lnk) InitWithRemoteForce(remoteURL string, force bool) error {
|
||||
if remoteURL != "" {
|
||||
// Safety check: prevent data loss by checking for existing managed files
|
||||
if l.HasUserContent() {
|
||||
if !force {
|
||||
return fmt.Errorf("❌ Directory \033[31m%s\033[0m already contains managed files\n 💡 Use 'lnk pull' to update from remote instead of 'lnk init -r'", l.repoPath)
|
||||
}
|
||||
}
|
||||
// Clone from remote
|
||||
return l.Clone(remoteURL)
|
||||
}
|
||||
@@ -108,27 +181,17 @@ func (l *Lnk) InitWithRemote(remoteURL string) error {
|
||||
}
|
||||
|
||||
// No existing repository, initialize Git repository
|
||||
if err := l.git.Init(); err != nil {
|
||||
return fmt.Errorf("failed to initialize git repository: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return l.git.Init()
|
||||
}
|
||||
|
||||
// Clone clones a repository from the given URL
|
||||
func (l *Lnk) Clone(url string) error {
|
||||
if err := l.git.Clone(url); err != nil {
|
||||
return fmt.Errorf("failed to clone repository: %w", err)
|
||||
}
|
||||
return nil
|
||||
return l.git.Clone(url)
|
||||
}
|
||||
|
||||
// AddRemote adds a remote to the repository
|
||||
func (l *Lnk) AddRemote(name, url string) error {
|
||||
if err := l.git.AddRemote(name, url); err != nil {
|
||||
return fmt.Errorf("failed to add remote %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
return l.git.AddRemote(name, url)
|
||||
}
|
||||
|
||||
// Add moves a file or directory to the repository and creates a symlink
|
||||
@@ -150,9 +213,15 @@ func (l *Lnk) Add(filePath string) error {
|
||||
return fmt.Errorf("failed to get relative path: %w", err)
|
||||
}
|
||||
|
||||
// Generate unique repository name from relative path
|
||||
repoName := generateRepoName(relativePath)
|
||||
destPath := filepath.Join(l.repoPath, repoName)
|
||||
// Generate repository path from relative path
|
||||
storagePath := l.getHostStoragePath()
|
||||
destPath := filepath.Join(storagePath, relativePath)
|
||||
|
||||
// Ensure destination directory exists (including parent directories for host-specific files)
|
||||
destDir := filepath.Dir(destPath)
|
||||
if err := os.MkdirAll(destDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create destination directory: %w", err)
|
||||
}
|
||||
|
||||
// Check if this relative path is already managed
|
||||
managedItems, err := l.getManagedItems()
|
||||
@@ -172,82 +241,208 @@ func (l *Lnk) Add(filePath string) error {
|
||||
}
|
||||
|
||||
// Move to repository (handles both files and directories)
|
||||
if info.IsDir() {
|
||||
if err := l.fs.MoveDirectory(absPath, destPath); err != nil {
|
||||
return fmt.Errorf("failed to move directory to repository: %w", err)
|
||||
}
|
||||
} else {
|
||||
if err := l.fs.MoveFile(absPath, destPath); err != nil {
|
||||
return fmt.Errorf("failed to move file to repository: %w", err)
|
||||
}
|
||||
if err := l.fs.Move(absPath, destPath, info); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create symlink
|
||||
if err := l.fs.CreateSymlink(destPath, absPath); err != nil {
|
||||
// Try to restore the original if symlink creation fails
|
||||
if info.IsDir() {
|
||||
_ = l.fs.MoveDirectory(destPath, absPath) // Ignore error in cleanup
|
||||
} else {
|
||||
_ = l.fs.MoveFile(destPath, absPath) // Ignore error in cleanup
|
||||
}
|
||||
return fmt.Errorf("failed to create symlink: %w", err)
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
return err
|
||||
}
|
||||
|
||||
// Add to .lnk tracking file using relative path
|
||||
if err := l.addManagedItem(relativePath); err != nil {
|
||||
// Try to restore the original state if tracking fails
|
||||
_ = os.Remove(absPath) // Ignore error in cleanup
|
||||
if info.IsDir() {
|
||||
_ = l.fs.MoveDirectory(destPath, absPath) // Ignore error in cleanup
|
||||
} else {
|
||||
_ = l.fs.MoveFile(destPath, absPath) // Ignore error in cleanup
|
||||
}
|
||||
_ = os.Remove(absPath)
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
return fmt.Errorf("failed to update tracking file: %w", err)
|
||||
}
|
||||
|
||||
// Add both the item and .lnk file to git in a single commit
|
||||
if err := l.git.Add(repoName); err != nil {
|
||||
// Try to restore the original state if git add fails
|
||||
_ = os.Remove(absPath) // Ignore error in cleanup
|
||||
_ = l.removeManagedItem(relativePath) // Ignore error in cleanup
|
||||
if info.IsDir() {
|
||||
_ = l.fs.MoveDirectory(destPath, absPath) // Ignore error in cleanup
|
||||
} else {
|
||||
_ = l.fs.MoveFile(destPath, absPath) // Ignore error in cleanup
|
||||
// For host-specific files, we need to add the relative path from repo root
|
||||
gitPath := relativePath
|
||||
if l.host != "" {
|
||||
gitPath = filepath.Join(l.host+".lnk", relativePath)
|
||||
}
|
||||
return fmt.Errorf("failed to add item to git: %w", err)
|
||||
if err := l.git.Add(gitPath); err != nil {
|
||||
// Try to restore the original state if git add fails
|
||||
_ = os.Remove(absPath)
|
||||
_ = l.removeManagedItem(relativePath)
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
return err
|
||||
}
|
||||
|
||||
// Add .lnk file to the same commit
|
||||
if err := l.git.Add(".lnk"); err != nil {
|
||||
if err := l.git.Add(l.getLnkFileName()); err != nil {
|
||||
// Try to restore the original state if git add fails
|
||||
_ = os.Remove(absPath) // Ignore error in cleanup
|
||||
_ = l.removeManagedItem(relativePath) // Ignore error in cleanup
|
||||
if info.IsDir() {
|
||||
_ = l.fs.MoveDirectory(destPath, absPath) // Ignore error in cleanup
|
||||
} else {
|
||||
_ = l.fs.MoveFile(destPath, absPath) // Ignore error in cleanup
|
||||
}
|
||||
return fmt.Errorf("failed to add .lnk file to git: %w", err)
|
||||
_ = os.Remove(absPath)
|
||||
_ = l.removeManagedItem(relativePath)
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
return err
|
||||
}
|
||||
|
||||
// Commit both changes together
|
||||
basename := filepath.Base(relativePath)
|
||||
if err := l.git.Commit(fmt.Sprintf("lnk: added %s", basename)); err != nil {
|
||||
// Try to restore the original state if commit fails
|
||||
_ = os.Remove(absPath) // Ignore error in cleanup
|
||||
_ = l.removeManagedItem(relativePath) // Ignore error in cleanup
|
||||
if info.IsDir() {
|
||||
_ = l.fs.MoveDirectory(destPath, absPath) // Ignore error in cleanup
|
||||
} else {
|
||||
_ = l.fs.MoveFile(destPath, absPath) // Ignore error in cleanup
|
||||
_ = os.Remove(absPath)
|
||||
_ = l.removeManagedItem(relativePath)
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddMultiple adds multiple files or directories to the repository in a single transaction
|
||||
func (l *Lnk) AddMultiple(paths []string) error {
|
||||
if len(paths) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Phase 1: Validate all paths first
|
||||
var relativePaths []string
|
||||
var absolutePaths []string
|
||||
var infos []os.FileInfo
|
||||
|
||||
for _, filePath := range paths {
|
||||
// Validate the file or directory
|
||||
if err := l.fs.ValidateFileForAdd(filePath); err != nil {
|
||||
return fmt.Errorf("validation failed for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Get absolute path
|
||||
absPath, err := filepath.Abs(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get absolute path for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Get relative path for tracking
|
||||
relativePath, err := getRelativePath(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get relative path for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Check if this relative path is already managed
|
||||
managedItems, err := l.getManagedItems()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get managed items: %w", err)
|
||||
}
|
||||
for _, item := range managedItems {
|
||||
if item == relativePath {
|
||||
return fmt.Errorf("❌ File is already managed by lnk: \033[31m%s\033[0m", relativePath)
|
||||
}
|
||||
}
|
||||
|
||||
// Get file info
|
||||
info, err := os.Stat(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to stat path %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
relativePaths = append(relativePaths, relativePath)
|
||||
absolutePaths = append(absolutePaths, absPath)
|
||||
infos = append(infos, info)
|
||||
}
|
||||
|
||||
// Phase 2: Process all files - move to repository and create symlinks
|
||||
var rollbackActions []func() error
|
||||
|
||||
for i, absPath := range absolutePaths {
|
||||
relativePath := relativePaths[i]
|
||||
info := infos[i]
|
||||
|
||||
// Generate repository path from relative path
|
||||
storagePath := l.getHostStoragePath()
|
||||
destPath := filepath.Join(storagePath, relativePath)
|
||||
|
||||
// Ensure destination directory exists
|
||||
destDir := filepath.Dir(destPath)
|
||||
if err := os.MkdirAll(destDir, 0755); err != nil {
|
||||
// Rollback previous operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to create destination directory: %w", err)
|
||||
}
|
||||
|
||||
// Move to repository
|
||||
if err := l.fs.Move(absPath, destPath, info); err != nil {
|
||||
// Rollback previous operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to move %s: %w", absPath, err)
|
||||
}
|
||||
|
||||
// Create symlink
|
||||
if err := l.fs.CreateSymlink(destPath, absPath); err != nil {
|
||||
// Try to restore the file we just moved, then rollback others
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to create symlink for %s: %w", absPath, err)
|
||||
}
|
||||
|
||||
// Add to tracking
|
||||
if err := l.addManagedItem(relativePath); err != nil {
|
||||
// Restore this file and rollback others
|
||||
_ = os.Remove(absPath)
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to update tracking file for %s: %w", absPath, err)
|
||||
}
|
||||
|
||||
// Add rollback action for this file
|
||||
rollbackAction := l.createRollbackAction(absPath, destPath, relativePath, info)
|
||||
rollbackActions = append(rollbackActions, rollbackAction)
|
||||
}
|
||||
|
||||
// Phase 3: Git operations - add all files and create single commit
|
||||
for i, relativePath := range relativePaths {
|
||||
// For host-specific files, we need to add the relative path from repo root
|
||||
gitPath := relativePath
|
||||
if l.host != "" {
|
||||
gitPath = filepath.Join(l.host+".lnk", relativePath)
|
||||
}
|
||||
if err := l.git.Add(gitPath); err != nil {
|
||||
// Rollback all operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to add %s to git: %w", absolutePaths[i], err)
|
||||
}
|
||||
}
|
||||
|
||||
// Add .lnk file to the same commit
|
||||
if err := l.git.Add(l.getLnkFileName()); err != nil {
|
||||
// Rollback all operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to add tracking file to git: %w", err)
|
||||
}
|
||||
|
||||
// Commit all changes together
|
||||
commitMessage := fmt.Sprintf("lnk: added %d files", len(paths))
|
||||
if err := l.git.Commit(commitMessage); err != nil {
|
||||
// Rollback all operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to commit changes: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createRollbackAction creates a rollback function for a single file operation
|
||||
func (l *Lnk) createRollbackAction(absPath, destPath, relativePath string, info os.FileInfo) func() error {
|
||||
return func() error {
|
||||
_ = os.Remove(absPath)
|
||||
_ = l.removeManagedItem(relativePath)
|
||||
return l.fs.Move(destPath, absPath, info)
|
||||
}
|
||||
}
|
||||
|
||||
// rollbackOperations executes rollback actions in reverse order
|
||||
func (l *Lnk) rollbackOperations(rollbackActions []func() error) {
|
||||
for i := len(rollbackActions) - 1; i >= 0; i-- {
|
||||
_ = rollbackActions[i]()
|
||||
}
|
||||
}
|
||||
|
||||
// Remove removes a symlink and restores the original file or directory
|
||||
func (l *Lnk) Remove(filePath string) error {
|
||||
// Get absolute path
|
||||
@@ -295,8 +490,6 @@ func (l *Lnk) Remove(filePath string) error {
|
||||
target = filepath.Join(filepath.Dir(absPath), target)
|
||||
}
|
||||
|
||||
repoName := filepath.Base(target)
|
||||
|
||||
// Check if target is a directory or file
|
||||
info, err := os.Stat(target)
|
||||
if err != nil {
|
||||
@@ -313,31 +506,29 @@ func (l *Lnk) Remove(filePath string) error {
|
||||
return fmt.Errorf("failed to update tracking file: %w", err)
|
||||
}
|
||||
|
||||
// Remove from Git first (while the item is still in the repository)
|
||||
if err := l.git.Remove(repoName); err != nil {
|
||||
return fmt.Errorf("failed to remove from git: %w", err)
|
||||
// Generate the correct git path for removal
|
||||
gitPath := relativePath
|
||||
if l.host != "" {
|
||||
gitPath = filepath.Join(l.host+".lnk", relativePath)
|
||||
}
|
||||
if err := l.git.Remove(gitPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add .lnk file to the same commit
|
||||
if err := l.git.Add(".lnk"); err != nil {
|
||||
return fmt.Errorf("failed to add .lnk file to git: %w", err)
|
||||
if err := l.git.Add(l.getLnkFileName()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Commit both changes together
|
||||
basename := filepath.Base(relativePath)
|
||||
if err := l.git.Commit(fmt.Sprintf("lnk: removed %s", basename)); err != nil {
|
||||
return fmt.Errorf("failed to commit changes: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Move back from repository (handles both files and directories)
|
||||
if info.IsDir() {
|
||||
if err := l.fs.MoveDirectory(target, absPath); err != nil {
|
||||
return fmt.Errorf("failed to restore directory: %w", err)
|
||||
}
|
||||
} else {
|
||||
if err := l.fs.MoveFile(target, absPath); err != nil {
|
||||
return fmt.Errorf("failed to restore file: %w", err)
|
||||
}
|
||||
if err := l.fs.Move(target, absPath, info); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -353,6 +544,7 @@ type StatusInfo struct {
|
||||
Ahead int
|
||||
Behind int
|
||||
Remote string
|
||||
Dirty bool
|
||||
}
|
||||
|
||||
// Status returns the repository sync status
|
||||
@@ -364,13 +556,14 @@ func (l *Lnk) Status() (*StatusInfo, error) {
|
||||
|
||||
gitStatus, err := l.git.GetStatus()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get repository status: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &StatusInfo{
|
||||
Ahead: gitStatus.Ahead,
|
||||
Behind: gitStatus.Behind,
|
||||
Remote: gitStatus.Remote,
|
||||
Dirty: gitStatus.Dirty,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -384,28 +577,24 @@ func (l *Lnk) Push(message string) error {
|
||||
// Check if there are any changes
|
||||
hasChanges, err := l.git.HasChanges()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check for changes: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if hasChanges {
|
||||
// Stage all changes
|
||||
if err := l.git.AddAll(); err != nil {
|
||||
return fmt.Errorf("failed to stage changes: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Create a sync commit
|
||||
if err := l.git.Commit(message); err != nil {
|
||||
return fmt.Errorf("failed to commit changes: %w", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Push to remote (this will be a no-op in tests since we don't have real remotes)
|
||||
// In real usage, this would push to the actual remote repository
|
||||
if err := l.git.Push(); err != nil {
|
||||
return fmt.Errorf("failed to push to remote: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return l.git.Push()
|
||||
}
|
||||
|
||||
// Pull fetches changes from remote and restores symlinks as needed
|
||||
@@ -417,7 +606,7 @@ func (l *Lnk) Pull() ([]string, error) {
|
||||
|
||||
// Pull changes from remote (this will be a no-op in tests since we don't have real remotes)
|
||||
if err := l.git.Pull(); err != nil {
|
||||
return nil, fmt.Errorf("failed to pull from remote: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Find all managed files in the repository and restore symlinks
|
||||
@@ -429,6 +618,22 @@ func (l *Lnk) Pull() ([]string, error) {
|
||||
return restored, nil
|
||||
}
|
||||
|
||||
// List returns the list of files and directories currently managed by lnk
|
||||
func (l *Lnk) List() ([]string, error) {
|
||||
// Check if repository is initialized
|
||||
if !l.git.IsGitRepository() {
|
||||
return nil, fmt.Errorf("❌ Lnk repository not initialized\n 💡 Run \033[1mlnk init\033[0m first")
|
||||
}
|
||||
|
||||
// Get managed items from .lnk file
|
||||
managedItems, err := l.getManagedItems()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get managed items: %w", err)
|
||||
}
|
||||
|
||||
return managedItems, nil
|
||||
}
|
||||
|
||||
// RestoreSymlinks finds all managed items from .lnk file and ensures they have proper symlinks
|
||||
func (l *Lnk) RestoreSymlinks() ([]string, error) {
|
||||
var restored []string
|
||||
@@ -446,8 +651,8 @@ func (l *Lnk) RestoreSymlinks() ([]string, error) {
|
||||
|
||||
for _, relativePath := range managedItems {
|
||||
// Generate repository name from relative path
|
||||
repoName := generateRepoName(relativePath)
|
||||
repoItem := filepath.Join(l.repoPath, repoName)
|
||||
storagePath := l.getHostStoragePath()
|
||||
repoItem := filepath.Join(storagePath, relativePath)
|
||||
|
||||
// Check if item exists in repository
|
||||
if _, err := os.Stat(repoItem); os.IsNotExist(err) {
|
||||
@@ -477,7 +682,7 @@ func (l *Lnk) RestoreSymlinks() ([]string, error) {
|
||||
|
||||
// Create symlink
|
||||
if err := l.fs.CreateSymlink(repoItem, symlinkPath); err != nil {
|
||||
return nil, fmt.Errorf("failed to create symlink for %s: %w", relativePath, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
restored = append(restored, relativePath)
|
||||
@@ -525,7 +730,7 @@ func (l *Lnk) isValidSymlink(symlinkPath, expectedTarget string) bool {
|
||||
|
||||
// getManagedItems returns the list of managed files and directories from .lnk file
|
||||
func (l *Lnk) getManagedItems() ([]string, error) {
|
||||
lnkFile := filepath.Join(l.repoPath, ".lnk")
|
||||
lnkFile := filepath.Join(l.repoPath, l.getLnkFileName())
|
||||
|
||||
// If .lnk file doesn't exist, return empty list
|
||||
if _, err := os.Stat(lnkFile); os.IsNotExist(err) {
|
||||
@@ -598,7 +803,7 @@ func (l *Lnk) removeManagedItem(relativePath string) error {
|
||||
|
||||
// writeManagedItems writes the list of managed items to .lnk file
|
||||
func (l *Lnk) writeManagedItems(items []string) error {
|
||||
lnkFile := filepath.Join(l.repoPath, ".lnk")
|
||||
lnkFile := filepath.Join(l.repoPath, l.getLnkFileName())
|
||||
|
||||
content := strings.Join(items, "\n")
|
||||
if len(items) > 0 {
|
||||
@@ -612,3 +817,373 @@ func (l *Lnk) writeManagedItems(items []string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindBootstrapScript searches for a bootstrap script in the repository
|
||||
func (l *Lnk) FindBootstrapScript() (string, error) {
|
||||
// Check if repository is initialized
|
||||
if !l.git.IsGitRepository() {
|
||||
return "", fmt.Errorf("❌ Lnk repository not initialized\n 💡 Run \033[1mlnk init\033[0m first")
|
||||
}
|
||||
|
||||
// Look for bootstrap.sh - simple, opinionated choice
|
||||
scriptPath := filepath.Join(l.repoPath, "bootstrap.sh")
|
||||
if _, err := os.Stat(scriptPath); err == nil {
|
||||
return "bootstrap.sh", nil
|
||||
}
|
||||
|
||||
return "", nil // No bootstrap script found
|
||||
}
|
||||
|
||||
// RunBootstrapScript executes the bootstrap script
|
||||
func (l *Lnk) RunBootstrapScript(scriptName string) error {
|
||||
scriptPath := filepath.Join(l.repoPath, scriptName)
|
||||
|
||||
// Verify the script exists
|
||||
if _, err := os.Stat(scriptPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("❌ Bootstrap script not found: \033[31m%s\033[0m", scriptName)
|
||||
}
|
||||
|
||||
// Make sure it's executable
|
||||
if err := os.Chmod(scriptPath, 0755); err != nil {
|
||||
return fmt.Errorf("❌ Failed to make bootstrap script executable: %w", err)
|
||||
}
|
||||
|
||||
// Run with bash (since we only support bootstrap.sh)
|
||||
cmd := exec.Command("bash", scriptPath)
|
||||
|
||||
// Set working directory to the repository
|
||||
cmd.Dir = l.repoPath
|
||||
|
||||
// Connect to stdout/stderr for user to see output
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Stdin = os.Stdin
|
||||
|
||||
// Run the script
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("❌ Bootstrap script failed with error: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// walkDirectory walks through a directory and returns all regular files
|
||||
func (l *Lnk) walkDirectory(dirPath string) ([]string, error) {
|
||||
var files []string
|
||||
|
||||
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Skip directories - we only want files
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Handle symlinks: include them as files if they point to regular files
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
// For symlinks, we'll include them but the AddMultiple logic
|
||||
// will handle validation appropriately
|
||||
files = append(files, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Include regular files
|
||||
if info.Mode().IsRegular() {
|
||||
files = append(files, path)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to walk directory %s: %w", dirPath, err)
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// ProgressCallback defines the signature for progress reporting callbacks
|
||||
type ProgressCallback func(current, total int, currentFile string)
|
||||
|
||||
// AddRecursiveWithProgress adds directory contents individually with progress reporting
|
||||
func (l *Lnk) AddRecursiveWithProgress(paths []string, progress ProgressCallback) error {
|
||||
var allFiles []string
|
||||
|
||||
for _, path := range paths {
|
||||
// Get absolute path
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get absolute path for %s: %w", path, err)
|
||||
}
|
||||
|
||||
// Check if it's a directory
|
||||
info, err := os.Stat(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to stat %s: %w", path, err)
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
// Walk directory to get all files
|
||||
files, err := l.walkDirectory(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to walk directory %s: %w", path, err)
|
||||
}
|
||||
allFiles = append(allFiles, files...)
|
||||
} else {
|
||||
// It's a regular file, add it directly
|
||||
allFiles = append(allFiles, absPath)
|
||||
}
|
||||
}
|
||||
|
||||
// Use AddMultiple for batch processing
|
||||
if len(allFiles) == 0 {
|
||||
return fmt.Errorf("no files found to add")
|
||||
}
|
||||
|
||||
// Apply progress threshold: only show progress for >10 files
|
||||
const progressThreshold = 10
|
||||
if len(allFiles) > progressThreshold && progress != nil {
|
||||
return l.addMultipleWithProgress(allFiles, progress)
|
||||
}
|
||||
|
||||
// For small operations, use regular AddMultiple without progress
|
||||
return l.AddMultiple(allFiles)
|
||||
}
|
||||
|
||||
// addMultipleWithProgress adds multiple files with progress reporting
|
||||
func (l *Lnk) addMultipleWithProgress(paths []string, progress ProgressCallback) error {
|
||||
if len(paths) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Phase 1: Validate all paths first (same as AddMultiple)
|
||||
var relativePaths []string
|
||||
var absolutePaths []string
|
||||
var infos []os.FileInfo
|
||||
|
||||
for _, filePath := range paths {
|
||||
// Validate the file or directory
|
||||
if err := l.fs.ValidateFileForAdd(filePath); err != nil {
|
||||
return fmt.Errorf("validation failed for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Get absolute path
|
||||
absPath, err := filepath.Abs(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get absolute path for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Get relative path for tracking
|
||||
relativePath, err := getRelativePath(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get relative path for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Check if this relative path is already managed
|
||||
managedItems, err := l.getManagedItems()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get managed items: %w", err)
|
||||
}
|
||||
for _, item := range managedItems {
|
||||
if item == relativePath {
|
||||
return fmt.Errorf("❌ File is already managed by lnk: \033[31m%s\033[0m", relativePath)
|
||||
}
|
||||
}
|
||||
|
||||
// Get file info
|
||||
info, err := os.Stat(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to stat path %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
relativePaths = append(relativePaths, relativePath)
|
||||
absolutePaths = append(absolutePaths, absPath)
|
||||
infos = append(infos, info)
|
||||
}
|
||||
|
||||
// Phase 2: Process all files with progress reporting
|
||||
var rollbackActions []func() error
|
||||
total := len(absolutePaths)
|
||||
|
||||
for i, absPath := range absolutePaths {
|
||||
// Report progress
|
||||
if progress != nil {
|
||||
progress(i+1, total, filepath.Base(absPath))
|
||||
}
|
||||
|
||||
relativePath := relativePaths[i]
|
||||
info := infos[i]
|
||||
|
||||
// Generate repository path from relative path
|
||||
storagePath := l.getHostStoragePath()
|
||||
destPath := filepath.Join(storagePath, relativePath)
|
||||
|
||||
// Ensure destination directory exists
|
||||
destDir := filepath.Dir(destPath)
|
||||
if err := os.MkdirAll(destDir, 0755); err != nil {
|
||||
// Rollback previous operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to create destination directory: %w", err)
|
||||
}
|
||||
|
||||
// Move to repository
|
||||
if err := l.fs.Move(absPath, destPath, info); err != nil {
|
||||
// Rollback previous operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to move %s: %w", absPath, err)
|
||||
}
|
||||
|
||||
// Create symlink
|
||||
if err := l.fs.CreateSymlink(destPath, absPath); err != nil {
|
||||
// Try to restore the file we just moved, then rollback others
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to create symlink for %s: %w", absPath, err)
|
||||
}
|
||||
|
||||
// Add to tracking
|
||||
if err := l.addManagedItem(relativePath); err != nil {
|
||||
// Restore this file and rollback others
|
||||
_ = os.Remove(absPath)
|
||||
_ = l.fs.Move(destPath, absPath, info)
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to update tracking file for %s: %w", absPath, err)
|
||||
}
|
||||
|
||||
// Add rollback action for this file
|
||||
rollbackAction := l.createRollbackAction(absPath, destPath, relativePath, info)
|
||||
rollbackActions = append(rollbackActions, rollbackAction)
|
||||
}
|
||||
|
||||
// Phase 3: Git operations - add all files and create single commit
|
||||
for i, relativePath := range relativePaths {
|
||||
// For host-specific files, we need to add the relative path from repo root
|
||||
gitPath := relativePath
|
||||
if l.host != "" {
|
||||
gitPath = filepath.Join(l.host+".lnk", relativePath)
|
||||
}
|
||||
if err := l.git.Add(gitPath); err != nil {
|
||||
// Rollback all operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to add %s to git: %w", absolutePaths[i], err)
|
||||
}
|
||||
}
|
||||
|
||||
// Add .lnk file to the same commit
|
||||
if err := l.git.Add(l.getLnkFileName()); err != nil {
|
||||
// Rollback all operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to add tracking file to git: %w", err)
|
||||
}
|
||||
|
||||
// Commit all changes together
|
||||
commitMessage := fmt.Sprintf("lnk: added %d files recursively", len(paths))
|
||||
if err := l.git.Commit(commitMessage); err != nil {
|
||||
// Rollback all operations
|
||||
l.rollbackOperations(rollbackActions)
|
||||
return fmt.Errorf("failed to commit changes: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddRecursive adds directory contents individually instead of the directory as a whole
|
||||
func (l *Lnk) AddRecursive(paths []string) error {
|
||||
var allFiles []string
|
||||
|
||||
for _, path := range paths {
|
||||
// Get absolute path
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get absolute path for %s: %w", path, err)
|
||||
}
|
||||
|
||||
// Check if it's a directory
|
||||
info, err := os.Stat(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to stat %s: %w", path, err)
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
// Walk directory to get all files
|
||||
files, err := l.walkDirectory(absPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to walk directory %s: %w", path, err)
|
||||
}
|
||||
allFiles = append(allFiles, files...)
|
||||
} else {
|
||||
// It's a regular file, add it directly
|
||||
allFiles = append(allFiles, absPath)
|
||||
}
|
||||
}
|
||||
|
||||
// Use AddMultiple for batch processing
|
||||
if len(allFiles) == 0 {
|
||||
return fmt.Errorf("no files found to add")
|
||||
}
|
||||
|
||||
return l.AddMultiple(allFiles)
|
||||
}
|
||||
|
||||
// PreviewAdd simulates an add operation and returns files that would be affected
|
||||
func (l *Lnk) PreviewAdd(paths []string, recursive bool) ([]string, error) {
|
||||
var allFiles []string
|
||||
|
||||
for _, path := range paths {
|
||||
// Get absolute path
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get absolute path for %s: %w", path, err)
|
||||
}
|
||||
|
||||
// Check if it's a directory
|
||||
info, err := os.Stat(absPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to stat %s: %w", path, err)
|
||||
}
|
||||
|
||||
if info.IsDir() && recursive {
|
||||
// Walk directory to get all files (same logic as AddRecursive)
|
||||
files, err := l.walkDirectory(absPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to walk directory %s: %w", path, err)
|
||||
}
|
||||
allFiles = append(allFiles, files...)
|
||||
} else {
|
||||
// It's a regular file or non-recursive directory, add it directly
|
||||
allFiles = append(allFiles, absPath)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate files (same validation as AddMultiple but without making changes)
|
||||
var validFiles []string
|
||||
for _, filePath := range allFiles {
|
||||
// Validate the file or directory
|
||||
if err := l.fs.ValidateFileForAdd(filePath); err != nil {
|
||||
return nil, fmt.Errorf("validation failed for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Get relative path for tracking
|
||||
relativePath, err := getRelativePath(filePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get relative path for %s: %w", filePath, err)
|
||||
}
|
||||
|
||||
// Check if this relative path is already managed
|
||||
managedItems, err := l.getManagedItems()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get managed items: %w", err)
|
||||
}
|
||||
for _, item := range managedItems {
|
||||
if item == relativePath {
|
||||
return nil, fmt.Errorf("❌ File is already managed by lnk: \033[31m%s\033[0m", relativePath)
|
||||
}
|
||||
}
|
||||
|
||||
validFiles = append(validFiles, filePath)
|
||||
}
|
||||
|
||||
return validFiles, nil
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
119
internal/fs/errors.go
Normal file
119
internal/fs/errors.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package fs
|
||||
|
||||
import "fmt"
|
||||
|
||||
// ANSI color codes for consistent formatting
|
||||
const (
|
||||
colorReset = "\033[0m"
|
||||
colorRed = "\033[31m"
|
||||
colorBold = "\033[1m"
|
||||
)
|
||||
|
||||
// formatError creates a consistently formatted error message with ❌ prefix
|
||||
func formatError(message string, args ...interface{}) string {
|
||||
return fmt.Sprintf("❌ "+message, args...)
|
||||
}
|
||||
|
||||
// formatPath formats a file path with red color
|
||||
func formatPath(path string) string {
|
||||
return fmt.Sprintf("%s%s%s", colorRed, path, colorReset)
|
||||
}
|
||||
|
||||
// formatCommand formats a command with bold styling
|
||||
func formatCommand(command string) string {
|
||||
return fmt.Sprintf("%s%s%s", colorBold, command, colorReset)
|
||||
}
|
||||
|
||||
// FileNotExistsError represents an error when a file does not exist
|
||||
type FileNotExistsError struct {
|
||||
Path string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *FileNotExistsError) Error() string {
|
||||
return formatError("File or directory not found: %s", formatPath(e.Path))
|
||||
}
|
||||
|
||||
func (e *FileNotExistsError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// FileCheckError represents an error when failing to check a file
|
||||
type FileCheckError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *FileCheckError) Error() string {
|
||||
return formatError("Unable to access file. Please check file permissions and try again.")
|
||||
}
|
||||
|
||||
func (e *FileCheckError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// UnsupportedFileTypeError represents an error when a file type is not supported
|
||||
type UnsupportedFileTypeError struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
func (e *UnsupportedFileTypeError) Error() string {
|
||||
return formatError("Cannot manage this type of file: %s\n 💡 lnk can only manage regular files and directories", formatPath(e.Path))
|
||||
}
|
||||
|
||||
func (e *UnsupportedFileTypeError) Unwrap() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotManagedByLnkError represents an error when a file is not managed by lnk
|
||||
type NotManagedByLnkError struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
func (e *NotManagedByLnkError) Error() string {
|
||||
return formatError("File is not managed by lnk: %s\n 💡 Use %s to manage this file first",
|
||||
formatPath(e.Path), formatCommand("lnk add"))
|
||||
}
|
||||
|
||||
func (e *NotManagedByLnkError) Unwrap() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SymlinkReadError represents an error when failing to read a symlink
|
||||
type SymlinkReadError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *SymlinkReadError) Error() string {
|
||||
return formatError("Unable to read symlink. The file may be corrupted or have invalid permissions.")
|
||||
}
|
||||
|
||||
func (e *SymlinkReadError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// DirectoryCreationError represents an error when failing to create a directory
|
||||
type DirectoryCreationError struct {
|
||||
Operation string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *DirectoryCreationError) Error() string {
|
||||
return formatError("Failed to create directory. Please check permissions and available disk space.")
|
||||
}
|
||||
|
||||
func (e *DirectoryCreationError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// RelativePathCalculationError represents an error when failing to calculate relative path
|
||||
type RelativePathCalculationError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *RelativePathCalculationError) Error() string {
|
||||
return formatError("Unable to create symlink due to path configuration issues. Please check file locations.")
|
||||
}
|
||||
|
||||
func (e *RelativePathCalculationError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
@@ -1,7 +1,6 @@
|
||||
package fs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -17,18 +16,19 @@ func New() *FileSystem {
|
||||
|
||||
// ValidateFileForAdd validates that a file or directory can be added to lnk
|
||||
func (fs *FileSystem) ValidateFileForAdd(filePath string) error {
|
||||
// Check if file exists
|
||||
// Check if file exists and get its info
|
||||
info, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return fmt.Errorf("❌ File does not exist: \033[31m%s\033[0m", filePath)
|
||||
return &FileNotExistsError{Path: filePath, Err: err}
|
||||
}
|
||||
return fmt.Errorf("❌ Failed to check file: %w", err)
|
||||
|
||||
return &FileCheckError{Err: err}
|
||||
}
|
||||
|
||||
// Allow both regular files and directories
|
||||
if !info.Mode().IsRegular() && !info.IsDir() {
|
||||
return fmt.Errorf("❌ Only regular files and directories are supported: \033[31m%s\033[0m", filePath)
|
||||
return &UnsupportedFileTypeError{Path: filePath}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -36,98 +36,79 @@ func (fs *FileSystem) ValidateFileForAdd(filePath string) error {
|
||||
|
||||
// ValidateSymlinkForRemove validates that a symlink can be removed from lnk
|
||||
func (fs *FileSystem) ValidateSymlinkForRemove(filePath, repoPath string) error {
|
||||
// Check if file exists
|
||||
// Check if file exists and is a symlink
|
||||
info, err := os.Lstat(filePath) // Use Lstat to not follow symlinks
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return fmt.Errorf("❌ File does not exist: \033[31m%s\033[0m", filePath)
|
||||
}
|
||||
return fmt.Errorf("❌ Failed to check file: %w", err)
|
||||
return &FileNotExistsError{Path: filePath, Err: err}
|
||||
}
|
||||
|
||||
return &FileCheckError{Err: err}
|
||||
}
|
||||
|
||||
// Check if it's a symlink
|
||||
if info.Mode()&os.ModeSymlink == 0 {
|
||||
return fmt.Errorf("❌ File is not managed by lnk: \033[31m%s\033[0m\n 💡 Use \033[1mlnk add\033[0m to manage this file first", filePath)
|
||||
return &NotManagedByLnkError{Path: filePath}
|
||||
}
|
||||
|
||||
// Check if symlink points to the repository
|
||||
// Get symlink target and resolve to absolute path
|
||||
target, err := os.Readlink(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read symlink: %w", err)
|
||||
return &SymlinkReadError{Err: err}
|
||||
}
|
||||
|
||||
// Convert relative path to absolute if needed
|
||||
if !filepath.IsAbs(target) {
|
||||
target = filepath.Join(filepath.Dir(filePath), target)
|
||||
}
|
||||
|
||||
// Clean the path to resolve any .. or . components
|
||||
// Clean paths and check if target is inside the repository
|
||||
target = filepath.Clean(target)
|
||||
repoPath = filepath.Clean(repoPath)
|
||||
|
||||
// Check if target is inside the repository
|
||||
if !strings.HasPrefix(target, repoPath+string(filepath.Separator)) && target != repoPath {
|
||||
return fmt.Errorf("❌ File is not managed by lnk: \033[31m%s\033[0m", filePath)
|
||||
return &NotManagedByLnkError{Path: filePath}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Move moves a file or directory from source to destination based on the file info
|
||||
func (fs *FileSystem) Move(src, dst string, info os.FileInfo) error {
|
||||
if info.IsDir() {
|
||||
return fs.MoveDirectory(src, dst)
|
||||
}
|
||||
return fs.MoveFile(src, dst)
|
||||
}
|
||||
|
||||
// MoveFile moves a file from source to destination
|
||||
func (fs *FileSystem) MoveFile(src, dst string) error {
|
||||
// Ensure destination directory exists
|
||||
dstDir := filepath.Dir(dst)
|
||||
if err := os.MkdirAll(dstDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create destination directory: %w", err)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
|
||||
return &DirectoryCreationError{Operation: "destination directory", Err: err}
|
||||
}
|
||||
|
||||
// Move the file
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return fmt.Errorf("failed to move file from %s to %s: %w", src, dst, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return os.Rename(src, dst)
|
||||
}
|
||||
|
||||
// CreateSymlink creates a relative symlink from target to linkPath
|
||||
func (fs *FileSystem) CreateSymlink(target, linkPath string) error {
|
||||
// Calculate relative path from linkPath to target
|
||||
linkDir := filepath.Dir(linkPath)
|
||||
relTarget, err := filepath.Rel(linkDir, target)
|
||||
relTarget, err := filepath.Rel(filepath.Dir(linkPath), target)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to calculate relative path: %w", err)
|
||||
return &RelativePathCalculationError{Err: err}
|
||||
}
|
||||
|
||||
// Create the symlink
|
||||
if err := os.Symlink(relTarget, linkPath); err != nil {
|
||||
return fmt.Errorf("failed to create symlink: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return os.Symlink(relTarget, linkPath)
|
||||
}
|
||||
|
||||
// MoveDirectory moves a directory from source to destination recursively
|
||||
func (fs *FileSystem) MoveDirectory(src, dst string) error {
|
||||
// Check if source is a directory
|
||||
info, err := os.Stat(src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to stat source: %w", err)
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
return fmt.Errorf("source is not a directory: %s", src)
|
||||
}
|
||||
|
||||
// Ensure destination parent directory exists
|
||||
dstParent := filepath.Dir(dst)
|
||||
if err := os.MkdirAll(dstParent, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create destination parent directory: %w", err)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
|
||||
return &DirectoryCreationError{Operation: "destination parent directory", Err: err}
|
||||
}
|
||||
|
||||
// Use os.Rename which works for directories
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return fmt.Errorf("failed to move directory from %s to %s: %w", src, dst, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
// Move the directory
|
||||
return os.Rename(src, dst)
|
||||
}
|
||||
|
218
internal/git/errors.go
Normal file
218
internal/git/errors.go
Normal file
@@ -0,0 +1,218 @@
|
||||
package git
|
||||
|
||||
import "fmt"
|
||||
|
||||
// ANSI color codes for consistent formatting
|
||||
const (
|
||||
colorReset = "\033[0m"
|
||||
colorBold = "\033[1m"
|
||||
colorGreen = "\033[32m"
|
||||
colorYellow = "\033[33m"
|
||||
)
|
||||
|
||||
// formatError creates a consistently formatted error message with ❌ prefix
|
||||
func formatError(message string, args ...interface{}) string {
|
||||
return fmt.Sprintf("❌ "+message, args...)
|
||||
}
|
||||
|
||||
// formatURL formats a URL with styling
|
||||
func formatURL(url string) string {
|
||||
return fmt.Sprintf("%s%s%s", colorBold, url, colorReset)
|
||||
}
|
||||
|
||||
// formatRemote formats a remote name with styling
|
||||
func formatRemote(remote string) string {
|
||||
return fmt.Sprintf("%s%s%s", colorGreen, remote, colorReset)
|
||||
}
|
||||
|
||||
// GitInitError represents an error during git initialization
|
||||
type GitInitError struct {
|
||||
Output string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *GitInitError) Error() string {
|
||||
return formatError("Failed to initialize git repository. Please ensure git is installed and try again.")
|
||||
}
|
||||
|
||||
func (e *GitInitError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// BranchSetupError represents an error setting up the default branch
|
||||
type BranchSetupError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *BranchSetupError) Error() string {
|
||||
return formatError("Failed to set up the default branch. Please check your git installation.")
|
||||
}
|
||||
|
||||
func (e *BranchSetupError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// RemoteExistsError represents an error when a remote already exists with different URL
|
||||
type RemoteExistsError struct {
|
||||
Remote string
|
||||
ExistingURL string
|
||||
NewURL string
|
||||
}
|
||||
|
||||
func (e *RemoteExistsError) Error() string {
|
||||
return formatError("Remote %s is already configured with a different repository (%s). Cannot add %s.",
|
||||
formatRemote(e.Remote), formatURL(e.ExistingURL), formatURL(e.NewURL))
|
||||
}
|
||||
|
||||
func (e *RemoteExistsError) Unwrap() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GitCommandError represents a generic git command execution error
|
||||
type GitCommandError struct {
|
||||
Command string
|
||||
Output string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *GitCommandError) Error() string {
|
||||
// Provide user-friendly messages based on common command types
|
||||
switch e.Command {
|
||||
case "add":
|
||||
return formatError("Failed to stage files for commit. Please check file permissions and try again.")
|
||||
case "commit":
|
||||
return formatError("Failed to create commit. Please ensure you have staged changes and try again.")
|
||||
case "remote add":
|
||||
return formatError("Failed to add remote repository. Please check the repository URL and try again.")
|
||||
case "rm":
|
||||
return formatError("Failed to remove file from git tracking. Please check if the file exists and try again.")
|
||||
case "log":
|
||||
return formatError("Failed to retrieve commit history.")
|
||||
case "remote":
|
||||
return formatError("Failed to retrieve remote repository information.")
|
||||
case "clone":
|
||||
return formatError("Failed to clone repository. Please check the repository URL and your network connection.")
|
||||
default:
|
||||
return formatError("Git operation failed. Please check your repository state and try again.")
|
||||
}
|
||||
}
|
||||
|
||||
func (e *GitCommandError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// NoRemoteError represents an error when no remote is configured
|
||||
type NoRemoteError struct{}
|
||||
|
||||
func (e *NoRemoteError) Error() string {
|
||||
return formatError("No remote repository is configured. Please add a remote repository first.")
|
||||
}
|
||||
|
||||
func (e *NoRemoteError) Unwrap() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoteNotFoundError represents an error when a specific remote is not found
|
||||
type RemoteNotFoundError struct {
|
||||
Remote string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *RemoteNotFoundError) Error() string {
|
||||
return formatError("Remote repository %s is not configured.", formatRemote(e.Remote))
|
||||
}
|
||||
|
||||
func (e *RemoteNotFoundError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// GitConfigError represents an error with git configuration
|
||||
type GitConfigError struct {
|
||||
Setting string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *GitConfigError) Error() string {
|
||||
return formatError("Failed to configure git settings. Please check your git installation.")
|
||||
}
|
||||
|
||||
func (e *GitConfigError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// UncommittedChangesError represents an error checking for uncommitted changes
|
||||
type UncommittedChangesError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *UncommittedChangesError) Error() string {
|
||||
return formatError("Failed to check repository status. Please verify your git repository is valid.")
|
||||
}
|
||||
|
||||
func (e *UncommittedChangesError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// DirectoryRemovalError represents an error removing a directory
|
||||
type DirectoryRemovalError struct {
|
||||
Path string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *DirectoryRemovalError) Error() string {
|
||||
return formatError("Failed to prepare directory for operation. Please check directory permissions.")
|
||||
}
|
||||
|
||||
func (e *DirectoryRemovalError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// DirectoryCreationError represents an error creating a directory
|
||||
type DirectoryCreationError struct {
|
||||
Path string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *DirectoryCreationError) Error() string {
|
||||
return formatError("Failed to create directory. Please check permissions and available disk space.")
|
||||
}
|
||||
|
||||
func (e *DirectoryCreationError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// PushError represents an error during git push operation
|
||||
type PushError struct {
|
||||
Reason string
|
||||
Output string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *PushError) Error() string {
|
||||
if e.Reason != "" {
|
||||
return formatError("Cannot push changes: %s", e.Reason)
|
||||
}
|
||||
return formatError("Failed to push changes to remote repository. Please check your network connection and repository permissions.")
|
||||
}
|
||||
|
||||
func (e *PushError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// PullError represents an error during git pull operation
|
||||
type PullError struct {
|
||||
Reason string
|
||||
Output string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *PullError) Error() string {
|
||||
if e.Reason != "" {
|
||||
return formatError("Cannot pull changes: %s", e.Reason)
|
||||
}
|
||||
return formatError("Failed to pull changes from remote repository. Please check your network connection and resolve any conflicts.")
|
||||
}
|
||||
|
||||
func (e *PullError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
@@ -34,7 +34,7 @@ func (g *Git) Init() error {
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git init failed: %w\nOutput: %s", err, string(output))
|
||||
return &GitInitError{Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
// Set the default branch to main
|
||||
@@ -42,7 +42,7 @@ func (g *Git) Init() error {
|
||||
cmd.Dir = g.repoPath
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("failed to set default branch to main: %w", err)
|
||||
return &BranchSetupError{Err: err}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func (g *Git) AddRemote(name, url string) error {
|
||||
return nil
|
||||
}
|
||||
// Different URL, error
|
||||
return fmt.Errorf("remote %s already exists with different URL: %s (trying to add: %s)", name, existingURL, url)
|
||||
return &RemoteExistsError{Remote: name, ExistingURL: existingURL, NewURL: url}
|
||||
}
|
||||
|
||||
// Remote doesn't exist, add it
|
||||
@@ -69,7 +69,7 @@ func (g *Git) AddRemote(name, url string) error {
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git remote add failed: %w\nOutput: %s", err, string(output))
|
||||
return &GitCommandError{Command: "remote add", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -164,7 +164,7 @@ func (g *Git) Add(filename string) error {
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git add failed: %w\nOutput: %s", err, string(output))
|
||||
return &GitCommandError{Command: "add", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -189,7 +189,7 @@ func (g *Git) Remove(filename string) error {
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git rm failed: %w\nOutput: %s", err, string(output))
|
||||
return &GitCommandError{Command: "rm", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -207,7 +207,7 @@ func (g *Git) Commit(message string) error {
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git commit failed: %w\nOutput: %s", err, string(output))
|
||||
return &GitCommandError{Command: "commit", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -223,7 +223,7 @@ func (g *Git) ensureGitConfig() error {
|
||||
cmd = exec.Command("git", "config", "user.name", "Lnk User")
|
||||
cmd.Dir = g.repoPath
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("failed to set git user.name: %w", err)
|
||||
return &GitConfigError{Setting: "user.name", Err: err}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,7 +235,7 @@ func (g *Git) ensureGitConfig() error {
|
||||
cmd = exec.Command("git", "config", "user.email", "lnk@localhost")
|
||||
cmd.Dir = g.repoPath
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("failed to set git user.email: %w", err)
|
||||
return &GitConfigError{Setting: "user.email", Err: err}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ func (g *Git) GetCommits() ([]string, error) {
|
||||
if strings.Contains(outputStr, "does not have any commits yet") {
|
||||
return []string{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("git log failed: %w", err)
|
||||
return nil, &GitCommandError{Command: "log", Output: outputStr, Err: err}
|
||||
}
|
||||
|
||||
commits := strings.Split(strings.TrimSpace(string(output)), "\n")
|
||||
@@ -282,18 +282,18 @@ func (g *Git) GetRemoteInfo() (string, error) {
|
||||
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to list remotes: %w", err)
|
||||
return "", &GitCommandError{Command: "remote", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
remotes := strings.Split(strings.TrimSpace(string(output)), "\n")
|
||||
if len(remotes) == 0 || remotes[0] == "" {
|
||||
return "", fmt.Errorf("no remote configured")
|
||||
return "", &NoRemoteError{}
|
||||
}
|
||||
|
||||
// Use the first remote
|
||||
url, err = g.getRemoteURL(remotes[0])
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get remote URL: %w", err)
|
||||
return "", &RemoteNotFoundError{Remote: remotes[0], Err: err}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,6 +305,7 @@ type StatusInfo struct {
|
||||
Ahead int
|
||||
Behind int
|
||||
Remote string
|
||||
Dirty bool
|
||||
}
|
||||
|
||||
// GetStatus returns the repository status relative to remote
|
||||
@@ -315,6 +316,12 @@ func (g *Git) GetStatus() (*StatusInfo, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check for uncommitted changes
|
||||
dirty, err := g.HasChanges()
|
||||
if err != nil {
|
||||
return nil, &UncommittedChangesError{Err: err}
|
||||
}
|
||||
|
||||
// Get the remote tracking branch
|
||||
cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")
|
||||
cmd.Dir = g.repoPath
|
||||
@@ -327,6 +334,7 @@ func (g *Git) GetStatus() (*StatusInfo, error) {
|
||||
Ahead: g.getAheadCount(remoteBranch),
|
||||
Behind: 0, // Can't be behind if no upstream
|
||||
Remote: remoteBranch,
|
||||
Dirty: dirty,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -336,6 +344,7 @@ func (g *Git) GetStatus() (*StatusInfo, error) {
|
||||
Ahead: g.getAheadCount(remoteBranch),
|
||||
Behind: g.getBehindCount(remoteBranch),
|
||||
Remote: remoteBranch,
|
||||
Dirty: dirty,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -401,7 +410,7 @@ func (g *Git) HasChanges() (bool, error) {
|
||||
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("git status failed: %w", err)
|
||||
return false, &GitCommandError{Command: "status", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return len(strings.TrimSpace(string(output))) > 0, nil
|
||||
@@ -414,7 +423,7 @@ func (g *Git) AddAll() error {
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git add failed: %w\nOutput: %s", err, string(output))
|
||||
return &GitCommandError{Command: "add", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -425,15 +434,15 @@ func (g *Git) Push() error {
|
||||
// First ensure we have a remote configured
|
||||
_, err := g.GetRemoteInfo()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot push: %w", err)
|
||||
return &PushError{Reason: err.Error(), Err: err}
|
||||
}
|
||||
|
||||
cmd := exec.Command("git", "push", "-u", "origin", "main")
|
||||
cmd := exec.Command("git", "push", "-u", "origin")
|
||||
cmd.Dir = g.repoPath
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git push failed: %w\nOutput: %s", err, string(output))
|
||||
return &PushError{Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -444,15 +453,15 @@ func (g *Git) Pull() error {
|
||||
// First ensure we have a remote configured
|
||||
_, err := g.GetRemoteInfo()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot pull: %w", err)
|
||||
return &PullError{Reason: err.Error(), Err: err}
|
||||
}
|
||||
|
||||
cmd := exec.Command("git", "pull", "origin", "main")
|
||||
cmd := exec.Command("git", "pull", "origin")
|
||||
cmd.Dir = g.repoPath
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git pull failed: %w\nOutput: %s", err, string(output))
|
||||
return &PullError{Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -462,20 +471,20 @@ func (g *Git) Pull() error {
|
||||
func (g *Git) Clone(url string) error {
|
||||
// Remove the directory if it exists to ensure clean clone
|
||||
if err := os.RemoveAll(g.repoPath); err != nil {
|
||||
return fmt.Errorf("failed to remove existing directory: %w", err)
|
||||
return &DirectoryRemovalError{Path: g.repoPath, Err: err}
|
||||
}
|
||||
|
||||
// Create parent directory
|
||||
parentDir := filepath.Dir(g.repoPath)
|
||||
if err := os.MkdirAll(parentDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create parent directory: %w", err)
|
||||
return &DirectoryCreationError{Path: parentDir, Err: err}
|
||||
}
|
||||
|
||||
// Clone the repository
|
||||
cmd := exec.Command("git", "clone", url, g.repoPath)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git clone failed: %w\nOutput: %s", err, string(output))
|
||||
return &GitCommandError{Command: "clone", Output: string(output), Err: err}
|
||||
}
|
||||
|
||||
// Set up upstream tracking for main branch
|
||||
|
Reference in New Issue
Block a user