mux-sesh 1.4.0 → 1.5.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.
@@ -1,17 +1,215 @@
1
1
  import { join } from 'path'
2
2
  import { mkdir } from 'fs/promises'
3
- import type { Config } from '../types'
3
+ import type { Config, IconConfig, KeybindMode, ProjectProfile, ProjectWildcard, SessionDefaults, SortOrder, ZoxideMode } from '../types'
4
+
5
+ const DEFAULT_EDITOR = 'nvim'
6
+ const DEFAULT_EDITOR_COMMAND =
7
+ "nvim -c \"lua vim.defer_fn(function() if pcall(require, 'telescope') then vim.cmd('Telescope find_files') end end, 100)\""
8
+ const DEFAULT_ICONS: IconConfig = {
9
+ tmux: '',
10
+ configured: '',
11
+ project: '',
12
+ opencode: '',
13
+ }
14
+
15
+ function isRecord(value: unknown): value is Record<string, unknown> {
16
+ return typeof value === 'object' && value !== null
17
+ }
18
+
19
+ function asString(value: unknown): string | undefined {
20
+ return typeof value === 'string' && value.length > 0 ? value : undefined
21
+ }
22
+
23
+ function asBoolean(value: unknown): boolean | undefined {
24
+ return typeof value === 'boolean' ? value : undefined
25
+ }
26
+
27
+ function asStringArray(value: unknown): string[] | undefined {
28
+ if (!Array.isArray(value)) {
29
+ return undefined
30
+ }
31
+
32
+ const strings = value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)
33
+ return strings.length > 0 ? strings : undefined
34
+ }
35
+
36
+ function asKeybindMode(value: unknown): KeybindMode | undefined {
37
+ return value === 'vim' || value === 'standard' ? value : undefined
38
+ }
39
+
40
+ function asZoxideMode(value: unknown): ZoxideMode | undefined {
41
+ return value === 'off' || value === 'rank' || value === 'merge' ? value : undefined
42
+ }
43
+
44
+ function asSortOrder(value: unknown): SortOrder | undefined {
45
+ return value === 'live-first' || value === 'configured-first' || value === 'zoxide-first' || value === 'alphabetical'
46
+ ? value
47
+ : undefined
48
+ }
49
+
50
+ function asPositiveInteger(value: unknown): number | undefined {
51
+ return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined
52
+ }
53
+
54
+ function expandHomePath(value: string, homeDir: string): string {
55
+ if (!value.startsWith('~')) {
56
+ return value
57
+ }
58
+
59
+ return join(homeDir, value.slice(1))
60
+ }
61
+
62
+ function normalizeSessionDefaults(value: unknown): SessionDefaults | undefined {
63
+ if (!isRecord(value)) {
64
+ return undefined
65
+ }
66
+
67
+ const startupCommand = asString(value.startup_command) ?? asString(value.startupCommand)
68
+ const previewCommand = asString(value.preview_command) ?? asString(value.previewCommand)
69
+
70
+ if (!startupCommand && !previewCommand) {
71
+ return undefined
72
+ }
4
73
 
5
- export function getDefaultConfig(): Config {
6
- const homeDir = process.env.HOME || '~'
74
+ return {
75
+ startupCommand,
76
+ previewCommand,
77
+ }
78
+ }
79
+
80
+ function normalizeIcons(value: unknown): IconConfig | undefined {
81
+ if (!isRecord(value)) {
82
+ return undefined
83
+ }
84
+
85
+ return {
86
+ tmux: asString(value.tmux) ?? DEFAULT_ICONS.tmux,
87
+ configured: asString(value.configured) ?? asString(value.config) ?? DEFAULT_ICONS.configured,
88
+ project: asString(value.project) ?? DEFAULT_ICONS.project,
89
+ opencode: asString(value.opencode) ?? DEFAULT_ICONS.opencode,
90
+ }
91
+ }
92
+
93
+ function normalizeProjectProfiles(value: unknown, homeDir: string): ProjectProfile[] | undefined {
94
+ if (!Array.isArray(value)) {
95
+ return undefined
96
+ }
97
+
98
+ const profiles = value.flatMap(entry => {
99
+ if (!isRecord(entry)) {
100
+ return []
101
+ }
102
+
103
+ const path = asString(entry.path)
104
+ if (!path) {
105
+ return []
106
+ }
107
+
108
+ return [
109
+ {
110
+ path: expandHomePath(path, homeDir),
111
+ sessionName: asString(entry.session_name) ?? asString(entry.sessionName),
112
+ startupCommand: asString(entry.startup_command) ?? asString(entry.startupCommand),
113
+ previewCommand: asString(entry.preview_command) ?? asString(entry.previewCommand),
114
+ listed: asBoolean(entry.listed),
115
+ icon: asString(entry.icon),
116
+ },
117
+ ]
118
+ })
119
+
120
+ return profiles.length > 0 ? profiles : undefined
121
+ }
122
+
123
+ function normalizeWildcards(value: unknown, homeDir: string): ProjectWildcard[] | undefined {
124
+ if (!Array.isArray(value)) {
125
+ return undefined
126
+ }
127
+
128
+ const wildcards = value.flatMap(entry => {
129
+ if (!isRecord(entry)) {
130
+ return []
131
+ }
132
+
133
+ const pattern = asString(entry.pattern)
134
+ if (!pattern) {
135
+ return []
136
+ }
137
+
138
+ return [
139
+ {
140
+ pattern: expandHomePath(pattern, homeDir),
141
+ sessionName: asString(entry.session_name) ?? asString(entry.sessionName),
142
+ startupCommand: asString(entry.startup_command) ?? asString(entry.startupCommand),
143
+ previewCommand: asString(entry.preview_command) ?? asString(entry.previewCommand),
144
+ },
145
+ ]
146
+ })
147
+
148
+ return wildcards.length > 0 ? wildcards : undefined
149
+ }
150
+
151
+ export function normalizeConfig(rawConfig: unknown, homeDir = process.env.HOME || '~'): Config {
152
+ const raw = isRecord(rawConfig) ? rawConfig : {}
153
+ const defaultConfig = getDefaultConfig(homeDir)
154
+
155
+ const projectPaths = (asStringArray(raw.project_paths) ?? asStringArray(raw.projectPaths) ?? defaultConfig.projectPaths).map(
156
+ projectPath => expandHomePath(projectPath, homeDir)
157
+ )
158
+ const reposPath = expandHomePath(
159
+ asString(raw.repos_path) ?? asString(raw.reposPath) ?? defaultConfig.reposPath,
160
+ homeDir
161
+ )
162
+ const editor = asString(raw.editor) ?? defaultConfig.editor
163
+ const editorCmd = asString(raw.editor_cmd) ?? asString(raw.editorCmd) ?? defaultConfig.editorCmd
164
+ const keybindMode = asKeybindMode(raw.keybind_mode) ?? asKeybindMode(raw.keybindMode) ?? defaultConfig.keybindMode
165
+ const zoxideMode = asZoxideMode(raw.zoxide_mode) ?? asZoxideMode(raw.zoxideMode) ?? defaultConfig.zoxideMode
166
+ const sortOrder = asSortOrder(raw.sort_order) ?? asSortOrder(raw.sortOrder) ?? defaultConfig.sortOrder
167
+ const autoUpdate = asBoolean(raw.auto_update) ?? asBoolean(raw.autoUpdate) ?? defaultConfig.autoUpdate
168
+ const dirLength = asPositiveInteger(raw.dir_length) ?? asPositiveInteger(raw.dirLength) ?? defaultConfig.dirLength
169
+ const hiddenSessions = asStringArray(raw.hidden_sessions) ?? asStringArray(raw.hiddenSessions) ?? defaultConfig.hiddenSessions
170
+ const icons = normalizeIcons(raw.icons) ?? defaultConfig.icons
171
+ const configuredDefaultSession = normalizeSessionDefaults(raw.default_session) ?? normalizeSessionDefaults(raw.defaultSession)
172
+ const defaultSession = {
173
+ startupCommand: configuredDefaultSession?.startupCommand ?? editorCmd,
174
+ previewCommand: configuredDefaultSession?.previewCommand,
175
+ }
176
+
177
+ return {
178
+ projectPaths,
179
+ reposPath,
180
+ editor,
181
+ editorCmd,
182
+ keybindMode,
183
+ zoxideMode,
184
+ sortOrder,
185
+ autoUpdate,
186
+ dirLength,
187
+ hiddenSessions,
188
+ icons,
189
+ defaultSession,
190
+ projects: normalizeProjectProfiles(raw.projects, homeDir) ?? defaultConfig.projects,
191
+ wildcards: normalizeWildcards(raw.wildcards, homeDir) ?? defaultConfig.wildcards,
192
+ }
193
+ }
194
+
195
+ export function getDefaultConfig(homeDir = process.env.HOME || '~'): Config {
7
196
  return {
8
197
  projectPaths: [join(homeDir, 'dev'), join(homeDir, 'personal')],
9
198
  reposPath: join(homeDir, 'dev', 'repos'),
10
- editor: 'nvim',
11
- editorCmd:
12
- "nvim -c \"lua vim.defer_fn(function() if pcall(require, 'telescope') then vim.cmd('Telescope find_files') end end, 100)\"",
199
+ editor: DEFAULT_EDITOR,
200
+ editorCmd: DEFAULT_EDITOR_COMMAND,
13
201
  keybindMode: 'vim',
202
+ zoxideMode: 'off',
203
+ sortOrder: 'live-first',
14
204
  autoUpdate: true,
205
+ dirLength: 1,
206
+ hiddenSessions: [],
207
+ icons: DEFAULT_ICONS,
208
+ defaultSession: {
209
+ startupCommand: DEFAULT_EDITOR_COMMAND,
210
+ },
211
+ projects: [],
212
+ wildcards: [],
15
213
  }
16
214
  }
17
215
 
@@ -21,19 +219,8 @@ export async function loadConfig(): Promise<Config> {
21
219
 
22
220
  try {
23
221
  const file = Bun.file(configPath)
24
- const config = await file.json()
25
-
26
- // Convert snake_case keys to camelCase for TypeScript
27
- return {
28
- ...getDefaultConfig(),
29
- projectPaths: config.project_paths || config.projectPaths,
30
- reposPath: config.repos_path || config.reposPath,
31
- editor: config.editor,
32
- editorCmd: config.editor_cmd || config.editorCmd,
33
- keybindMode: config.keybind_mode || config.keybindMode,
34
- autoUpdate: config.auto_update || config.autoUpdate,
35
- }
36
- } catch (error) {
222
+ return normalizeConfig(await file.json(), process.env.HOME || '~')
223
+ } catch {
37
224
  // Config doesn't exist, create default
38
225
  const defaultConfig = getDefaultConfig()
39
226
  await saveConfig(defaultConfig)
@@ -0,0 +1,36 @@
1
+ import type { Config, Item, ProjectProfile } from '../types'
2
+ import { resolveProjectSession } from './session-rules'
3
+
4
+ function displayPath(path: string): string {
5
+ return path.replace(process.env.HOME || '', '~')
6
+ }
7
+
8
+ function isListedProjectProfile(profile: ProjectProfile): boolean {
9
+ return profile.listed === true
10
+ }
11
+
12
+ export async function getListedSessionItems(config: Config): Promise<Item[]> {
13
+ const listedProfiles = (config.projects ?? []).filter(isListedProjectProfile)
14
+
15
+ return Promise.all(
16
+ listedProfiles.map(async profile => {
17
+ const resolvedSession = await resolveProjectSession(profile.path, config)
18
+
19
+ return {
20
+ title: resolvedSession.sessionName,
21
+ desc: displayPath(profile.path),
22
+ path: profile.path,
23
+ isSession: false,
24
+ itemKind: 'configured' as const,
25
+ icon: profile.icon,
26
+ }
27
+ })
28
+ )
29
+ }
30
+
31
+ export function mergeSessionItems(tmuxSessions: Item[], listedSessions: Item[]): Item[] {
32
+ const liveSessionTitles = new Set(tmuxSessions.map(item => item.title))
33
+ const uniqueListedSessions = listedSessions.filter(item => !liveSessionTitles.has(item.title))
34
+
35
+ return [...tmuxSessions, ...uniqueListedSessions]
36
+ }
@@ -0,0 +1,101 @@
1
+ import { basename } from 'path'
2
+ import { spawn } from 'bun'
3
+ import type { Config, ProjectProfile, ProjectWildcard } from '../types'
4
+ import { matchesGlob, normalizePathForMatching } from '../util/glob'
5
+
6
+ export interface ResolvedProjectSession {
7
+ sessionName: string
8
+ startupCommand?: string
9
+ previewCommand?: string
10
+ source: 'project' | 'wildcard' | 'default'
11
+ }
12
+
13
+ export interface ResolveProjectSessionOptions {
14
+ getGitRoot?: (projectPath: string) => Promise<string | null>
15
+ }
16
+
17
+ function sanitizeSessionName(value: string): string {
18
+ return value.replace(/[.\s/]+/g, '_')
19
+ }
20
+
21
+ function pathMatches(projectPath: string, pattern: string): boolean {
22
+ return matchesGlob(normalizePathForMatching(projectPath), normalizePathForMatching(pattern), {
23
+ pathSeparatorAware: true,
24
+ })
25
+ }
26
+
27
+ function findProjectProfile(projectPath: string, config: Config): ProjectProfile | undefined {
28
+ return config.projects?.find(profile => normalizePathForMatching(profile.path) === projectPath)
29
+ }
30
+
31
+ function findWildcard(projectPath: string, config: Config): ProjectWildcard | undefined {
32
+ return config.wildcards?.find(wildcard => pathMatches(projectPath, wildcard.pattern))
33
+ }
34
+
35
+ export async function getGitRoot(projectPath: string): Promise<string | null> {
36
+ try {
37
+ const proc = spawn(['git', '-C', projectPath, 'rev-parse', '--show-toplevel'], {
38
+ stderr: 'pipe',
39
+ })
40
+ const output = (await new Response(proc.stdout).text()).trim()
41
+ await proc.exited
42
+
43
+ if (proc.exitCode !== 0 || output.length === 0) {
44
+ return null
45
+ }
46
+
47
+ return output
48
+ } catch {
49
+ return null
50
+ }
51
+ }
52
+
53
+ function buildSessionName(projectPath: string, dirLength = 1, gitRoot: string | null): string {
54
+ const namingPath = normalizePathForMatching(gitRoot ?? projectPath)
55
+ const parts = namingPath.split('/').filter(Boolean)
56
+ const segmentCount = Math.max(1, dirLength)
57
+ const relevantParts = parts.slice(-segmentCount)
58
+ const joined = relevantParts.length > 0 ? relevantParts.join('_') : basename(projectPath)
59
+
60
+ return sanitizeSessionName(joined)
61
+ }
62
+
63
+ export async function resolveProjectSession(
64
+ projectPath: string,
65
+ config: Config,
66
+ options: ResolveProjectSessionOptions = {}
67
+ ): Promise<ResolvedProjectSession> {
68
+ const normalizedProjectPath = normalizePathForMatching(projectPath)
69
+ const getGitRootForPath = options.getGitRoot ?? getGitRoot
70
+ const projectProfile = findProjectProfile(normalizedProjectPath, config)
71
+
72
+ if (projectProfile) {
73
+ const gitRoot = await getGitRootForPath(projectPath)
74
+ return {
75
+ sessionName: sanitizeSessionName(projectProfile.sessionName ?? buildSessionName(projectPath, config.dirLength, gitRoot)),
76
+ startupCommand: projectProfile.startupCommand ?? config.defaultSession?.startupCommand,
77
+ previewCommand: projectProfile.previewCommand ?? config.defaultSession?.previewCommand,
78
+ source: 'project',
79
+ }
80
+ }
81
+
82
+ const wildcard = findWildcard(normalizedProjectPath, config)
83
+ if (wildcard) {
84
+ const gitRoot = await getGitRootForPath(projectPath)
85
+ return {
86
+ sessionName: sanitizeSessionName(wildcard.sessionName ?? buildSessionName(projectPath, config.dirLength, gitRoot)),
87
+ startupCommand: wildcard.startupCommand ?? config.defaultSession?.startupCommand,
88
+ previewCommand: wildcard.previewCommand ?? config.defaultSession?.previewCommand,
89
+ source: 'wildcard',
90
+ }
91
+ }
92
+
93
+ const gitRoot = await getGitRootForPath(projectPath)
94
+
95
+ return {
96
+ sessionName: buildSessionName(projectPath, config.dirLength, gitRoot),
97
+ startupCommand: config.defaultSession?.startupCommand,
98
+ previewCommand: config.defaultSession?.previewCommand,
99
+ source: 'default',
100
+ }
101
+ }
@@ -1,4 +1,4 @@
1
- import { basename } from 'path'
1
+ import { spawn } from 'bun'
2
2
  import type { Item, Config } from '../types'
3
3
  import {
4
4
  switchTmuxSession,
@@ -6,16 +6,31 @@ import {
6
6
  killTmuxSession,
7
7
  renameTmuxSession,
8
8
  createNamedTmuxSession,
9
+ getCurrentTmuxSessionName,
10
+ getTmuxSessionDirectory,
9
11
  } from '../tmux/index'
12
+ import { getGitRoot, resolveProjectSession } from '../config/session-rules'
13
+ import { getLastSessionTarget } from '../tmux/workflows'
10
14
  import { isGitHubURL, cloneGitHubRepo } from '../util/github'
11
15
  import { requestShutdown } from '../util/shutdown'
12
16
 
13
- export async function handleSelect(item: Item) {
17
+ function quoteShellArg(value: string): string {
18
+ return `'${value.replaceAll("'", "'\\''")}'`
19
+ }
20
+
21
+ export async function handleSelect(item: Item, config: Config | null) {
14
22
  if (item.isSession) {
15
23
  await switchTmuxSession(item.title)
16
24
  await requestShutdown(0)
17
25
  } else {
18
- await createTmuxSession(item.title, item.path)
26
+ if (!config) {
27
+ throw new Error('Config is not loaded yet')
28
+ }
29
+
30
+ const resolvedSession = await resolveProjectSession(item.path, config)
31
+ await createTmuxSession(resolvedSession.sessionName, item.path, {
32
+ startupCommand: resolvedSession.startupCommand,
33
+ })
19
34
  await requestShutdown(0)
20
35
  }
21
36
  }
@@ -70,18 +85,90 @@ export async function handleNewSessionSubmit(
70
85
  try {
71
86
  if (!config) return
72
87
  const clonedPath = await cloneGitHubRepo(searchTerm, config)
73
- const repoName = basename(clonedPath)
74
- await createTmuxSession(repoName, clonedPath)
88
+ const resolvedSession = await resolveProjectSession(clonedPath, config)
89
+ await createTmuxSession(resolvedSession.sessionName, clonedPath, {
90
+ startupCommand: resolvedSession.startupCommand,
91
+ })
75
92
  await requestShutdown(0)
76
93
  } catch (error) {
77
94
  throw new Error(`Error cloning repository: ${error}`)
78
95
  }
79
96
  } else if (items.length > 0 && cursor < items.length) {
80
97
  const selectedItem = items[cursor]
81
- await createTmuxSession(selectedItem.title, selectedItem.path)
98
+ if (!config) {
99
+ throw new Error('Config is not loaded yet')
100
+ }
101
+
102
+ const resolvedSession = await resolveProjectSession(selectedItem.path, config)
103
+ await createTmuxSession(resolvedSession.sessionName, selectedItem.path, {
104
+ startupCommand: resolvedSession.startupCommand,
105
+ })
82
106
  await requestShutdown(0)
83
107
  } else {
84
108
  await createNamedTmuxSession(searchTerm)
85
109
  await requestShutdown(0)
86
110
  }
87
111
  }
112
+
113
+ export async function handleLastSession(items: Item[]) {
114
+ const currentSessionName = await getCurrentTmuxSessionName().catch(() => undefined)
115
+ const target = getLastSessionTarget(items, currentSessionName)
116
+
117
+ if (!target) {
118
+ throw new Error('No previous tmux session is available')
119
+ }
120
+
121
+ await switchTmuxSession(target.title)
122
+ await requestShutdown(0)
123
+ }
124
+
125
+ export async function handleRootSession(item: Item | undefined, config: Config | null) {
126
+ if (!item) {
127
+ throw new Error('No session or project is selected')
128
+ }
129
+
130
+ if (!config) {
131
+ throw new Error('Config is not loaded yet')
132
+ }
133
+
134
+ const itemPath = item.isSession ? await getTmuxSessionDirectory(item.title) : item.path
135
+ const rootPath = (await getGitRoot(itemPath)) ?? itemPath
136
+ const resolvedSession = await resolveProjectSession(rootPath, config)
137
+
138
+ await createTmuxSession(resolvedSession.sessionName, rootPath, {
139
+ startupCommand: resolvedSession.startupCommand,
140
+ })
141
+ await requestShutdown(0)
142
+ }
143
+
144
+ export async function handleEditTarget(item: Item | undefined, config: Config | null) {
145
+ if (!item || item.itemKind !== 'configured') {
146
+ throw new Error('Select a configured session to edit its target')
147
+ }
148
+
149
+ if (!config) {
150
+ throw new Error('Config is not loaded yet')
151
+ }
152
+
153
+ const command = `${config.editor} ${quoteShellArg(item.path)}`
154
+
155
+ if (process.env.TMUX) {
156
+ const proc = spawn(['tmux', 'new-window', '-c', item.path, command], { stderr: 'pipe' })
157
+ await proc.exited
158
+
159
+ if (proc.exitCode !== 0) {
160
+ throw new Error(`Failed to open editor for '${item.title}'`)
161
+ }
162
+
163
+ await requestShutdown(0)
164
+ return
165
+ }
166
+
167
+ spawn(['sh', '-lc', command], {
168
+ cwd: item.path,
169
+ stdin: 'inherit',
170
+ stdout: 'inherit',
171
+ stderr: 'inherit',
172
+ })
173
+ await requestShutdown(0)
174
+ }