dsh-remote 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/search.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // Windows remotes). Walks the remote tree over SFTP readdir/stat/readFile with
4
4
  // the same bounded-parallelism + ignore rules as the mirror sync.
5
5
  import { joinRemotePath, relPathUnder, shq } from './paths.js'
6
+ import { parseIgnoreRule } from './ignore.js'
6
7
 
7
8
  function mapLimit(items, limit, fn) {
8
9
  const limitN = Math.max(1, Math.min(Math.floor(limit) || 1, items.length))
@@ -81,11 +82,21 @@ export async function searchTree(sftp, rootDir, opts = {}) {
81
82
  let cancelled = false
82
83
  const startedAt = Date.now()
83
84
 
84
- /** True when the caller asked us to stop (abort, or the time budget is spent). */
85
+ /** True when the caller asked us to stop (abort, time budget, or a full cap). */
85
86
  const shouldStop = () => {
86
87
  if (cancelled || truncated) return true
87
88
  if (signal && signal.aborted) { cancelled = true; return true }
88
89
  if (maxDurationMs > 0 && Date.now() - startedAt >= maxDurationMs) { truncated = true; return true }
90
+ // A full cap is itself the honest truncation signal — there may be more
91
+ // matches beyond it in files this walk never reads. Before this branch,
92
+ // `truncated` was only set when a FURTHER match arrived past the cap, but
93
+ // the per-entry guard skips remaining files unread, so a cap filled exactly
94
+ // on a file's last matching line never set it: shouldStop never fired, the
95
+ // directory loop burned a readdir round-trip on every remaining directory,
96
+ // and the walk ended with truncated:false while dropping matches (or said
97
+ // TRUNCATED only after maxDurationMs burned). Continues the issue #44
98
+ // hardening: a cancellable walk must also stop for its own caps.
99
+ if (matches.length >= maxMatches) { truncated = true; return true }
89
100
  return false
90
101
  }
91
102
 
@@ -160,7 +171,18 @@ export async function searchTree(sftp, rootDir, opts = {}) {
160
171
  return { matches, scanned, truncated, cancelled }
161
172
  }
162
173
 
163
- function parseGrepLines(stdout, maxMatches) {
174
+ /**
175
+ * Map one reported hit back to the absolute remote path the rest of the plugin
176
+ * prints. The tools run with cwd = the search root (see searchViaShell) and are
177
+ * given '.', so they report './src/a.ts'; the SFTP walk reports the absolute
178
+ * path for the same file.
179
+ */
180
+ function absoluteMatchPath(p, rootDir) {
181
+ const rel = String(p).replace(/^\.\//, '')
182
+ return rel.startsWith('/') ? rel : joinRemotePath(rootDir, rel)
183
+ }
184
+
185
+ function parseGrepLines(stdout, maxMatches, rootDir) {
164
186
  const matches = []
165
187
  let truncated = false
166
188
  for (const line of String(stdout || '').split('\n')) {
@@ -168,14 +190,62 @@ function parseGrepLines(stdout, maxMatches) {
168
190
  const m = line.match(/^(.*?):(\d+):(.*)$/)
169
191
  if (!m) continue
170
192
  if (matches.length >= maxMatches) { truncated = true; break }
171
- matches.push({ path: m[1], line: Number(m[2]), text: m[3] })
193
+ matches.push({ path: absoluteMatchPath(m[1], rootDir), line: Number(m[2]), text: m[3] })
172
194
  }
173
195
  return { matches, truncated }
174
196
  }
175
197
 
198
+ /** Number of DISTINCT files that produced a hit. NOT a scan count: the remote
199
+ * tool never reports how many files it opened, and inventing that number would
200
+ * be a lie. (The SFTP walk reports its own real scan count.) */
201
+ function distinctFiles(matches) {
202
+ return new Set(matches.map((m) => m.path)).size
203
+ }
204
+
205
+ /**
206
+ * Per-tool exclude flags for the search ignore rules.
207
+ *
208
+ * The fast path must apply the SAME rules as the SFTP walk (they arrive as
209
+ * opts.ignorePatterns, built by lib/main.js from lib/ignore.js), but the tools
210
+ * do not share a vocabulary: rg takes --glob, grep takes --exclude /
211
+ * --exclude-dir. A basename rule maps 1:1. A rule containing a "/" (or a
212
+ * leading "/") is anchored to the search root: rg can express that because it
213
+ * runs with cwd = the search root, whereas grep's --exclude* only ever match
214
+ * BASENAMES. Anchored rules are therefore passed to rg only, and grep still
215
+ * descends into them -- a documented limitation of the grep fallback instead of
216
+ * pretended parity (DEFAULT_SEARCH_IGNORE's 'Library/Caches/' is one).
217
+ *
218
+ * Every flag is shq-quoted: the whole thing is one remote shell line.
219
+ */
220
+ function shellExcludes(patterns) {
221
+ const rg = []
222
+ const grep = []
223
+ for (const raw of (Array.isArray(patterns) ? patterns : String(patterns || '').split('\n'))) {
224
+ const rule = parseIgnoreRule(raw)
225
+ if (!rule) continue
226
+ if (rule.anchored) {
227
+ rg.push('--glob=' + shq('!' + rule.pattern + (rule.dirOnly ? '/' : '')))
228
+ continue
229
+ }
230
+ if (rule.dirOnly) {
231
+ rg.push('--glob=' + shq('!' + rule.pattern + '/'))
232
+ grep.push('--exclude-dir=' + shq(rule.pattern))
233
+ } else {
234
+ rg.push('--glob=' + shq('!' + rule.pattern))
235
+ grep.push('--exclude=' + shq(rule.pattern))
236
+ }
237
+ }
238
+ return { rg: rg.length ? ' ' + rg.join(' ') : '', grep: grep.length ? ' ' + grep.join(' ') : '' }
239
+ }
240
+
176
241
  /**
177
- * POSIX fast path: `rg` then `grep -R`. Returns null when the remote has
178
- * neither, so the caller can fall back to an SFTP walk (Windows / no grep).
242
+ * POSIX fast path: 'rg' then 'grep -R'. Throws when the remote has neither, so
243
+ * the caller can fall back to an SFTP walk (Windows / no grep).
244
+ *
245
+ * ignorePatterns (the raw lines lib/main.js compiled the SFTP walk's matcher
246
+ * from) become per-tool exclude flags: the two tools spell them differently and
247
+ * '-I' means opposite things, so the flag sets are built separately. Both tools
248
+ * run from the search root so anchored rules match like the walk's.
179
249
  */
180
250
  export async function searchViaShell(pool, rootDir, opts = {}) {
181
251
  const {
@@ -184,34 +254,44 @@ export async function searchViaShell(pool, rootDir, opts = {}) {
184
254
  glob,
185
255
  contextLines = 0,
186
256
  maxMatches = 500,
257
+ ignorePatterns = [],
187
258
  signal,
188
259
  } = opts
189
260
  // Honour an already-aborted signal before spawning a remote grep on a huge tree.
190
261
  if (signal && signal.aborted) {
191
262
  return { matches: [], scanned: 0, truncated: false, cancelled: true, via: 'none' }
192
263
  }
264
+ const ex = shellExcludes(ignorePatterns)
193
265
  const ic = ignoreCase ? ' -i' : ''
194
- const globFlag = glob ? ` --glob ${shq(glob)}` : ''
195
- const ctx = contextLines > 0 ? ` -C ${Number(contextLines)}` : ''
196
- const rg = `rg -n --no-heading -I${ic}${globFlag}${ctx} --max-count ${maxMatches} -- ${shq(pattern)} ${shq(rootDir)}`
197
- const grepGlob = glob ? ` --include=${shq(glob)}` : ''
198
- const grep = `grep -R -n -I -E${ic}${grepGlob}${ctx} -- ${shq(pattern)} ${shq(rootDir)}`
199
- const script = `if command -v rg >/dev/null 2>&1; then ${rg}; elif command -v grep >/dev/null 2>&1; then ${grep}; else exit 127; fi`
266
+ const ctx = contextLines > 0 ? ' -C ' + Number(contextLines) : ''
267
+ const globFlag = glob ? ' --glob=' + shq(glob) : ''
268
+ // -I is "ignore binary files" to grep but "--no-filename" to rg. rg must NOT
269
+ // get it: without a file name every row is unusable and parseGrepLines drops
270
+ // all of them, which silently turned every POSIX search into zero matches.
271
+ const rg = 'rg -n --no-heading' + ic + globFlag + ctx + ex.rg + ' --max-count ' + maxMatches + ' -- ' + shq(pattern) + ' .'
272
+ const grepGlob = glob ? ' --include=' + shq(glob) : ''
273
+ const grep = 'grep -R -n -I -E' + ic + grepGlob + ctx + ex.grep + ' -- ' + shq(pattern) + ' .'
274
+ // Both tools run from the search root: the ignore rules are anchored there,
275
+ // and rg matches --glob patterns against paths relative to the cwd (with an
276
+ // absolute search root, --glob=!Library/Caches/ matches nothing at all).
277
+ const script = 'cd ' + shq(rootDir) + ' || exit 2; if command -v rg >/dev/null 2>&1; then ' + rg + '; elif command -v grep >/dev/null 2>&1; then ' + grep + '; else exit 127; fi'
200
278
  const res = await pool.exec(script, { timeoutMs: opts.timeoutMs, signal })
201
279
  // A cancelled call must return as cancelled (with whatever partial output the
202
280
  // remote produced), NOT throw: throwing would make searchRemote fall through
203
281
  // to the slower SFTP walk, i.e. keep running after the caller said stop.
204
282
  if (res.signal === 'ABORTED') {
205
- const partial = parseGrepLines(res.stdout, maxMatches)
206
- return { matches: partial.matches, scanned: partial.matches.length, truncated: false, cancelled: true, via: 'none' }
283
+ const partial = parseGrepLines(res.stdout, maxMatches, rootDir)
284
+ return { matches: partial.matches, scanned: distinctFiles(partial.matches), truncated: false, cancelled: true, via: 'none' }
207
285
  }
208
286
  // 0 = hits, 1 = no hits; other codes mean the tools are missing / failed.
209
287
  if (res.signal === 'TIMEOUT') throw new Error('search timed out')
210
- if (res.code !== 0 && res.code !== 1) throw new Error(res.stderr || `search exit ${res.code}`)
211
- const parsed = parseGrepLines(res.stdout, maxMatches)
288
+ if (res.code !== 0 && res.code !== 1) throw new Error(res.stderr || 'search exit ' + res.code)
289
+ const parsed = parseGrepLines(res.stdout, maxMatches, rootDir)
212
290
  return {
213
291
  matches: parsed.matches,
214
- scanned: parsed.matches.length,
292
+ // DISTINCT files with hits, not match rows: the shell path cannot know how
293
+ // many files the tool opened, so this must not pretend to be a scan count.
294
+ scanned: distinctFiles(parsed.matches),
215
295
  truncated: parsed.truncated || /truncated|max-count/i.test(String(res.stderr || '')),
216
296
  via: /rg/.test(String(res.stderr || '')) ? 'rg' : 'grep',
217
297
  }
@@ -86,7 +86,11 @@ export function buildSftpSurface(sftp, { commandTimeoutMs, onTimeout }) {
86
86
  sftp.rename(a, b, (e2) => {
87
87
  if (e2) {
88
88
  // Roll the original back into place before reporting the failure.
89
- return sftp.rename(bak, b, () => cb(e2))
89
+ return sftp.rename(bak, b, (rollbackError) => {
90
+ if (!rollbackError) return cb(e2)
91
+ const message = `SFTP install failed (${e2.message || e2}). Rollback failed (${rollbackError.message || rollbackError}). Original file retained at ${bak}`
92
+ return cb(Object.assign(new AggregateError([e2, rollbackError], message), { code: e2.code }))
93
+ })
90
94
  }
91
95
  // Best effort: a leftover backup must not fail the operation.
92
96
  sftp.unlink(bak, () => cb(null))
package/lib/sshconfig.js CHANGED
@@ -26,6 +26,13 @@
26
26
  // • `Include` directives, globbed, expanded in place, relative to ~/.ssh
27
27
  // (falling back to the including file's directory), depth- and cycle-limited.
28
28
  // • backslash line continuations.
29
+ // • `Match` lines are block boundaries exactly like Host lines — criteria are
30
+ // NOT evaluated here, so a Match section's options belong to NOTHING, never
31
+ // to the Host block above (continues the ssh-config alias line: #38 import,
32
+ // #211 alias backend).
33
+ // • `keyword=value` is accepted alongside `keyword value` (ssh_config(5)).
34
+ // • options BEFORE the first Host/Match line ride along as file-level defaults
35
+ // at lowest precedence, so a bare alias still receives them.
29
36
  //
30
37
  // The module is pure (I/O is injectable), so it is unit-testable without a real
31
38
  // home directory — see test/sshconfig.test.js.
@@ -182,32 +189,74 @@ export function splitValue(value) {
182
189
 
183
190
  const stripQuotes = (s) => String(s || '').replace(/^"(.*)"$/s, '$1').replace(/^'(.*)'$/s, '$1')
184
191
 
192
+ /** Split one config line into [keyword, value] (null when there is no value).
193
+ * ssh_config(5): keyword and value are separated by whitespace, or by optional
194
+ * whitespace and exactly one `=` — `Port=2222`, `Port = 2222` and `Port 2222`
195
+ * all mean the same thing to ssh, so a keyword may never contain `=`. */
196
+ const matchKeywordValue = (line) => String(line).match(/^([^\s=]+)(?:\s*=\s*|\s+)(.*)$/)
197
+
185
198
  /**
186
199
  * Parse OpenSSH config text into Host BLOCKS, preserving pattern lists.
200
+ *
201
+ * Three ssh facts the parser owes the resolver (continues the ssh-config alias
202
+ * line, issues #38 / #211):
203
+ * • a `Match` line ends the current block exactly as a `Host` line does —
204
+ * Match criteria are NOT evaluated here, so the section's options belong to
205
+ * nothing rather than leaking into the block above;
206
+ * • `keyword=value` is valid ssh_config(5) syntax (matchKeywordValue);
207
+ * • options BEFORE the first Host/Match line apply to every host: they are
208
+ * collected into one leading `global: true` block (first-obtained, exactly
209
+ * as ssh processes a file top-to-bottom).
187
210
  * @param {string} text
188
- * @returns {Array<{patterns: string[], values: Record<string, string|number>, line: number}>}
211
+ * @returns {Array<{patterns: string[], values: Record<string, string|number>, line: number, global?: true}>}
189
212
  */
190
213
  export function parseHostBlocks(text) {
191
214
  const blocks = []
192
215
  let current = null
216
+ let globalBlock = null
217
+ let inSection = false
193
218
  const lines = configLines(text)
194
219
  for (let i = 0; i < lines.length; i += 1) {
195
220
  const line = lines[i].trim()
196
221
  if (!line || line.startsWith('#')) continue
197
- const m = line.match(/^(\S+)\s+(.*)$/)
222
+ const m = matchKeywordValue(line)
198
223
  if (!m) continue
199
224
  const key = m[1].toLowerCase()
200
225
  const value = m[2].trim()
201
226
  if (key === 'host') {
227
+ inSection = true
202
228
  current = { patterns: splitValue(value), values: {}, line: i + 1 }
203
229
  blocks.push(current)
204
230
  continue
205
231
  }
206
- if (!current || !KNOWN_PARAMS.has(key)) continue
232
+ if (key === 'match') {
233
+ // The section's options are not ours to evaluate: set no target, so they
234
+ // are attributed to nothing instead of leaking into the block above
235
+ // (verified against real `ssh -G`, which never lets them leak).
236
+ inSection = true
237
+ current = null
238
+ continue
239
+ }
240
+ let target = current
241
+ if (!target && !inSection) {
242
+ // Before the first Host/Match line: a file-level option, global to every
243
+ // host in real ssh.
244
+ if (!globalBlock) globalBlock = { patterns: ['*'], values: {}, line: i + 1, global: true }
245
+ target = globalBlock
246
+ }
247
+ if (!target || !KNOWN_PARAMS.has(key)) continue
207
248
  // First value wins inside a block too (a repeated parameter is ignored).
208
- if (Object.prototype.hasOwnProperty.call(current.values, key)) continue
209
- current.values[key] = key === 'port' ? (Number(value) || value) : stripQuotes(value)
249
+ if (Object.prototype.hasOwnProperty.call(target.values, key)) continue
250
+ target.values[key] = key === 'port' ? (Number(value) || value) : stripQuotes(value)
210
251
  }
252
+ // File-level options sit at the TOP of the file, and ssh processes a config
253
+ // top-to-bottom with first-obtained-wins: a top `Port 2200` is obtained BEFORE
254
+ // any Host block's own port, so `ssh -G a` reports 2200 even when block a
255
+ // sets its own port (verified against real ssh). Unshift keeps the block
256
+ // array in physical file order, so the resolver's cross-block
257
+ // first-obtained-wins reproduces that exactly — globals are defaults for
258
+ // parameters no one set, and WIN for parameters they set first.
259
+ if (globalBlock) blocks.unshift(globalBlock)
211
260
  return blocks
212
261
  }
213
262
 
@@ -222,7 +271,7 @@ export function parseSshConfig(text) {
222
271
  for (const raw of configLines(text)) {
223
272
  const line = raw.trim()
224
273
  if (!line || line.startsWith('#')) continue
225
- const m = line.match(/^(\S+)\s+(.*)$/)
274
+ const m = matchKeywordValue(line)
226
275
  if (!m) continue
227
276
  const key = m[1].toLowerCase()
228
277
  const val = m[2].trim()
@@ -231,6 +280,9 @@ export function parseSshConfig(text) {
231
280
  entries.push(cur)
232
281
  continue
233
282
  }
283
+ // Same boundary as parseHostBlocks: a Match section's options are not ours
284
+ // to evaluate and must not leak into the entry above.
285
+ if (key === 'match') { cur = null; continue }
234
286
  if (!cur) continue
235
287
  if (key === 'hostname' && !cur.hostName) cur.hostName = stripQuotes(val)
236
288
  else if (key === 'user' && !cur.user) cur.user = stripQuotes(val)
@@ -324,7 +376,10 @@ export function resolveSshHost(alias, text) {
324
376
  if (!name) return out
325
377
  for (const block of parseHostBlocks(text)) {
326
378
  if (!hostBlockMatches(block.patterns, name)) continue
327
- out.matched = true
379
+ // File-level defaults (global: true) carry values but do not NAME the
380
+ // alias: an unknown host keeps matched=false, so the no-matching-block
381
+ // warning survives a file that merely carries global options.
382
+ if (!block.global) out.matched = true
328
383
  // first obtained value wins, ACROSS blocks in file order
329
384
  for (const [key, value] of Object.entries(block.values)) {
330
385
  if (key === 'hostname') { if (!out.hostName) out.hostName = String(value) }
@@ -18,8 +18,9 @@ export function createSyncActivity() {
18
18
  const result = await fn((next) => { stats = next || {} })
19
19
  if (current()) {
20
20
  const conflicts = Array.isArray(stats.conflicts) ? stats.conflicts.map((c) => ({ path: c.path, reason: c.reason })) : []
21
- const partial = !!(stats.failed || stats.abortedError || stats.truncated || stats.skippedLarge)
22
- entries.set(local, { token, phase: conflicts.length ? 'conflicts' : partial ? 'partial' : 'completed', operation, updatedAt: new Date().toISOString(), files: stats.files || 0, conflicts, error: stats.abortedError || '' })
21
+ const partial = !!(stats.cancelled || stats.failed || stats.abortedError || stats.truncated || stats.skippedLarge)
22
+ const phase = conflicts.length && !stats.cancelled ? 'conflicts' : partial ? 'partial' : 'completed'
23
+ entries.set(local, { token, phase, operation, updatedAt: new Date().toISOString(), files: stats.files || 0, conflicts, error: stats.abortedError || '', ...(stats.cancelled ? { cancelled: true } : {}) })
23
24
  }
24
25
  return result
25
26
  } catch (err) {