Skip to content
Open

M1 #3920

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions extension/src/debugAdapter/goDebug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ export function normalizeSeparators(filePath: string): string {
// casing.
// This is a workaround for issue in https://github.com/Microsoft/vscode/issues/9448#issuecomment-244804026
if (filePath.indexOf(':') === 1) {
filePath = filePath.substr(0, 1).toUpperCase() + filePath.substr(1);
filePath = filePath.substring(0, 1).toUpperCase() + filePath.substring(1);
}
return filePath.replace(/\/|\\/g, '/');
}
Expand Down Expand Up @@ -634,7 +634,7 @@ export class Delve {
if (mode === 'exec' || (mode === 'debug' && !isProgramDirectory)) {
dlvArgs.push(program);
} else if (currentGOWorkspace && !launchArgs.packagePathToGoModPathMap[dirname]) {
dlvArgs.push(dirname.substr(currentGOWorkspace.length + 1));
dlvArgs.push(dirname.substring(currentGOWorkspace.length + 1));
}
// add user-specified dlv flags first. When duplicate flags are specified,
// dlv doesn't mind but accepts the last flag value.
Expand Down Expand Up @@ -1212,7 +1212,7 @@ export class GoDebugSession extends LoggingDebugSession {
}

const relativeRemotePath = remotePath
.substr(importPathIndex)
.substring(importPathIndex)
.split(this.remotePathSeparator)
.join(this.localPathSeparator);
const pathToConvertWithLocalSeparator = remotePath
Expand Down Expand Up @@ -1253,7 +1253,7 @@ export class GoDebugSession extends LoggingDebugSession {
const goroot = this.getGOROOT();
const localGoRootImportPath = path.join(
goroot,
srcIndex >= 0 ? remotePathWithLocalSeparator.substr(srcIndex) : path.join('src', relativeRemotePath)
srcIndex >= 0 ? remotePathWithLocalSeparator.substring(srcIndex) : path.join('src', relativeRemotePath)
);
if (this.fileSystem.existsSync(localGoRootImportPath)) {
return localGoRootImportPath;
Expand Down Expand Up @@ -1281,7 +1281,7 @@ export class GoDebugSession extends LoggingDebugSession {
const localGoPathImportPath = path.join(
gopath,
indexGoModCache >= 0
? remotePathWithLocalSeparator.substr(indexGoModCache)
? remotePathWithLocalSeparator.substring(indexGoModCache)
: path.join('pkg', 'mod', relativeRemotePath)
);
if (this.fileSystem.existsSync(localGoPathImportPath)) {
Expand Down Expand Up @@ -1340,7 +1340,7 @@ export class GoDebugSession extends LoggingDebugSession {
const index = pathToConvert.indexOf(`${this.remotePathSeparator}src${this.remotePathSeparator}`);
const goroot = this.getGOROOT();
if (goroot && index > 0) {
return path.join(goroot, pathToConvert.substr(index));
return path.join(goroot, pathToConvert.substring(index));
}

const indexGoModCache = pathToConvert.indexOf(
Expand All @@ -1352,7 +1352,7 @@ export class GoDebugSession extends LoggingDebugSession {
return path.join(
gopath,
pathToConvert
.substr(indexGoModCache)
.substring(indexGoModCache)
.split(this.remotePathSeparator ?? '')
.join(this.localPathSeparator)
);
Expand Down Expand Up @@ -1647,7 +1647,7 @@ export class GoDebugSession extends LoggingDebugSession {
: (<ListVarsOut>listPkgVarsOut).Variables;
let initdoneIndex = -1;
for (let i = 0; i < globals.length; i++) {
globals[i].name = globals[i].name.substr(packageName.length + 1);
globals[i].name = globals[i].name.substring(packageName.length + 1);
if (initdoneIndex === -1 && globals[i].name === this.initdone) {
initdoneIndex = i;
}
Expand Down Expand Up @@ -2308,7 +2308,7 @@ export class GoDebugSession extends LoggingDebugSession {
return resolve();
}
const spaceIndex = stdout.indexOf(' ');
const result = stdout.substr(0, spaceIndex) === 'main' ? 'main' : stdout.substr(spaceIndex).trim();
const result = stdout.substring(0, spaceIndex) === 'main' ? 'main' : stdout.substring(spaceIndex).trim();
this.packageInfo.set(dir, result);
resolve(result);
}
Expand Down
4 changes: 2 additions & 2 deletions extension/src/diffUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ function parseUniDiffs(diffOutput: jsDiff.IUniDiff[]): FilePatch[] {
uniDiff.hunks.forEach((hunk: jsDiff.IHunk) => {
let startLine = hunk.oldStart;
hunk.lines.forEach((line) => {
switch (line.substr(0, 1)) {
switch (line.substring(0, 1)) {
case '-':
edit = new Edit(EditTypes.EDIT_DELETE, new Position(startLine - 1, 0));
edit.end = new Position(startLine, 0);
Expand All @@ -104,7 +104,7 @@ function parseUniDiffs(diffOutput: jsDiff.IUniDiff[]): FilePatch[] {
break;
case '+':
edit = new Edit(EditTypes.EDIT_INSERT, new Position(startLine - 1, 0));
edit.text += line.substr(1) + '\n';
edit.text += line.substring(1) + '\n';
edits.push(edit);
break;
case ' ':
Expand Down
2 changes: 1 addition & 1 deletion extension/src/goBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export async function goBuild(
if (!isMod) {
// Find the right importPath instead of directly using `.`. Fixes https://github.com/Microsoft/vscode-go/issues/846
if (currentGoWorkspace && !isMod) {
importPath = cwd.substr(currentGoWorkspace.length + 1);
importPath = cwd.substring(currentGoWorkspace.length + 1);
} else {
outputChannel.error(
`Not able to determine import path of current package by using cwd: ${cwd} and Go workspace: ${currentGoWorkspace}`
Expand Down
168 changes: 82 additions & 86 deletions extension/src/goCover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,95 +214,91 @@ function clearCoverage() {
* @param packageDirPath Absolute path of the package for which the coverage was calculated
* @param dir Directory to execute go list in
*/
export function applyCodeCoverageToAllEditors(coverProfilePath: string, dir?: string): Promise<void> {
const v = new Promise<void>((resolve, reject) => {
try {
const showCounts = getGoConfig().get('coverShowCounts') as boolean;
const coveragePath = new Map<string, CoverageData>(); // <filename> from the cover profile to the coverage data.

// Clear existing coverage files
clearCoverage();

// collect the packages named in the coverage file
const seenPaths = new Set<string>();
// for now read synchronously and hope for no errors
const contents = fs.readFileSync(coverProfilePath).toString();
contents.split('\n').forEach((line) => {
// go test coverageprofile generates output:
// filename:StartLine.StartColumn,EndLine.EndColumn Hits CoverCount
// where the filename is either the import path + '/' + base file name, or
// the actual file path (either absolute or starting with .)
// See https://golang.org/issues/40251.
//
// The first line will be like "mode: set" which we will ignore.
// TODO: port https://golang.org/cl/179377 for faster parsing.

const parse = line.match(/^(\S+)\:(\d+)\.(\d+)\,(\d+)\.(\d+)\s(\d+)\s(\d+)/);
if (!parse) {
return;
}
export async function applyCodeCoverageToAllEditors(coverProfilePath: string, dir?: string): Promise<void> {
Copy link

Copilot AI Nov 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing applyCodeCoverageToAllEditors from synchronous to asynchronous is a breaking change. All callers of this function must be updated to await the Promise. Verify that all call sites have been updated throughout the codebase to handle the async version, otherwise this will cause runtime errors.

Copilot uses AI. Check for mistakes.
try {
const showCounts = getGoConfig().get('coverShowCounts') as boolean;
const coveragePath = new Map<string, CoverageData>(); // <filename> from the cover profile to the coverage data.

let filename = parse[1];
if (filename.startsWith('.' + path.sep)) {
// If it's a relative file path, convert it to an absolute path.
// From now on, we can assume that it's a real file name if it is
// an absolute path.
filename = path.resolve(filename);
}
// If this is not a real file name, that's package_path + file name,
// Record it in seenPaths for `go list` call to resolve package path ->
// directory mapping.
if (!path.isAbsolute(filename)) {
const lastSlash = filename.lastIndexOf('/');
if (lastSlash !== -1) {
seenPaths.add(filename.slice(0, lastSlash));
}
}
// Clear existing coverage files
clearCoverage();

// and fill in coveragePath
const coverage = coveragePath.get(parse[1]) || emptyCoverageData();
// When line directive is used this information is artificial and
// the source code file can be non-existent or wrong (go.dev/issues/41222).
// There is no perfect way to guess whether the line/col in coverage profile
// is bogus. At least, we know that 0 or negative values are not true line/col.
const startLine = parseInt(parse[2], 10);
const startCol = parseInt(parse[3], 10);
const endLine = parseInt(parse[4], 10);
const endCol = parseInt(parse[5], 10);
if (startLine < 1 || startCol < 1 || endLine < 1 || endCol < 1) {
return;
}
const range = new vscode.Range(
// Convert lines and columns to 0-based
startLine - 1,
startCol - 1,
endLine - 1,
endCol - 1
);

const counts = parseInt(parse[7], 10);
// If is Covered (CoverCount > 0)
if (counts > 0) {
coverage.coveredOptions.push(...elaborate(range, counts, showCounts));
} else {
coverage.uncoveredOptions.push(...elaborate(range, counts, showCounts));
// collect the packages named in the coverage file
const seenPaths = new Set<string>();
// Read coverage file asynchronously to avoid blocking the UI
const contents = await fs.promises.readFile(coverProfilePath, 'utf8');
contents.split('\n').forEach((line) => {
// go test coverageprofile generates output:
// filename:StartLine.StartColumn,EndLine.EndColumn Hits CoverCount
// where the filename is either the import path + '/' + base file name, or
// the actual file path (either absolute or starting with .)
// See https://golang.org/issues/40251.
//
// The first line will be like "mode: set" which we will ignore.
// TODO: port https://golang.org/cl/179377 for faster parsing.

const parse = line.match(/^(\S+)\:(\d+)\.(\d+)\,(\d+)\.(\d+)\s(\d+)\s(\d+)/);
if (!parse) {
return;
}

let filename = parse[1];
if (filename.startsWith('.' + path.sep)) {
// If it's a relative file path, convert it to an absolute path.
// From now on, we can assume that it's a real file name if it is
// an absolute path.
filename = path.resolve(filename);
}
// If this is not a real file name, that's package_path + file name,
// Record it in seenPaths for `go list` call to resolve package path ->
// directory mapping.
if (!path.isAbsolute(filename)) {
const lastSlash = filename.lastIndexOf('/');
if (lastSlash !== -1) {
seenPaths.add(filename.slice(0, lastSlash));
}
}

coveragePath.set(filename, coverage);
});

getImportPathToFolder([...seenPaths], dir).then((pathsToDirs) => {
createCoverageData(pathsToDirs, coveragePath);
setDecorators();
vscode.window.visibleTextEditors.forEach(applyCodeCoverage);
resolve();
});
} catch (e) {
vscode.window.showInformationMessage((e as any).msg);
reject(e);
}
});
return v;
// and fill in coveragePath
const coverage = coveragePath.get(parse[1]) || emptyCoverageData();
// When line directive is used this information is artificial and
// the source code file can be non-existent or wrong (go.dev/issues/41222).
// There is no perfect way to guess whether the line/col in coverage profile
// is bogus. At least, we know that 0 or negative values are not true line/col.
const startLine = parseInt(parse[2], 10);
const startCol = parseInt(parse[3], 10);
const endLine = parseInt(parse[4], 10);
const endCol = parseInt(parse[5], 10);
if (startLine < 1 || startCol < 1 || endLine < 1 || endCol < 1) {
return;
}
const range = new vscode.Range(
// Convert lines and columns to 0-based
startLine - 1,
startCol - 1,
endLine - 1,
endCol - 1
);

const counts = parseInt(parse[7], 10);
// If is Covered (CoverCount > 0)
if (counts > 0) {
coverage.coveredOptions.push(...elaborate(range, counts, showCounts));
} else {
coverage.uncoveredOptions.push(...elaborate(range, counts, showCounts));
}

coveragePath.set(filename, coverage);
});

const pathsToDirs = await getImportPathToFolder([...seenPaths], dir);
createCoverageData(pathsToDirs, coveragePath);
setDecorators();
vscode.window.visibleTextEditors.forEach(applyCodeCoverage);
} catch (e) {
const errorMsg = (e as any).msg || String(e);
vscode.window.showInformationMessage(errorMsg);
throw e;
}
}

// add decorations to the range
Expand Down Expand Up @@ -356,7 +352,7 @@ function createCoverageData(pathsToDirs: Map<string, string>, coveragePath: Map<
*/
function setCoverageDataByFilePath(filePath: string, data: CoverageData) {
if (filePath.startsWith('_')) {
filePath = filePath.substr(1);
filePath = filePath.substring(1);
}
if (process.platform === 'win32') {
const parts = filePath.split('/');
Expand Down
22 changes: 18 additions & 4 deletions extension/src/goDebugConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,14 +394,27 @@ export class GoDebugConfigurationProvider implements vscode.DebugConfigurationPr
const child = spawn(getBinPath('dlv'), ['substitute-path-guess-helper']);
let stdoutData = '';
let stderrData = '';
child.stdout.on('data', (data) => {

const stdoutHandler = (data: Buffer) => {
stdoutData += data;
});
child.stderr.on('data', (data) => {
};
const stderrHandler = (data: Buffer) => {
stderrData += data;
});
};

// Cleanup function to remove all listeners
const cleanup = () => {
child.stdout?.removeListener('data', stdoutHandler);
child.stderr?.removeListener('data', stderrHandler);
child.removeAllListeners('close');
child.removeAllListeners('error');
};

child.stdout.on('data', stdoutHandler);
child.stderr.on('data', stderrHandler);

child.on('close', (code) => {
cleanup();
if (code !== 0) {
resolve(null);
} else {
Expand All @@ -414,6 +427,7 @@ export class GoDebugConfigurationProvider implements vscode.DebugConfigurationPr
});

child.on('error', (error) => {
cleanup();
resolve(null);
});
});
Expand Down
6 changes: 3 additions & 3 deletions extension/src/goGenerateTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ export const toggleTestFile: CommandFactory = () => () => {
}
let targetFilePath = '';
if (currentFilePath.endsWith('_test.go')) {
targetFilePath = currentFilePath.substr(0, currentFilePath.lastIndexOf('_test.go')) + '.go';
targetFilePath = currentFilePath.substring(0, currentFilePath.lastIndexOf('_test.go')) + '.go';
} else {
targetFilePath = currentFilePath.substr(0, currentFilePath.lastIndexOf('.go')) + '_test.go';
targetFilePath = currentFilePath.substring(0, currentFilePath.lastIndexOf('.go')) + '_test.go';
}
for (const doc of vscode.window.visibleTextEditors) {
if (doc.document.fileName === targetFilePath) {
Expand Down Expand Up @@ -269,7 +269,7 @@ function generateTests(
return element.startsWith(generatedWord);
})
.map((element) => {
return element.substr(generatedWord.length);
return element.substring(generatedWord.length);
});
message = `Generated ${lines.join(', ')}`;
testsGenerated = true;
Expand Down
2 changes: 1 addition & 1 deletion extension/src/goImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async function askUserForImport(goCtx: GoExtensionContext): Promise<string | und
return vscode.window.showQuickPick(packages);
} catch (err) {
if (typeof err === 'string' && err.startsWith(missingToolMsg)) {
promptForMissingTool(err.substr(missingToolMsg.length));
promptForMissingTool(err.substring(missingToolMsg.length));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion extension/src/goInstall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export const installCurrentPackage: CommandFactory = () => async () => {

// Find the right importPath instead of directly using `.`. Fixes https://github.com/Microsoft/vscode-go/issues/846
const currentGoWorkspace = getCurrentGoWorkspaceFromGOPATH(getCurrentGoPath(), cwd);
const importPath = currentGoWorkspace && !isMod ? cwd.substr(currentGoWorkspace.length + 1) : '.';
const importPath = currentGoWorkspace && !isMod ? cwd.substring(currentGoWorkspace.length + 1) : '.';
args.push(importPath);

outputChannel.info(`Installing ${importPath === '.' ? 'current package' : importPath}`);
Expand Down
4 changes: 2 additions & 2 deletions extension/src/goLint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,12 @@ export async function goLint(
return;
}
if (flag.startsWith('--config=') || flag.startsWith('-config=')) {
let configFilePath = flag.substr(flag.indexOf('=') + 1).trim();
let configFilePath = flag.substring(flag.indexOf('=') + 1).trim();
if (!configFilePath) {
return;
}
configFilePath = resolvePath(configFilePath);
args.push(`${flag.substr(0, flag.indexOf('=') + 1)}${configFilePath}`);
args.push(`${flag.substring(0, flag.indexOf('=') + 1)}${configFilePath}`);
return;
}
args.push(flag);
Expand Down
Loading
Loading