-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathhelpers.ts
More file actions
189 lines (167 loc) · 6.95 KB
/
helpers.ts
File metadata and controls
189 lines (167 loc) · 6.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { getDefaultEnvManagerSetting, getDefaultPkgManagerSetting } from '../../features/settings/settingHelpers';
import { EnvironmentManagers, PythonProjectManager } from '../../internal.api';
import { getUvEnvironments } from '../../managers/builtin/uvEnvironments';
import { ISSUES_URL } from '../constants';
import { traceInfo, traceVerbose, traceWarn } from '../logging';
import { getWorkspaceFolders } from '../workspace.apis';
import { EventNames } from './constants';
import { sendTelemetryEvent } from './sender';
/**
* Extracts the base tool name from a manager ID.
* Example: 'ms-python.python:venv' -> 'venv'
* Example: 'ms-python.python:conda' -> 'conda'
*/
function extractToolName(managerId: string): string {
// Manager IDs follow the pattern 'extensionId:toolName'
const parts = managerId.split(':');
return parts.length > 1 ? parts[1].toLowerCase() : managerId.toLowerCase();
}
export function sendManagerSelectionTelemetry(pm: PythonProjectManager) {
const ems: Set<string> = new Set();
const ps: Set<string> = new Set();
pm.getProjects().forEach((project) => {
const m = getDefaultEnvManagerSetting(pm, project.uri);
if (m) {
ems.add(m);
}
const p = getDefaultPkgManagerSetting(pm, project.uri);
if (p) {
ps.add(p);
}
});
ems.forEach((em) => {
sendTelemetryEvent(EventNames.ENVIRONMENT_MANAGER_SELECTED, undefined, { managerId: em });
});
ps.forEach((pkg) => {
sendTelemetryEvent(EventNames.PACKAGE_MANAGER_SELECTED, undefined, { managerId: pkg });
});
}
export async function sendProjectStructureTelemetry(
pm: PythonProjectManager,
envManagers: EnvironmentManagers,
): Promise<void> {
const projects = pm.getProjects();
// 1. Total project count
const totalProjectCount = projects.length;
// 2. Unique interpreter count
const interpreterPaths = new Set<string>();
for (const project of projects) {
try {
const env = await envManagers.getEnvironment(project.uri);
if (env?.environmentPath) {
interpreterPaths.add(env.environmentPath.fsPath);
}
} catch {
// Ignore errors when getting environment for a project
}
}
const uniqueInterpreterCount = interpreterPaths.size;
// 3. Projects under workspace root count
const workspaceFolders = getWorkspaceFolders() ?? [];
let projectUnderRoot = 0;
for (const project of projects) {
for (const wsFolder of workspaceFolders) {
const workspacePath = wsFolder.uri.fsPath;
const projectPath = project.uri.fsPath;
// Check if project is a subdirectory of workspace folder:
// - Path must start with workspace path
// - Path must not be equal to workspace path
// - The character after workspace path must be a path separator
if (
projectPath !== workspacePath &&
projectPath.startsWith(workspacePath) &&
(projectPath[workspacePath.length] === '/' || projectPath[workspacePath.length] === '\\')
) {
projectUnderRoot++;
break; // Count each project only once even if under multiple workspace folders
}
}
}
sendTelemetryEvent(EventNames.PROJECT_STRUCTURE, undefined, {
totalProjectCount,
uniqueInterpreterCount,
projectUnderRoot,
});
}
/**
* Sends telemetry about which environment tools are actively used across all projects.
* This tracks ACTUAL USAGE (which environments are set for projects), not just what's installed.
*
* Fires one event per tool that has at least one project using it.
* This allows simple deduplication: dcount(machineId) by toolName gives unique users per tool.
*
* Called once at extension activation to understand user's environment tool usage patterns.
*/
export async function sendEnvironmentToolUsageTelemetry(
pm: PythonProjectManager,
envManagers: EnvironmentManagers,
): Promise<void> {
try {
const projects = pm.getProjects();
// Track which tools are used (Set ensures uniqueness)
const toolsUsed = new Set<string>();
// Lazily loaded once when a venv environment is first encountered
let uvEnvPaths: string[] | undefined;
// Check which environment manager is used for each project
for (const project of projects) {
try {
const env = await envManagers.getEnvironment(project.uri);
if (env?.envId?.managerId) {
let toolName = extractToolName(env.envId.managerId);
// UV environments share the venv manager. Check the persistent UV env list instead
if (toolName === 'venv' && env.environmentPath) {
uvEnvPaths ??= await getUvEnvironments();
if (uvEnvPaths.includes(env.environmentPath.fsPath)) {
toolName = 'uv';
}
}
// Normalize 'global' to 'system' for consistency
if (toolName === 'global') {
toolName = 'system';
}
toolsUsed.add(toolName);
}
} catch {
// Ignore errors when getting environment for a project
}
}
// Fire one event per tool used
toolsUsed.forEach((tool) => {
sendTelemetryEvent(EventNames.ENVIRONMENT_TOOL_USAGE, undefined, {
toolName: tool,
});
});
} catch (error) {
// Telemetry failures must never disrupt extension activation
traceVerbose('Failed to send environment tool usage telemetry:', error);
}
}
/**
* Logs a summary of environment discovery results after startup.
* If no environments are found, logs guidance to help users troubleshoot.
*/
export async function logDiscoverySummary(envManagers: EnvironmentManagers): Promise<void> {
const managers = envManagers.managers;
let totalEnvCount = 0;
const managerSummaries: string[] = [];
for (const manager of managers) {
try {
const envs = await manager.getEnvironments('all');
totalEnvCount += envs.length;
managerSummaries.push(`${manager.displayName}: ${envs.length}`);
} catch {
managerSummaries.push(`${manager.displayName}: error`);
}
}
if (totalEnvCount === 0) {
traceWarn(
`No Python environments were found. ` +
`Try running "Python Environments: Run Python Environment Tool (PET) in Terminal..." from the Command Palette to diagnose. ` +
`If environments should be detected, please report this: ${ISSUES_URL}/new`,
);
} else {
traceInfo(
`Environment discovery complete: ${totalEnvCount} environments found (${managerSummaries.join(', ')})`,
);
}
}