mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
fix(wsl-hosts): tighten mapped-drive moves from review
- With an unreadable journal, also block local drive-letter rows (and fence their terminal folders) unless the letter last answered outside WSL. - Journal only the drive letters the exported state names, so UNC-only moves stay journal version 1; at start compare only the drives the scope uses. - Carry "Not moving" reasons through a nothing-to-move refusal so they render. - Share one lookup per drive letter, re-read only letters last known in WSL, and never read a drive from the background prune. - Git-for-Windows gate fails closed (unreadable links, timeout), handles bare and separate-git-dir repos, reads through the share, and words each case. - List projects on an unanswered drive under "Not moving"; pure-render drive cache in the entry hook; reject `..` escapes in file:///W:/ URLs. Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as NodeFs from 'node:fs'
|
||||
import type { Repo } from '../../../shared/repository/repo-types'
|
||||
|
||||
const realpathNative = vi.hoisted(() => vi.fn())
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof NodeFs>()
|
||||
return { ...actual, realpath: Object.assign(actual.realpath, { native: realpathNative }) }
|
||||
})
|
||||
|
||||
import {
|
||||
clearWslMappedDriveShareCacheForTests,
|
||||
readWslMappedDriveShareNow
|
||||
} from '../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import { wslMoveDistroMappedDrivesLastKnown } from './wsl-move-mapped-drive-ports'
|
||||
|
||||
const repo = (id: string, path: string): Repo => ({
|
||||
id,
|
||||
path,
|
||||
displayName: id,
|
||||
badgeColor: '#000',
|
||||
addedAt: 0
|
||||
})
|
||||
const store = {
|
||||
getRepos: () => [repo('w', 'W:\\home\\me\\app')],
|
||||
getFolderWorkspaces: () => []
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
clearWslMappedDriveShareCacheForTests()
|
||||
realpathNative.mockReset()
|
||||
})
|
||||
|
||||
describe('the prune check’s mapped drives', () => {
|
||||
it('never reads a drive, and counts one with no answer yet as in use', () => {
|
||||
expect(wslMoveDistroMappedDrivesLastKnown(store, 'Ubuntu')).toBe('unverifiable')
|
||||
expect(realpathNative).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses the last answer a preview or add already got', async () => {
|
||||
await readWslMappedDriveShareNow('W', {
|
||||
platform: 'win32',
|
||||
realpathRoot: async () => '\\\\wsl.localhost\\Ubuntu\\',
|
||||
now: () => 0,
|
||||
timeoutMs: 50
|
||||
})
|
||||
expect(wslMoveDistroMappedDrivesLastKnown(store, 'Ubuntu')).toEqual([
|
||||
{ letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
])
|
||||
expect(wslMoveDistroMappedDrivesLastKnown(store, 'Debian')).toEqual([])
|
||||
expect(realpathNative).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,38 +1,55 @@
|
||||
/** The move's view of drive letters mapped into a distro: Windows only, read fresh each time. */
|
||||
/** The move's view of drive letters mapped into a distro; Windows only. */
|
||||
import type { Store } from '../../persistence/loading-store/store'
|
||||
import type { WslMoveDriverDeps } from '../../persistence/moving-wsl-projects/execution/wsl-move-driver-ports'
|
||||
import { readWslMoveMappedDrives } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-mapped-drives'
|
||||
import { windowsGitWorktreePaths } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-windows-git-worktrees'
|
||||
import { wslMoveDriveLettersInUse } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-mapped-drives'
|
||||
import { windowsGitWorktreeVerdict } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-windows-git-worktrees'
|
||||
import type { WslMappedDrive } from '../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { readWslMappedDriveShareNow } from '../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import {
|
||||
classifyWslMappedDrive,
|
||||
readWslMappedDriveShareNow,
|
||||
wslMappedDriveLastKnownShare,
|
||||
wslMappedDriveMatches
|
||||
} from '../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
|
||||
export function wslMoveMappedDrivePorts(): Pick<
|
||||
WslMoveDriverDeps,
|
||||
'readMappedDriveShare' | 'windowsGitWorktrees'
|
||||
'driveShares' | 'windowsGitVerdict'
|
||||
> {
|
||||
return process.platform === 'win32'
|
||||
? {
|
||||
readMappedDriveShare: (letter) => readWslMappedDriveShareNow(letter),
|
||||
windowsGitWorktrees: windowsGitWorktreePaths
|
||||
driveShares: {
|
||||
classify: (letter) => classifyWslMappedDrive(letter),
|
||||
readNow: (letter) => readWslMappedDriveShareNow(letter)
|
||||
},
|
||||
windowsGitVerdict: windowsGitWorktreeVerdict
|
||||
}
|
||||
: {}
|
||||
}
|
||||
|
||||
/** For the orchestrator's prune check; absent off Windows, where no drive is mapped. */
|
||||
export function readWslMoveDistroMappedDrives(
|
||||
/**
|
||||
* For the orchestrator's prune check, which runs in the background: last-known answers only, so it
|
||||
* never reads a drive (a mapped share's read can boot its stopped distro). Unknown is in use.
|
||||
*/
|
||||
export function wslMoveDistroMappedDrivesLastKnown(
|
||||
store: Pick<Store, 'getRepos' | 'getFolderWorkspaces'>,
|
||||
distro: string
|
||||
): (() => Promise<readonly WslMappedDrive[] | 'unverifiable'>) | undefined {
|
||||
): readonly WslMappedDrive[] | 'unverifiable' {
|
||||
if (process.platform !== 'win32') {
|
||||
return undefined
|
||||
return []
|
||||
}
|
||||
return async () => {
|
||||
const read = await readWslMoveMappedDrives(
|
||||
{ repos: store.getRepos(), folderWorkspaces: store.getFolderWorkspaces() },
|
||||
distro,
|
||||
(letter) => readWslMappedDriveShareNow(letter)
|
||||
)
|
||||
// Pruning is the cautious side: an unanswered drive may still hold this distro's projects.
|
||||
return read.unverifiableLetters.length === 0 ? read.mappedDrives : 'unverifiable'
|
||||
const letters = wslMoveDriveLettersInUse({
|
||||
repos: store.getRepos(),
|
||||
folderWorkspaces: store.getFolderWorkspaces()
|
||||
})
|
||||
const mapped: WslMappedDrive[] = []
|
||||
for (const letter of letters) {
|
||||
const known = wslMappedDriveLastKnownShare(letter)
|
||||
if (!known) {
|
||||
return 'unverifiable'
|
||||
}
|
||||
if (wslMappedDriveMatches(known.share, distro, undefined)) {
|
||||
mapped.push({ letter, share: known.share })
|
||||
}
|
||||
}
|
||||
return mapped
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import type { Store } from '../../persistence/loading-store/store'
|
||||
import { listWslMoveCutoverChain } from '../../persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal'
|
||||
import { moveProjectsToWslHost } from '../../persistence/moving-wsl-projects/wsl-move-driver'
|
||||
import { previewWslMove } from '../../persistence/moving-wsl-projects/execution/wsl-move-driver-preview'
|
||||
import { readWslMoveDistroMappedDrives } from './wsl-move-mapped-drive-ports'
|
||||
import { wslMoveDistroMappedDrivesLastKnown } from './wsl-move-mapped-drive-ports'
|
||||
import { wslMovedDistroVerdict } from '../../persistence/moving-wsl-projects/quiescence/wsl-move-moved-distro-check'
|
||||
import { WslMoveOrchestrator } from '../../persistence/moving-wsl-projects/wsl-move-orchestrator'
|
||||
import type {
|
||||
@@ -139,11 +139,8 @@ function createOrchestrator(
|
||||
autoMovesBridgeProjects: wslMoveAutoMovesBridgeProjects,
|
||||
prepareHost: (distro, stillWanted) => prepareHost(userDataPath, distro, stillWanted),
|
||||
isDistroInUse: async (distro) =>
|
||||
await isDistroInUse(
|
||||
store,
|
||||
userDataPath,
|
||||
distro,
|
||||
readWslMoveDistroMappedDrives(store, distro)
|
||||
await isDistroInUse(store, userDataPath, distro, () =>
|
||||
wslMoveDistroMappedDrivesLastKnown(store, distro)
|
||||
),
|
||||
hostRemovalPending: async (distro) => await wslHostRemovalPending(userDataPath, distro),
|
||||
hasHost: async (distro) =>
|
||||
|
||||
+50
-7
@@ -35,7 +35,10 @@ vi.mock('../../../telemetry/cohort-classifier', () => ({
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
|
||||
let rig: WslMoveRig
|
||||
// What Windows answers now, and the answer each letter last gave (null: never answered).
|
||||
let shares: Record<string, WslMappedDriveRead>
|
||||
let known: Record<string, string | null>
|
||||
let reads: string[]
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1')
|
||||
@@ -43,7 +46,15 @@ beforeEach(() => {
|
||||
rig = createWslMoveKillRig()
|
||||
rig.world.repos = [{ ...rig.world.repos[0], path: 'W:\\home\\dev\\app' }]
|
||||
shares = { W: { share: W.share } }
|
||||
rig.world.deps.readMappedDriveShare = async (letter) => shares[letter] ?? { share: null }
|
||||
known = { W: W.share }
|
||||
reads = []
|
||||
rig.world.deps.driveShares = {
|
||||
classify: async (letter) => (letter in known ? { share: known[letter] } : null),
|
||||
readNow: async (letter) => {
|
||||
reads.push(letter)
|
||||
return shares[letter] ?? { share: null }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -96,20 +107,30 @@ describe('moving a project saved under a mapped drive', () => {
|
||||
expect(listWslMoveCutovers(rig.userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves out only the projects of a drive that does not answer', async () => {
|
||||
it('lists the projects of a drive that does not answer as not moving, and moves the rest', async () => {
|
||||
// An offline share elsewhere must not block moving the distro's other projects.
|
||||
rig.world.repos = [
|
||||
rig.world.repos[0],
|
||||
{ ...rig.world.repos[0], id: 'repo-s', path: 'S:\\shared\\tool' }
|
||||
]
|
||||
shares = { W: { share: W.share }, S: 'unverifiable' }
|
||||
expect(await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })).toMatchObject({
|
||||
outcome: 'ready',
|
||||
repoIds: ['repo-1'],
|
||||
mappedDrives: [W]
|
||||
mappedDrives: [W],
|
||||
refused: [{ kind: 'repo', id: 'repo-s', reason: 'mapped-drive-unverifiable' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('never reads a drive last known to point outside WSL', async () => {
|
||||
rig.world.repos = [
|
||||
rig.world.repos[0],
|
||||
{ ...rig.world.repos[0], id: 'repo-c', path: 'C:\\src\\site' }
|
||||
]
|
||||
known.C = null
|
||||
await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })
|
||||
expect(reads).toEqual(['W'])
|
||||
})
|
||||
|
||||
it('refuses a start that can no longer read a drive the preview showed', async () => {
|
||||
await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })
|
||||
shares = { W: 'unverifiable' }
|
||||
@@ -123,11 +144,33 @@ describe('moving a project saved under a mapped drive', () => {
|
||||
expect(listWslMoveCutovers(rig.userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('lists a repo with Windows-authored worktrees as not moving', async () => {
|
||||
rig.world.deps.windowsGitWorktrees = async () => ['W:/home/dev/app-trees/x']
|
||||
it('carries why when the only candidate is a repo the host Git cannot take', async () => {
|
||||
rig.world.deps.windowsGitVerdict = async () => 'windows-git-worktrees'
|
||||
expect(await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })).toMatchObject({
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_nothing_new'
|
||||
code: 'wsl_move_nothing_new',
|
||||
refused: [{ kind: 'repo', id: 'repo-1', reason: 'windows-git-worktrees' }]
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('moving UNC projects beside a mapped-drive project', () => {
|
||||
beforeEach(() => {
|
||||
const unc = { ...rig.world.repos[0], path: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\app' }
|
||||
rig.world.repos = [unc, { ...unc, id: 'repo-w', path: 'W:\\home\\dev\\other' }]
|
||||
})
|
||||
|
||||
it('journals no mapping, as version 1, when the moved rows name no mapped drive', async () => {
|
||||
const request = { distro: 'Ubuntu', repoIds: ['repo-1'], folderWorkspaceIds: [] }
|
||||
const preview = await previewWslMove(rig.world.deps, request)
|
||||
expect(preview).toMatchObject({ outcome: 'ready', repoIds: ['repo-1'], mappedDrives: [] })
|
||||
// The unselected W: drive answering differently by now doesn't refuse this start.
|
||||
shares = { W: { share: '\\\\wsl.localhost\\Ubuntu\\home' } }
|
||||
expect(
|
||||
await moveProjectsToWslHost(rig.world.deps, { ...request, mappedDrives: [] })
|
||||
).toMatchObject({ outcome: 'moved' })
|
||||
const [record] = listWslMoveCutovers(rig.userDataPath)
|
||||
expect(record.version).toBe(1)
|
||||
expect(record.mappedDrives).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
} from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import { wslHostsAcceptNewWork } from '../../../wsl/host-lifecycle/wsl-host-gate'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { readWslMoveSourceDrives } from './wsl-move-driver-source-drives'
|
||||
import { journaledWslMoveDrives, readWslMoveSourceDrives } from './wsl-move-driver-source-drives'
|
||||
import { listWslMoveCutoverChain } from '../cutover-recovery/wsl-move-cutover-journal'
|
||||
|
||||
import { type WslMovePlan, planWslMove } from '../manifest-scope/wsl-move-delta-plan'
|
||||
@@ -238,7 +238,7 @@ export async function prepareWslMove(
|
||||
? { repoIds: request.repoIds ?? [], folderWorkspaceIds: request.folderWorkspaceIds ?? [] }
|
||||
: undefined
|
||||
const catalog = deps.readCatalog()
|
||||
const drives = await readWslMoveSourceDrives(deps, catalog, request.distro, expectedMappedDrives)
|
||||
const drives = await readWslMoveSourceDrives(deps, catalog, request, expectedMappedDrives)
|
||||
if ('outcome' in drives) {
|
||||
return drives
|
||||
}
|
||||
@@ -248,13 +248,12 @@ export async function prepareWslMove(
|
||||
request.distro,
|
||||
await host.readHolding(),
|
||||
selection,
|
||||
drives.mappedDrives,
|
||||
drives.windowsGitWorktreeRepoIds
|
||||
drives
|
||||
)
|
||||
if (planned.outcome === 'refused') {
|
||||
return refusal(planned.code)
|
||||
return refusal(planned.code, planned.refused?.length ? { refused: planned.refused } : {})
|
||||
}
|
||||
const { plan } = planned
|
||||
let { plan } = planned
|
||||
// A delta goes to the host its chain already moved into; another host would split the projects.
|
||||
if (plan.destinationEnvironmentId && plan.destinationEnvironmentId !== host.environmentId) {
|
||||
return refusal('wsl_move_host_unavailable', { detail: 'destination_changed' })
|
||||
@@ -266,6 +265,10 @@ export async function prepareWslMove(
|
||||
return refusal('wsl_move_export_incomplete', { reasons: [...exported.blockers] })
|
||||
}
|
||||
assertWslMoveManifestFits(exported.manifest)
|
||||
plan = {
|
||||
...plan,
|
||||
mappedDrives: journaledWslMoveDrives(drives.mappedDrives, exported.mappedDriveLetters)
|
||||
}
|
||||
} catch (error) {
|
||||
const tooLarge = manifestTooLargeRefusal(error)
|
||||
if (tooLarge) {
|
||||
|
||||
@@ -28,7 +28,8 @@ import type {
|
||||
} from '../manifest-scope/wsl-move-manifest-export'
|
||||
import type { WslMoveGateInputs } from '../quiescence/wsl-move-terminal-gate'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type { WslMappedDriveRead } from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import type { WslMoveDriveShares } from '../manifest-scope/wsl-move-mapped-drives'
|
||||
import type { WslMoveWindowsGitVerdict } from '../manifest-scope/wsl-move-windows-git-worktrees'
|
||||
|
||||
/** Throws `WslMoveScopeChangedError` when a planned row is gone: plan again. */
|
||||
export type WslMoveManifestExporter = (
|
||||
@@ -76,10 +77,10 @@ export type WslMoveDriverDeps = {
|
||||
*/
|
||||
isDistroRegistered: (distro: string, distroGuid?: string) => Promise<boolean | null>
|
||||
exportManifest: WslMoveManifestExporter
|
||||
/** What a drive letter maps to right now, uncached; absent off Windows (no drive is mapped). */
|
||||
readMappedDriveShare?: (letter: string) => Promise<WslMappedDriveRead>
|
||||
/** Linked worktrees of a mapped-drive repo whose links Git for Windows wrote. */
|
||||
windowsGitWorktrees?: (repoPath: string, distro: string) => Promise<string[]>
|
||||
/** What drive letters map to; absent off Windows, where no drive is mapped. */
|
||||
driveShares?: WslMoveDriveShares
|
||||
/** Whether the host's Git can take a mapped-drive repo, read through its share path. */
|
||||
windowsGitVerdict?: (readablePath: string, distro: string) => Promise<WslMoveWindowsGitVerdict>
|
||||
/** Busy, working, automation and dispatch facts for the scope, from their owning stores. */
|
||||
gateInputs: (scope: WslMoveTerminalScope) => Promise<WslMoveGateInputs>
|
||||
/** The panes the scope's live terminals belong to; read before Sleep ends their sessions. */
|
||||
|
||||
+66
-33
@@ -1,59 +1,92 @@
|
||||
/**
|
||||
* The mapped drives a move plans with: read fresh at preview, and at start again, refusing when
|
||||
* they differ from what the preview showed (the start request carries them back). With them, the
|
||||
* mapped-drive repos whose worktrees Git for Windows created, which the plan refuses.
|
||||
* the drives the selection names differ from what the preview showed (the start request carries
|
||||
* them back). With them, the mapped-drive repos the host's Git can't take, which the plan refuses.
|
||||
*/
|
||||
import {
|
||||
WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL,
|
||||
type WslMoveRefusal
|
||||
type WslMoveRefusal,
|
||||
type WslMoveRequest
|
||||
} from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
import {
|
||||
sameWslMappedDrives,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { readWslMoveMappedDrives } from '../manifest-scope/wsl-move-mapped-drives'
|
||||
import { findWindowsGitWorktreeRepoIds } from '../manifest-scope/wsl-move-windows-git-worktrees'
|
||||
import {
|
||||
readWslMoveMappedDrives,
|
||||
wslMoveDriveLettersInUse
|
||||
} from '../manifest-scope/wsl-move-mapped-drives'
|
||||
import type { WslMoveScopeDrives, WslMoveScopeRefusal } from '../manifest-scope/wsl-move-scope'
|
||||
import { findWindowsGitRefusals } from '../manifest-scope/wsl-move-windows-git-worktrees'
|
||||
import type { WslMoveCatalogRows, WslMoveDriverDeps } from './wsl-move-driver-ports'
|
||||
|
||||
export type WslMoveSourceDrives = {
|
||||
export type WslMoveSourceDrives = Required<WslMoveScopeDrives> & {
|
||||
mappedDrives: WslMappedDrive[]
|
||||
windowsGitWorktreeRepoIds: ReadonlySet<string>
|
||||
windowsGitRefusals: ReadonlyMap<string, WslMoveScopeRefusal>
|
||||
}
|
||||
|
||||
/** The letters the request's rows name; every local row's when it names none. */
|
||||
function requestedLetters(
|
||||
catalog: WslMoveCatalogRows,
|
||||
request: Pick<WslMoveRequest, 'repoIds' | 'folderWorkspaceIds'>
|
||||
): string[] {
|
||||
const whole = !request.repoIds && !request.folderWorkspaceIds
|
||||
return wslMoveDriveLettersInUse({
|
||||
repos: catalog.repos.filter((repo) => whole || request.repoIds?.includes(repo.id)),
|
||||
folderWorkspaces: catalog.folderWorkspaces.filter(
|
||||
(folder) => whole || request.folderWorkspaceIds?.includes(folder.id)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export async function readWslMoveSourceDrives(
|
||||
deps: Pick<WslMoveDriverDeps, 'readMappedDriveShare' | 'windowsGitWorktrees'>,
|
||||
deps: Pick<WslMoveDriverDeps, 'driveShares' | 'windowsGitVerdict'>,
|
||||
catalog: WslMoveCatalogRows,
|
||||
distro: string,
|
||||
request: WslMoveRequest,
|
||||
/** At start: the drives the preview showed. Null for a preview. */
|
||||
expected: readonly WslMappedDrive[] | null
|
||||
): Promise<WslMoveSourceDrives | WslMoveRefusal> {
|
||||
const read = deps.readMappedDriveShare
|
||||
? await readWslMoveMappedDrives(catalog, distro, deps.readMappedDriveShare)
|
||||
const read = deps.driveShares
|
||||
? await readWslMoveMappedDrives(catalog, request.distro, deps.driveShares)
|
||||
: { mappedDrives: [], unverifiableLetters: [] }
|
||||
// A drive that doesn't answer (an offline network share, say) only keeps its own projects out;
|
||||
// a start loses a drive the preview showed, so it refuses rather than move without it.
|
||||
const lostLetters = (expected ?? []).filter((drive) =>
|
||||
read.unverifiableLetters.includes(drive.letter.toUpperCase())
|
||||
)
|
||||
if (lostLetters.length > 0) {
|
||||
return {
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_unavailable',
|
||||
detail: WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL
|
||||
if (expected) {
|
||||
// Only drives this selection names count: an unrelated W: never stops a UNC-only start.
|
||||
const relevant = new Set([
|
||||
...expected.map((drive) => drive.letter.toUpperCase()),
|
||||
...requestedLetters(catalog, request)
|
||||
])
|
||||
if (read.unverifiableLetters.some((letter) => relevant.has(letter))) {
|
||||
return {
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_unavailable',
|
||||
detail: WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL
|
||||
}
|
||||
}
|
||||
const fresh = read.mappedDrives.filter((drive) => relevant.has(drive.letter.toUpperCase()))
|
||||
if (!sameWslMappedDrives(expected, fresh)) {
|
||||
return { outcome: 'refused', code: 'wsl_move_scope_changed', detail: 'mapped-drives-changed' }
|
||||
}
|
||||
}
|
||||
const { mappedDrives } = read
|
||||
if (expected && !sameWslMappedDrives(expected, mappedDrives)) {
|
||||
return { outcome: 'refused', code: 'wsl_move_scope_changed', detail: 'mapped-drives-changed' }
|
||||
}
|
||||
const windowsGitWorktreeRepoIds =
|
||||
deps.windowsGitWorktrees && mappedDrives.length > 0
|
||||
? await findWindowsGitWorktreeRepoIds(
|
||||
const windowsGitRefusals =
|
||||
deps.windowsGitVerdict && read.mappedDrives.length > 0
|
||||
? await findWindowsGitRefusals(
|
||||
catalog.repos,
|
||||
distro,
|
||||
mappedDrives,
|
||||
deps.windowsGitWorktrees
|
||||
request.distro,
|
||||
read.mappedDrives,
|
||||
deps.windowsGitVerdict
|
||||
)
|
||||
: new Set<string>()
|
||||
return { mappedDrives, windowsGitWorktreeRepoIds }
|
||||
: new Map<string, WslMoveScopeRefusal>()
|
||||
return { ...read, windowsGitRefusals }
|
||||
}
|
||||
|
||||
/** The drives a move journals: only those its exported paths named, so a UNC move stays v1. */
|
||||
export function journaledWslMoveDrives(
|
||||
mappedDrives: readonly WslMappedDrive[],
|
||||
exportedLetters: readonly string[] | undefined
|
||||
): WslMappedDrive[] {
|
||||
if (!exportedLetters) {
|
||||
return [...mappedDrives]
|
||||
}
|
||||
const named = new Set(exportedLetters)
|
||||
return mappedDrives.filter((drive) => named.has(drive.letter.toUpperCase()))
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
wslMoveTakenRowIdentity,
|
||||
type WslMoveRowRef
|
||||
} from '../cutover-recovery/wsl-move-retained-source'
|
||||
import { collectWslMoveScope, type WslMoveScope } from './wsl-move-scope'
|
||||
import { collectWslMoveScope, type WslMoveScope, type WslMoveScopeDrives } from './wsl-move-scope'
|
||||
import { isLocalWslMoveRow } from '../quiescence/wsl-move-scope-guard'
|
||||
|
||||
type WslMovePlanState = {
|
||||
@@ -80,7 +80,7 @@ export type WslMovePlan = {
|
||||
|
||||
export type WslMovePlanResult =
|
||||
| { outcome: 'ready'; plan: WslMovePlan }
|
||||
| { outcome: 'refused'; code: WslMovePlanRefusal }
|
||||
| { outcome: 'refused'; code: WslMovePlanRefusal; refused?: WslMoveScope['refused'] }
|
||||
|
||||
const COMMITTED_FROM = WSL_MOVE_CUTOVER_PHASES.indexOf('destination-committed')
|
||||
|
||||
@@ -100,8 +100,7 @@ export function planWslMove(
|
||||
host: WslMoveHostHolding,
|
||||
/** The projects the user ticked; absent means the whole distro. */
|
||||
selection?: { repoIds: readonly string[]; folderWorkspaceIds: readonly string[] },
|
||||
mappedDrives: readonly WslMappedDrive[] = [],
|
||||
windowsGitWorktreeRepoIds: ReadonlySet<string> = new Set()
|
||||
drives: WslMoveScopeDrives = {}
|
||||
): WslMovePlanResult {
|
||||
const journalKey = wslMoveJournalKey(distro)
|
||||
const chain = listWslMoveCutoverChain(userDataPath, journalKey)
|
||||
@@ -127,7 +126,7 @@ export function planWslMove(
|
||||
.flatMap((cutover) => wslMoveScopeRefs(cutover).map(wslMoveRowKey))
|
||||
)
|
||||
const held = new Set(refsOf(host).map(wslMoveRowKey))
|
||||
const scope = collectWslMoveScope(state, distro, mappedDrives, windowsGitWorktreeRepoIds)
|
||||
const scope = collectWslMoveScope(state, distro, drives)
|
||||
const selected = (ref: WslMoveRowRef): boolean =>
|
||||
!selection ||
|
||||
(ref.kind === 'repo' ? selection.repoIds : selection.folderWorkspaceIds).includes(ref.id)
|
||||
@@ -154,7 +153,9 @@ export function planWslMove(
|
||||
let keys = ownerScopes.get(owner.migrationId)
|
||||
if (!keys) {
|
||||
keys = new Set(
|
||||
refsOf(collectWslMoveScope(state, distro, owner.mappedDrives)).map(wslMoveRowKey)
|
||||
refsOf(collectWslMoveScope(state, distro, { mappedDrives: owner.mappedDrives })).map(
|
||||
wslMoveRowKey
|
||||
)
|
||||
)
|
||||
ownerScopes.set(owner.migrationId, keys)
|
||||
}
|
||||
@@ -191,7 +192,8 @@ export function planWslMove(
|
||||
}
|
||||
}
|
||||
if (fresh.length === 0) {
|
||||
return { outcome: 'refused', code: 'wsl_move_nothing_new' }
|
||||
// The reasons go along, or "already on the host" would hide why nothing can move.
|
||||
return { outcome: 'refused', code: 'wsl_move_nothing_new', refused: scope.refused }
|
||||
}
|
||||
return {
|
||||
outcome: 'ready',
|
||||
@@ -212,7 +214,7 @@ export function planWslMove(
|
||||
removed,
|
||||
heldByHost,
|
||||
refused: scope.refused,
|
||||
mappedDrives: mappedDrives.map((drive) => ({ ...drive }))
|
||||
mappedDrives: (drives.mappedDrives ?? []).map((drive) => ({ ...drive }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,6 +74,8 @@ export type WslMoveManifestExport = {
|
||||
worktrees: { sourceWorktreeId: string; destinationWorktreeId: string }[]
|
||||
/** Moved disabled (the wire carries no enabled automation); re-enable on the host after commit. */
|
||||
automationsToReenable: string[]
|
||||
/** The mapped drive letters the export's paths named: the only ones the move journals. */
|
||||
mappedDriveLetters?: string[]
|
||||
}
|
||||
|
||||
/** The plan names a project or folder that is no longer a local row of this distro. */
|
||||
@@ -170,7 +172,10 @@ export function exportWslMoveManifest(
|
||||
const dormantState = workspaceSession
|
||||
? { ...inspection.payload, workspaceSession }
|
||||
: inspection.payload
|
||||
const rewriter = createUncToLinuxPathRewriter(request.distro, request.mappedDrives)
|
||||
const usedLetters = new Set<string>()
|
||||
const rewriter = createUncToLinuxPathRewriter(request.distro, request.mappedDrives, (letter) =>
|
||||
usedLetters.add(letter)
|
||||
)
|
||||
const payload = rewriteOrcadMigrationPayloadPaths(
|
||||
{ ...catalog, ...(hasDormantState(dormantState) ? { dormantState } : {}) },
|
||||
rewriter
|
||||
@@ -215,7 +220,8 @@ export function exportWslMoveManifest(
|
||||
sourceWorktreeId,
|
||||
destinationWorktreeId: rewriteOrcadMigrationWorktreeId(sourceWorktreeId, rewriter)
|
||||
})),
|
||||
automationsToReenable: inspection.automationsEnabledAtSource
|
||||
automationsToReenable: inspection.automationsEnabledAtSource,
|
||||
mappedDriveLetters: [...usedLetters].sort()
|
||||
}
|
||||
|
||||
function isLocalRepo(repo: Repo): boolean {
|
||||
|
||||
+18
-6
@@ -49,7 +49,7 @@ describe('collectWslMoveScope with mapped drives', () => {
|
||||
}
|
||||
|
||||
it('takes local W: projects with the mapping and ignores them without it', () => {
|
||||
expect(collectWslMoveScope(state, 'Ubuntu', [W])).toEqual({
|
||||
expect(collectWslMoveScope(state, 'Ubuntu', { mappedDrives: [W] })).toEqual({
|
||||
repoIds: ['app'],
|
||||
folderWorkspaceIds: ['notes'],
|
||||
refused: [{ kind: 'repo', id: 'drvfs', reason: 'windows-drive' }]
|
||||
@@ -61,11 +61,23 @@ describe('collectWslMoveScope with mapped drives', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a mapped-drive repo with worktrees Git for Windows created', () => {
|
||||
expect(collectWslMoveScope(state, 'Ubuntu', [W], new Set(['app'])).refused).toContainEqual({
|
||||
kind: 'repo',
|
||||
id: 'app',
|
||||
reason: 'windows-git-worktrees'
|
||||
it('refuses a mapped-drive repo the host Git cannot take, with its reason', () => {
|
||||
const scope = collectWslMoveScope(state, 'Ubuntu', {
|
||||
mappedDrives: [W],
|
||||
windowsGitRefusals: new Map([['app', 'windows-git-dir' as const]])
|
||||
})
|
||||
expect(scope.refused).toContainEqual({ kind: 'repo', id: 'app', reason: 'windows-git-dir' })
|
||||
})
|
||||
|
||||
it('lists local projects of a drive that did not answer instead of dropping them', () => {
|
||||
expect(collectWslMoveScope(state, 'Ubuntu', { unverifiableLetters: ['W'] })).toEqual({
|
||||
repoIds: [],
|
||||
folderWorkspaceIds: [],
|
||||
refused: [
|
||||
{ kind: 'repo', id: 'app', reason: 'mapped-drive-unverifiable' },
|
||||
{ kind: 'repo', id: 'drvfs', reason: 'mapped-drive-unverifiable' },
|
||||
{ kind: 'folder-workspace', id: 'notes', reason: 'mapped-drive-unverifiable' }
|
||||
]
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* The drive letters mapped into a distro (`net use W: \\wsl.localhost\Ubuntu`) that local
|
||||
* projects are saved under. Read fresh at preview and again at start, never from a cache: the
|
||||
* move journals this mapping, and every recovery maps the moved paths with it.
|
||||
* projects are saved under. Only a letter last known to map into WSL is read again, fresh, for
|
||||
* each preview and start; C:, D: or another network share is never touched after it is known.
|
||||
*/
|
||||
import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types'
|
||||
import { parseWslUncPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import {
|
||||
@@ -13,14 +14,25 @@ import {
|
||||
import { isLocalWslMoveRow } from '../quiescence/wsl-move-scope-guard'
|
||||
import { wslMoveRepoPaths } from './wsl-move-scope'
|
||||
|
||||
export type WslMoveDriveShares = {
|
||||
/** The letter's last known share; an unknown letter gets one bounded, cached lookup. */
|
||||
classify: (letter: string) => Promise<{ share: string | null } | null>
|
||||
/** Fresh from Windows, bounded; concurrent reads of a letter share one lookup. */
|
||||
readNow: (letter: string) => Promise<WslMappedDriveRead>
|
||||
}
|
||||
|
||||
export type WslMoveMappedDrivesRead = {
|
||||
mappedDrives: WslMappedDrive[]
|
||||
/** Windows did not answer for these letters, which local projects use. */
|
||||
/** Letters local projects use that may map into this distro, but Windows did not answer for. */
|
||||
unverifiableLetters: string[]
|
||||
}
|
||||
|
||||
const DRIVE_PATH = /^([A-Za-z]):[\\/]/
|
||||
|
||||
export function wslMoveDriveLetterOf(path: string): string | null {
|
||||
return DRIVE_PATH.exec(path)?.[1].toUpperCase() ?? null
|
||||
}
|
||||
|
||||
/** The distinct drive letters, uppercase, every path the move's scope reads names. */
|
||||
export function wslMoveDriveLettersInUse(rows: {
|
||||
repos: readonly Repo[]
|
||||
@@ -30,29 +42,49 @@ export function wslMoveDriveLettersInUse(rows: {
|
||||
...rows.repos.filter(isLocalWslMoveRow).flatMap((repo) => wslMoveRepoPaths(repo)),
|
||||
...rows.folderWorkspaces.filter(isLocalWslMoveRow).map((folder) => folder.folderPath)
|
||||
]
|
||||
const letters = new Set(paths.flatMap((path) => DRIVE_PATH.exec(path)?.[1].toUpperCase() ?? []))
|
||||
const letters = new Set(paths.flatMap((path) => wslMoveDriveLetterOf(path) ?? []))
|
||||
return [...letters].sort()
|
||||
}
|
||||
|
||||
type LetterRead = { mapped: WslMappedDrive } | 'unverifiable' | 'elsewhere'
|
||||
|
||||
async function readLetter(
|
||||
letter: string,
|
||||
distro: string,
|
||||
shares: WslMoveDriveShares
|
||||
): Promise<LetterRead> {
|
||||
const known = await shares.classify(letter).catch(() => null)
|
||||
if (known === null) {
|
||||
return 'unverifiable'
|
||||
}
|
||||
if (known.share === null || !parseWslUncPath(known.share)) {
|
||||
return 'elsewhere'
|
||||
}
|
||||
const read = await shares.readNow(letter).catch((): WslMappedDriveRead => 'unverifiable')
|
||||
if (read === 'unverifiable') {
|
||||
// Last known in another distro: its projects aren't this move's to list.
|
||||
return wslMappedDriveMatches(known.share, distro, undefined) ? 'unverifiable' : 'elsewhere'
|
||||
}
|
||||
return wslMappedDriveMatches(read.share, distro, undefined)
|
||||
? { mapped: { letter, share: read.share } }
|
||||
: 'elsewhere'
|
||||
}
|
||||
|
||||
export async function readWslMoveMappedDrives(
|
||||
rows: { repos: readonly Repo[]; folderWorkspaces: readonly FolderWorkspace[] },
|
||||
distro: string,
|
||||
readShare: (letter: string) => Promise<WslMappedDriveRead>
|
||||
shares: WslMoveDriveShares
|
||||
): Promise<WslMoveMappedDrivesRead> {
|
||||
const letters = wslMoveDriveLettersInUse(rows)
|
||||
const reads = await Promise.all(
|
||||
letters.map(async (letter) => ({
|
||||
letter,
|
||||
read: await readShare(letter).catch((): WslMappedDriveRead => 'unverifiable')
|
||||
}))
|
||||
letters.map(async (letter) => ({ letter, read: await readLetter(letter, distro, shares) }))
|
||||
)
|
||||
const unverifiableLetters = reads
|
||||
.filter(({ read }) => read === 'unverifiable')
|
||||
.map(({ letter }) => letter)
|
||||
const mappedDrives = reads.flatMap(({ letter, read }) =>
|
||||
read !== 'unverifiable' && wslMappedDriveMatches(read.share, distro, undefined)
|
||||
? [{ letter, share: read.share }]
|
||||
: []
|
||||
)
|
||||
return { mappedDrives, unverifiableLetters }
|
||||
return {
|
||||
mappedDrives: reads.flatMap(({ read }) =>
|
||||
typeof read === 'object' ? [{ ...read.mapped }] : []
|
||||
),
|
||||
unverifiableLetters: reads
|
||||
.filter(({ read }) => read === 'unverifiable')
|
||||
.map(({ letter }) => letter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,20 @@ import type { OrcadMigrationPathRewriter } from '../../migrating-orcad-catalog/p
|
||||
|
||||
export function createUncToLinuxPathRewriter(
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
mappedDrives: readonly WslMappedDrive[] = [],
|
||||
/** Told each drive letter a rewrite mapped, so a move journals only the drives it names. */
|
||||
onMappedDrive?: (letter: string) => void
|
||||
): OrcadMigrationPathRewriter {
|
||||
const fileUrl = new RegExp(`^file://(?:wsl\\.localhost|wsl\\$)/([^/]+)(/.*)?$`, 'i')
|
||||
const noted = (value: string, mapped: string | null): string | null => {
|
||||
const letter = mapped === null ? null : DRIVE_LETTER.exec(value)?.[1]
|
||||
if (letter) {
|
||||
onMappedDrive?.(letter.toUpperCase())
|
||||
}
|
||||
return mapped
|
||||
}
|
||||
const toLinux = (value: string): string | null =>
|
||||
wslMoveSourcePathToLinux(value, distro, mappedDrives)
|
||||
noted(value, wslMoveSourcePathToLinux(value, distro, mappedDrives))
|
||||
return {
|
||||
path: (value, form) => {
|
||||
switch (form) {
|
||||
@@ -27,13 +36,16 @@ export function createUncToLinuxPathRewriter(
|
||||
if (match && decodeSegment(match[1]).toLowerCase() === distro.toLowerCase()) {
|
||||
return `file://${match[2] ?? '/'}`
|
||||
}
|
||||
return wslMappedDriveFileUrlToLinux(value, distro, mappedDrives) ?? value
|
||||
return noted(value, wslMappedDriveFileUrlToLinux(value, distro, mappedDrives)) ?? value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A drive path (`W:\x`) or drive file URL (`file:///W:/x`); UNC paths name no letter.
|
||||
const DRIVE_LETTER = /^(?:file:\/\/\/)?([A-Za-z]):[\\/]/i
|
||||
|
||||
// Relative Windows paths need host-side POSIX separators.
|
||||
function toPosix(value: string): string {
|
||||
return value.replace(/\\/g, '/')
|
||||
|
||||
@@ -20,8 +20,23 @@ export type WslMoveScopeRefusal =
|
||||
| 'windows-drive'
|
||||
| 'mixed-locations'
|
||||
| 'not-local'
|
||||
/** Linked worktrees Git for Windows created: the host's Git can't follow their links. */
|
||||
/** Worktree records Git for Windows wrote: the host's Git can't follow their links. */
|
||||
| 'windows-git-worktrees'
|
||||
/** Its own `.git` file names a Windows path (a worktree or separate Git folder). */
|
||||
| 'windows-git-dir'
|
||||
/** Its Git records couldn't be read in time, so they couldn't be checked. */
|
||||
| 'git-unreadable'
|
||||
/** Windows didn't say where its drive letter points just now. */
|
||||
| 'mapped-drive-unverifiable'
|
||||
|
||||
/** What the move learned about mapped drives before scoping. */
|
||||
export type WslMoveScopeDrives = {
|
||||
mappedDrives?: readonly WslMappedDrive[]
|
||||
/** Mapped-drive repos the host's Git can't take (wsl-move-windows-git-worktrees). */
|
||||
windowsGitRefusals?: ReadonlyMap<string, WslMoveScopeRefusal>
|
||||
/** Letters Windows didn't answer for that may map into this distro. */
|
||||
unverifiableLetters?: readonly string[]
|
||||
}
|
||||
|
||||
export type WslMoveScope = {
|
||||
repoIds: string[]
|
||||
@@ -38,22 +53,29 @@ type WslMoveScopeState = {
|
||||
export function collectWslMoveScope(
|
||||
state: WslMoveScopeState,
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = [],
|
||||
/** Mapped-drive repos with worktrees Git for Windows created (wsl-move-windows-git-worktrees). */
|
||||
windowsGitWorktreeRepoIds: ReadonlySet<string> = new Set()
|
||||
drives: WslMoveScopeDrives = {}
|
||||
): WslMoveScope {
|
||||
const scope: WslMoveScope = { repoIds: [], folderWorkspaceIds: [], refused: [] }
|
||||
const mappedDrives = drives.mappedDrives ?? []
|
||||
const toLinux = (path: string): string | null =>
|
||||
wslMoveSourcePathToLinux(path, distro, mappedDrives)
|
||||
// Listed, not dropped: the drive may well map here, so the user should check it again.
|
||||
const unverifiable = (path: string): boolean =>
|
||||
drives.unverifiableLetters?.includes(/^([A-Za-z]):[\\/]/.exec(path)?.[1].toUpperCase() ?? '') ??
|
||||
false
|
||||
for (const repo of state.repos) {
|
||||
const paths = wslMoveMappedRepoPaths(repo, mappedDrives)
|
||||
const local = getRepoExecutionHostId(repo) === 'local'
|
||||
if (local && unverifiable(repo.path)) {
|
||||
scope.refused.push({ kind: 'repo', id: repo.id, reason: 'mapped-drive-unverifiable' })
|
||||
continue
|
||||
}
|
||||
// Partly in-distro repos must refuse visibly rather than disappear from the preview.
|
||||
if (!paths.some((path) => toLinux(path) !== null)) {
|
||||
continue
|
||||
}
|
||||
const reason =
|
||||
refusalFor(paths, toLinux, getRepoExecutionHostId(repo) !== 'local') ??
|
||||
(windowsGitWorktreeRepoIds.has(repo.id) ? 'windows-git-worktrees' : null)
|
||||
refusalFor(paths, toLinux, !local) ?? drives.windowsGitRefusals?.get(repo.id) ?? null
|
||||
if (reason) {
|
||||
scope.refused.push({ kind: 'repo', id: repo.id, reason })
|
||||
} else {
|
||||
@@ -65,14 +87,16 @@ export function collectWslMoveScope(
|
||||
projectGroups: [...state.projectGroups]
|
||||
}
|
||||
for (const workspace of state.folderWorkspaces) {
|
||||
if (toLinux(workspace.folderPath) === null) {
|
||||
continue
|
||||
}
|
||||
// Isolate this row: other hosts may reuse the same folder ID.
|
||||
const remote =
|
||||
resolveFolderWorkspaceHost({ ...hostState, folderWorkspaces: [workspace] }, workspace.id)
|
||||
.kind !== 'local'
|
||||
const reason = refusalFor([workspace.folderPath], toLinux, remote)
|
||||
if (toLinux(workspace.folderPath) === null && (remote || !unverifiable(workspace.folderPath))) {
|
||||
continue
|
||||
}
|
||||
const reason = unverifiable(workspace.folderPath)
|
||||
? 'mapped-drive-unverifiable'
|
||||
: refusalFor([workspace.folderPath], toLinux, remote)
|
||||
if (reason) {
|
||||
scope.refused.push({ kind: 'folder-workspace', id: workspace.id, reason })
|
||||
} else {
|
||||
|
||||
+60
-29
@@ -3,10 +3,7 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import {
|
||||
findWindowsGitWorktreeRepoIds,
|
||||
windowsGitWorktreePaths
|
||||
} from './wsl-move-windows-git-worktrees'
|
||||
import { findWindowsGitRefusals, windowsGitWorktreeVerdict } from './wsl-move-windows-git-worktrees'
|
||||
|
||||
let root: string
|
||||
beforeEach(() => {
|
||||
@@ -16,36 +13,59 @@ afterEach(() => {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function worktreeLink(repo: string, name: string, link: string): void {
|
||||
const entry = join(repo, '.git', 'worktrees', name)
|
||||
mkdirSync(entry, { recursive: true })
|
||||
writeFileSync(join(entry, 'gitdir'), `${link}\n`)
|
||||
function write(path: string, text: string): void {
|
||||
mkdirSync(join(path, '..'), { recursive: true })
|
||||
writeFileSync(path, text)
|
||||
}
|
||||
|
||||
describe('windowsGitWorktreePaths', () => {
|
||||
it('names the worktrees whose links Git for Windows wrote', async () => {
|
||||
const verdict = (path: string) => windowsGitWorktreeVerdict(path, 'Ubuntu')
|
||||
|
||||
describe('windowsGitWorktreeVerdict', () => {
|
||||
it('refuses worktree records Git for Windows wrote, stale ones included', async () => {
|
||||
const repo = join(root, 'app')
|
||||
worktreeLink(repo, 'win', 'W:/home/me/app-trees/win/.git')
|
||||
worktreeLink(repo, 'linux', '/home/me/app-trees/linux/.git')
|
||||
expect(await windowsGitWorktreePaths(repo, 'Ubuntu')).toEqual(['W:/home/me/app-trees/win'])
|
||||
write(join(repo, '.git', 'worktrees', 'linux', 'gitdir'), '/home/me/trees/linux/.git\n')
|
||||
expect(await verdict(repo)).toBe('ok')
|
||||
write(join(repo, '.git', 'worktrees', 'gone', 'gitdir'), 'W:/home/me/trees/gone/.git\n')
|
||||
expect(await verdict(repo)).toBe('windows-git-worktrees')
|
||||
})
|
||||
|
||||
it('names a repo that is itself a worktree Git for Windows created', async () => {
|
||||
const repo = join(root, 'tree')
|
||||
mkdirSync(repo)
|
||||
writeFileSync(join(repo, '.git'), 'gitdir: W:/home/me/app/.git/worktrees/tree\n')
|
||||
expect(await windowsGitWorktreePaths(repo, 'Ubuntu')).toEqual([repo])
|
||||
it('checks a bare repo through its own records', async () => {
|
||||
const bare = join(root, 'bare.git')
|
||||
write(join(bare, 'HEAD'), 'ref: refs/heads/main\n')
|
||||
mkdirSync(join(bare, 'objects'))
|
||||
write(join(bare, 'worktrees', 'x', 'gitdir'), 'W:/home/me/x/.git\n')
|
||||
expect(await verdict(bare)).toBe('windows-git-worktrees')
|
||||
})
|
||||
|
||||
it('finds none for a folder outside Git or a repo with Linux-only links', async () => {
|
||||
expect(await windowsGitWorktreePaths(join(root, 'none'), 'Ubuntu')).toEqual([])
|
||||
const repo = join(root, 'linux')
|
||||
worktreeLink(repo, 'a', '/home/me/a/.git')
|
||||
expect(await windowsGitWorktreePaths(repo, 'Ubuntu')).toEqual([])
|
||||
it('refuses a `.git` file that names a Windows path, a worktree or a separate Git folder', async () => {
|
||||
const tree = join(root, 'tree')
|
||||
write(join(tree, '.git'), 'gitdir: W:/home/me/app/.git/worktrees/tree\n')
|
||||
expect(await verdict(tree)).toBe('windows-git-dir')
|
||||
})
|
||||
|
||||
it('follows a separate Git folder with no `commondir` to its own records', async () => {
|
||||
const repo = join(root, 'separate')
|
||||
write(join(repo, '.git'), 'gitdir: ../store.git\n')
|
||||
write(join(root, 'store.git', 'worktrees', 'x', 'gitdir'), 'W:/home/me/x/.git\n')
|
||||
expect(await verdict(repo)).toBe('windows-git-worktrees')
|
||||
})
|
||||
|
||||
it('fails closed on records it cannot read; only a folder outside Git passes', async () => {
|
||||
expect(await verdict(join(root, 'plain'))).toBe('ok')
|
||||
const gitdirDir = join(root, 'a')
|
||||
mkdirSync(join(gitdirDir, '.git', 'worktrees', 'x', 'gitdir'), { recursive: true })
|
||||
await expect(verdict(gitdirDir)).rejects.toThrow()
|
||||
const commonDirDir = join(root, 'b')
|
||||
write(join(commonDirDir, '.git'), 'gitdir: ../bgit\n')
|
||||
mkdirSync(join(root, 'bgit', 'commondir'), { recursive: true })
|
||||
await expect(verdict(commonDirDir)).rejects.toThrow()
|
||||
const worktreesFile = join(root, 'c')
|
||||
write(join(worktreesFile, '.git', 'worktrees'), 'not a folder')
|
||||
await expect(verdict(worktreesFile)).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('findWindowsGitWorktreeRepoIds', () => {
|
||||
describe('findWindowsGitRefusals', () => {
|
||||
const repo = (id: string, path: string): Repo => ({
|
||||
id,
|
||||
path,
|
||||
@@ -55,13 +75,14 @@ describe('findWindowsGitWorktreeRepoIds', () => {
|
||||
})
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
|
||||
it('checks only mapped-drive repos, and fails closed on an unreadable one', async () => {
|
||||
it('reads mapped-drive repos through the share, failing closed on errors and timeouts', async () => {
|
||||
const checked: string[] = []
|
||||
const ids = await findWindowsGitWorktreeRepoIds(
|
||||
const refusals = await findWindowsGitRefusals(
|
||||
[
|
||||
repo('win', 'W:\\home\\me\\win'),
|
||||
repo('clean', 'W:\\home\\me\\clean'),
|
||||
repo('broken', 'W:\\home\\me\\broken'),
|
||||
repo('hung', 'W:\\home\\me\\hung'),
|
||||
repo('unc', '\\\\wsl.localhost\\Ubuntu\\home\\me\\unc')
|
||||
],
|
||||
'Ubuntu',
|
||||
@@ -71,10 +92,20 @@ describe('findWindowsGitWorktreeRepoIds', () => {
|
||||
if (path.endsWith('broken')) {
|
||||
throw new Error('EACCES')
|
||||
}
|
||||
return path.endsWith('win') ? ['W:/home/me/win-tree'] : []
|
||||
}
|
||||
if (path.endsWith('hung')) {
|
||||
return new Promise(() => {})
|
||||
}
|
||||
return path.endsWith('win') ? 'windows-git-worktrees' : 'ok'
|
||||
},
|
||||
20
|
||||
)
|
||||
expect([...ids].sort()).toEqual(['broken', 'win'])
|
||||
expect(Object.fromEntries(refusals)).toEqual({
|
||||
win: 'windows-git-worktrees',
|
||||
broken: 'git-unreadable',
|
||||
hung: 'git-unreadable'
|
||||
})
|
||||
expect(checked).toContain('\\\\wsl.localhost\\Ubuntu\\home\\me\\win')
|
||||
expect(checked.some((path) => path.startsWith('W:'))).toBe(false)
|
||||
expect(checked).not.toContain('\\\\wsl.localhost\\Ubuntu\\home\\me\\unc')
|
||||
})
|
||||
})
|
||||
|
||||
+129
-56
@@ -1,80 +1,153 @@
|
||||
/**
|
||||
* A repo saved under a mapped drive may have linked worktrees Git for Windows created: their
|
||||
* `.git` files and `.git/worktrees/<name>/gitdir` links hold `W:/…` paths. The host's Linux Git
|
||||
* can't follow those, and its `git worktree prune` would delete their metadata, so such a repo
|
||||
* stays here (the opposite of wsl-drive-project-windows-git's `wsl-authored-worktrees`).
|
||||
* A repo saved under a mapped drive usually runs Git for Windows, so its linked worktrees' links
|
||||
* (`.git` files, `.git/worktrees/<name>/gitdir`) hold `W:/…` paths. The host's Linux Git can't
|
||||
* follow those, and its `git worktree prune` would delete their records, so such a repo stays here
|
||||
* (the opposite of wsl-drive-project-windows-git's `wsl-authored-worktrees`). Fails closed: only a
|
||||
* folder with no Git at all passes without reading its records.
|
||||
*/
|
||||
import { readFile, stat } from 'node:fs/promises'
|
||||
import type { Stats } from 'node:fs'
|
||||
import { readdir, readFile, stat } from 'node:fs/promises'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { toWindowsWslUncPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import {
|
||||
toWslDistroUncPath,
|
||||
wslMappedDriveOf,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import {
|
||||
isForeignLink,
|
||||
readWorktreeLinks
|
||||
} from '../../../git/worktrees/removal/worktree-prune-guard'
|
||||
import { isForeignLink } from '../../../git/worktrees/removal/worktree-prune-guard'
|
||||
import { isLocalWslMoveRow } from '../quiescence/wsl-move-scope-guard'
|
||||
import type { WslMoveScopeRefusal } from './wsl-move-scope'
|
||||
|
||||
/** The worktrees of the repo at `repoPath` whose links Git for Windows wrote; none outside Git. */
|
||||
export async function windowsGitWorktreePaths(repoPath: string, distro: string): Promise<string[]> {
|
||||
const dotGit = join(repoPath, '.git')
|
||||
const info = await stat(dotGit).catch((error: unknown) => {
|
||||
// Only "no `.git`" means no Git; any other failure fails the check closed.
|
||||
if (isMissing(error)) {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
})
|
||||
if (!info) {
|
||||
return []
|
||||
}
|
||||
let commonDir = dotGit
|
||||
if (!info.isDirectory()) {
|
||||
const link = /^gitdir:\s*(.+)$/m.exec(await readFile(dotGit, 'utf8'))?.[1]?.trim()
|
||||
if (!link) {
|
||||
return []
|
||||
}
|
||||
// The repo is itself a linked worktree Git for Windows created.
|
||||
if (isForeignLink(link, true)) {
|
||||
return [repoPath]
|
||||
}
|
||||
const gitDir = link.startsWith('/')
|
||||
? toWindowsWslUncPath(link, distro)
|
||||
: resolve(repoPath, link)
|
||||
const common = (await readFile(join(gitDir, 'commondir'), 'utf8').catch(() => '')).trim()
|
||||
commonDir = common ? resolve(gitDir, common) : gitDir
|
||||
}
|
||||
return (await readWorktreeLinks(join(commonDir, 'worktrees')))
|
||||
.filter(({ link }) => isForeignLink(link, true))
|
||||
.map(({ link }) => link.replace(/[\\/]\.git$/, ''))
|
||||
}
|
||||
export type WslMoveWindowsGitVerdict =
|
||||
| 'ok'
|
||||
/** Worktree records (live or stale) whose links Git for Windows wrote. */
|
||||
| 'windows-git-worktrees'
|
||||
/** Its own `.git` file names a Windows path: a Git for Windows worktree or `--separate-git-dir`. */
|
||||
| 'windows-git-dir'
|
||||
|
||||
// Long enough for a cold distro share; a repo whose records don't answer by then stays here.
|
||||
const GIT_RECORDS_TIMEOUT_MS = 5_000
|
||||
|
||||
const isWindowsLink = (link: string): boolean => isForeignLink(link, true)
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
||||
}
|
||||
|
||||
/**
|
||||
* The local repos on a mapped drive with worktrees the host's Git can't use. A repo whose links
|
||||
* can't be read counts as one: the check fails closed.
|
||||
*/
|
||||
export async function findWindowsGitWorktreeRepoIds(
|
||||
async function statOrNull(path: string): Promise<Stats | null> {
|
||||
return stat(path).catch((error: unknown) => {
|
||||
if (isMissing(error)) {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
})
|
||||
}
|
||||
|
||||
/** A path Git wrote, as this process reads it: Linux paths through the distro's share. */
|
||||
function readable(base: string, link: string, distro: string): string {
|
||||
return link.startsWith('/') ? toWindowsWslUncPath(link, distro) : resolve(base, link)
|
||||
}
|
||||
|
||||
/** The repo's common Git directory, null outside Git, or the Windows-link verdict. */
|
||||
async function commonDirOf(
|
||||
repoPath: string,
|
||||
distro: string
|
||||
): Promise<{ commonDir: string } | null | 'windows-git-dir'> {
|
||||
const dotGit = join(repoPath, '.git')
|
||||
const info = await statOrNull(dotGit)
|
||||
if (!info) {
|
||||
const bare =
|
||||
(await statOrNull(join(repoPath, 'HEAD'))) && (await statOrNull(join(repoPath, 'objects')))
|
||||
return bare ? { commonDir: repoPath } : null
|
||||
}
|
||||
if (info.isDirectory()) {
|
||||
return { commonDir: dotGit }
|
||||
}
|
||||
const link = /^gitdir:\s*(.+)$/m.exec(await readFile(dotGit, 'utf8'))?.[1]?.trim()
|
||||
if (!link) {
|
||||
throw new Error('git_link_unreadable')
|
||||
}
|
||||
if (isWindowsLink(link)) {
|
||||
return 'windows-git-dir'
|
||||
}
|
||||
const gitDir = readable(repoPath, link, distro)
|
||||
const common = await readFile(join(gitDir, 'commondir'), 'utf8').then(
|
||||
(text) => text.trim(),
|
||||
(error: unknown) => {
|
||||
// No `commondir`: a separate Git folder, which is its own common directory.
|
||||
if (isMissing(error)) {
|
||||
return ''
|
||||
}
|
||||
throw error
|
||||
}
|
||||
)
|
||||
if (common && isWindowsLink(common)) {
|
||||
return 'windows-git-dir'
|
||||
}
|
||||
return { commonDir: common ? readable(gitDir, common, distro) : gitDir }
|
||||
}
|
||||
|
||||
/** `repoPath` in a spelling this process reads (the share's, for a mapped drive). */
|
||||
export async function windowsGitWorktreeVerdict(
|
||||
repoPath: string,
|
||||
distro: string
|
||||
): Promise<WslMoveWindowsGitVerdict> {
|
||||
const found = await commonDirOf(repoPath, distro)
|
||||
if (found === null || found === 'windows-git-dir') {
|
||||
return found ?? 'ok'
|
||||
}
|
||||
const admin = join(found.commonDir, 'worktrees')
|
||||
const entries = await readdir(admin).catch((error: unknown) => {
|
||||
if (isMissing(error)) {
|
||||
return []
|
||||
}
|
||||
throw error
|
||||
})
|
||||
for (const entry of entries) {
|
||||
// An unreadable record fails the check: it may be one the host's prune would delete.
|
||||
const link = (await readFile(join(admin, entry, 'gitdir'), 'utf8')).trim()
|
||||
if (isWindowsLink(link)) {
|
||||
return 'windows-git-worktrees'
|
||||
}
|
||||
}
|
||||
return 'ok'
|
||||
}
|
||||
|
||||
async function verdictWithin(
|
||||
check: () => Promise<WslMoveWindowsGitVerdict>,
|
||||
timeoutMs: number
|
||||
): Promise<WslMoveWindowsGitVerdict | 'git-unreadable'> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const timeout = new Promise<'git-unreadable'>((done) => {
|
||||
timer = setTimeout(() => done('git-unreadable'), timeoutMs)
|
||||
})
|
||||
const verdict = check().catch((): 'git-unreadable' => 'git-unreadable')
|
||||
return Promise.race([verdict, timeout]).finally(() => clearTimeout(timer))
|
||||
}
|
||||
|
||||
/** The local mapped-drive repos the host's Git can't take, each with why; read via the share. */
|
||||
export async function findWindowsGitRefusals(
|
||||
repos: readonly Repo[],
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[],
|
||||
windowsGitWorktrees: (repoPath: string, distro: string) => Promise<string[]>
|
||||
): Promise<Set<string>> {
|
||||
check: (readablePath: string, distro: string) => Promise<WslMoveWindowsGitVerdict>,
|
||||
timeoutMs = GIT_RECORDS_TIMEOUT_MS
|
||||
): Promise<Map<string, WslMoveScopeRefusal>> {
|
||||
const onMappedDrive = repos.filter(
|
||||
(repo) => isLocalWslMoveRow(repo) && wslMappedDriveOf(repo.path, mappedDrives) !== null
|
||||
)
|
||||
const found = await Promise.all(
|
||||
onMappedDrive.map(async (repo) =>
|
||||
(await windowsGitWorktrees(repo.path, distro).catch(() => [repo.path])).length > 0
|
||||
? [repo.id]
|
||||
: []
|
||||
)
|
||||
const verdicts = await Promise.all(
|
||||
onMappedDrive.map(async (repo) => {
|
||||
const sharePath = toWslDistroUncPath(repo.path, mappedDrives)
|
||||
return [repo.id, await verdictWithin(() => check(sharePath, distro), timeoutMs)] as const
|
||||
})
|
||||
)
|
||||
return new Set(found.flat())
|
||||
const refusals = new Map<string, WslMoveScopeRefusal>()
|
||||
for (const [id, verdict] of verdicts) {
|
||||
if (verdict !== 'ok') {
|
||||
refusals.set(id, verdict)
|
||||
}
|
||||
}
|
||||
return refusals
|
||||
}
|
||||
|
||||
@@ -13,13 +13,14 @@ import { defaultWslOrcadEnvironmentId } from '../../../wsl/orcad/wsl-orcad-deplo
|
||||
/**
|
||||
* A bridge project of the distro (local, on its UNC path or a drive mapped into it, not moved) or
|
||||
* its WSL host record. A host file that cannot be read counts as in use: a failed read never makes
|
||||
* a distro look gone. Drives are read only when nothing else keeps the distro; unread, in use.
|
||||
* a distro look gone. Mapped drives come from last-known answers only: this runs in the
|
||||
* background, where reading a share can boot its stopped distro. Unknown counts as in use.
|
||||
*/
|
||||
export async function isDistroInUse(
|
||||
store: Pick<Store, 'getRepos' | 'getFolderWorkspaces'>,
|
||||
userDataPath: string,
|
||||
distro: string,
|
||||
readMappedDrives?: () => Promise<readonly WslMappedDrive[] | 'unverifiable'>
|
||||
lastKnownMappedDrives?: () => readonly WslMappedDrive[] | 'unverifiable'
|
||||
): Promise<boolean> {
|
||||
const environmentId = defaultWslOrcadEnvironmentId(distro)
|
||||
try {
|
||||
@@ -41,10 +42,10 @@ export async function isDistroInUse(
|
||||
return unc !== null && wslMoveJournalKey(unc.distro) === key
|
||||
})
|
||||
const onUnc = hasBridgeProject([])
|
||||
if (onUnc || !readMappedDrives) {
|
||||
if (onUnc || !lastKnownMappedDrives) {
|
||||
return onUnc
|
||||
}
|
||||
const mappedDrives = await readMappedDrives().catch(() => 'unverifiable' as const)
|
||||
const mappedDrives = lastKnownMappedDrives()
|
||||
return mappedDrives === 'unverifiable' || hasBridgeProject(mappedDrives)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id'
|
||||
import { parseWorkspaceKey } from '../../../../shared/workspace/identity/workspace-scope'
|
||||
import { isWslUncPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import { mayBeInWsl } from './wsl-move-unread-journal-folders'
|
||||
import {
|
||||
getRepoExecutionHostId,
|
||||
LOCAL_EXECUTION_HOST_ID
|
||||
@@ -142,7 +142,7 @@ function matchesFence(
|
||||
if (fence.readable) {
|
||||
return inScope(fence.state.fenced, ref) || (includeHidden && inScope(fence.state.hidden, ref))
|
||||
}
|
||||
return !store || isWslUncPath(projectPath(store, ref) ?? '')
|
||||
return !store || mayBeInWsl(projectPath(store, ref) ?? '')
|
||||
}
|
||||
|
||||
export function assertWslMoveProjectWritable(
|
||||
@@ -256,14 +256,17 @@ export function isWslMoveWorkspaceBlocked(
|
||||
|
||||
/**
|
||||
* Whether a new terminal's folder is one a move is taking, whatever workspace it names. A
|
||||
* Linux-spelled folder names no distro, so it matches any moving distro. An unreadable journal lets
|
||||
* no move reach commit, so it fences nothing here.
|
||||
* Linux-spelled folder names no distro, so it matches any moving distro. An unreadable journal may
|
||||
* hide a committed move, so it fences every Windows-spelled folder that may be in WSL.
|
||||
*/
|
||||
export function isWslMoveCwdFenced(cwd: string): boolean {
|
||||
const fence = loaded?.view
|
||||
if (!fence?.readable) {
|
||||
if (!fence) {
|
||||
return false
|
||||
}
|
||||
if (!fence.readable) {
|
||||
return mayBeInWsl(cwd)
|
||||
}
|
||||
return fence.state.fencedRoots.some(({ distro, roots, mappedDrives }) => {
|
||||
const path = comparableWslPath(cwd, distro, mappedDrives)
|
||||
return path !== null && roots.some((root) => isAtOrUnder(path, root))
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/** A journal this build can't read (corrupt, or from a newer build) still fences moved W:\ rows. */
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { wslMoveCutoverFixture as cutover } from '../../__fixtures__/wsl-mover/wsl-move-cutover-fixture'
|
||||
import {
|
||||
clearWslMappedDriveShareCacheForTests,
|
||||
readWslMappedDriveShareNow
|
||||
} from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import { wslMoveJournalDirectory } from '../cutover-recovery/wsl-move-cutover-journal'
|
||||
import {
|
||||
isWslMoveCwdFenced,
|
||||
isWslMoveProjectBlocked,
|
||||
loadWslMoveFence,
|
||||
resetWslMoveFenceForTests
|
||||
} from './wsl-move-scope-guard'
|
||||
|
||||
let userDataPath: string
|
||||
beforeEach(() => {
|
||||
userDataPath = mkdtempSync(join(tmpdir(), 'wsl-move-unread-'))
|
||||
const record = cutover('move-1', 'destination-committed', {
|
||||
mappedDrives: [{ letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }]
|
||||
})
|
||||
mkdirSync(wslMoveJournalDirectory(userDataPath), { recursive: true })
|
||||
// A version this build doesn't know: the whole journal reads as unreadable.
|
||||
writeFileSync(
|
||||
join(wslMoveJournalDirectory(userDataPath), 'move-1.json'),
|
||||
JSON.stringify({ ...record, version: 3 })
|
||||
)
|
||||
})
|
||||
afterEach(() => {
|
||||
resetWslMoveFenceForTests()
|
||||
clearWslMappedDriveShareCacheForTests()
|
||||
rmSync(userDataPath, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const repos = [
|
||||
{ id: 'moved-w', path: 'W:\\home\\dev\\repo-1' },
|
||||
{ id: 'local-c', path: 'C:\\src\\site' },
|
||||
{ id: 'unc', path: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\other' }
|
||||
]
|
||||
const store = { getRepo: (id: string) => repos.find((repo) => repo.id === id) }
|
||||
|
||||
describe('an unreadable WSL move journal', () => {
|
||||
it('blocks drive-letter rows not known to be outside WSL, and their terminals', async () => {
|
||||
// C: has answered as a local disk before; W: never has.
|
||||
await readWslMappedDriveShareNow('C', {
|
||||
platform: 'win32',
|
||||
realpathRoot: async () => 'C:\\',
|
||||
now: () => 0,
|
||||
timeoutMs: 50
|
||||
})
|
||||
loadWslMoveFence(userDataPath)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'moved-w' })).toBe(true)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'unc' })).toBe(true)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'local-c' })).toBe(false)
|
||||
expect(isWslMoveCwdFenced('W:\\home\\dev\\repo-1\\src')).toBe(true)
|
||||
expect(isWslMoveCwdFenced('\\\\wsl.localhost\\Ubuntu\\home\\dev\\repo-1')).toBe(true)
|
||||
expect(isWslMoveCwdFenced('C:\\src\\site')).toBe(false)
|
||||
})
|
||||
|
||||
it('still blocks a drive last known to map into WSL', async () => {
|
||||
await readWslMappedDriveShareNow('W', {
|
||||
platform: 'win32',
|
||||
realpathRoot: async () => '\\\\wsl.localhost\\Ubuntu\\',
|
||||
now: () => 0,
|
||||
timeoutMs: 50
|
||||
})
|
||||
loadWslMoveFence(userDataPath)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'moved-w' })).toBe(true)
|
||||
})
|
||||
})
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/** What an unreadable WSL move journal still fences: folders its moves could have taken. */
|
||||
import { isWslUncPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
classifyWslMappedDrive,
|
||||
wslMappedDriveLastKnownShare
|
||||
} from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
|
||||
/**
|
||||
* Without the journal, any folder a move could have taken: a UNC path, or a drive letter not
|
||||
* known to point outside WSL (a moved `W:\` row has nothing else marking it as moved).
|
||||
*/
|
||||
export function mayBeInWsl(path: string): boolean {
|
||||
if (isWslUncPath(path)) {
|
||||
return true
|
||||
}
|
||||
const letter = /^([A-Za-z]):[\\/]/.exec(path)?.[1]
|
||||
if (!letter) {
|
||||
return false
|
||||
}
|
||||
const known = wslMappedDriveLastKnownShare(letter)
|
||||
if (!known) {
|
||||
// One bounded, cached lookup, so a local drive's projects unblock once it answers.
|
||||
void classifyWslMappedDrive(letter).catch(() => {})
|
||||
}
|
||||
return !known || (known.share !== null && isWslUncPath(known.share))
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
classifyWslMappedDrive,
|
||||
clearWslMappedDriveShareCacheForTests,
|
||||
readWslMappedDriveShareNow,
|
||||
wslMappedDriveLastKnownShare,
|
||||
resolveWslMappedDrivePath,
|
||||
type WslMappedDriveShareDeps
|
||||
} from './wsl-mapped-drive-share'
|
||||
@@ -162,7 +164,7 @@ describe('readWslMappedDriveShareNow', () => {
|
||||
it('tells a slow drive apart from one that maps nowhere', async () => {
|
||||
await expect(
|
||||
readWslMappedDriveShareNow(
|
||||
'W',
|
||||
'Q',
|
||||
deps(() => new Promise<string>(() => {}))
|
||||
)
|
||||
).resolves.toBe('unverifiable')
|
||||
@@ -184,3 +186,43 @@ describe('readWslMappedDriveShareNow', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('fresh reads and last-known answers', () => {
|
||||
it('shares one lookup between concurrent reads, so a hung share pins one thread', async () => {
|
||||
const realpathRoot = vi.fn(() => new Promise<string>(() => {}))
|
||||
const reads = await Promise.all(
|
||||
[1, 2, 3].map(() => readWslMappedDriveShareNow('Z', deps(realpathRoot)))
|
||||
)
|
||||
expect(reads).toEqual(['unverifiable', 'unverifiable', 'unverifiable'])
|
||||
// A later read waits out the hung lookup instead of stacking another.
|
||||
await expect(readWslMappedDriveShareNow('Z', deps(realpathRoot))).resolves.toBe('unverifiable')
|
||||
expect(realpathRoot).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('asks again once an older lookup settles, so each read is fresh', async () => {
|
||||
let answer!: (real: string) => void
|
||||
const realpathRoot = vi
|
||||
.fn<WslMappedDriveShareDeps['realpathRoot']>()
|
||||
.mockImplementationOnce(() => new Promise((done) => (answer = done)))
|
||||
.mockResolvedValueOnce('\\\\wsl.localhost\\Debian\\')
|
||||
const first = readWslMappedDriveShareNow('W', deps(realpathRoot, { timeoutMs: 500 }))
|
||||
const second = readWslMappedDriveShareNow('W', deps(realpathRoot, { timeoutMs: 500 }))
|
||||
answer('\\\\wsl.localhost\\Ubuntu\\')
|
||||
await expect(first).resolves.toEqual({ share: '\\\\wsl.localhost\\Ubuntu' })
|
||||
await expect(second).resolves.toEqual({ share: '\\\\wsl.localhost\\Debian' })
|
||||
expect(realpathRoot).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('remembers each answer, and classifies an unknown letter with one cached lookup', async () => {
|
||||
expect(wslMappedDriveLastKnownShare('C')).toBeNull()
|
||||
const realpathRoot = vi.fn(async () => 'C:\\')
|
||||
await expect(classifyWslMappedDrive('C', deps(realpathRoot))).resolves.toEqual({ share: null })
|
||||
await expect(classifyWslMappedDrive('c', deps(realpathRoot))).resolves.toEqual({ share: null })
|
||||
expect(realpathRoot).toHaveBeenCalledTimes(1)
|
||||
await readWslMappedDriveShareNow(
|
||||
'W',
|
||||
deps(async () => '\\\\wsl.localhost\\Ubuntu\\')
|
||||
)
|
||||
expect(wslMappedDriveLastKnownShare('w')).toEqual({ share: '\\\\wsl.localhost\\Ubuntu' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -23,6 +23,8 @@ export type WslMappedDriveShareDeps = {
|
||||
type CacheEntry = { settledAt: number | null; lookup: Promise<string | null> }
|
||||
|
||||
const cache = new Map<string, CacheEntry>()
|
||||
// Each letter's last settled answer from either lookup; background paths read only this.
|
||||
const lastKnown = new Map<string, string | null>()
|
||||
|
||||
const defaultDeps: WslMappedDriveShareDeps = {
|
||||
platform: process.platform,
|
||||
@@ -57,7 +59,7 @@ function startDriveLookup(key: string, deps: WslMappedDriveShareDeps): CacheEntr
|
||||
entry.lookup = deps.realpathRoot(`${key}:\\`).then(
|
||||
(real) => {
|
||||
entry.settledAt = deps.now()
|
||||
return parseWslUncPath(real) ? real.replace(/[\\/]+$/, '') : null
|
||||
return remember(key, real)
|
||||
},
|
||||
() => {
|
||||
// A failed lookup is asked again by the next add.
|
||||
@@ -101,9 +103,57 @@ export async function resolveWslMappedDrivePath(
|
||||
/** What a drive letter maps to right now; `unverifiable` when Windows didn't answer in time. */
|
||||
export type WslMappedDriveRead = { share: string | null } | 'unverifiable'
|
||||
|
||||
function remember(key: string, real: string): string | null {
|
||||
const share = parseWslUncPath(real) ? real.replace(/[\\/]+$/, '') : null
|
||||
lastKnown.set(key, share)
|
||||
return share
|
||||
}
|
||||
|
||||
type FreshLookup = { serial: number; settled: Promise<{ share: string | null }> }
|
||||
// Serials order fresh lookups, so a request can tell one started after it from an older one.
|
||||
let freshSerial = 0
|
||||
const freshLookups = new Map<string, FreshLookup>()
|
||||
|
||||
function startFreshLookup(key: string, deps: WslMappedDriveShareDeps): FreshLookup {
|
||||
const entry: FreshLookup = {
|
||||
serial: ++freshSerial,
|
||||
settled: deps.realpathRoot(`${key}:\\`).then(
|
||||
(real) => ({ share: remember(key, real) }),
|
||||
// No such drive, or not one Windows can resolve: nothing is mapped there.
|
||||
() => ({ share: null })
|
||||
)
|
||||
}
|
||||
freshLookups.set(key, entry)
|
||||
void entry.settled.finally(() => {
|
||||
if (freshLookups.get(key) === entry) {
|
||||
freshLookups.delete(key)
|
||||
}
|
||||
})
|
||||
return entry
|
||||
}
|
||||
|
||||
/** Joins a lookup started after `after`; waits out an older one rather than stack another. */
|
||||
async function freshAnswer(
|
||||
key: string,
|
||||
deps: WslMappedDriveShareDeps,
|
||||
after: number
|
||||
): Promise<{ share: string | null }> {
|
||||
for (;;) {
|
||||
const current = freshLookups.get(key)
|
||||
if (!current) {
|
||||
return startFreshLookup(key, deps).settled
|
||||
}
|
||||
if (current.serial > after) {
|
||||
return current.settled
|
||||
}
|
||||
await current.settled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks Windows again, bypassing the cache, for a decision that rewrites saved state: a drive
|
||||
* remapped within the cache's minute must not convert a project into another distro or folder.
|
||||
* remapped within the cache's minute must not move a project into another distro or folder.
|
||||
* Concurrent reads of a letter share one lookup, so a hung share pins one fs thread.
|
||||
*/
|
||||
export async function readWslMappedDriveShareNow(
|
||||
letter: string,
|
||||
@@ -117,14 +167,33 @@ export async function readWslMappedDriveShareNow(
|
||||
const timeout = new Promise<'unverifiable'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('unverifiable'), timeoutMs)
|
||||
})
|
||||
const lookup = deps.realpathRoot(`${letter.toUpperCase()}:\\`).then(
|
||||
(real): WslMappedDriveRead => ({
|
||||
share: parseWslUncPath(real) ? real.replace(/[\\/]+$/, '') : null
|
||||
}),
|
||||
// No such drive, or not one Windows can resolve: nothing is mapped there.
|
||||
(): WslMappedDriveRead => ({ share: null })
|
||||
)
|
||||
return Promise.race([lookup, timeout]).finally(() => clearTimeout(timer))
|
||||
const answer = freshAnswer(letter.toUpperCase(), deps, freshSerial)
|
||||
return Promise.race([answer, timeout]).finally(() => clearTimeout(timer))
|
||||
}
|
||||
|
||||
/** The letter's last answer, never read here; null before any lookup of it settled. */
|
||||
export function wslMappedDriveLastKnownShare(letter: string): { share: string | null } | null {
|
||||
const key = letter.toUpperCase()
|
||||
return lastKnown.has(key) ? { share: lastKnown.get(key) ?? null } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The letter's last answer, classifying an unknown letter with one bounded, cached lookup; null
|
||||
* when that lookup did not settle in time.
|
||||
*/
|
||||
export async function classifyWslMappedDrive(
|
||||
letter: string,
|
||||
deps: WslMappedDriveShareDeps = defaultDeps
|
||||
): Promise<{ share: string | null } | null> {
|
||||
if (deps.platform !== 'win32' || !/^[A-Za-z]$/.test(letter)) {
|
||||
return { share: null }
|
||||
}
|
||||
const known = wslMappedDriveLastKnownShare(letter)
|
||||
if (known) {
|
||||
return known
|
||||
}
|
||||
await resolveDriveShare(letter, deps)
|
||||
return wslMappedDriveLastKnownShare(letter)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -146,4 +215,6 @@ export function wslMappedDriveMatches(
|
||||
|
||||
export function clearWslMappedDriveShareCacheForTests(): void {
|
||||
cache.clear()
|
||||
lastKnown.clear()
|
||||
freshLookups.clear()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { WslMovePreview } from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
import { WslMovePreviewBody, wslMoveNotMovingLines } from './WslMovePreviewBody'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const names: Record<string, string> = { app: 'app', notes: 'notes' }
|
||||
|
||||
function renderPreview(preview: WslMovePreview): void {
|
||||
render(
|
||||
<WslMovePreviewBody
|
||||
distro="Ubuntu"
|
||||
rows={[]}
|
||||
selected={[]}
|
||||
counts={{ projects: 0, workspaces: 0, terminals: 0, chats: 0 }}
|
||||
preview={preview}
|
||||
notMoving={wslMoveNotMovingLines(preview, (ref) => names[ref.id] ?? ref.id, 'Ubuntu')}
|
||||
blockers={[]}
|
||||
onToggle={vi.fn()}
|
||||
onSkip={vi.fn()}
|
||||
onRecheck={vi.fn()}
|
||||
onStart={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
describe('WslMovePreviewBody', () => {
|
||||
it('says why when the only candidate is a repo the host Git cannot take', () => {
|
||||
renderPreview({
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_nothing_new',
|
||||
refused: [{ kind: 'repo', id: 'app', reason: 'windows-git-worktrees' }]
|
||||
})
|
||||
expect(screen.getByText(/Git for Windows recorded some of its worktrees/)).toBeVisible()
|
||||
expect(screen.getByText(/None of these projects can move/)).toBeVisible()
|
||||
expect(screen.queryByText(/already on the Ubuntu host/)).toBeNull()
|
||||
})
|
||||
|
||||
it('lists a project whose drive did not answer under "Not moving"', () => {
|
||||
renderPreview({
|
||||
outcome: 'ready',
|
||||
distro: 'Ubuntu',
|
||||
repoIds: [],
|
||||
folderWorkspaceIds: [],
|
||||
changed: [],
|
||||
heldByHost: [],
|
||||
refused: [{ kind: 'folder-workspace', id: 'notes', reason: 'mapped-drive-unverifiable' }],
|
||||
blockers: []
|
||||
})
|
||||
expect(screen.getByText('notes')).toBeVisible()
|
||||
expect(screen.getByText(/couldn’t check where its drive letter points/)).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -183,8 +183,13 @@ export function wslMoveNotMovingLines(
|
||||
distro: string,
|
||||
t: Translate = translate
|
||||
): { name: string; why: string }[] {
|
||||
const refused = preview.refused?.map((entry) => ({
|
||||
name: nameOf({ kind: entry.kind === 'repo' ? 'repo' : 'folder', id: entry.id }),
|
||||
why: wslMoveScopeRefusalReason(entry.reason, t)
|
||||
}))
|
||||
if (preview.outcome !== 'ready') {
|
||||
return []
|
||||
// A refused preview carries why each project can't move when none can.
|
||||
return refused ?? []
|
||||
}
|
||||
return [
|
||||
...preview.heldByHost.map((ref) => ({
|
||||
@@ -198,9 +203,6 @@ export function wslMoveNotMovingLines(
|
||||
'Moved earlier, then changed here by an older version of Orca. It is not moved again.'
|
||||
)
|
||||
})),
|
||||
...preview.refused.map((entry) => ({
|
||||
name: nameOf({ kind: entry.kind === 'repo' ? 'repo' : 'folder', id: entry.id }),
|
||||
why: wslMoveScopeRefusalReason(entry.reason, t)
|
||||
}))
|
||||
...(refused ?? [])
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const resolveWslMappedDrivePath = vi.hoisted(() =>
|
||||
vi.fn(async (_path: string): Promise<string | null> => '\\\\wsl.localhost\\Ubuntu')
|
||||
)
|
||||
vi.mock('../sidebar/wsl-mapped-drive-path', () => ({ resolveWslMappedDrivePath }))
|
||||
|
||||
import {
|
||||
refreshWslMappedDriveShare,
|
||||
resetWslMappedDriveShareStoreForTests,
|
||||
useWslMappedDriveShare
|
||||
} from './wsl-mapped-drive-share-store'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
resetWslMappedDriveShareStoreForTests()
|
||||
resolveWslMappedDrivePath.mockClear()
|
||||
})
|
||||
|
||||
describe('useWslMappedDriveShare', () => {
|
||||
it('shows a known answer at once when a menu opens again, without asking main', async () => {
|
||||
const first = renderHook(() => useWslMappedDriveShare('W:\\home\\me\\app'))
|
||||
await waitFor(() => expect(first.result.current).toBe('\\\\wsl.localhost\\Ubuntu'))
|
||||
first.unmount()
|
||||
const again = renderHook(() => useWslMappedDriveShare('W:\\home\\me\\app'))
|
||||
expect(again.result.current).toBe('\\\\wsl.localhost\\Ubuntu')
|
||||
expect(resolveWslMappedDrivePath).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('refreshes a stale answer outside render and updates every reader', async () => {
|
||||
const view = renderHook(() => useWslMappedDriveShare('W:\\x'))
|
||||
await waitFor(() => expect(view.result.current).toBe('\\\\wsl.localhost\\Ubuntu'))
|
||||
resolveWslMappedDrivePath.mockResolvedValueOnce(null)
|
||||
await act(async () => refreshWslMappedDriveShare('W', Date.now() + 120_000))
|
||||
await waitFor(() => expect(view.result.current).toBeNull())
|
||||
expect(resolveWslMappedDrivePath).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Which share each drive letter maps to, as main last answered, for the move's entry points. Render
|
||||
* reads only the stored answer; an effect refreshes it, so a menu opened again shows its item at
|
||||
* once while a stale answer is checked in the background.
|
||||
*/
|
||||
import { useEffect, useSyncExternalStore } from 'react'
|
||||
import { resolveWslMappedDrivePath } from '../sidebar/wsl-mapped-drive-path'
|
||||
|
||||
const REFRESH_AFTER_MS = 60_000
|
||||
const DRIVE_PATH = /^([A-Za-z]):[\\/]/
|
||||
|
||||
type Entry = { share: string | null; at: number }
|
||||
|
||||
let entries: ReadonlyMap<string, Entry> = new Map()
|
||||
const listeners = new Set<() => void>()
|
||||
const inFlight = new Set<string>()
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
}
|
||||
|
||||
const snapshot = (): ReadonlyMap<string, Entry> => entries
|
||||
|
||||
/** Asks main again when the letter has no answer yet or its answer is older than a minute. */
|
||||
export function refreshWslMappedDriveShare(letter: string, now: number = Date.now()): void {
|
||||
const entry = entries.get(letter)
|
||||
if (inFlight.has(letter) || (entry && now - entry.at < REFRESH_AFTER_MS)) {
|
||||
return
|
||||
}
|
||||
inFlight.add(letter)
|
||||
// Main bounds and caches the lookup per drive letter.
|
||||
void resolveWslMappedDrivePath(`${letter}:\\`)
|
||||
.then((share) => {
|
||||
entries = new Map(entries).set(letter, { share, at: Date.now() })
|
||||
listeners.forEach((listener) => listener())
|
||||
})
|
||||
.finally(() => inFlight.delete(letter))
|
||||
}
|
||||
|
||||
/** The share the drive of a drive-letter `path` maps to, as last answered; null otherwise. */
|
||||
export function useWslMappedDriveShare(path: string | null): string | null {
|
||||
const letter = path ? (DRIVE_PATH.exec(path)?.[1].toUpperCase() ?? null) : null
|
||||
const current = useSyncExternalStore(subscribe, snapshot)
|
||||
useEffect(() => {
|
||||
if (letter) {
|
||||
refreshWslMappedDriveShare(letter)
|
||||
}
|
||||
}, [letter])
|
||||
return letter ? (current.get(letter)?.share ?? null) : null
|
||||
}
|
||||
|
||||
export function resetWslMappedDriveShareStoreForTests(): void {
|
||||
entries = new Map()
|
||||
inFlight.clear()
|
||||
listeners.clear()
|
||||
}
|
||||
@@ -82,6 +82,13 @@ export function wslMoveRefusalMessage(
|
||||
{ distro }
|
||||
)
|
||||
case 'wsl_move_nothing_new':
|
||||
if (refusal.refused?.length) {
|
||||
return t(
|
||||
'wslMove.refusal.nothingMovable',
|
||||
'None of these projects can move to the {{distro}} host yet. Each one says why.',
|
||||
{ distro }
|
||||
)
|
||||
}
|
||||
return t('wslMove.refusal.nothingNew', 'These projects are already on the {{distro}} host.', {
|
||||
distro
|
||||
})
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
* offered only where WSL hosts are: the internal gate open (the preload omits the API otherwise)
|
||||
* and the Experimental switch on. Main refuses every call with the gate closed regardless.
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import {
|
||||
getRepoExecutionHostId,
|
||||
@@ -17,7 +16,7 @@ import {
|
||||
useWslHostsAcceptNewWork,
|
||||
useWslHostServerFilesMissing
|
||||
} from '../sidebar/use-wsl-hosts-enabled'
|
||||
import { resolveWslMappedDrivePath } from '../sidebar/wsl-mapped-drive-path'
|
||||
import { useWslMappedDriveShare } from './wsl-mapped-drive-share-store'
|
||||
import { openWslMoveDialog } from './wsl-move-dialog-store'
|
||||
import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-record-fields'
|
||||
import { findWslHostForDistro, wslMoveCatalogCandidates } from './wsl-move-scope-rows'
|
||||
@@ -48,41 +47,6 @@ export type WslMoveTarget = {
|
||||
}
|
||||
|
||||
const DRIVE_PATH = /^[A-Za-z]:[\\/]/
|
||||
const SHARE_CACHE_TTL_MS = 60_000
|
||||
// Per drive letter, so a menu opened again shows its item at once instead of after the lookup.
|
||||
const shareCache = new Map<string, { share: string | null; at: number }>()
|
||||
|
||||
function cachedShare(letter: string): { share: string | null } | null {
|
||||
const entry = shareCache.get(letter)
|
||||
return entry && Date.now() - entry.at < SHARE_CACHE_TTL_MS ? entry : null
|
||||
}
|
||||
|
||||
/** The share a drive letter maps to once main resolved it; null for any other drive. */
|
||||
function useMappedDriveShare(path: string | null): string | null {
|
||||
const letter = path && DRIVE_PATH.test(path) ? path[0].toUpperCase() : null
|
||||
const [resolved, setResolved] = useState<{ letter: string; share: string | null } | null>(null)
|
||||
useEffect(() => {
|
||||
if (!letter || cachedShare(letter)) {
|
||||
return
|
||||
}
|
||||
let current = true
|
||||
// Main bounds and caches the lookup per drive letter.
|
||||
void resolveWslMappedDrivePath(`${letter}:\\`).then((share) => {
|
||||
shareCache.set(letter, { share, at: Date.now() })
|
||||
if (current) {
|
||||
setResolved({ letter, share })
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
current = false
|
||||
}
|
||||
}, [letter])
|
||||
if (!letter) {
|
||||
return null
|
||||
}
|
||||
return cachedShare(letter)?.share ?? (resolved?.letter === letter ? resolved.share : null)
|
||||
}
|
||||
|
||||
/** The host a local project's folder could move to, or null where no move is offered. */
|
||||
export function useWslMoveTargetForPath(
|
||||
path: string | null | undefined,
|
||||
@@ -92,7 +56,7 @@ export function useWslMoveTargetForPath(
|
||||
const serverFilesMissing = useWslHostServerFilesMissing()
|
||||
const environments = useAppStore((s) => s.runtimeEnvironments)
|
||||
const offered = enabled && !serverFilesMissing && isLocal && path ? path : null
|
||||
const share = useMappedDriveShare(offered)
|
||||
const share = useWslMappedDriveShare(offered)
|
||||
return offered ? wslMoveTargetOfPath(offered, share, environments) : null
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,22 @@ export function wslMoveScopeRefusalReason(reason: string, t: Translate = transla
|
||||
case 'windows-git-worktrees':
|
||||
return t(
|
||||
'wslMove.scopeRefused.windowsGitWorktrees',
|
||||
'Git for Windows created some of its worktrees, and Git on the WSL host can’t use them. Remove those worktrees, then move it.'
|
||||
'Git for Windows recorded some of its worktrees, including any since deleted, and Git on the WSL host can’t use those records. Remove those worktrees, or run git worktree repair from WSL, then move it.'
|
||||
)
|
||||
case 'windows-git-dir':
|
||||
return t(
|
||||
'wslMove.scopeRefused.windowsGitDir',
|
||||
'Its Git folder is linked by a Windows path (a worktree or a separate Git folder Git for Windows set up), which Git on the WSL host can’t follow.'
|
||||
)
|
||||
case 'git-unreadable':
|
||||
return t(
|
||||
'wslMove.scopeRefused.gitUnreadable',
|
||||
'Orca couldn’t read its Git details in time to check them, so it stays on this computer. Check again in a moment.'
|
||||
)
|
||||
case 'mapped-drive-unverifiable':
|
||||
return t(
|
||||
'wslMove.scopeRefused.mappedDriveUnverifiable',
|
||||
'Orca couldn’t check where its drive letter points just now. Make sure the drive is connected, then check again.'
|
||||
)
|
||||
default:
|
||||
return t('wslMove.scopeRefused.other', 'It cannot move.')
|
||||
|
||||
@@ -24773,7 +24773,8 @@
|
||||
"scopeChanged": "A project changed while the move was getting ready, so nothing was moved. Check the projects and try again.",
|
||||
"cancelled": "Move cancelled. Nothing was moved.",
|
||||
"finishedEarlierMove": "Orca first finished an earlier move into {{distro}}. Reload the window, then start this move again.",
|
||||
"mappedDriveUnverifiable": "Orca could not check a drive letter some projects are saved on. Make sure the drive is connected, then try again."
|
||||
"mappedDriveUnverifiable": "Orca could not check a drive letter some projects are saved on. Make sure the drive is connected, then try again.",
|
||||
"nothingMovable": "None of these projects can move to the {{distro}} host yet. Each one says why."
|
||||
},
|
||||
"step": {
|
||||
"preparing": "Preparing",
|
||||
@@ -24812,7 +24813,10 @@
|
||||
"mixedLocations": "Some of its folders are outside this distro, so it stays on this computer.",
|
||||
"notLocal": "It already runs on another host.",
|
||||
"other": "It cannot move.",
|
||||
"windowsGitWorktrees": "Git for Windows created some of its worktrees, and Git on the WSL host can’t use them. Remove those worktrees, then move it."
|
||||
"windowsGitWorktrees": "Git for Windows recorded some of its worktrees, including any since deleted, and Git on the WSL host can’t use those records. Remove those worktrees, or run git worktree repair from WSL, then move it.",
|
||||
"windowsGitDir": "Its Git folder is linked by a Windows path (a worktree or a separate Git folder Git for Windows set up), which Git on the WSL host can’t follow.",
|
||||
"gitUnreadable": "Orca couldn’t read its Git details in time to check them, so it stays on this computer. Check again in a moment.",
|
||||
"mappedDriveUnverifiable": "Orca couldn’t check where its drive letter points just now. Make sure the drive is connected, then check again."
|
||||
},
|
||||
"reloadToast": {
|
||||
"title": "Reload to finish the move"
|
||||
|
||||
@@ -35,6 +35,14 @@ describe('mapped-drive paths', () => {
|
||||
expect(wslMappedDriveFileUrlToLinux('file:///X:/home/me', 'Ubuntu', [W])).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses a file URL whose `..` climbs out of the share, as the path form does', () => {
|
||||
expect(wslMappedDriveFileUrlToLinux('file:///H:/a/../../etc/passwd', 'Ubuntu', [H])).toBeNull()
|
||||
expect(wslMappedDriveFileUrlToLinux('file:///H:/a/%2E%2E/%2E%2E/etc', 'Ubuntu', [H])).toBeNull()
|
||||
expect(wslMappedDriveFileUrlToLinux('file:///H:/me/../me/x', 'Ubuntu', [H])).toBe(
|
||||
'file:///home/me/../me/x'
|
||||
)
|
||||
})
|
||||
|
||||
it('restores a folded key case from the innermost moved root', () => {
|
||||
const roots = ['/home/me/App', '/home/me/App/Trees/Feature']
|
||||
expect(wslMappedDriveComparisonKeyToLinux('w:/home/me/app/src', 'Ubuntu', [W], roots)).toBe(
|
||||
|
||||
@@ -83,13 +83,22 @@ export function wslMappedDriveFileUrlToLinux(
|
||||
const match = mappedDrives.length > 0 ? DRIVE_FILE_URL.exec(url) : null
|
||||
const drive = match ? wslMappedDriveOf(`${match[1]}:\\`, mappedDrives) : null
|
||||
const root = drive ? wslUncPathToLinux(drive.share, distro) : null
|
||||
if (!match || root === null) {
|
||||
if (!match || !drive || root === null || !staysOnShare(match[2] ?? '/', drive)) {
|
||||
return null
|
||||
}
|
||||
const encodedRoot = root === '/' ? '' : root.split('/').map(encodeURIComponent).join('/')
|
||||
return `file://${encodedRoot}${match[2] ?? '/'}${match[3] ?? ''}`
|
||||
}
|
||||
|
||||
/** A URL tail that, decoded, stays inside the share, as the path form requires. */
|
||||
function staysOnShare(tail: string, drive: WslMappedDrive): boolean {
|
||||
try {
|
||||
return wslMappedDrivePathToShare(`${drive.letter}:${decodeURIComponent(tail)}`, drive) !== null
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A `normalizeRuntimePathForComparison` key on a mapped drive (`w:/home/me/app`), which folded
|
||||
* the case Linux needs: its Linux path with the case of the innermost `linuxRoots` entry holding
|
||||
|
||||
@@ -100,6 +100,8 @@ export type WslMoveRefusal = {
|
||||
/** User-facing, for `wsl_move_export_incomplete`. */
|
||||
reasons?: string[]
|
||||
detail?: string
|
||||
/** With `wsl_move_nothing_new`: the projects that can't move, and why. */
|
||||
refused?: { kind: 'repo' | 'folder-workspace'; id: string; reason: string }[]
|
||||
}
|
||||
|
||||
export type WslMoveResult =
|
||||
|
||||
Reference in New Issue
Block a user