smartnav.psm1
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# SmartNav.psm1
# Poor man's zoxide for PowerShell - frecency-based smart cd
# DB: JSON at $env:USERPROFILE\.smartnav\dirs.json

$Script:DBPath = "$($env:USERPROFILE)\.smartnav\dirs.json"

# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------

function Initialize-SmartNav {
    $dir = Split-Path $Script:DBPath
    if (-not (Test-Path $dir)) {
        New-Item -Path $dir -ItemType Directory | Out-Null
    }
    if (-not (Test-Path $Script:DBPath)) {
        '[]' | Set-Content $Script:DBPath -Encoding UTF8
    }
}

function Read-NavDB {
    Initialize-SmartNav
    $raw = Get-Content $Script:DBPath -Raw -Encoding UTF8
    if ([string]::IsNullOrWhiteSpace($raw)) { return @() }
    try {
        $parsed = $raw | ConvertFrom-Json
        # ConvertFrom-Json returns a single object when the array has 1 item,
        # so force it to always be an array.
        return @($parsed)
    }
    catch {
        Write-Warning "SmartNav: DB corrupt, resetting. ($($_.Exception.Message))"
        '[]' | Set-Content $Script:DBPath -Encoding UTF8
        return @()
    }
}

function Write-NavDB {
    param([object[]]$Entries)
    $Entries | ConvertTo-Json -Depth 3 | Set-Content $Script:DBPath -Encoding UTF8
}

# Frecency score: combines visit count and how recent the last visit was.
# Returns a float so Sort-Object can rank properly.
function Get-Frecency {
    param(
        [int]$Score,
        [string]$LastAccess   # ISO 8601 string
    )
    try {
        $age = (Get-Date) - [datetime]$LastAccess
        $hoursSince = $age.TotalHours
    }
    catch {
        $hoursSince = 999999
    }

    # Decay buckets (mirrors zoxide's rough weighting)
    $weight = switch ($true) {
        ($hoursSince -lt 1) { 4.0 }
        ($hoursSince -lt 24) { 2.0 }
        ($hoursSince -lt 168) { 0.5 }   # < 1 week
        default { 0.25 }
    }

    return [math]::Round($Score * $weight, 4)
}

# ---------------------------------------------------------------------------
# Public functions
# ---------------------------------------------------------------------------

function Update-NavScore {
    param([string]$Path)

    if ([string]::IsNullOrWhiteSpace($Path)) { return }
    if (-not (Test-Path $Path)) { return }

    $entries = Read-NavDB
    $now = (Get-Date).ToString('o')
    $existing = $entries | Where-Object { $_.path -eq $Path }

    if ($existing) {
        $existing.score = $existing.score + 1
        $existing.last_access = $now
    }
    else {
        $entries += [PSCustomObject]@{
            path        = $Path
            score       = 1
            last_access = $now
        }
    }

    Write-NavDB -Entries $entries
}

function Get-NavMatch {
    param([string]$Query)

    $entries = Read-NavDB
    if ($entries.Count -eq 0) { return $null }

    # 1. Try regex match on path components
    $escaped = [regex]::Escape($Query)
    $matched = $entries | Where-Object {
        try { $_.path -match $escaped }
        catch { $false }
    }

    # 2. Fallback: plain substring (case-insensitive)
    if (-not $matched) {
        $matched = $entries | Where-Object {
            $_.path -like "*$Query*"
        }
    }

    if (-not $matched) { return $null }

    # 3. Sort by frecency, pick best
    $best = $matched |
    ForEach-Object {
        [PSCustomObject]@{
            path     = $_.path
            frecency = Get-Frecency -Score $_.score -LastAccess $_.last_access
        }
    } |
    Sort-Object -Property frecency -Descending |
    Select-Object -First 1

    # 4. Validate the path still exists on disk
    if ($best -and (Test-Path $best.path)) {
        return $best.path
    }

    # 5. Path is stale - remove it and return null
    $cleaned = $entries | Where-Object { $_.path -ne $best.path }
    Write-NavDB -Entries @($cleaned)
    return $null
}

# ---------------------------------------------------------------------------
# cd override
# ---------------------------------------------------------------------------

function cd {
    param(
        [Parameter(Position = 0)]
        [string]$Path
    )

    # No args: go home
    if (-not $Path) {
        Push-Location $env:USERPROFILE
        Update-NavScore $PWD.Path
        return
    }

    # "-": go back
    if ($Path -eq '-') {
        Pop-Location
        Update-NavScore $PWD.Path
        return
    }

    # "~": explicit home
    if ($Path -eq '~') {
        Push-Location $env:USERPROFILE
        Update-NavScore $PWD.Path
        return
    }

    # Actual path: navigate directly
    if (Test-Path $Path) {
        Push-Location $Path
        Update-NavScore $PWD.Path
        return
    }

    # Fuzzy match: search history
    $match = Get-NavMatch $Path
    if ($match) {
        Write-Host "  -> $match" -ForegroundColor DarkGray
        Push-Location $match
        Update-NavScore $PWD.Path
    }
    else {
        Write-Host "No matches for '$Path'" -ForegroundColor Red
    }
}

# ---------------------------------------------------------------------------
# Bonus: list top visited dirs (like zoxide query -l)
# ---------------------------------------------------------------------------

function Get-NavHistory {
    param(
        [int]$Top = 20,
        [string]$Filter = ''
    )

    $entries = Read-NavDB
    if ($entries.Count -eq 0) {
        Write-Host "No history yet." -ForegroundColor DarkGray
        return
    }

    $results = $entries |
    ForEach-Object {
        [PSCustomObject]@{
            frecency = Get-Frecency -Score $_.score -LastAccess $_.last_access
            score    = $_.score
            path     = $_.path
        }
    } |
    Where-Object { $_.path -like "*$Filter*" } |
    Sort-Object -Property frecency -Descending |
    Select-Object -First $Top

    $results | Format-Table -AutoSize
}

# ---------------------------------------------------------------------------
# Exports
# ---------------------------------------------------------------------------

Export-ModuleMember -Function cd, Get-NavHistory, Update-NavScore, Get-NavMatch