How do I get exit code after running command in integrated terminal in vscode - visual-studio-code

After running terminal.sendtext("some command"), how do I get the exit code of the command? If this is not possible, is there a way to run the command in external terminal(using something likechild_process.spawnSync()) and get the exit code?

You could do something like this
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
ls.on('exit', (code) => {
console.log(`child process exited with code ${code}`);
});
Reference : https://nodejs.org/dist/latest-v12.x/docs/api/child_process.html#child_process_event_close

You could use the new terminal exit api, see v1.71 Release Notes: terminal exit status api:
TerminalExitStatus.reason
Extension authors now have better insight into why a terminal exited
via the new TerminalExitReason API.
export enum TerminalExitReason {
Unknown = 0,
Shutdown = 1,
Process = 2,
User = 3,
Extension = 4,
}

Related

Dart how to hide cmd when using Process.run?

After building the Dart application, function Process.run starts to open a visible cmd for a second-two.
final bool checkEnvironment = environment == ShellEnvironment.powershell;
ProcessResult result = await Process.run(
checkEnvironment ? 'powershell' : command,
checkEnvironment ? [command] : args,
runInShell: checkEnvironment,
);
Link with example(gif): https://imgur.com/jSPN6ew For each command it opens a new cmd window.
If i launch the application with idea(not a build version) - such thing does not happen
Also tried this version - still the same problem:
final bool checkEnvironment = environment == ShellEnvironment.powershell;
ProcessResult result = await Process.run(
'start',
checkEnvironment ? ['/min', 'powershell', '-command', command] : ['/min', 'cmd', '/c', command],
runInShell: true,
);
Found an article that runInShell creates a new window so i removed it, but the result is still the same.
final bool checkEnvironment = environment == ShellEnvironment.powershell;
ProcessResult result = await Process.run(
checkEnvironment ? 'powershell.exe' : 'cmd',
checkEnvironment ? ['-command', command] : ['/c', command],
);
You might have found a solution here: https://github.com/flutter/flutter/issues/47891. BUT do not use it! It does not work with window 7 and creates a problem when after closing the app user cannot delete the app due to one instance of CMD is still running.
Try this approach instead
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
} else {
AllocConsole();
ShowWindow(GetConsoleWindow(), SW_HIDE);
}
You can replace it in windows/runner/main.cpp

Error occurs when debugging rust program with vscode (windows only)

I am trying to debug the code below with vscode, but an error occurs.
Development environment
Microsoft Windows 10 Home 10.0.19042 Build 19042
rustc 1.49.0 (e1884a8e3 2020-12-29)
Vscode 1.54.3
CodeLLDB v1.6.1
// Cargo.toml
//[dependencies]
//datafusion = "3.0.0"
//arrow = "3.0.0"
//tokio = { version = "0.2", features = ["macros", "blocking", "rt-core", "rt-threaded", "sync"] }
use std::time::{Duration, Instant};
use arrow::util::pretty;
use datafusion::error::Result;
use datafusion::prelude::*;
/// This example demonstrates executing a simple query against an Arrow data source (CSV) and
/// fetching results
#[tokio::main]
async fn main() -> Result<()> {
println!("======== Start Program ========");
let start = Instant::now();
// let res_path = r"/root/workspace/project/hello_arrow/res/sample_01.csv";
// http://insideairbnb.com/get-the-data.html
// listing_id,id,date,reviewer_id,reviewer_name,comments
// Boston, Massachusetts, United States
let res_path = r"D:\workspace\vscode\arrow_rust\res\review.01.csv";
// create local execution context
let mut ctx = ExecutionContext::new();
// register csv file with the execution context
ctx.register_csv("datatable_01", res_path, CsvReadOptions::new())?;
// execute the query
let sql = "SELECT count(id) from datatable_01";
let df = ctx.sql(sql)?;
let results = df.collect().await?;
// print the results
pretty::print_batches(&results)?;
let duration = start.elapsed();
println!("Time elapsed in expensive_function() is: {:?}", duration);
println!("======== End Program ========");
Ok(())
}
Error Code
configuration: {
type: 'lldb',
request: 'launch',
name: 'Debug Window',
program: '${workspaceRoot}/target/debug/arrow_rust.exe',
args: [],
cwd: '${workspaceRoot}',
sourceLanguages: [ 'rust' ],
__configurationTarget: 5,
relativePathBase: 'd:\\workspace\\vscode\\arrow_rust'
}
Listening on port 8541
error: arrow_rust.exe :: Class 'arrow::datatypes::DataType' has a member '__0' of type 'alloc::vec::Vec<arrow::datatypes::Field>' which does not have a complete definition.
Debug adapter exit code=3221225620, signal=null.
The program runs normally. Debugging fine on Linux for the same code.
Is there any other way to debug on Windows?
I have the same problem.
Inspired by the link below, I have solved it.
https://github.com/vadimcn/vscode-lldb/issues/410#issuecomment-786791796
The reason is that I have installed NVIDIA Nsight.
As shown below, the msdia140.dll for Nsight has been loaded by codelldb.
Run PowerShell as administrator. Execute the command below to register the component. Then codelldb works.
regsvr32.exe C:\Users\【user name】\.vscode\extensions\vadimcn.vscode-lldb-1.6.8\lldb\bin\msdia140.dll
Update
For newer versions, the DLL has moved to another folder:
regsvr32.exe C:\Users\[user name]\.vscode\extensions\vadimcn.vscode-lldb-1.8.1\adapter\msdia140.dll

How delete a channel with a specific command?

I made a code that closes the specific channel that you write the command in.
This is my code that redirects each command to its own folder and runs the code in it.
events\message.js
module.exports = (client, message) => {
// Ignore all bots
if (message.author.bot) return;
// Ignore messages not starting with the prefix (in config.json)
if (message.content.indexOf(client.config.prefix) !== 0) return;
// Our standard argument/command name definition.
const args = message.content.slice(client.config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Grab the command data from the client.commands Enmap
const cmd = client.commands.get(command);
// If that command doesn't exist, silently exit and do nothing
if (!cmd) return;
// Run the command
cmd.run(client, message, args);
};
And my code that deletes the channel the command is written in.
const ms = require('ms');
const Discord = require('discord.js');
const client = new Discord.Client();
exports.run = async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR", "Ticket Admin"))
return message.reply('You need a specify permission to setup a ticket!');
if (message.author.bot) return;
const msgargs = message.content.slice(client.config.prefix.length).trim().split(/ +/g);
const command = msgargs.shift().toLowerCase();
if(command == "close") {
if(!message.channel.name.includes("ticket-")) return message.channel.send("You cannot use that here!")
message.channel.delete();
}
};
but the problem is that it doesn't want to delete the channel with "ticket-" in his name and it's the channel that the command was written in.
any help will be appreciated.
your file name isn't the same ass your command.
so when you send the command $ticket-close it runs the ticket-close file but in the ticket-close file, you are verifying if the command was closed and not so it end it.
you need to have the same name for your file code and your command to verify,(if(command == "close")).
or just don't check what was the command.

Failing e2e tests pass build in Teamcity

we have recently just killed all our e2e tests in Teamcity (ooops) by upgrading node version.
I'm sure this is something we are able to sort out, BUT it has highlighted that Teamcity isn't set up right (or something else is a miss).
As I say all tests fail but that build step just says it exits with code 0 and carries on building successfully.
[15:53:13][Step 4/6] 51 specs, 51 failures
[15:53:13][Step 4/6] Finished in 106.981 seconds
[15:53:13][Step 4/6]
[15:53:13][Step 4/6] closing code: null
[15:53:13][Step 4/6] Process exited with code 0
we are using protractor for the tests and running them using command line runner in the build step.
npm run teamcity-e2e
Sorry if this is quite vague, but hopefully it will mean something to someone and they can point me in the right direction :)
cheers..
-- Edit after more investigation --
I now know the problem is with my node script I created (teamcity-e2e.js) ...
const exec = require('child_process').exec;
const server = exec('live-server ./dist --port=3000 --no-browser');
const tests = exec('npm run e2e');
tests.stdout.on('data', function(data) {
console.log(data);
});
tests.stderr.on('data', function(data) {
console.log(data);
});
tests.on('close', function(code) {
console.log('closing code: ' + code);
exec('taskkill /PID ' + server.pid + ' /T /F');
});
Though I don't know what the problem is so still after help please anyone ;)
awesome I've fixed it :)
the quick and simple answer was my node script wasn't actually returning an exit code DOH :)
here is my fixed solution...
const exec = require('child_process').exec;
const server = exec('npm run server:test');
const tests = exec('npm run e2e');
tests.stdout.on('data', function(data) {
console.log(data);
});
tests.stderr.on('data', function(data) {
console.log(data);
});
tests.on('close', function(code) {
console.log('closing code: ' + code);
exec('taskkill /PID ' + server.pid + ' /T /F');
process.exit(code); //here's the bad boy ;)
});

How to detect an error in mapreduce

Let's have an "error_test.js" file that contains:
db = db.getMongo().getDB( "mydb" );
db.mycol.insert( { hello : "world" } );
print("it is shown");
db.runCommand(
{
mapReduce: "mycol",
map: function(){ print(not_exists); },
reduce: function(key, values){},
out: { replace: "myrescol" }
}
);
print("it is shown too (after error in mapreduce!)");
If I run the file (in Windows command line), I get:
mypath>mongo error_test.js
MongoDB shell version: 2.4.0
connecting to: test
it is shown
it is shown too (after error in mapreduce!)
mypath>echo %errorlevel%
0
mypath>
So we can deduce that:
the mapreduce error doesn't stop the execution.
the mapreduce error is not shown to the user.
the mapreduce error is not translated to the exit code (0 = success) (so a caller program can't detect the error).
The only way to know of the error is by looking for the following line at "mongod.log":
Wed Jun 12 10:02:37.393 [conn14] JavaScript execution failed: ReferenceError: not_exists is not defined near '(){ print(not_exists)'
Same happens if we use the "db.doEval(my_js)" method in Java and we put the content of "error_test.js" file into the "my_js" variable: The mapreduce error is not detected (no excepcion is launched, no null value is returned, "ok : 1.0" appears in the response).
So my question is: How can I detect an error in the mapreduce? (both in a js file and in the doEval() method)
Thank you
You need to capture the return document from db.runCommand() into a variable and then check its ok value in your script - you can then throw an error or print output, etc.
print("it is shown");
var res = db.runCommand(
{
mapReduce: "mycol",
map: function(){ print(not_exists); },
reduce: function(key, values){},
out: { replace: "myrescol" }
}
);
printjson(res);
if (res.ok == 0) {
print("Oopsy!");
throw("error! " + res.errmsg + " returned from mapreduce");
}
print("it is shown too (after error in mapreduce!)");